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/master
<file_sep># Turtle Python mini-project to plot a histogram with Turtle graphics module. This project was completed successfully as part of the requirement for Nanyang Technological University's MA1008 Introduction to Computation Thinking course, with an A- Grade. **Disclaimer : The source code that was used to implement the coursework project is no longer maintained. There may be errors or bugs that did not exist at the time of creation.** <file_sep>#Name: <NAME> #Matric Number: U1820770G import math Heighttxt = open("Height.txt","r") #opening the file OriginalHeightList = Heighttxt.readlines() ListLength = len(OriginalHeightList) #to be used as end limit for range function HeightList = [] for n in range(1,ListLength): HeightList += [float(OriginalHeightList[n])] #HeightList is list of heights in float form, enabling calculations HListLength = len(HeightList) #to be used as end limit for range function Seg1 = 0 #Assigning values to variable used to calculate number of people in height category Seg2 = 0 Seg3 = 0 Seg4 = 0 Seg5 = 0 Seg6 = 0 Seg7 = 0 Seg8 = 0 Seg9 = 0 Seg10 = 0 for i in range(0,HListLength): #to sort the list of heights into the number of people in their respective height category if 1.10 <= HeightList[i] < 1.21: #manual assignment of limits is preferable for better readability when bar chart is plotted Seg1 += 1 if 1.21 <= HeightList[i] < 1.32: Seg2 += 1 if 1.32 <= HeightList[i] < 1.43: Seg3 += 1 if 1.43 <= HeightList[i] < 1.54: Seg4 += 1 if 1.54 <= HeightList[i] < 1.65: Seg5 += 1 if 1.65 <= HeightList[i] < 1.76: Seg6 += 1 if 1.76 <= HeightList[i] < 1.87: Seg7 += 1 if 1.87 <= HeightList[i] < 1.98: Seg8 += 1 if 1.98 <= HeightList[i] < 2.09: Seg9 += 1 if 2.09 <= HeightList[i] < 2.20: Seg10 += 1 Segs = [Seg1, Seg2, Seg3, Seg4, Seg5, Seg6, Seg7, Seg8, Seg9, Seg10] #for plotting of bar chart later XInterval = ['1.10-1.21','1.21-1.32','1.32-1.43','1.43-1.54','1.54-1.65','1.65-1.76','1.76-1.87','1.87-1.98','1.98-2.09','2.09-2.20'] #label x-axis intervals Heighttxt.close() #end of consolidation of information import turtle #start of plotting of bar chart turtle.setworldcoordinates(-100,-100,1500,1800) turtle.title('Number Of People against Height Category(m)') turtle.bgcolor('linen') #filling the background color def axis(): #plotting of axes of bar chart x = turtle.Turtle() y = turtle.Turtle() x.speed(0) #for fastest plotting of axes y.speed(0) countx = 0 county = 0 xinterval = 0 yinterval = 1 while countx < 1000: x.forward(100) x.right(90) x.forward(10) x.penup() #to adjust interval words to a suitable position x.forward(40) x.right(90) x.forward(40) x.write(XInterval[xinterval],font = ('Arial',6,'underline')) #font adjusted for better visibility on barchart x.back(40) x.left(90) x.back(40) x.pendown() x.back(10) x.left(90) xinterval += 1 countx += 100 else: x.forward(100) x.write('Height Category(m)',font = ('Arial',11,'bold')) #labelling of x-axis y.left(90) while county < 1500: y.forward(100) y.left(90) y.forward(10) y.penup() #to adjust interval words to a suitable position y.forward(30) y.left(90) y.forward(30) y.write(str(yinterval),font = ('Arial',7)) #font adjusted for better visibility on barchart y.back(30) y.right(90) y.back(30) y.pendown() y.back(10) y.right(90) yinterval += 1 county += 100 else: y.forward(100) y.write('Number Of People',font = ('Arial',11,'bold')) #labelling of y-axis axis() def net(): net = turtle.Turtle() net.speed(0) net.penup() net.left(90) net.forward(100) net.right(90) net.pendown() netcount = 0 while netcount < 1500: #plotting reference lines net.color('grey') net.forward(1100) net.back(1100) net.penup() net.left(90) net.forward(100) net.right(90) net.pendown() netcount += 100 else: #adding the title at the top of the bar chart net.penup() net.left(90) net.forward(100) net.right(90) net.forward(100) net.pendown() net.color('black') net.write('Number Of People against Height Category(m)',font = ('Arial',13,'underline')) net.hideturtle() net() bar = turtle.Turtle() bar.speed(10) #for quick plot of bar def individualbar(a,b): #base code to plot individual bar with customizable color fill bar.begin_fill() bar.color('black',b) bar.pendown() bar.setheading(90) bar.forward(a*100) bar.right(90) bar.forward(100) bar.right(90) bar.forward(a*100) bar.end_fill() def plotbars(): #code to plot collective sets of data into bar chart bar.forward(50) individualbar(Seg1,'red') individualbar(Seg2,'tomato') individualbar(Seg3,'orange') individualbar(Seg4,'gold') individualbar(Seg5,'darkseagreen') individualbar(Seg6,'green') individualbar(Seg7,'cornflowerblue') individualbar(Seg8,'mediumslateblue') individualbar(Seg9,'purple') individualbar(Seg10,'violet') bar.hideturtle() plotbars() turtle.done()
50abfbcc26814c3f7e07a2d0b42b0de4bf0475fd
[ "Markdown", "Python" ]
2
Markdown
leeyunfai/Turtle
79b6aeedb5a7f5666ce00e913252f568a2f92294
182dda03521aabb76794a1aad03b2b2264401e9b
refs/heads/master
<repo_name>Quartzing/Tiles-to-word<file_sep>/main.cpp #include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; vector<string> readFile(string filename) { vector<string> data; string d; fstream file(filename, ios::in); //assert(file.is_open()); while(file) { file>>d; data.push_back(d); //cout<<d<<endl; } file.close(); return data; } bool isMatch(const string &word, string tiles, bool withWildcard) { if(word.size() > tiles.size()) return false; if(word.size()==0 || tiles.size()==0) return false; bool found=false; for(auto& c : word) { found=false; for(string::iterator itr=tiles.begin(); itr!=tiles.end(); itr++) { if(c==*itr) { *itr=1; found=true; } if(withWildcard) { if(*itr==' ') { *itr=1; found=true; } } } if(!found) return false; } return true; } int main(int argc, char** argv) { string withW=argv[1]; string tiles=argv[2]; bool withWildcard=false; if(withW=="-w") withWildcard=true; auto dictionary=readFile("dictionary.txt"); cout<<dictionary.size()<<endl; // looping the dictionary for(auto word : dictionary) { // copy a new tile string if(isMatch(word, tiles, withWildcard)) { // This is one way to output the result cout<<word<<endl; } } return 0; }<file_sep>/README.md # Tiles-to-word # Question “You are given a dictionary (dictionary.txt), containing a list of words, one per line. Imagine you have seven tiles. Each tile is either blank or contains a single lowercase letter (a-z).

Please list all the words from the dictionary that can be produced by using some or all of the seven tiles, in any order. A blank tile is a wildcard, and can be used in place of any letter.

 1. Find all of the words that can be formed if you don't have to deal with blank tiles. 2. Find all of the words that can be formed, including those where blank tiles are used as wildcards. 3. Please bear in mind you will need to process several hundred of 7-tile sets with the same dictionary. Expectations: a) Please write down the reasoning or the explanation behind your solution in plain English or pseudo-code. Please do a big O analysis of your solution, need not be overtly mathematical, an informal big O analysis will do. b) Please provide the source code of your implementation. c) Please include instructions on how to compile and run your code. d) Bonus points for source code in C/C++/C#. “ # Solution: As no tile information was provided, I made a general algorithm that can rum with whatever tiles provided. Loop for each word in the dictionary, and for each word, check the characters in the word if it is in the tiles provided. The only difference between q1 and q2 is if we treat blank tile as wildcard. Following is the pseudo-code. ``` for(word in dictionary) { if(word.size() < tiles.size()) { for(character in word) { for(tile in tilelist) { if(character == tile || tile == ‘ ‘) { Record that tile; } if(didn’t found that tile) return false; } } } } ``` The source code is written in C++. It is in the file “main.cpp”. You can compile and run it with the following command: ## Windows: ``` g++ main.cpp -o main.exe ``` And then run it by: ### without wildcard ``` main -wo “your tiles” ``` ### with wildcard ``` main -w “your tiles” ``` ## Linux: ``` g++ main.cpp -o main ``` And then run it by: ### without wildcard ``` ./main -wo “your tiles” ``` ### with wildcard ``` ./main -w “your tiles” ```
eea12bf8b7d6138bf3dd5698365561805278caae
[ "Markdown", "C++" ]
2
C++
Quartzing/Tiles-to-word
35456e595a6170d8a2df18caa25307784df19bf6
07a33bed18d7d3ed3abea7d5a47b119067322fd8
refs/heads/main
<repo_name>heros20/Notaire<file_sep>/src/Form/ContactType.php <?php namespace App\Form; use App\Entity\Contact; use App\Entity\User; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Security\Core\Security; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Validator\Constraints\NotBlank; class ContactType extends AbstractType { private $security; public function __construct(Security $security) { $this->security = $security; } public function buildForm(FormBuilderInterface $builder, array $options) { if ($this->security->isGranted('ROLE_ADMIN')){ $builder ->add('recipient', EntityType::class, [ 'class' => User::class, 'choice_label' => 'email', 'label' => 'Destinataire *', 'label_attr' => ['class' => 'formConnex_label2'], 'attr' => ['class' => 'class="form-control-material"'], 'empty_data' => '', 'constraints' => [ new NotBlank([ 'message' => 'Veuillez renseigner votre Email', ]) ] ]); } if (!$this->security->isGranted('ROLE_USER')) { $builder ->add('name', TextType::class, [ 'label' => 'Nom *', 'label_attr' => ['class' => 'formConnex_label2'], 'attr' => ['class' => 'class="form-control-material"'], ]) ->add('email', EmailType::class, [ 'label' => 'Email *', 'label_attr' => ['class' => 'formConnex_label2'], 'attr' => ['class' => "form-control-material"] ]) ->add('phone'); } else { } $builder ->add('message', TextareaType::class, [ 'label' => 'Message *', 'empty_data' => '', 'constraints' => [ new NotBlank([ 'message' => 'Veuillez renseigner votre Email', ]) ] ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Contact::class, ]); } } <file_sep>/src/Controller/ContactController.php <?php namespace App\Controller; use App\Entity\Contact; use App\entity\User; use App\Form\ContactType; use Symfony\Component\Security\Core\Security; use App\Repository\ContactRepository; use App\Repository\UserRepository; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; use Symfony\Component\Routing\Annotation\Route; #[Route('/contact')] class ContactController extends AbstractController { private $security; public function __construct(Security $security) { $this->security = $security; } #[Route('/', name: 'contact', methods: ['GET', 'POST'])] public function new(Request $request, MailerInterface $mailer, UserRepository $repoUser): Response { $user = $this->getUser(); $id_user = 1; $contact = new Contact(); $form = $this->createForm(ContactType::class, $contact); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $recipient = $repoUser->find($id_user); $contact->setIsRead(false) ->setRecipient($recipient); $email = new TemplatedEmail(); if ($this->security->isGranted('ROLE_USER')) { $contact->setSender($this->getUser()); $email->from($contact->getSender()->getEmail()) ->context([ 'contact' => $contact, 'mail' => $contact->getSender()->getEmail(), 'message' => $contact->getMessage() ]); }else { $email->from($contact->getEmail()) ->context([ 'contact' => $contact, 'mail' => $contact->getEmail(), 'message' => $contact->getMessage() ]); } $email->to(new Address('<EMAIL>')) ->subject('Contact') ->htmlTemplate('emails/contact.html.twig'); // dd($email); $mailer->send($email); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($contact); $entityManager->flush(); $this->addFlash('message', 'Votre email à bien été envoyé'); return $this->redirectToRoute('home'); } $user = $this->getUser(); return $this->render('contact/index.html.twig', [ 'contact' => $contact, 'form' => $form->createView(), 'user' => $user ]); } } <file_sep>/src/DataFixtures/CategoryFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use App\Entity\Category; class CategoryFixtures extends Fixture { public function load(ObjectManager $manager) { $category1 = (new Category()) ->setTitle('Villa'); $manager->persist($category1); $category2 = (new Category()) ->setTitle('Maison'); $manager->persist($category2); $category3 = (new Category()) ->setTitle('Appartement') ->setDescription('Découvrez ce magnifique appart du 16 ème'); $manager->persist($category3); $category4 = (new Category()) ->setTitle('Terrain constructible'); $manager->persist($category4); $category5 = (new Category()) ->setTitle('Terrain non constructible'); $manager->persist($category5); $manager->flush(); $this->addReference('category1', $category1); $this->addReference('category2', $category2); $this->addReference('category3', $category3); $this->addReference('category4', $category4); $this->addReference('category5', $category5); } } <file_sep>/src/DataFixtures/UserFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use App\entity\User; use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use DateTime; class UserFixtures extends Fixture { private $passwordHasher; private $tokengenerator; public function __construct(UserPasswordHasherInterface $passwordHasher, TokenGeneratorInterface $tokengenerator) { $this->passwordHasher = $passwordHasher; $this->tokengenerator = $tokengenerator; } public function load(ObjectManager $manager) { $admin = new User(); $admin->setName('Quillet') ->setUsername('Kevin') ->setToken($this->tokengenerator->generateToken()) ->setCreatedAt(new DateTime()) ->setEmail('<EMAIL>') ->setRoles(array('ROLE_ADMIN')) ->setPassword($this->passwordHasher->hashPassword( $admin, '123456' )); $manager->persist($admin); $admin2 = new User(); $admin2->setName('Daufresne') ->setUsername('Sebastien') ->setToken($this->tokengenerator->generateToken()) ->setCreatedAt(new DateTime()) ->setEmail('<EMAIL>') ->setRoles(array('ROLE_ADMIN')) ->setPassword($this->passwordHasher->hashPassword( $admin2, '123456' )); $manager->persist($admin2); $admin3 = new User(); $admin3->setName('Zenon') ->setUsername('Stella') ->setToken($this->tokengenerator->generateToken()) ->setCreatedAt(new DateTime()) ->setEmail('<EMAIL>') ->setRoles(array('ROLE_ADMIN')) ->setPassword($this->passwordHasher->hashPassword( $admin3, '123456' )); $manager->persist($admin3); // $admin4 = new User(); // $admin4->setName('Michellus') // ->setUsername('Michel') // ->setToken($this->tokengenerator->generateToken()) // ->setCreatedAt(new DateTime()) // ->setEmail('<EMAIL>') // ->setRoles(array('ROLE_ADMIN')) // ->setPassword($this->passwordHasher->hashPassword( // $admin4, // 'michel' // )); // $manager->persist($admin4); $manager->flush(); } } <file_sep>/src/DataFixtures/DepartementFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use App\Entity\Departement; class DepartementFixtures extends Fixture { public function load(ObjectManager $manager) { $departement1 = (new Departement()) ->setTitle('Deauville') ->setCodePostal('14') ->setDescription('Venez visitez ce magnifique département'); $departement2 = (new Departement()) ->setTitle('Charente-Maritime') ->setCodePostal('173'); $departement3 = (new Departement()) ->setTitle('Paris') ->setCodePostal('75') ->setDescription('Situé en plein coeur des champs élysée'); $departement4 = (new Departement()) ->setTitle('Honfleur') ->setCodePostal('76') ->setDescription('Situé en plein centre ville'); $departement5 = (new Departement()) ->setTitle('Caen') ->setCodePostal('14') ->setDescription('Situé en plein centre ville'); $departement6 = (new Departement()) ->setTitle('Havre') ->setCodePostal('76000'); $departement7 = (new Departement()) ->setTitle('Epaignes') ->setCodePostal('27260'); $departement8 = (new Departement()) ->setTitle('Cormeilles') ->setCodePostal('27260'); $manager->persist($departement1); $manager->persist($departement2); $manager->persist($departement3); $manager->persist($departement4); $manager->persist($departement5); $manager->persist($departement6); $manager->persist($departement7); $manager->persist($departement8); $manager->flush(); $this->addReference('departement1', $departement1); $this->addReference('departement2', $departement2); $this->addReference('departement3', $departement3); $this->addReference('departement4', $departement4); $this->addReference('departement5', $departement5); $this->addReference('departement6', $departement6); $this->addReference('departement7', $departement7); $this->addReference('departement8', $departement8); } } <file_sep>/src/Form/ImagesAnnonceType.php <?php namespace App\Form; use App\Entity\Annonce; use App\Entity\Ville; use App\Entity\Category; use App\Entity\Departement; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; class ImagesAnnonceType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('image', FileType::class, [ 'label' => 'image(s) supplémentaire', 'multiple' => true, 'mapped' => false, 'required' => false, ]) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Annonce::class, ]); } } <file_sep>/assets/app.js import './portal/assets/css/portal.css'; // import './portal-theme-bs5-v2.0/assets/plugins/fontawesome/js/all.min.js'; // import './portal/assets/plugins/popper.min.js'; // import './portal/assets/plugins/bootstrap/js/bootstrap.js'; import './portal/assets/js/app.js'; import './styles/app.css'; window.onload = () => { // Gestion des boutons "Supprimer" // on cible les liens let links = document.querySelectorAll("[data-token]") // on boucle sur links for (const link of links) { //on ecoute le clic link.addEventListener("click", function(e){ // // on empeche la navigation e.preventDefault() // on demande confirmation if (confirm('voulez-vous supprimer cette image')) { // on envoie une requete Ajax vers le href du lien avec la méthode DELETE fetch(this.getAttribute("href"), { method: "POST", headers: { 'X-Requested-With' : "XMLHttpRequest", 'Content-Type': 'application/json' }, body: JSON.stringify({'_token': this.dataset.token}) }).then( // on recupere la réponse en JSON response => response.json() ).then(response => { console.log(response); if(response.success) this.parentElement.remove() else alert(response.error) }).catch(e => { console.log(e); }) } }) } $(function() { // je stock la recherche d'une url var url = window.location.href; // je cible tous mes liens $("a").each(function() { // je verifie que l'url du lien et de la recherche son les mêmes if (url == (this.href)) { $(this).closest("li").addClass("active"); } }); }); } // any CSS you import will output into a single css file (app.css in this case) // start the Stimulus application // import './bootstrap'; <file_sep>/src/Entity/Annonce.php <?php namespace App\Entity; use App\Repository\AnnonceRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity; /** * @ORM\Entity(repositoryClass=AnnonceRepository::class) * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false) */ class Annonce { use SoftDeleteableEntity; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank * @Assert\Length( * min = 2, * max = 255, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums" * ) */ private $title; /** * @Gedmo\Slug(fields={"title"}) * @ORM\Column(length=128, unique=true) */ private $slug; /** * @ORM\Column(type="text") * @Assert\NotBlank * @Assert\Length( * min = 2, * max = 255, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums" * ) */ private $description; /** * @ORM\Column(type="string", length=255) */ private $image; /** * @ORM\Column(type="integer", nullable=true) * @Assert\NotBlank * @Assert\Length( * min = 2, * minMessage = "Vous devez respecter {{ limit }} chiffres minimum", * ) */ private $superficie; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 2, * minMessage = "Vous devez respecter {{ limit }} chiffres minimum", * ) */ private $superficieTerrain; /** * @ORM\Column(type="integer") * @Assert\NotBlank * @Assert\Length( * min = 2, * minMessage = "Vous devez respecter {{ limit }} chiffres minimum", * ) */ private $price; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 1, * minMessage = "Vous devez respecter {{ min }} caractères minimums" * ) */ private $status; /** * @ORM\Column(type="string", length=20, nullable=true) */ private $etat; /** * @ORM\Column(type="string", length=1, nullable=true) */ private $dpe; /** * @ORM\Column(type="string", length=1, nullable=true) */ private $ges; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 1, * minMessage = "Vous devez respecter {{ min }} caractères minimums" * ) */ private $nbrePieces; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 1, * minMessage = "Vous devez respecter {{ min }} caractères minimums" * ) */ private $nbreChambre; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 1, * minMessage = "Vous devez respecter {{ min }} caractères minimums" * ) */ private $salleBain; /** * @ORM\Column(type="integer", nullable=true) * @Assert\Length( * min = 1, * minMessage = "Vous devez respecter {{ min }} caractères minimums" * ) */ private $wc; /** * @ORM\Column(type="string", length=3, nullable=true) */ private $garage; /** * @ORM\Column(type="string", length=3, nullable=true) */ private $piscine; /** * @ORM\ManyToMany(targetEntity=Category::class, inversedBy="annonces") * @Assert\NotBlank */ private $category; /** * @ORM\ManyToOne(targetEntity=Ville::class, inversedBy="annonces") * @ORM\JoinColumn(nullable=true) * @Assert\NotBlank */ private $ville; /** * @ORM\ManyToOne(targetEntity=Departement::class, inversedBy="annonces") * @ORM\JoinColumn(nullable=false) * @Assert\NotBlank */ private $departement; /** * @ORM\ManyToMany(targetEntity=User::class, inversedBy="favoris") */ private $favoris; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\Column(type="datetime", nullable=true) */ private $modifiedAt; /** * @ORM\OneToMany(targetEntity=Images::class, mappedBy="annonce", orphanRemoval=true, cascade={"persist"}) */ private $images; /** * @ORM\OneToMany(targetEntity=Contact::class, mappedBy="Annonce") */ private $contacts; public function __construct() { $this->createdAt = new \DateTime; $this->category = new ArrayCollection(); $this->favoris = new ArrayCollection(); $this->images = new ArrayCollection(); $this->contacts = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function setSlug($slug) { $this->code = $slug; } public function getSlug() { return $this->slug; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image): self { $this->image = $image; return $this; } public function getSuperficie(): ?int { return $this->superficie; } public function setSuperficie(?int $superficie): self { $this->superficie = $superficie; return $this; } public function getSuperficieTerrain(): ?int { return $this->superficieTerrain; } public function setSuperficieTerrain(?int $superficieTerrain): self { $this->superficieTerrain = $superficieTerrain; return $this; } public function getPrice(): ?int { return $this->price; } public function setPrice(int $price): self { $this->price = $price; return $this; } public function getStatus(): ?int { return $this->status; } public function setStatus(int $status): self { $this->status = $status; return $this; } public function getEtat(): ?bool { return $this->etat; } public function setEtat(?bool $etat): self { $this->etat = $etat; return $this; } public function getDpe(): ?string { return $this->dpe; } public function setDpe(?string $dpe): self { $this->dpe = $dpe; return $this; } public function getGes(): ?string { return $this->ges; } public function setGes(?string $ges): self { $this->ges = $ges; return $this; } public function getNbrePieces(): ?int { return $this->nbrePieces; } public function setNbrePieces(?int $nbrePieces): self { $this->nbrePieces = $nbrePieces; return $this; } public function getNbreChambre(): ?int { return $this->nbreChambre; } public function setNbreChambre(?int $nbreChambre): self { $this->nbreChambre = $nbreChambre; return $this; } public function getSalleBain(): ?int { return $this->salleBain; } public function setSalleBain(?int $salleBain): self { $this->salleBain = $salleBain; return $this; } public function getWc(): ?int { return $this->wc; } public function setWc(?int $wc): self { $this->wc = $wc; return $this; } public function getGarage(): ?string { return $this->garage; } public function setGarage(?string $garage): self { $this->garage = $garage; return $this; } public function getPiscine(): ?string { return $this->piscine; } public function setPiscine(?string $piscine): self { $this->piscine = $piscine; return $this; } /** * @return Collection|Category[] */ public function getCategory(): Collection { return $this->category; } public function addCategory(Category $category): self { if (!$this->category->contains($category)) { $this->category[] = $category; } return $this; } public function removeCategory(Category $category): self { $this->category->removeElement($category); return $this; } public function getVille(): ?Ville { return $this->ville; } public function setVille(?Ville $ville): self { $this->ville = $ville; return $this; } public function getDepartement(): ?Departement { return $this->departement; } public function setDepartement(?Departement $departement): self { $this->departement = $departement; return $this; } /** * @return Collection|User[] */ public function getFavoris(): Collection { return $this->favoris; } public function addFavori(User $favori): self { if (!$this->favoris->contains($favori)) { $this->favoris[] = $favori; } return $this; } public function removeFavori(User $favori): self { $this->favoris->removeElement($favori); return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getModifiedAt(): ?\DateTimeInterface { return $this->modifiedAt; } public function setModifiedAt(?\DateTimeInterface $modifiedAt): self { $this->modifiedAt = $modifiedAt; return $this; } /** * @return Collection|Images[] */ public function getImages(): Collection { return $this->images; } public function addImage(Images $image): self { if (!$this->images->contains($image)) { $this->images[] = $image; $image->setAnnonce($this); } return $this; } public function removeImage(Images $image): self { if ($this->images->removeElement($image)) { // set the owning side to null (unless already changed) if ($image->getAnnonce() === $this) { $image->setAnnonce(null); } } return $this; } /** * @return Collection|Contact[] */ public function getContacts(): Collection { return $this->contacts; } public function addContact(Contact $contact): self { if (!$this->contacts->contains($contact)) { $this->contacts[] = $contact; $contact->setAnnonce($this); } return $this; } public function removeContact(Contact $contact): self { if ($this->contacts->removeElement($contact)) { // set the owning side to null (unless already changed) if ($contact->getAnnonce() === $this) { $contact->setAnnonce(null); } } return $this; } } <file_sep>/src/Controller/AnnonceController.php <?php namespace App\Controller; use App\Entity\Annonce; use App\Entity\Images; use App\Form\AnnonceType; use App\Form\ImagesAnnonceType; use App\Repository\AnnonceRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\String\Slugger\SluggerInterface; use Symfony\Component\HttpFoundation\File\File; use App\Service\FileUploader; use Symfony\Component\HttpFoundation\JsonResponse; #[Route('admin/annonce')] class AnnonceController extends AbstractController { #[Route('/', name: 'annonce_index', methods: ['GET'])] public function index(AnnonceRepository $annonceRepository): Response { $annonces = $annonceRepository->findBy( [], ['createdAt' => 'DESC'] ); return $this->render('annonce/index.html.twig', [ 'annonces' => $annonces, ]); } #[Route('/new', name: 'annonce_new', methods: ['GET', 'POST'])] public function new(Request $request, FileUploader $fileUploader): Response { $annonce = new Annonce(); $form = $this->createForm(AnnonceType::class, $annonce); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // /** @var UploadedFile $imageFile */ // $imageMultiple = $form->get('image')->getData(); $annonceFile = $form->get('fileimage')->getData(); // foreach ($imageMultiple as $image) { // // on genere un nouveau nom de fichier // $fichier = md5(uniqid()). '.' . $image->guessExtension(); // // on copie le fichier dans le dossier uploads // $image->move( // $this->getParameter('images_directory'), // $fichier // ); // // on stock l'image dans la Bdd (son nom) // $img = new Images(); // $img->setName($fichier); // $annonce->addImage($img); // } if ($annonceFile) { $annonceFileName = $fileUploader->upload($annonceFile); $annonce->setimage($annonceFileName); } $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($annonce); $entityManager->flush(); return $this->redirectToRoute('annonce_index'); } return $this->render('annonce/new.html.twig', [ 'annonce' => $annonce, 'form' => $form->createView(), ]); } #[Route('/{id}', name: 'annonce_show', methods: ['GET'])] public function show(Annonce $annonce): Response { return $this->render('annonce/show.html.twig', [ 'annonce' => $annonce, ]); } #[Route('/{id}/edit', name: 'annonce_edit', methods: ['GET', 'POST'])] public function edit(Request $request, Annonce $annonce, FileUploader $fileUploader): Response { $form = $this->createForm(AnnonceType::class, $annonce); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { /** @var UploadedFile $imageFile */ $imageMultiple = $form->get('image')->getData(); $annonceFile = $form->get('fileimage')->getData(); // foreach ($imageMultiple as $image) { // // on genere un nouveau nom de fichier // $fichier = md5(uniqid()). '.' . $image->guessExtension(); // // on copie le fichier dans le dossier uploads // $image->move( // $this->getParameter('images_directory'), // $fichier // ); // on stock l'image dans la Bdd (son nom) // $img = new Images(); // $img->setName($fichier); // $annonce->addImage($img); //} if ($annonceFile) { $annonceFileName = $fileUploader->upload($annonceFile); $annonce->setimage($annonceFileName); } $this->getDoctrine()->getManager()->flush(); // $form['image']->getData(); return $this->redirectToRoute('annonce_index'); } return $this->render('annonce/edit.html.twig', [ 'annonce' => $annonce, 'form' => $form->createView(), ]); } #[Route('/{id}', name: 'annonce_delete', methods: ['POST'])] public function delete(Request $request, Annonce $annonce): Response { if ($this->isCsrfTokenValid('delete'.$annonce->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($annonce); $entityManager->flush(); } return $this->redirectToRoute('annonce_index'); } #[Route('/supprimer/image/{id}', name: 'annonce_delete_image', methods: ["POST"])] public function deleteImage(Images $image, Request $request): JsonResponse { $data = json_decode($request->getContent(), true); // on verifie si le token est valide // if ($this->isCsrfTokenValid('delete'.$image->getId(), $data['_token'])) { // on recupere le nom de l'image $nom = $image->getName(); // on supprime le fichier unlink($this->getParameter('images_directory').'/'.$nom); // on supprime l'entrée de la Bdd $em = $this->getDoctrine()->getManager(); $em->remove($image); $em->flush(); // on répond en Json return new JsonResponse(['success' => 1]); // else { // return new JsonResponse(['error' => 'token invalide'], 400); // } } #[Route('/add/images/{id}', name: 'add_new_images', methods: ['GET', 'POST'])] public function AddImages(Request $request, Annonce $annonce): Response { $form = $this->createForm(ImagesAnnonceType::class, $annonce); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { /** @var UploadedFile $imageFile */ $imageMultiple = $form->get('image')->getData(); foreach ($imageMultiple as $image) { // on genere un nouveau nom de fichier $fichier = md5(uniqid()). '.' . $image->guessExtension(); // on copie le fichier dans le dossier uploads $image->move( $this->getParameter('images_directory'), $fichier ); // on stock l'image dans la Bdd (son nom) $img = new Images(); $img->setName($fichier); $annonce->addImage($img); } $this->getDoctrine()->getManager()->flush(); // $form['image']->getData(); return $this->redirectToRoute('annonce_index'); } return $this->render('images_annonce/index.html.twig', [ 'annonce' => $annonce, 'form' => $form->createView(), ]); } } <file_sep>/src/Entity/Images.php <?php namespace App\Entity; use App\Repository\ImagesRepository; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity; /** * @ORM\Entity(repositoryClass=ImagesRepository::class) * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false) */ class Images { use SoftDeleteableEntity; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $name; /** * @ORM\ManyToOne(targetEntity=Annonce::class, inversedBy="images") * @ORM\JoinColumn(nullable=false) */ private $annonce; public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getAnnonce(): ?Annonce { return $this->annonce; } public function setAnnonce(?Annonce $annonce): self { $this->annonce = $annonce; return $this; } } <file_sep>/src/Controller/RegistrationController.php <?php namespace App\Controller; use App\Entity\User; use App\Form\ResetPassType; use App\Form\ForgetPasswordType; use App\Form\RegistrationFormType; use App\Form\ResetType; use App\Security\EmailVerifier; use DateTime; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\FormError; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mime\Address; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface; class RegistrationController extends AbstractController { private $emailVerifier; public function __construct(EmailVerifier $emailVerifier) { $this->emailVerifier = $emailVerifier; } #[Route('/inscription', name: 'app_register')] public function register(Request $request, UserPasswordHasherInterface $passwordHasher): Response { $user = new User(); $form = $this->createForm(RegistrationFormType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // encode the plain password $user->setPassword( $passwordHasher->hashPassword( $user, $form->get('plainPassword')->getData() ) ); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($user); $entityManager->flush(); $this->emailVerifier->sendEmailConfirmation('app_verify_email', $user, (new TemplatedEmail()) ->from(new Address('<EMAIL>', 'agence notarial')) ->to($user->getEmail()) ->subject('Confirmation de votre compte') ->htmlTemplate('registration/confirmation_email.html.twig') ); return $this->redirectToRoute('attente'); } return $this->render('registration/register.html.twig', [ 'registrationForm' => $form->createView(), ]); } #[Route('/verification-email', name: 'app_verify_email')] public function verifyUserEmail(Request $request): Response { $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); // validate email confirmation link, sets User::isVerified=true and persists try { $this->emailVerifier->handleEmailConfirmation($request, $this->getUser()); } catch (VerifyEmailExceptionInterface $exception) { $this->addFlash('verify_email_error', $exception->getReason()); return $this->redirectToRoute('app_register'); } // @TODO Change the redirect on success and handle or remove the flash message in your templates $this->addFlash('success', 'Your email address has been verified.'); return $this->redirectToRoute('profile'); } #[Route('/verification', name: 'attente')] public function attente() { return $this->render('emails/attente.html.twig', [ 'controller_name' => 'HomeController', ]); } #[Route('/email', name: 'forget')] public function forget_password(Request $request, MailerInterface $mailer, TokenGeneratorInterface $tokenInterface) { $form = $this->createForm(ForgetPasswordType::class)->handleRequest($request); if($form->isSubmitted() && $form->isValid()){ $email = $form->getData("email"); $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email"=>$email["email"]]); if(!$user){ $this->addFlash("errors","cet email n'existe pas"); }else{ $token = $tokenInterface->generateToken(); $user->setResetToken($token) ->setResetTokenAt(new DateTime("now")); $this->getDoctrine()->getManager()->persist($user); $this->getDoctrine()->getManager()->flush(); $url = $this->generateUrl("reset",['token' =>$token], UrlGeneratorInterface::ABSOLUTE_URL); $mail = (new TemplatedEmail()) ->from('<EMAIL>') ->to($user->getEmail()) ->subject('Mot de passe oublié') ->htmlTemplate('emails/motdepasse.html.twig') ->context([ "url" => $url ]); $mailer->send($mail); $this->addFlash('successMdp','Un email de reinitialisation de mot de passe vous a été envoyé'); return $this->redirectToRoute('app_login'); } } return $this->render('emails/mdp.html.twig',[ 'form' => $form->createView() ]); } #[Route('/mot-de-passe/{token}', name: 'reset')] public function reset(Request $request, $token, UserPasswordHasherInterface $passwordHasher){ $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["reset_token" =>$token]); //Vérifier l'utilisateur existe ou pas if (!$user) { return $this->redirectToRoute('404'); } $form = $this->createForm(ResetType::class)->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->setResetToken(null); $user->setPassword( $<PASSWORD>->hash<PASSWORD>( $user, $form->get('password')->getData() ) ); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('app_login'); } return $this->render('emails/reset.html.twig', [ 'form' => $form->createView() ]); } #[Route('/mdp/edit', name: 'update_pass')] public function resetPassword(Request $request, UserPasswordHasherInterface $passwordHasher){ $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } $form = $this->createForm(ResetType::class)->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->setPassword( $passwordHasher->hashPassword( $user, $form->get('password')->getData() ) ); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('app_login'); } return $this->render('emails/reset.html.twig', [ 'form' => $form->createView() ]); } } <file_sep>/assets/front.js import "./scss/main.scss"; import $ from "jquery"; import noUiSlider from "nouislider"; import 'nouislider/dist/nouislider.css'; import './FlexSlider/flexslider.css'; import './FlexSlider/jquery.flexslider-min.js'; AOS.init(); $(document).ready(() => { $('.deroulant').on('mouseenter',function(){ $(".sous").css('display','block'); }); $('.sous').on('mouseleave',function(){ $(".sous").css('display','none'); }); $('#carousel').flexslider({ animation: "slide", controlNav: true, directionNav: false, animationLoop: false, slideshow: false, itemWidth: 210, itemMargin: 5, slideshowSpeed: 7000, asNavFor: '#slider' }); $('#slider').flexslider({ animation: "slide", controlNav: false, directionNav: false, animationLoop: false, slideshow: false, sync: "#carousel" }); }) $(function() { // je stock la recherche d'une url var url = window.location.href; // je cible tous mes liens $(".navbar__menu a").each(function() { // je verifie que l'url du lien et de la recherche son les mêmes if (url == (this.href)) { $(this).closest("li").addClass("active"); } }); }); const slider = document.getElementById('price-slider'); const min = document.getElementById('min') const max = document.getElementById('max') if (slider) { const range = noUiSlider.create(slider, { start: [400, 1000000], tooltips: [true,true], connect: true, step: 1000, range: { 'min': 1000, 'max': 300000 } }) range.on('slide',function(values,handle){ if(handle === 0){ min.value = Math.round(values[0]) } if(handle === 1){ max.value = Math.round(values[1]) } }); } <file_sep>/src/Entity/User.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use App\Repository\UserRepository; use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity(repositoryClass=UserRepository::class) * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false) * @UniqueEntity(fields="email", message="Cet email existe déja.") */ class User implements UserInterface, PasswordAuthenticatedUserInterface { use SoftDeleteableEntity; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=180, unique=true) * @Assert\Email( * message = "Veuillez renseigner un email valide" * ) * @Assert\NotBlank( * message = "Veuillez renseigner votre email" * ) */ private $email; /** * @ORM\Column(type="json") */ private $roles = []; /** * @var string The hashed password * @ORM\Column(type="string") */ private $password; /** * @ORM\Column(type="string", length=30) * @Assert\Length( * min = 2, * max = 30, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums", * ) * @Assert\NotBlank( * message = "Veuillez renseigner votre nom" * ) */ private $name; /** * @ORM\Column(type="string", length=30) * @Assert\NotBlank( * message = "Veuillez renseigner votre prénom" * ) * @Assert\Length( * min = 2, * max = 30, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums" * ) */ private $username; /** * @ORM\Column(type="string", length=10, nullable=true) * @Assert\Regex(pattern="/^[0-9]*$/", message="Veuillez renseigner un numéro valide") */ private $phone; /** * @ORM\Column(type="string", unique=true, nullable=true) */ private $token; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\Column(type="datetime", nullable=true) */ private $modifiedAt; /** * @ORM\ManyToMany(targetEntity=Annonce::class, mappedBy="favoris") */ private $favoris; /** * @ORM\OneToMany(targetEntity=Contact::class, mappedBy="sender") */ private $sent; /** * @ORM\OneToMany(targetEntity=Contact::class, mappedBy="recipient") */ private $received; /** * @ORM\Column(type="boolean",nullable=true) */ private $IsVerified; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $reset_token; /** * @ORM\Column(type="datetime", nullable=true) */ private $resetTokenAt; public function __construct() { $this->createdAt = new \DateTime; $this->modifieddAt = new \DateTime; $this->favoris = new ArrayCollection(); $this->sent = new ArrayCollection(); $this->received = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUserIdentifier(): string { return (string) $this->email; } /** * @see UserInterface */ public function getRoles(): array { $roles = $this->roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function setRoles(array $roles): self { $this->roles = $roles; return $this; } /** * @see PasswordAuthenticatedUserInterface */ public function getPassword(): string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } /** * Returning a salt is only needed, if you are not using a modern * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml. * * @see UserInterface */ public function getSalt(): ?string { return null; } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = <PASSWORD>; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getUsername(): ?string { return $this->username; } public function setUsername(string $username): self { $this->username = $username; return $this; } public function getPhone(): ?string { return $this->phone; } public function setPhone(?string $phone): self { $this->phone = $phone; return $this; } public function getToken(): ?string { return $this->token; } public function setToken(string $token): self { $this->token = $token; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getModifiedAt(): ?\DateTimeInterface { return $this->modifiedAt; } public function setModifiedAt(?\DateTimeInterface $modifiedAt): self { $this->modifiedAt = $modifiedAt; return $this; } /** * @return Collection|Annonce[] */ public function getFavoris(): Collection { return $this->favoris; } public function addFavori(Annonce $favori): self { if (!$this->favoris->contains($favori)) { $this->favoris[] = $favori; $favori->addFavori($this); } return $this; } public function removeFavori(Annonce $favori): self { if ($this->favoris->removeElement($favori)) { $favori->removeFavori($this); } return $this; } /** * @return Collection|Contact[] */ public function getSent(): Collection { return $this->sent; } public function addSent(Contact $sent): self { if (!$this->sent->contains($sent)) { $this->sent[] = $sent; $sent->setSender($this); } return $this; } public function removeSent(Contact $sent): self { if ($this->sent->removeElement($sent)) { // set the owning side to null (unless already changed) if ($sent->getSender() === $this) { $sent->setSender(null); } } return $this; } /** * @return Collection|Contact[] */ public function getReceived(): Collection { return $this->received; } public function addReceived(Contact $received): self { if (!$this->received->contains($received)) { $this->received[] = $received; $received->setRecipient($this); } return $this; } public function removeReceived(Contact $received): self { if ($this->received->removeElement($received)) { // set the owning side to null (unless already changed) if ($received->getRecipient() === $this) { $received->setRecipient(null); } } return $this; } public function getIsVerified(): ?bool { return $this->IsVerified; } public function setIsVerified(bool $IsVerified): self { $this->IsVerified = $IsVerified; return $this; } public function getResetToken(): ?string { return $this->reset_token; } public function setResetToken(?string $reset_token): self { $this->reset_token = $reset_token; return $this; } public function getResetTokenAt(): ?\DateTimeInterface { return $this->resetTokenAt; } public function setResetTokenAt(\DateTimeInterface $resetTokenAt): self { $this->resetTokenAt = $resetTokenAt; return $this; } } <file_sep>/src/Controller/ArchiveController.php <?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use App\Repository\AnnonceRepository; use App\Repository\CategoryRepository; use App\Repository\ContactRepository; use App\Repository\DepartementRepository; use App\Repository\ImagesRepository; use App\Repository\UserRepository; use App\Repository\VilleRepository; #[Route('admin/archives')] class ArchiveController extends AbstractController { #[Route('/', name: 'archives_index')] public function index(AnnonceRepository $annonceRepository,CategoryRepository $categoryRepository,ContactRepository $contactRepository,DepartementRepository $departementRepository,ImagesRepository $imagesRepository,UserRepository $userRepository,VilleRepository $villeRepository): Response { $em = $this->getDoctrine()->getManager(); $em->getFilters()->disable('softdeleteable'); $annonces = $annonceRepository->findAll(); $categorys = $categoryRepository->findAll(); $departements = $departementRepository->findAll(); $users = $userRepository->findAll(); $villes = $villeRepository->findAll(); $em->getFilters()->enable('softdeleteable'); return $this->render('archives/index.html.twig', [ 'annonces' => $annonces, 'categorys' => $categorys, 'departements' => $departements, 'users' => $users, 'villes' => $villes, ]); } #[Route('/{id}', name: 'category_restore', methods: ['POST'])] public function delete(Request $request, Category $category): Response { if ($this->isCsrfTokenValid('delete'.$category->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($category); $entityManager->flush(); } return $this->redirectToRoute('category_index'); } } <file_sep>/src/DataFixtures/AnnonceFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use App\Entity\Annonce; use App\DataFixtures\VilleFixtures; use App\DataFixtures\CategoryFixtures; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use App\DataFixtures\DepartementFixtures; class AnnonceFixtures extends Fixture implements DependentFixtureInterface { public function load(ObjectManager $manager) { $annonce1 = new Annonce(); $annonce1->setTitle('Villa'); $annonce1->setDescription('Découvrez cette magnifique villa au bord de mer'); $annonce1->setImage('villa.jpg'); $annonce1->setPrice(10000000); $annonce1->setSuperficie(10000); $annonce1->setSuperficieTerrain(1500); $annonce1->setDpe('a'); $annonce1->setGes('d'); $annonce1->setNbrePieces(10); $annonce1->setNbreChambre(20); $annonce1->setSalleBain(4); $annonce1->setWc(4); $annonce1->setGarage('oui'); $annonce1->setPiscine('oui'); $annonce1->setStatus(true); $annonce1->setVille($this->getReference('ville1')); $annonce1->setDepartement($this->getReference('departement1')); $annonce1->addCategory($this->getReference('category1')); $manager->persist($annonce1); $annonce2 = new Annonce(); $annonce2->setTitle('Villa'); $annonce2->setDescription('Découvrez cette magnifique villa'); $annonce2->setImage('villa2.jpg'); $annonce2->setPrice(10000000); $annonce2->setSuperficie(10000); $annonce2->setSuperficieTerrain(1500); $annonce2->setDpe('a'); $annonce2->setGes('d'); $annonce2->setNbrePieces(10); $annonce2->setNbreChambre(20); $annonce2->setSalleBain(4); $annonce2->setWc(4); $annonce2->setGarage('oui'); $annonce2->setPiscine('oui'); $annonce2->setStatus(true); $annonce2->setVille($this->getReference('ville2')); $annonce2->setDepartement($this->getReference('departement2')); $annonce2->addCategory($this->getReference('category1')); $manager->persist($annonce2); $annonce3 = new Annonce(); $annonce3->setTitle('Appartement'); $annonce3->setDescription('Appartement du 16 ème'); $annonce3->setImage('appartement.jpg'); $annonce3->setPrice(10000); $annonce3->setSuperficie(100); $annonce3->setDpe('a'); $annonce3->setGes('a'); $annonce3->setNbrePieces(1); $annonce3->setNbreChambre(2); $annonce3->setSalleBain(1); $annonce3->setWc(1); $annonce3->setGarage('non'); $annonce3->setPiscine('non'); $annonce3->setStatus(true); $annonce3->setVille($this->getReference('ville3')); $annonce3->setDepartement($this->getReference('departement3')); $annonce3->addCategory($this->getReference('category3')); $manager->persist($annonce3); $annonce4 = new Annonce(); $annonce4->setTitle('Résidence'); $annonce4->setDescription('Résidence'); $annonce4->setImage('appartement2.jpg'); $annonce4->setPrice(100000); $annonce4->setSuperficie(800); $annonce4->setDpe('b'); $annonce4->setGes('c'); $annonce4->setNbrePieces(8); $annonce4->setNbreChambre(9); $annonce4->setSalleBain(6); $annonce4->setWc(8); $annonce4->setGarage('non'); $annonce4->setPiscine('oui'); $annonce4->setStatus(true); $annonce4->setVille($this->getReference('ville4')); $annonce4->setDepartement($this->getReference('departement4')); $annonce4->addCategory($this->getReference('category2')); $manager->persist($annonce4); $manager->flush(); $annonce5 = new Annonce(); $annonce5->setTitle('Maison'); $annonce5->setDescription('Maison avec vue sur le musée'); $annonce5->setImage('maison.jpg'); $annonce5->setPrice(10000); $annonce5->setSuperficie(180); $annonce5->setSuperficieTerrain('500'); $annonce5->setDpe('c'); $annonce5->setGes('a'); $annonce5->setNbrePieces(4); $annonce5->setNbreChambre(4); $annonce5->setSalleBain(2); $annonce5->setWc(1); $annonce5->setGarage('oui'); $annonce5->setPiscine('non'); $annonce5->setStatus(true); $annonce5->setVille($this->getReference('ville5')); $annonce5->setDepartement($this->getReference('departement5')); $annonce5->addCategory($this->getReference('category2')); $manager->persist($annonce5); $annonce6 = new Annonce(); $annonce6->setTitle('Maison'); $annonce6->setDescription('Découvrez cette magnifique maison Normande'); $annonce6->setImage('maison2.jpg'); $annonce6->setPrice(10000); $annonce6->setSuperficie(10000); $annonce6->setSuperficieTerrain(1500); $annonce6->setDpe('d'); $annonce6->setGes('d'); $annonce6->setNbrePieces(4); $annonce6->setNbreChambre(3); $annonce6->setSalleBain(2); $annonce6->setWc(2); $annonce6->setGarage('oui'); $annonce6->setPiscine('oui'); $annonce6->setStatus(true); $annonce6->setVille($this->getReference('ville6')); $annonce6->setDepartement($this->getReference('departement6')); $annonce6->addCategory($this->getReference('category2')); $manager->persist($annonce6); $annonce7 = new Annonce(); $annonce7->setTitle('terrain constructible'); $annonce7->setDescription('Terrain pour lot de maison'); $annonce7->setImage('terrain.jpg'); $annonce7->setPrice(1000000); $annonce7->setSuperficie(10000); $annonce7->setSuperficieTerrain(1500); $annonce7->setDpe('a'); $annonce7->setGes('d'); $annonce7->setStatus(true); $annonce7->setVille($this->getReference('ville5')); $annonce7->setDepartement($this->getReference('departement7')); $annonce7->addCategory($this->getReference('category4')); $manager->persist($annonce7); $annonce8 = new Annonce(); $annonce8->setTitle('Terrain non constructible'); $annonce8->setDescription('Terrain non constructible'); $annonce8->setImage('terrain2.jpg'); $annonce8->setPrice(100000); $annonce8->setSuperficie(900); $annonce8->setDpe('a'); $annonce8->setGes('a'); $annonce8->setStatus(true); $annonce8->setVille($this->getReference('ville5')); $annonce8->setDepartement($this->getReference('departement3')); $annonce8->addCategory($this->getReference('category5')); $manager->persist($annonce8); $annonce9 = new Annonce(); $annonce9->setTitle('Résidence'); $annonce9->setDescription('Résidence'); $annonce9->setImage('appartement.jpg'); $annonce9->setPrice(10000); $annonce9->setSuperficie(150); $annonce9->setDpe('d'); $annonce9->setGes('a'); $annonce9->setNbrePieces(8); $annonce9->setNbreChambre(9); $annonce9->setSalleBain(6); $annonce9->setWc(8); $annonce9->setGarage('non'); $annonce9->setPiscine('oui'); $annonce9->setStatus(true); $annonce9->setVille($this->getReference('ville6')); $annonce9->setDepartement($this->getReference('departement4')); $annonce9->addCategory($this->getReference('category3')); $manager->persist($annonce9); $manager->flush(); $annonce10 = new Annonce(); $annonce10->setTitle('Maison'); $annonce10->setDescription('Maison avec vue sur le musée'); $annonce10->setImage('maison.jpg'); $annonce10->setPrice(10000); $annonce10->setSuperficie(180); $annonce10->setSuperficieTerrain('50'); $annonce10->setDpe('a'); $annonce10->setGes('d'); $annonce10->setNbrePieces(4); $annonce10->setNbreChambre(4); $annonce10->setSalleBain(2); $annonce10->setWc(1); $annonce10->setGarage('oui'); $annonce10->setPiscine('oui'); $annonce10->setStatus(true); $annonce10->setVille($this->getReference('ville4')); $annonce10->setDepartement($this->getReference('departement5')); $annonce10->addCategory($this->getReference('category2')); $manager->persist($annonce10); $manager->flush(); } public function getDependencies() { return [ DepartementFixtures::class, CategoryFixtures::class, VilleFixtures::class, ]; } } <file_sep>/src/Entity/Ville.php <?php namespace App\Entity; use App\Repository\VilleRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity; /** * @ORM\Entity(repositoryClass=VilleRepository::class) * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false) */ class Ville { use SoftDeleteableEntity; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=80) * @Assert\NotBlank * @Assert\Length( * min = 1, * max = 80, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums" * ) */ private $title; /** * @ORM\Column(type="integer") * @Assert\NotBlank * @Assert\Length( * min = 5, * max = 5, * minMessage = "Vous devez respecter {{ min }} characters minimums", * maxMessage = "Vous devez respecter {{ min }} characters maximums" * ) */ private $codePostal; /** * @ORM\Column(type="text", nullable=true) */ private $description; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\OneToMany(targetEntity=Annonce::class, mappedBy="ville") */ private $annonces; public function __construct() { $this->createdAt = new \DateTime; $this->annonces = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getCodePostal(): ?int { return $this->codePostal; } public function setCodePostal(int $codePostal): self { $this->codePostal = $codePostal; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): self { $this->description = $description; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } /** * @return Collection|Annonce[] */ public function getAnnonces(): Collection { return $this->annonces; } public function addAnnonce(Annonce $annonce): self { if (!$this->annonces->contains($annonce)) { $this->annonces[] = $annonce; $annonce->setVille($this); } return $this; } public function removeAnnonce(Annonce $annonce): self { if ($this->annonces->removeElement($annonce)) { // set the owning side to null (unless already changed) if ($annonce->getVille() === $this) { $annonce->setVille(null); } } return $this; } } <file_sep>/src/Data/SearchData.php <?php namespace App\Data; use App\Entity\Category; use App\Entity\Ville; use App\Entity\Departement; class SearchData { /** * @var Category[] */ public $category = []; /** * @var Departement[] */ public $departement = []; /** * @var Ville[] */ public $ville = []; /** * @var null|integer */ public $max; /** * @var null|integer */ public $min; /** * @var null|integer */ public $status; }<file_sep>/src/Controller/AdminController.php <?php namespace App\Controller; use App\Entity\Contact; use App\Entity\User; use App\Form\ContactType; use App\Form\InfoType; use App\Repository\AnnonceRepository; use App\Repository\UserRepository; use App\Repository\VilleRepository; use App\Repository\CategoryRepository; use App\Repository\DepartementRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Routing\Annotation\Route; #[Route('/admin')] class AdminController extends AbstractController { #[Route('/', name: 'admin')] public function index(AnnonceRepository $annonceRepository,UserRepository $userRepository,VilleRepository $villeRepository,CategoryRepository $categoryRepository, DepartementRepository $departementRepository): Response { $annonces = $annonceRepository->findAll(); $countAnnonces = $annonceRepository->countById($annonces); $users = $userRepository->findAll(); $countUsers = $userRepository->countById($users); $villes = $villeRepository->findAll(); $countvilles = $villeRepository->countById($villes); $categorys = $categoryRepository->findAll(); $countcategorys = $categoryRepository->countById($categorys); $departements = $departementRepository->findAll(); $countdepartements = $departementRepository->countById($departements); return $this->render('admin/index.html.twig', [ 'countAnnonces' => $countAnnonces, 'countUsers' => $countUsers, 'countvilles' => $countvilles, 'countcategorys' => $countcategorys, 'countdepartements' => $countdepartements ]); } #[Route('/utilisateur', name: 'utilisateur_index')] public function utilisateur(UserRepository $userRepository): Response { return $this->render('admin/user.html.twig',[ 'users' => $userRepository->findAll() ]); } #[Route('/utilisateur/{id}', name: 'utilisateur_show', methods: ['GET'])] public function show(User $user): Response { return $this->render('admin/show-user.html.twig', [ 'user' => $user, ]); } #[Route('/utilisateur/{id}/edit', name: 'utilisateur_edit', methods: ['GET', 'POST'])] public function edit(Request $request, User $user, UserRepository $userRepository): Response { $originalPassword = $user->getPassword(); $form = $this->createForm(InfoType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $user->setPassword($originalPassword); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('utilisateur_index'); } return $this->render('admin/edit-user.html.twig', [ 'user' => $user, 'form' => $form->createView(), ]); } #[Route('/user/{id}', name: 'user_delete', methods: ['POST'])] public function delete(Request $request, User $user): Response { if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($user); $entityManager->flush(); } return $this->redirectToRoute('utilisateur_index'); } #[Route('/profil', name: 'profil_admin')] public function admin_profil(Request $request): Response { $user = $this->getUser(); return $this->render('admin/profil_admin.html.twig', [ 'user' => $user ]); } #[Route('/profil/edit', name: 'edit_profil_admin')] public function edit_admin_profil(Request $request): Response { $user = $this->getUser(); $form = $this->createForm(InfoType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->setModifiedAt(new \DateTime()); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('profil_admin'); } return $this->render('admin/edit_profil_admin.html.twig', [ 'form' => $form->createView(), ]); } #[Route('/notif', name: 'notif_admin')] public function admin_notif(): Response { $user = $this->getUser(); return $this->render('admin/notif_admin.html.twig', [ 'user' => $user ]); } #[Route('/notif/show/{id}', name: 'notif_show_admin')] public function admin_show_notif(Contact $message): Response { $user = $this->getUser(); $message->setIsRead(true); $em = $this->getDoctrine()->getManager(); $em->persist($message); $em->flush(); return $this->render('admin/notif_show_admin.html.twig', [ 'contact' => $message, 'user' => $user ]); } #[Route('/notif/delete/{id}', name: 'notif_delete')] public function notifDelete(Contact $message): Response { $em = $this->getDoctrine()->getManager(); $em->remove($message); $em->flush(); return $this->redirectToRoute('notif_admin'); } #[Route('/utilisateur/message/{id}', name: 'utilisateur_notif')] public function reponse(Request $request, $id,Contact $message): Response { $user = $this->getUser(); $contact = new Contact(); $form = $this->createForm(ContactType::class, $contact); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $contact->setIsRead(false) ->setSender($this->getDoctrine() ->getRepository(User::class) ->find($user->getId())) ->setRecipient($this->getDoctrine() ->getRepository(User::class) ->find($id)); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($contact); $entityManager->flush(); $this->addFlash('message', 'Votre message à bien était envoyer'); return $this->redirectToRoute('notif_admin'); } return $this->render('admin/form_notif_user.html.twig', [ 'contact' => $contact, 'form' => $form->createView(), 'user' => $user, ]); } #[Route('/notif/message', name: 'notif_new')] public function message(Request $request): Response { $user = $this->getUser(); $contact = new Contact(); $form = $this->createForm(ContactType::class, $contact); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $contact->setIsRead(false) ->setSender($this->getDoctrine() ->getRepository(User::class) ->find($user->getId())); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($contact); $entityManager->flush(); $this->addFlash('message', 'Votre message à bien était envoyez'); return $this->redirectToRoute('notif_admin'); } return $this->render('admin/form_notif.html.twig', [ 'contact' => $contact, 'form' => $form->createView(), 'user' => $user ]); } } <file_sep>/src/Repository/AnnonceRepository.php <?php namespace App\Repository; use App\Entity\Annonce; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; use App\Data\SearchData; use Doctrine\ORM\Tools\Pagination\Paginator; use Knp\Component\Pager\PaginatorInterface; use Doctrine\ORM\QueryBuilder; /** * @method Annonce|null find($id, $lockMode = null, $lockVersion = null) * @method Annonce|null findOneBy(array $criteria, array $orderBy = null) * @method Annonce[] findAll() * @method Annonce[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class AnnonceRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Annonce::class); } /** * recupère les produits en lien avec une recherche * @return Annonce[] */ // public function countNbElement() // { // $query = $this->createQueryBuilder('e'); // $query ->select($query->expr()->count('e')); // return (int) $query->getQuery()->getSingleScalarResult(); // } public function findSearch(SearchData $search): array { $query = $this ->getSearchQuery($search)->getQuery(); return $query->getResult(); } /** * recupère le prix min et max d'une recherche * @return integer[] **/ public function findMinMax(SearchData $search): array { $results = $this->getSearchQuery($search) ->select('MIN(a.price) as min', 'MAX(a.price) as max') ->getQuery() ->getScalarResult(); return [(int)$results[0]['min'], (int)$results[0]['max']]; } private function getSearchQuery(SearchData $search): QueryBuilder { $query = $this ->createQueryBuilder('a') ->select('c', 'a') ->join('a.category', 'c'); if (!empty($search->min)) { $query = $query ->andWhere('a.price >= :min') ->setParameter('min', $search->min); } if (!empty($search->max)) { $query = $query ->andWhere('a.price <= :max') ->setParameter('max', $search->max); } if (!empty($search->status)) { $query = $query ->andWhere('a.status IN (:status)') ->setParameter('status', $search->status); } if (!empty($search->category)) { $query = $query ->andWhere('c.id IN (:category)') ->setParameter('category', $search->category); } if (!empty($search->ville)) { for ($i=0; $i < count($search->ville) ; $i++) { $query = $query ->andWhere('a.ville IN (:ville)') ->setParameter('ville', $search->ville); } } if (!empty($search->departement)) { for ($i=0; $i < count($search->departement) ; $i++) { $query = $query ->andWhere('a.departement IN (:departement)') ->setParameter('departement', $search->departement); } } // dd($search->category); return $query ; } /* public function findByExampleField($value) { return $this->createQueryBuilder('a') ->andWhere('a.exampleField = :val') ->setParameter('val', $value) ->orderBy('a.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?Annonce { return $this->createQueryBuilder('a') ->andWhere('a.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Controller/ProfileController.php <?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use App\Entity\Annonce; use App\Entity\Contact; use App\Entity\User; use App\Form\InfoType; use App\Repository\AnnonceRepository; use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\String\Slugger\SluggerInterface; use Symfony\Component\HttpFoundation\File\File; use App\Service\FileUploader; use AsyncAws\Ses\ValueObject\Message; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Form\FormError; #[Route('/profil')] class ProfileController extends AbstractController { #[Route('/', name: 'profile')] public function index(): Response { $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } return $this->render('profile/index.html.twig', [ 'controller_name' => 'ProfileController', 'user' => $user ]); } #[Route('/edit', name: 'infos_perso_edit', methods: ['GET', 'POST'])] public function infos_persoEdit(Request $request): Response { $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } $form = $this->createForm(InfoType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->setModifiedAt(new \DateTime()); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('profile'); } return $this->render('profile/edit.html.twig', [ 'controller_name' => 'ProfileController', 'form' => $form->createView(), ]); } #[Route('/notification', name: 'notif')] public function notif(): Response { $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } return $this->render('profile/notification.html.twig', [ 'controller_name' => 'ProfileController', 'user' => $user, ]); } #[Route('/notification/show/{id}', name: 'notif_show')] public function notifShow(Contact $message): Response { $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } $message->setIsRead(true); $em = $this->getDoctrine()->getManager(); $em->persist($message); $em->flush(); return $this->render('profile/notif_show.html.twig', [ 'controller_name' => 'ProfileController', 'contact' => $message, ]); } #[Route('/notif/delete/{id}', name: 'notification_delete')] public function notifDelete(Contact $message): Response { $user = $this->getUser(); if (!$user) { return $this->redirectToRoute('404'); } $em = $this->getDoctrine()->getManager(); $em->remove($message); $em->flush(); return $this->redirectToRoute('notif'); } #[Route('/favoris', name: 'favoris')] public function favori(): Response { $annonces = $this->getDoctrine()->getRepository(Annonce::class)->findBy( [], ['title' => 'ASC'] ); $users = $this->getDoctrine()->getRepository(User::class)->findBy( [], ['name' => 'ASC'] ); return $this->render('profile/favoris.html.twig', [ 'annonces' => $annonces, 'users' => $users ]); } #[Route('/favoris/retrait/{id}', name: 'remove_favoris')] public function retraitFavoris(Annonce $annonce): Response { $annonce->removeFavori($this->getUser()); $em = $this->getDoctrine()->getManager(); $em->persist($annonce); $em->flush(); return $this->redirectToRoute('favoris'); } } <file_sep>/src/DataFixtures/VilleFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use App\Entity\Ville; class VilleFixtures extends Fixture { public function load(ObjectManager $manager) { $ville1 = (new Ville()) ->setTitle('Deauville') ->setCodePostal('14800'); $ville2 = (new Ville()) ->setTitle('Pont-Audemer') ->setCodePostal('27260'); $ville3 = (new Ville()) ->setTitle('Paris') ->setCodePostal('75') ->setDescription('Belle appartement à Paris'); $ville4 = (new Ville()) ->setTitle('Honfleur') ->setCodePostal('76'); $ville5 = (new Ville()) ->setTitle('Caen') ->setCodePostal('14') ->setDescription('Facilitez de vie au coeur du centre ville'); $ville6 = (new Ville()) ->setTitle('Havre') ->setCodePostal('76000'); $manager->persist($ville1); $manager->persist($ville2); $manager->persist($ville3); $manager->persist($ville4); $manager->persist($ville5); $manager->persist($ville6); $manager->flush(); $this->addReference('ville1', $ville1); $this->addReference('ville2', $ville2); $this->addReference('ville3', $ville3); $this->addReference('ville4', $ville4); $this->addReference('ville5', $ville5); $this->addReference('ville6', $ville6); } } <file_sep>/src/Form/AnnonceType.php <?php namespace App\Form; use App\Entity\Annonce; use App\Entity\Ville; use App\Entity\Category; use App\Entity\Departement; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; class AnnonceType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title', TextType::class, [ 'label' => 'Titre', 'attr' => ['placeholder' => 'Titre de l\'annonce...'] ]) ->add('description', TextareaType::class, [ 'label' => 'Description', 'attr' => ['placeholder' => 'Description de l\'annonce...'] ]) ->add('image', FileType::class, [ 'label' => 'image(s) supplémentaire', 'multiple' => true, 'mapped' => false, 'required' => false, ]) ->add('fileimage', FileType::class, [ 'label' => 'image à la une', 'attr' => ['id' =>'customFileInput'], 'mapped' => false, 'required' => false, 'constraints' => [ new File([ 'maxSize' => '4000k', 'mimeTypes' => [ 'image/jpg', 'image/jpeg', 'image/png', ], 'mimeTypesMessage' => 'Veuillez uploader une image sous format jpg, jpeg ou png', ]) ], ]) ->add('superficie', NumberType::class, [ 'label' => 'Superficie (m²)', 'attr' => ['placeholder' => 'Superficie en chiffres...'] ]) ->add('superficieTerrain', NumberType::class, [ 'label' => 'Superficie Terrain (m²)', 'attr' => ['placeholder' => 'optionnel...'] ]) ->add('price', NumberType::class, [ 'label' => 'Prix ( € )', 'attr' => ['placeholder' => '300000 '] ]) ->add('status', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ 'Vente' => 1, 'Location' => 2, ], // 'multiple' => true, // 'expanded' => true, ]) ->add('etat', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ '--------' => null, 'Vendu' => 'Vendu', 'Loué' => 'Loué', ], // 'multiple' => true, // 'expanded' => true, ]) ->add('ville', EntityType::class, [ 'label' => 'Ville *', 'attr' => ['class' => 'p-2'], 'class' => Ville::class, 'choice_label' => 'title', // 'multiple' => true, // 'expanded' => true, ]) ->add('departement', EntityType::class, [ 'label' => 'Departement *', 'attr' => ['class' => 'p-2'], 'class' => Departement::class, 'choice_label' => 'title', // 'multiple' => true, // 'expanded' => true, ]) ->add('category', EntityType::class, [ 'label' => 'Categorie(s) *', 'attr' => ['class' => 'pt-2 pb-5'], 'class' => Category::class, 'choice_label' => 'title', 'multiple' => true, // 'expanded' => true, ]) ->add('dpe', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ 'aucune' => '1', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E', 'F' => 'F', 'G' => 'G', ], // 'multiple' => true, // 'expanded' => true, ]) ->add('ges', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ 'aucune' => '1', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E', 'F' => 'F', 'G' => 'G', ], // 'multiple' => true, // 'expanded' => true, ]) ->add('nbrePieces', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', '13' => '13', '14' => '14', '15' => '15', ], // 'multiple' => true, // 'expanded' => true, ]) ->add('nbreChambre', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10' ], // 'multiple' => true, // 'expanded' => true, ]) ->add('salleBain', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5' ], // 'multiple' => true, // 'expanded' => true, ]) ->add('wc', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5' ], // 'multiple' => true, // 'expanded' => true, ]) ->add('garage', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ 'oui' => 'oui', 'non' => 'non' ], // 'multiple' => true, // 'expanded' => true, ]) ->add('piscine', ChoiceType::class, [ 'attr' => ['class' => 'p-2'], 'choices' => [ 'oui' => 'oui', 'non' => 'non' ], // 'multiple' => true, // 'expanded' => true, ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Annonce::class, ]); } } <file_sep>/src/Form/SearchForm.php <?php namespace App\Form; use App\Data\SearchData; use App\Entity\Category; use App\Entity\Ville; use App\Entity\Departement; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\formBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class SearchForm extends AbstractType { public function buildForm(formBuilderInterface $builder, array $options) { $builder ->add('category', EntityType::class, [ 'label' => false, 'required' => false, 'attr' => ['class' => 'filter_selecte'], 'class' => Category::class, // 'expanded' => true, 'multiple' => true ]) ->add('ville', EntityType::class, [ 'label' => false, 'required' => false, 'class' => Ville::class, 'choice_label' => 'title', // 'expanded' => true, 'multiple' => true, 'attr' => ['class' => 'filter_selecte'], ]) ->add('departement', EntityType::class, [ 'label' => false, 'required' => false, 'class' => Departement::class, 'choice_label' => 'title', // 'expanded' => true, 'multiple' => true, 'attr' => ['class' => 'filter_selecte'], ]) ->add('status', ChoiceType::class, [ 'choices' => [ 'Vente et location' => NULL, 'Vente' => 1, 'Location' => 2, ], 'attr' => ['class' => 'filter_selecte'], // 'multiple' => true, // 'expanded' => true, ]) ->add('min', NumberType::class, [ 'label' => false, 'required' => false, 'attr' => [ 'placeholder' => 'Prix min', 'class' => 'filter_input' ] ]) ->add('max', NumberType::class, [ 'label' => false, 'required' => false, 'attr' => [ 'placeholder' => 'Prix max', 'class' => 'filter_input' ] ]); } public function configurationOptions(optionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => SearchData::class, //'csrf_protection' => false ]); } public function getBlockPrefix() { return ''; } } <file_sep>/src/Controller/SecurityController.php <?php namespace App\Controller; use App\Form\ResetPassType; use App\Repository\UserRepository; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; class SecurityController extends AbstractController { #[Route('/connexion', name: 'app_login')] public function login(AuthenticationUtils $authenticationUtils): Response { $user = $this->getUser(); if ($user) { return $this->redirectToRoute('home'); } // get the login error if there is one $error = $authenticationUtils->getLastAuthenticationError(); // last username entered by the user $lastUsername = $authenticationUtils->getLastUsername(); return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]); } #[Route('/deconnexion', name: 'app_logout')] public function logout() { throw new \LogicException('Cette méthode peut être vide - elle sera interceptée par la clé de déconnexion de votre pare-feu'); } } <file_sep>/src/Controller/HomeController.php <?php namespace App\Controller; use App\Data\SearchData; use App\Form\SearchForm; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Annotation\Route; use App\Repository\AnnonceRepository; use App\Entity\Annonce; use App\Entity\Category; use App\Entity\Ville; use App\Entity\Departement; use App\Entity\Contact; use App\entity\User; use App\Form\ContactType; use Symfony\Component\Security\Core\Security; use App\Repository\ContactRepository; use App\Repository\UserRepository; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; class HomeController extends AbstractController { private $security; public function __construct(Security $security) { $this->security = $security; } #[Route('/', name: 'home')] public function index(): Response { $annonces = $this->getDoctrine()->getRepository(Annonce::class)->findBy( [], ['createdAt' => 'DESC'], $limit = 9 ); return $this->render('home/index.html.twig', [ 'annonces' => $annonces ]); } #[Route('/presentation', name: 'presentation')] public function presentation(): Response { return $this->render('home/presentation.html.twig', [ 'controller_name' => 'HomeController', ]); } #[Route('/competence', name: 'competence')] public function competence(): Response { return $this->render('home/competence.html.twig', [ 'controller_name' => 'HomeController', ]); } #[Route('/annonces', name: 'annonces')] public function annonces(AnnonceRepository $repository,Request $request): Response { $data = new SearchData(); $form = $this->createForm(SearchForm::class, $data, [ 'method' => 'GET', ]); $form->handleRequest($request); [$min, $max] = $repository->findMinMax($data); $searchAnnonce = $repository->findSearch($data); // dd($searchAnnonce); return $this->render('home/annonces.html.twig', [ // 'annonces' => $annonces, 'searchAnnonce' => $searchAnnonce, 'form' => $form->createView(), 'min' => $min, 'max' => $max ]); } #[Route('/annonces/{slug}', name: 'frontAnnonce_show', methods: ['GET', 'POST'])] public function show(Annonce $annonce,Request $request, MailerInterface $mailer, UserRepository $repoUser): Response { $user = $this->getUser(); $id_user = 2; $contact = new Contact(); $form = $this->createForm(ContactType::class, $contact); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $recipient = $repoUser->find($id_user); $contact->setIsRead(false) ->setAnnonce($annonce) ->setRecipient($recipient); $email = new TemplatedEmail(); $message ='<p></p>'; $message .='<h1 style="background-color:lime">'.$annonce->getTitle().'</h1>'; $message .= '<p>'.$contact->getMessage().'</p>'; if ($this->security->isGranted('ROLE_USER')) { $message .= '<p>'.$user->getName().'</p>'; $message .= '<p>'.$user->getUsername().'<p>'; $contact->setSender($this->getUser()); $email->from($contact->getSender()->getEmail()) ->context([ 'contact' => $contact, 'mail' => $contact->getSender()->getEmail(), 'message' => $message, ]); }else { $message .= '<p>'.$contact->getName().'</p>'; $email->from($contact->getEmail()) ->context([ 'contact' => $contact, 'mail' => $contact->getEmail(), 'message' => $message, ]); } $email->to(new Address('<EMAIL>')) ->subject('Contact') ->htmlTemplate('emails/annonce_contact.html.twig'); $mailer->send($email); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($contact); $entityManager->flush(); $this->addFlash('message', 'Votre email à bien était envoyé'); return $this->redirectToRoute('home'); } $user = $this->getUser(); $dpe = $annonce->getDpe(); $ges = $annonce->getGes(); return $this->render('home/show.html.twig', [ 'annonce' => $annonce, 'contact' => $contact, 'form' => $form->createView(), 'user' => $user, 'dpe' => $dpe, 'ges' => $ges ]); } #[Route('/annonces/favoris/ajout/{id}', name: 'ajout_favoris')] public function ajoutFavoris(Annonce $annonce): Response { if (!$annonce) { return $this->redirectToRoute('404'); } $annonce->addFavori($this->getUser()); $em = $this->getDoctrine()->getManager(); $em->persist($annonce); $em->flush(); return $this->redirectToRoute('favoris'); } #[Route('/annonces/favoris/retrait/{id}', name: 'retrait_favoris')] public function retraitFavoris(Annonce $annonce): Response { if (!$annonce) { return $this->redirectToRoute('404'); } $annonce->removeFavori($this->getUser()); $em = $this->getDoctrine()->getManager(); $em->persist($annonce); $em->flush(); return $this->redirectToRoute('favoris'); } #[Route('/conditions_generales', name: 'conditions_generales')] public function conditionsLenerales(): Response { return $this->render('home/conditions_generales.html.twig', [ 'controller_name' => 'HomeController', ]); } #[Route('/mentions_legales', name: 'mentions_legales')] public function mentionsLegales(): Response { return $this->render('home/mentions_legales.html.twig', [ 'controller_name' => 'HomeController', ]); } #[Route('/404', name: '404')] public function FunctionName(): Response { return $this->render('home/404.html.twig', []); } } <file_sep>/src/Entity/Category.php <?php namespace App\Entity; use App\Repository\CategoryRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity; /** * @ORM\Entity(repositoryClass=CategoryRepository::class) * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false) */ class Category { use SoftDeleteableEntity; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank * @Assert\Length( * min = 2, * max = 255, * minMessage = "Vous devez respecter {{ limit }} caractères minimums", * maxMessage = "Vous devez respecter {{ limit }} caractères maximums" * ) */ private $title; /** * @ORM\Column(type="text", nullable=true) */ private $description; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\Column(type="datetime", nullable=true) */ private $modifiedAt; /** * @ORM\ManyToMany(targetEntity=Annonce::class, mappedBy="category") */ private $annonces; public function __construct() { $this->createdAt = new \DateTime; $this->modifiedAt = new \DateTime; $this->annonces = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): self { $this->description = $description; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getModifiedAt(): ?\DateTimeInterface { return $this->modifiedAt; } public function setModifiedAt(?\DateTimeInterface $modifiedAt): self { $this->modifiedAt = $modifiedAt; return $this; } /** * @return Collection|Annonce[] */ public function getAnnonces(): Collection { return $this->annonces; } public function addAnnonce(Annonce $annonce): self { if (!$this->annonces->contains($annonce)) { $this->annonces[] = $annonce; $annonce->addCategory($this); } return $this; } public function removeAnnonce(Annonce $annonce): self { if ($this->annonces->removeElement($annonce)) { $annonce->removeCategory($this); } return $this; } public function __toString() { return $this->title; } }
3847cee1d912442777ef7b9070382c0aec91b36d
[ "JavaScript", "PHP" ]
26
PHP
heros20/Notaire
7a365ed6ce94e6aa620b0658479421d81bd7a224
54dc173d73ad29b19c8ba8627cb5762e6059025e
refs/heads/master
<file_sep>class SongsController < ApplicationController get '/songs' do @songs = Song.all erb :"songs/index" end get '/songs/new' do @genres = Genre.all # @artists = Artist.all erb :"songs/new" end get '/songs/:name' do @song = Song.find_by_slug(params[:name]) erb :"songs/show" end post '/songs' do art= Artist.find_or_create_by(name: params[:artist_name]) art_id = art.id Song.create(name: params[:song_name], artist_id: art_id, genre_ids: params[:genres] ) redirect '/songs' end get '/songs/:name/edit' do @genres = Genre.all @song = Song.find_by_slug(params[:name]) erb :"songs/edit" end patch '/songs/:name' do @song = Song.find_by_slug(params[:song_name]) art= Artist.find_or_create_by(name: params[:artist_name]) art_id = art.id @song.update(name: params[:song_name], artist_id: art_id, genre_ids: params[:genres] ) redirect "/songs/#{@song.slug}" end delete '/songs/:name' do @song = Song.find_by_slug(params[:name]) @song.destroy redirect "/songs" end end <file_sep>class GenresController < ApplicationController get '/genres' do @genres = Genre.all erb :"genres/index" end get '/genres/:name' do @genre = Genre.find_by_slug(params[:name]) erb :"genres/show" end end <file_sep>module Slugifiable module ClassMethods def find_by_slug(phrase) self.all.find { |i| i.slug == phrase} end end module InstanceMethods def slug self.name.gsub(/[^A-Za-z0-9 ]/,'').gsub(/[ ]/, "-").downcase end end end<file_sep># Add seed data here. Seed your database with `rake db:seed` Artist.destroy_all Song.destroy_all Genre.destroy_all artist1 = Artist.create(name: "<NAME>") artist2 = Artist.create(name: "<NAME>") song1 = Song.create(name: "songthings2genres", artist_id: 1) song2 = Song.create(name: "songthings1genre", artist_id: 2) genre1 = Genre.create(name: "pop") genre2 = Genre.create(name: "pop2") songgenre1 = SongGenre.create(song_id: 1, genre_id: 1) songgenre2 = SongGenre.create(song_id: 1, genre_id: 2) songgenre3 = SongGenre.create(song_id: 2, genre_id: 1)<file_sep>class ArtistsController < ApplicationController get '/artists' do @artists = Artist.all erb :"artists/index" end get '/artists/:name' do @artist = Artist.find_by_slug(params[:name]) genre_array = [] @artist.songs.each do |song| song.genres.each do |genre| genre_array << genre end end @array = genre_array.uniq erb :"artists/show" end end
1792458d2cbffc099d776fd79058401717077953
[ "Ruby" ]
5
Ruby
jordan-laird/playlister-sinatra-houston-web-100818
28fcda1193b5bfd151cff1995f897731575af43a
925c899b0f616ce645f9fdbc95f1ae2d5f2ce4ed
refs/heads/master
<repo_name>echodarkstar/gdelt_daily_updater<file_sep>/dailydl.py #Import libraries import urllib.request import re,sys,zipfile import schedule import time,os import csv from pandas import read_csv def job(): #Getting GDELT Event url content into a format that can be manipulated url = 'http://data.gdeltproject.org/events/index.html' response = urllib.request.urlopen(url) data = response.read() # a `bytes` object text = data.decode('utf-8') # a `str`; this step can't be used if data is binary #Pattern match text so that it returns string between "" as is the case for links def doit(text): matches=re.search(r'\"(.+?)\"',text).group(0) return matches #Get the href tag for the current day global curr_file # global variable to be used in dlProgress curr_file = doit(text.split()[17]).strip("\"") #Append filename to the events url. From this, we'll be able to download our file. fin_url = ( "http://data.gdeltproject.org/events/" + curr_file) #Function to display progress percentage of download def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + curr_file + "...%d%%" % percent) sys.stdout.flush() #Download today's file urllib.request.urlretrieve(fin_url, curr_file,reporthook=dlProgress) sys.stdout.write("\n") #Get column headers from website url = "http://gdeltproject.org/data/lookups/CSV.header.dailyupdates.txt" response = urllib.request.urlopen(url) data = response.read() # a `bytes` object text = data.decode('utf-8') # a `str`; this step can't be used if data is binary #Extracting the zip file into csv zip = zipfile.ZipFile(curr_file) zip.extractall() #Remove zip file os.remove(curr_file) #Creating new csv with appropriate headers df = read_csv(curr_file.strip('.zip') , sep='\t', lineterminator='\n', header=None, low_memory=False) df.columns = text.split() os.remove(curr_file.strip('.zip')) df.to_csv(curr_file.strip('.zip'), sep='\t') return schedule.CancelJob #Bug : Actor/Action GEOID in csv is not clean. # schedule.every(5).minutes.do(job) # schedule.every().hour.do(job) schedule.every().day.at('10:00').do(job) # while 1: schedule.run_pending() time.sleep(1) <file_sep>/README.md # gdelt_daily_updater This python script fetches GDELT data for the current day and extracts the zip file resulting in a csv file.
669b5b121a6c569fd076764ffb323b3bc5592eb3
[ "Markdown", "Python" ]
2
Python
echodarkstar/gdelt_daily_updater
4980384cc5b7e46cbfd5c9a7612b71da54c86ac8
1a65820545467c07b26c4f7f30b975bcaf6ff3c9
refs/heads/master
<file_sep>import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'generic-components/tests/helpers/start-app'; var application; module('Acceptance: NameInputComponent', { beforeEach: function() { application = startApp(); }, afterEach: function() { Ember.run(application, 'destroy'); } }); test('visiting /name-input-component', function(assert) { visit('/name-input-component'); andThen(function() { var expectedValues = ["fname", "lname", "sfx"]; assert.equal(currentURL(), '/name-input-component'); assert.equal(find('#name-input').length, 1, "Name input field should exist"); assert.ok(find('.name-field').length > 1, "We should have more than 1 field"); for(var value in expectedValues){ if(expectedValues.hasOwnProperty(value)){ var checkAttr = "#"+expectedValues[value]; assert.equal(find(checkAttr).length, 1, "We should have all the expected form fields"); assert.ok($(find(checkAttr)).attr("placeholder") !== "", "We should have placeholder values from route"); } } assert.ok($(find("#submitButton")).text() !== "", "We should have button text"); }); });
0339905d9aaf45ed3611e719ab60546f3e76aef0
[ "JavaScript" ]
1
JavaScript
NerdsvilleCEO/generic-components-ember
8b12b9d08615a46d35d8619ef0396ed5b164b867
d878d0d3d2e9a18e5a0f459d3cd59aef263f1709
refs/heads/master
<repo_name>Pranavdev007/Portfolio<file_sep>/src/components/resume.js import React, { Component } from 'react'; import { Grid, Cell } from 'react-mdl'; import Education from './education'; import Experience from './experience'; import Skills from './skills'; class Resume extends Component { render() { return( <div> <Grid> <Cell col={4}> <div style={{textAlign: 'center'}}> </div> <h2 style={{paddingTop: '2em'}}><NAME></h2> <h4 style={{color: 'grey'}}>Programmer</h4> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/> <h5>Address</h5> <p>34, Bohri, Jammu</p> <h5>Phone</h5> <p>+91-9123456789</p> <h5>Email</h5> <p><EMAIL></p> <h5>Web</h5> <p>localhost</p> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/> </Cell> <Cell className="resume-right-col" col={8}> <h2>Education</h2> <Education startYear={2017} endYear={2021} schoolName="LPU " schoolDescription="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s" /> <hr style={{borderTop: '3px solid #e22947'}} /> <h2>Experience</h2> <Experience startYear={2021} endYear={2022} jobName="<NAME>" jobDescription="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s" /> <Experience startYear={2022} endYear={'Present'} jobName="<NAME>" jobDescription="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s" /> <hr style={{borderTop: '3px solid #e22947'}} /> <h2>Skills</h2> <Skills skill="javascript" progress={100} /> <Skills skill="HTML/CSS" progress={80} /> <Skills skill="NodeJS" progress={50} /> <Skills skill="React" progress={70} /> </Cell> </Grid> </div> ) } } export default Resume;
05ff9e7416e3dcba46f760fdb61078d1cb00ef4a
[ "JavaScript" ]
1
JavaScript
Pranavdev007/Portfolio
76e5c1a2c6fb44841894c6a79e544df52a60de97
5352a7adf854cfc41198d207b2a628f1b36b740d
refs/heads/master
<repo_name>sergui20/chat-test<file_sep>/server/classes/usuarios.js class Users { constructor(){ this.users = []; } addUser(id, username, room){ let user = { id, username, room } this.users.push(user); return this.users; } getUser(id) { let user = this.users.filter( el =>{ return el.id === id })[0]; console.log('Classes', user) return user; } getAllUsers(){ return this.users } getUsersByGroup(sala){ let roomUsers = this.users.filter(user => { return user.room === sala }) return roomUsers } removeUser(id){ let offlineUser = this.getUser(id); this.users = this.users.filter( user=>{ return user.id != id }) return offlineUser; } } module.exports = { Users }<file_sep>/server/sockets/socket.js // socket server const { io } = require('../server'); const { Users } = require('../classes/usuarios'); const createMessage = require('../utils/utilities'); const users = new Users(); io.on('connection', (client) => { client.on('chatLogin', function(user, callback){ if(!user.nombre || !user.sala){ return callback({ err: true, mensaje: 'El nombre o la sala son necesarios' }) } client.join(user.sala); let activeUsers = users.addUser(client.id, user.nombre, user.sala); let roomUsers = users.getUsersByGroup(user.sala) // Array de users en la sala client.broadcast.to(user.sala).emit('loginEvent', users.getUsersByGroup(user.sala) ) client.broadcast.to(user.sala).emit('sendMessage', createMessage('Admin', `${user.nombre} has joined`)); callback(roomUsers); }) client.on('sendMessage', function(data, callback){ let user = users.getUser(client.id); let message = createMessage(data.name, data.message); client.broadcast.to(user.room).emit('sendMessage', message); callback(message); }) client.on('disconnect', function(){ let offlineUser = users.removeUser(client.id); client.broadcast.to(offlineUser.room).emit('logoutEvent', createMessage('Admin', `${offlineUser.username} left the chat`)) client.broadcast.to(offlineUser.room).emit('loginEvent', users.getUsersByGroup(offlineUser.room)) }) //Mensaje privado client.on('P2Pmessage', (data) => { let user = users.getUser(client.id) client.broadcast.to(data.receiver).emit('P2Pmessage', createMessage(user.username, data.message)) }) client.on('Istyping', function(data){ console.log('Server gets ', data) client.broadcast.to(data.room).emit('Istyping', data) client.broadcast.to(data.room).emit('notTyping') }) });
27bb212901244949d8136ee578f988cd1ff6db37
[ "JavaScript" ]
2
JavaScript
sergui20/chat-test
cd33214b2b8cae6b27a000f1b964a023d0b075cb
57239a96e30d0825fd092ba5b7a6d025e667c70f
refs/heads/master
<file_sep>dofile("urlcode.lua") dofile("table_show.lua") local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local item_dir = os.getenv('item_dir') local username = nil local username_escaped = nil local username_id_urls = {} local allowed_strings = {} local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} local abortgrab = false for ignore in io.open("ignore-list", "r"):lines() do downloaded[ignore] = true end allowed_strings[item_value] = true read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end allowed = function(url, parenturl) if string.match(url, "'+") or string.match(url, "[<>\\]") or string.match(url, "//$") or not string.match(url, "^https?://[^/]*ipernity%.com") then return false end if string.match(url, "%?lc=[01]") or string.match(url, "/in/favorite/") or string.match(url, "/in/keyword/") or (string.match(url, "^https?://[^/]*ipernity%.com/feed/doc") and string.match(url, "keywords=")) then return false end --if username_escaped ~= nil and (string.match(url, "^(.+[^a-zA-Z0-9%.%-_])" .. username_escaped .. "$") -- or string.match(url, "^(.+[^a-zA-Z0-9%.%-_])" .. username_escaped .. "([^a-zA-Z0-9%.%-_].+)")) then -- for s in string.gmatch(url, "([0-9]+)") do -- allowed_strings[s] = true -- end --end for s in string.gmatch(url, "([0-9]+)") do if allowed_strings[s] == true then return true end end for s in string.gmatch(url, "([a-zA-Z0-9%-%._]+)") do if allowed_strings[s] == true then return true end end if string.match(url, "^https?://api%.ipernity%.com") then return true end if string.match(url, "^https?://cdn%.ipernity%.com") and parenturl ~= nil and not (string.match(parenturl, "/favorite/") or string.match(parenturl, "/favorite$") or string.match(parenturl, "/favorites/by/") or string.match(url, "%.buddy%.jpg$") or string.match(url, "%.header%.[0-9]+%.jpg")) then return true end return false end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if username_escaped ~= nil and (string.match(parent["url"], "/keywords?/") or string.match(parent["url"], "/favorites?/") or string.match(parent["url"], "/favorites?$") or string.match(parent["url"], "/keywords?$")) and not string.match(url, "@") then return false end if string.match(url, "%.buddy%.jpg$") or string.match(url, "%.header%.[0-9]+%.jpg") then return false end if (downloaded[url] ~= true and addedtolist[url] ~= true) and (allowed(url, parent["url"]) or html == 0) then addedtolist[url] = true return true end return false end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil downloaded[url] = true local function check(urla) local origurl = url local url = string.match(urla, "^([^#]+)") if (downloaded[url] ~= true and addedtolist[url] ~= true) and allowed(url, origurl) then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true end end local function checknewurl(newurl) if string.match(newurl, "^https?:////") then check(string.gsub(newurl, ":////", "://")) elseif string.match(newurl, "^https?://") then check(newurl) elseif string.match(newurl, "^https?:\\/\\?/") then check(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^\\/\\/") then check(string.match(url, "^(https?:)")..string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^//") then check(string.match(url, "^(https?:)")..newurl) elseif string.match(newurl, "^\\/") then check(string.match(url, "^(https?://[^/]+)")..string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^/") then check(string.match(url, "^(https?://[^/]+)")..newurl) end end local function checknewshorturl(newurl) if string.match(newurl, "^%?") then check(string.match(url, "^(https?://[^%?]+)")..newurl) elseif not (string.match(newurl, "^https?:\\?/\\?//?/?") or string.match(newurl, "^[/\\]") or string.match(newurl, "^[jJ]ava[sS]cript:") or string.match(newurl, "^[mM]ail[tT]o:") or string.match(newurl, "^vine:") or string.match(newurl, "^android%-app:") or string.match(newurl, "^%${")) then check(string.match(url, "^(https?://.+/)")..newurl) end end if string.match(url, "&amp;") then check(string.gsub(url, "&amp;", "&")) end if string.match(url, "[^0-9]75x") and string.match(url, "%?r2$") then check(string.match(url, "^([^%?]+)")) end if (allowed(url, nil) or username == nil) and not string.match(url, "^https?://cdn%.ipernity%.com") then html = read_file(file) for newuserid in string.gmatch(html, '"user_id":"([0-9]+)"') do if newuserid ~= tostring(item_value) then return urls end end if string.match(url, "^https?://api%.ipernity%.com") then os.execute("sleep 0.2") if string.match(html, 'ok="0"') or string.match(html, 'status="error"') then abortgrab = true end end if username == nil and string.match(url, "^https?://[^/]*ipernity%.com/home/") then username = string.match(html, '"user_id"%s*:%s*' .. item_value .. '%s*,%s*"folder"%s*:%s*"([^"]+)"') if username ~= nil then username_escaped = string.gsub(username, "([%%%^%$%(%)%.%[%]%*%+%-%?])", "%%%1") allowed_strings[username] = true end end if string.match(html, '"mediakey"%s*:%s*"[^"]+"') then local mediakey = string.match(html, '"mediakey"%s*:%s*"([^"]+)"') local is_image = true for embed_extension in string.gmatch(html, '"embed"%s*:%s*"([^"]*)"') do if embed_extension ~= "jpg" then is_image = false end end if not is_image then -- for _, lang in ipairs({"ca", "cs", "zh", "de", "en", "es", "eo", "el", "fr", "gl", "it", "nl", "pt", "pl", "sv", "ru"}) do for _, lang in ipairs({"en"}) do -- for _, external in ipairs({"0", "1"}) do for _, external in ipairs({"0"}) do -- for _, autostart in ipairs({"true", "false"}) do for _, autostart in ipairs({"true"}) do check("http://api.ipernity.com/media.php/" .. mediakey .. "?lang=" .. lang .. "&external=" .. external .. "&autostart=" .. autostart) check("http://api.ipernity.com/media.php/" .. mediakey .. "?lang=" .. lang .. "&external=" .. external) end end end end end if username_escaped ~= nil then for start in string.gmatch(url, "^(.+[^a-zA-Z0-9%.%-_])" .. username_escaped .. "$") do check(start .. item_value) end for start, end_ in string.gmatch(url, "^(.+[^a-zA-Z0-9%.%-_])" .. username_escaped .. "([^a-zA-Z0-9%.%-_].+)") do check(start .. item_value .. end_) end end for newurl in string.gmatch(html, '([^"]+)') do checknewurl(newurl) end for newurl in string.gmatch(html, "([^']+)") do checknewurl(newurl) end for newurl in string.gmatch(html, ">%s*([^<%s]+)") do checknewurl(newurl) end for newurl in string.gmatch(html, "[^%-]href='([^']+)'") do checknewshorturl(newurl) end for newurl in string.gmatch(html, '[^%-]href="([^"]+)"') do checknewshorturl(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code == 302 and username_id_urls[url["url"]] == true then return wget.actions.EXIT elseif string.match(url["url"], '^http://www.ipernity.com/home/[0-9]+$') and (status_code == 404 or status_code == 403 or status_code == 410) then return wget.actions.EXIT end if abortgrab == true then io.stdout:write("ABORTING...\n") return wget.actions.ABORT end if status_code >= 500 or (status_code >= 400 and status_code ~= 403 and status_code ~= 404 and status_code ~= 410) or status_code == 0 then io.stdout:write("Server returned "..http_stat.statcode.." ("..err.."). Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 if allowed(url["url"], nil) then return wget.actions.ABORT else return wget.actions.EXIT end else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end wget.callbacks.before_exit = function(exit_status, exit_status_string) if abortgrab == true then return wget.exits.IO_FAIL end return exit_status end
718dac136a24370aab051d0a7df9b8a3c340806b
[ "Lua" ]
1
Lua
ArchiveTeam/ipernity-grab
55d064839f495f868387a83b727f1ee40fe0bc04
df2aaae67cf2fa189b63f41725fc2b3de4b2eb42
refs/heads/master
<repo_name>NickC148/Python_Bootcamp<file_sep>/Day 3/Excercises/Ex 4.py # Using the table below: # ItemNo Description No Cost Each # IT445 Snark bits 12 2.79 # IT123 Pistle dibs 5 11.13 # BK001 Yannie not Laurel 1 123.15 # a. Use a tuple assignment create the variables item_no, desc, no, cost_each using a range. # b. Create an item_list of tuples each containing the values for each line. # c. Looping through the list, for each tuple use the variables above as indices, calculating the # amount and print a line. Using a pre initialised total sum the amounts. # d. Print the total. # A items = [] for x in range(3): items.append({'ItemNo': None, 'Description': None, 'No': None, 'Cost Each': None}) # B items[0]['ItemNo'] = 'IT445' items[0]['Description'] = 'Snark bits' items[0]['No'] = 12 items[0]['Cost Each'] = 2.79 items[1]['ItemNo'] = 'IT123' items[1]['Description'] = 'Pistle dibs' items[1]['No'] = 5 items[1]['Cost Each'] = 11.13 items[2]['ItemNo'] = 'BK001' items[2]['Description'] = 'Yannie not Laurel' items[2]['No'] = 1 items[2]['Cost Each'] = 123.15 item_list = [] for x in range(3): item_list.append(items[x]) # C total = 0 for y in item_list: sumT = y['No'] * y['Cost Each'] total = total + sumT print 'The sum for {0} is {1}'.format(y['Description'], sumT) # D print 'The total for everything is {0}'.format(total) <file_sep>/Day 1/1 - Coding Basics/1-1 Data Types.py # ---------------------------------------- # int, long, float, string, boolean, None # ---------------------------------------- i = 4 l = 12l f = 1.2 s = 'xyz' n = i + l print i, l, f, s, n # 4 12 1.2 xyz 16 s2 = s + str(f) print s2 # xyz1.2 print type(i), type(l), type(f), type(s), type(n), type(s2) # <type 'int'> <type 'long'> <type 'float'> <type 'str'> <type 'long'> <type 'str'> print """i:%s l:%s f:%s s:%s n:%s s2:%s""" % (type(i), type(l), type(f), type(s), type(n), type(s2)) # i:<type 'int'> # l:<type 'long'> # f:<type 'float'> # s:<type 'str'> # n:<type 'long'> # s2:<type 'str'> s3 = '%s --- %s -- %d - %ld %f' % (s, s2, i, l, f) print s3 # xyz --- xyz1.2 -- 4 - 12 1.200000 xt = True xf = False xn = None print xt, xf, xn # True False None print repr(xt), repr(xf), repr(xn) # True False None print `xt`, `xf`, `xn`, `i`, `s` # True False None 4 'xyz' <file_sep>/Day 1/2 - Advanced Concepts/2-1 Modules/2-1-1 Modules.py # We have a module called fibo which contains the following lines. # Fibonacci numbers module # see https://docs.python.org/2/tutorial/modules.html def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result import fibo print dir(fibo) # ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fib', 'fib2'] print fibo.fib(1000) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 print fibo.fib(100) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] print fibo.__name__ # 'fibo' fib = fibo.fib print fib(500) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 reload(fibo) import fibo as fib print fib.fib(500) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 reload(fibo) from fibo import fib as fibonacci print fibonacci(500) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 # would not encourage this usage reload(fibo) from fibo import * print fib2(500) #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-8 Data Compression.py ### 2-8-8 Data Compression ### # Common data archiving and compression formats are directly supported by modules including: zlib, # gzip, bz2, zipfile and tarfile. import zlib s = 'witch which has which witches wrist watch' print len(s) t = zlib.compress(s) print len(t) print zlib.decompress(t) # 226805979 <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-10 Quality Control.py ### 2-8-10 Quality Control ### # One approach for developing high quality software is to write tests for each function as it is # developed and to run those tests frequently during the development process. # The doctest module provides a tool for scanning a module and validating tests embedded in a # program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along # with its results into the docstring. This improves the documentation by providing the user with an # example and it allows the doctest module to make sure the code remains true to the documentation. def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests # The unittest module is not as effortless as the doctest module, but it allows a more comprehensive # set of tests to be maintained in a separate file. import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests <file_sep>/Day 1/2 - Advanced Concepts/2-1 Modules/2-1-3 Output Formatting.py s = 'Hello World.' str(s) #'Hello World' repr(s) #"'Hello World.'" str(1.0/7.0) # '0.142857142857' repr(1.0/7.0) # '0.14285714285714285' x = 10 * 3.25 y = 200 * 200 s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' print s # The value of x is 32.5, and y is 40000... # The repr() of a string adds string quotes and backslashes: hello = 'hello, world\n' hellos = repr(hello) print hellos #'hello, world\n' # The argument to repr() may be any Python object: repr((x, y, ('spam', 'eggs'))) #"(32.5, 40000, ('spam', 'eggs'))" # Here are three ways to write a table of squares and cubes: for x in range(1, 11): print repr(x).rjust(2), repr(x*x).rjust(3), # Note trailing comma on previous line print repr(x*x*x).rjust(4) # 1 1 1 # 2 4 8 # 3 9 27 # 4 16 64 # 5 25 125 # 6 36 216 # 7 49 343 # 8 64 512 # 9 81 729 # 10 100 1000 for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) # 1 1 1 # 2 4 8 # 3 9 27 # 4 16 64 # 5 25 125 # 6 36 216 # 7 49 343 # 8 64 512 # 9 81 729 # 10 100 1000 for x in range(1, 11): print '%2d %3d %4d' % (x, x*x, x*x*x) # 1 1 1 # 2 4 8 # 3 9 27 # 4 16 64 # 5 25 125 # 6 36 216 # 7 49 343 # 8 64 512 # 9 81 729 # 10 100 1000 '12'.zfill(5) # '%05d' % 12 # '00012' '-3.14'.zfill(7) # '%07.2f' % -3.14 # '-003.14'% '3.14159265359'.zfill(5) # '%05.11f' % 3.14159265359 # '3.14159265359' print 'We are the {} who say "{}!"'.format('knights', 'Ni') # We are the knights who say "Ni!" print 'We who say "{1}" are the {0}!'.format('knights', 'Ni') # We who say "Ni" are the knights! print 'This {food} is {adjective}.'.format( food='spam', adjective='absolutely horrible') # This spam is absolutely horrible. print 'The story of {0}, {1}, and {other} {other} {other}.'.format('Bill', 'Manfred', other='Georg') # The story of Bill, Manfred, and Georg Ge<NAME>. import math print 'The value of PI is approximately {}.'.format(math.pi) # The value of PI is approximately 3.14159265359. print 'The value of PI is approximately {!r}.'.format(math.pi) # The value of PI is approximately 3.141592653589793. print 'The value of PI is approximately {0:.3f}.'.format(math.pi) # The value of PI is approximately 3.142. table = {'Peter': 4127, 'Paul': 4098, 'Mary': 7678} for name, phone in table.items(): print '{0:10} ==> {1:10d}'.format(name, phone) # Paul ==> 4098 # Mary ==> 7678 # Peter ==> 4127 print ('Peter: {0[Peter]:d}; Paul: {0[Paul]:d}; ' 'Mary: {0[Mary]:d}'.format(table)) # Peter: 4127; Paul: 4098; Mary: 7678 print 'Peter: {Peter:d}; Paul: {Paul:d}; Mary: {Mary:d}'.format(**table) # Peter: 4127; Paul: 4098; Mary: 7678 <file_sep>/Day 2/2 - Advanced Concepts Cont/2-6 A First Look at Classes.py # -- simple basic class without methods or members class Class: pass # -- simple class with class variable i and simple method f class ClassOne: '''A simple example class one''' i = 12345 def f(self): return 'Hello my world' x = ClassOne() print x.i # 12345 print x.f() #['__doc__', '__init__', '__module__', 'data'] # -- class with a constructor __init__ creating a data list instance class ClassTwo: '''A simple example class two''' def __init__(self): self.data = [] x = ClassTwo() print dir(x) x.data.append('fred') print x.data # ['fred'] # -- class and instance variables class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance d = Dog('Fido') e = Dog('Buddy') print d.kind, d.name # shared by all dogs # canine Fido print e.kind, e.name # shared by all dogs # canine Buddy # -- Function defined outside the class # -- Note that this practice usually only serves to confuse the reader of a program. def f1(self, x, y): return min(x, x+y) class C: f = f1 def g(self): return 'hello world' h = g c = C() print c.h() # hello world print c.f(4, 5) # 4 # -- Methods may call other methods by using method attributes of the self argument: class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x) bag = Bag() bag.add('cow') print bag.data # ['cow'] bag.addtwice('moon') print bag.data #['cow', 'moon', 'moon'] <file_sep>/Day 3/Excercises/All.py # Take this list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and print out all # the elements of the list that are less than 5. Instead of printing the elements # one by one, make a new list that has all the elements less than 5 from this list # in it and print out this new list. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] for num in a: if num < 5: b.append(num) print b # Create a list for the names of the months. Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] # Given the dates '20180304', '20171031', '20160602', '19951223' # (dates in the format 'YYYYMMDD'), write a function to be able to # convert these dates to the form 1st January, 1901. The (st nd rd th) # is called the ordinal suffix, we want the day without leading zero # ending in its ordinal suffix, the written month with a comma and the # full year. dates = ['20180304', '20171031', '20160602', '19951223'] def convert_date(): formatted_dates = [] for date in dates: year = date[0:4] numeric_month = date[4:6] numeric_day = date[6:8] day = format_Day(numeric_day) month = format_month(numeric_month) newDateString = day + ' ' + month + ', ' + year formatted_dates.append(newDateString) return formatted_dates def format_Day(day): day = get_ordinal_suffix(day) if day[0] == '0': day = day.replace('0', '') return day def get_ordinal_suffix(day): if day[1] == '1': return day + 'st' elif day[1] == '2': return day + 'nd' elif day[1] == '3': return day + 'rd' else: return day + 'th' def format_month(month): # Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return Months[int(month) - 1] newDates = convert_date() print newDates # Using the table below: # ItemNo Description No Cost Each # IT445 Snark bits 12 2.79 # IT123 Pistle dibs 5 11.13 # BK001 <NAME> Laurel 1 123.15 # a. Use a tuple assignment create the variables item_no, desc, no, cost_each using a range. # b. Create an item_list of tuples each containing the values for each line. # c. Looping through the list, for each tuple use the variables above as indices, calculating the # amount and print a line. Using a pre initialised total sum the amounts. # d. Print the total. # A items = [] for x in range(3): items.append({'ItemNo': None, 'Description': None, 'No': None, 'Cost Each': None}) # B items[0]['ItemNo'] = 'IT445' items[0]['Description'] = 'Snark bits' items[0]['No'] = 12 items[0]['Cost Each'] = 2.79 items[1]['ItemNo'] = 'IT123' items[1]['Description'] = 'Pistle dibs' items[1]['No'] = 5 items[1]['Cost Each'] = 11.13 items[2]['ItemNo'] = 'BK001' items[2]['Description'] = 'Yannie not Laurel' items[2]['No'] = 1 items[2]['Cost Each'] = 123.15 item_list = [] for x in range(3): item_list.append(items[x]) # C total = 0 for y in item_list: sumT = y['No'] * y['Cost Each'] total = total + sumT print 'The sum for {0} is {1}'.format(y['Description'], sumT) # D print 'The total for everything is {0}'.format(total) <file_sep>/Day 2/2 - Advanced Concepts Cont/2-7 Exceptions.py import sys try: 10 * (1/0) except ZeroDivisionError as e: print 'Divide by zero', e.message, e.args try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() try: try: raise NameError('Pig Swill') except NameError: print 'Lets pass it on' raise except: print "Expected error from pass on:", sys.exc_info()[0] <file_sep>/Day 1/2 - Advanced Concepts/2-1 Modules/2-1-2 Packages.py # Packages are a way of structuring modules using sub directories. For the example below Python # searches through the directories on sys.path looking for the package subdirectory. There has to # be an __init__.py in each directory that forms part of the package. sound/ # Top-level package __init__.py # Initialize the sound package formats/ # Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ # Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ # Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ... # Adding the following line into the __init__.py for the effects subdirectory would allow for # an import sound.effects.*, but bear in mind that import * is generally frowned upon. __all__ = ["echo", "surround", "reverse"] # From Python 2.5 zip files can be treated like directories. Adding a zip file to sys.path means # that all files with extension of [‘.py’, ‘.pyc’, ‘.pyo’] are treated like source or compiled # python. Packages stored in the zip file with their sub directories would work as described above. <file_sep>/Day 2/Excercises/manifest/manifest.py #!/usr/bin/env python import sys import os import os.path import stat import glob import argparse exists = os.path.exists BLACK = '\033[30m\033[%dm' RED = '\033[31m\033[%dm' GREEN = '\033[32m\033[%dm' ORANGE = '\033[33m\033[%dm' BLUE = '\033[34m\033[%dm' PURPLE = '\033[35m\033[%dm' CYAN = '\033[36m\033[%dm' WHITE = '\033[37m\033[%dm' def printer(colour): def model(*args): text = '%s ' * len(args) % args if sys.platform == 'win32': print text return print '%s%s%s' % (colour % (1), text, colour % (0)) return model red = printer(RED) green = printer(GREEN) orange = printer(ORANGE) blue = printer(BLUE) purple = printer(PURPLE) cyan = printer(CYAN) parser = argparse.ArgumentParser() if sys.platform == 'win32': parser.add_argument('-d', '--deploydir', type=str, default='/nedbank/deployments') parser.add_argument('-w', '--workdir', type=str, default='/nedbank/deployments/work') parser.add_argument('-s', '--start', type=str, default='/nedbank') else: parser.add_argument('-d', '--deploydir', type=str, default='/main/nedcor/bbd/common/deployments') parser.add_argument('-w', '--workdir', type=str, default='/main/nedcor/bbd/common/deployments/work') parser.add_argument('-s', '--start', type=str, default='/main/nedcor/bbd/common') parser.add_argument('-u', '--usetar', default=False, action="store_true", help="use tar") parser.add_argument('-t', '--testing', default=False, action="store_true", help="verbose") parser.add_argument('-v', '--verbose', default=False, action="store_true", help="verbose") parser.add_argument('manifest_file', type=str, help='manifest_file') options = parser.parse_args() vars = {} def mkdir(dir): if not exists(dir): orange('making dir %s' % (dir)) os.makedirs(dir, 0775) mkdir(options.deploydir) mkdir(options.workdir) def fixname(name): result = name if len(result) > 2 and result[1] == ':': result = result[2:] result = result.replace('\\', '/') return result check_rc = '''\ if [[ $rc -ne 0 ]] then echo backup failed exit $rc fi '''.splitlines() class Project: global options def __init__(self, name): self.name = fixname(name) self.programs = [] self.binfiles = [] self.gnts = [] self.cntls = [] self.artifacts = [] def write_sh(self, command): self.shfile.write('%s\n' % (command)) if options.verbose: green(command) def open_shell(self, type='build'): shfilename = '%s/%s_%s.sh' % (options.workdir, self.name.replace('/', '_'), type) if options.verbose: orange(shfilename) self.shfile = open(shfilename, 'wt') os.chmod(shfilename, stat.S_IRWXU | stat.S_IRWXG) self.write_sh('#! /bin/ksh') def close_shell(self): self.shfile.close() def make_source_tar(self): project_name = self.name.replace('/', '_') self.programs_list_name = '%s/%s_program.list' % ( options.workdir, project_name) self.source_list_name = '%s/%s_source.list' % ( options.workdir, project_name) ofile = open(self.programs_list_name, 'wt') for program in self.programs: ofile.write('%s\n' % (program)) ofile.close() command = 'dbxsrc -s %s -o %s -f %s' % ( options.start, self.source_list_name, self.programs_list_name) self.write_sh(command) if options.usetar: self.write_sh('tar vcfL %s_source.tar %s' % (project_name, self.source_list_name)) self.write_sh('gzip %s_source.tar' % (project_name)) else: command = 'zip %s_source.zip -@ < %s' % ( project_name, self.source_list_name) self.write_sh(command) def make_deploy_zip(self): project_name = self.name.replace('/', '_') self.open_shell('build') if len(self.programs) > 0: self.make_source_tar() self.package_list_name = '%s/%s_package.list' % ( options.workdir, project_name) ofile = open(self.package_list_name, 'wt') for program in self.programs: ofile.write('%s\n' % (program)) for binfile in self.binfiles: ofile.write('%s\n' % (binfile)) for gnt in self.gnts: ofile.write('%s\n' % (gnt)) for cntl in self.cntls: ofile.write('%s\n' % (cntl)) for artifact, _ in self.artifacts: ofile.write('%s\n' % (artifact)) ofile.close() command = 'zip -j %s_package.zip -@ < %s' % ( project_name, self.package_list_name) self.write_sh(command) command = 'zip -0 -j %s_deploy.zip %s_package.zip' % ( project_name, project_name) self.write_sh(command) if len(self.programs) > 0: if options.usetar: command = 'zip -0 -j %s_deploy.zip %s_source.tar.gz' % ( project_name, project_name) else: command = 'zip -0 -j %s_deploy.zip %s_source.zip' % ( project_name, project_name) self.write_sh(command) command = 'zip -j %s_deploy.zip %s_backup.list' % ( project_name, project_name) self.write_sh(command) command = 'zip -j %s_deploy.zip %s_backup.sh' % ( project_name, project_name) self.write_sh(command) command = 'zip -j %s_deploy.zip %s_extract.sh' % ( project_name, project_name) self.write_sh(command) command = 'zip -j %s_deploy.zip %s_restore.sh' % ( project_name, project_name) self.write_sh(command) self.deploy_file = '%s/%s_deploy' % (options.deploydir, project_name) command = 'cat /usr/bin/unzipsfx %s_deploy.zip > %s' % ( project_name, self.deploy_file) self.write_sh(command) command = 'chmod 755 %s' % (self.deploy_file) self.write_sh(command) command = 'zip -A %s' % (self.deploy_file) self.write_sh(command) self.close_shell() def make_backup_shell(self): project_name = self.name.replace('/', '_') self.backup_list_name = '%s/%s_backup.list' % ( options.workdir, project_name) ofile = open(self.backup_list_name, 'wt') self.open_shell('backup') for program in self.programs: _, name = os.path.split(program) ofile.write('%s/%s\n' % (self.program_dir, name)) for binfile in self.binfiles: _, name = os.path.split(binfile) ofile.write('%s/%s\n' % (self.binfile_dir, name)) for gnt in self.gnts: _, name = os.path.split(gnt) ofile.write('%s/%s\n' % (self.gnt_dir, name)) for cntl in self.cntls: _, name = os.path.split(cntl) ofile.write('%s/%s\n' % (self.cntl_dir, name)) for artifact, arti_dir in self.artifacts: _, name = os.path.split(artifact) ofile.write('%s/%s\n' % (arti_dir, name)) ofile.close() date_format = '$(date +%Y%m%d-%H%M%S)' if options.usetar: self.write_sh('if [[ ! -e "%s_backup.tar" ]]' % (project_name)) self.write_sh('then') self.write_sh(' tar vcfL %s_backup.tar %s_backup.list' % (project_name, project_name)) self.write_sh(' rc=$?') self.write_sh(' chmod 440 %s_backup.tar' % (project_name)) for line in check_rc: self.write_sh(line) self.write_sh(' cp %s_backup.tar %s_backup_%s.tar' % (project_name, date_format, project_name)) self.write_sh('fi') else: self.write_sh('if [[ ! -e "%s_backup.zip" ]]' % (project_name)) self.write_sh('then') self.write_sh(' zip %s_backup.zip -@ < %s_backup.list' % (project_name, project_name)) self.write_sh(' rc=$?') self.write_sh(' chmod 440 %s_backup.zip' % (project_name)) for line in check_rc: self.write_sh(line) self.write_sh(' cp %s_backup.zip %s_backup_%s.zip' % (project_name, date_format, project_name)) self.write_sh('fi') self.close_shell() def make_extract_shell(self): project_name = self.name.replace('/', '_') self.open_shell('extract') if options.usetar: self.write_sh('if [[ ! -e "%s_backup.tar" ]]' % (project_name)) self.write_sh('then') self.write_sh(' ./%s_backup.sh' % (project_name)) self.write_sh(' rc=$?') for line in check_rc: self.write_sh(line) self.write_sh('fi') else: self.write_sh('if [[ ! -e "%s_backup.zip" ]]' % (project_name)) self.write_sh('then') self.write_sh(' ./%s_backup.sh' % (project_name)) self.write_sh(' rc=$?') for line in check_rc: self.write_sh(line) self.write_sh('fi') for i, program in enumerate(self.programs): if i == 0: command = 'mkdir -p %s' % (self.program_dir) self.write_sh(command) _, name = os.path.split(program) command = 'unzip -o %s_package.zip -d %s %s' % ( project_name, self.program_dir, name) self.write_sh(command) for i, binfile in enumerate(self.binfiles): if i == 0: command = 'mkdir -p %s' % (self.binfile_dir) self.write_sh(command) _, name = os.path.split(binfile) command = 'unzip -o %s_package.zip -d %s %s' % ( project_name, self.binfile_dir, name) self.write_sh(command) for i, gnt in enumerate(self.gnts): if i == 0: command = 'mkdir -p %s' % (self.gnt_dir) self.write_sh(command) _, name = os.path.split(gnt) command = 'unzip -o %s_package.zip -d %s %s' % ( project_name, self.gnt_dir, name) self.write_sh(command) for i, cntl in enumerate(self.cntls): if i == 0: command = 'mkdir -p %s' % (self.cntl_dir) self.write_sh(command) _, name = os.path.split(cntl) command = 'unzip -o %s_package.zip -d %s %s' % ( project_name, self.cntl_dir, name) self.write_sh(command) prev_arti_dir = '' for artifact, arti_dir in self.artifacts: if arti_dir != prev_arti_dir: prev_arti_dir = arti_dir command = 'mkdir -p %s' % (arti_dir) self.write_sh(command) _, name = os.path.split(artifact) command = 'unzip -o %s_package.zip -d %s %s' % ( project_name, arti_dir, name) self.write_sh(command) self.close_shell() def make_restore_shell(self): project_name = self.name.replace('/', '_') self.open_shell('restore') if options.usetar: command = 'tar vxf %s_backup.tar' % (project_name) else: command = 'unzip -d / %s_backup.zip' % (project_name) self.write_sh(command) self.close_shell() def run_build(self): project_name = self.name.replace('/', '_') cur_dir = os.curdir os.chdir(options.workdir) os.system('./%s_build.sh' % (project_name)) os.chdir(cur_dir) START, PROGRAM, BINFILE, GNT, CNTL, ARTIFACT = 0, 1, 2, 3, 4, 5 state = START def remove_comment(line): p = line.find('#') if p >= 0: line = line[:p] return line def expand(line): result = '' while True: s = line.find('${') if s < 0: result += line break result += line[:s] line = line[s+2:] e = line.find('}') if e < 0: result += line break var = line[:e] line = line[e+1:] if var in vars: result += vars[var] return result def make_list(file): if '*' in file or '?' in file: return glob.glob(file) return [file] def parse_manifest(sourceFile): ifile = open(sourceFile, 'rt') lines = ifile.readlines() ifile.close() project = None lineNo = 0 for line in lines: lineNo += 1 line = expand(remove_comment(line.strip())) if len(line) == 0: continue fields = line.split('=') if len(fields) == 2: vars[fields[0]] = fields[1] continue fields = line.split() if fields[0] == 'include': if len(fields) == 2: ifile = open(fields[1], 'rt') includeLines = ifile.readlines() ifile.close() lines[lineNo:lineNo] = includeLines continue if fields[0] == 'project' and len(fields) > 1: project = Project(fields[1]) if options.verbose: green('project %s' % (project.name)) continue if project == None: print('expecting project name') return None if len(fields) > 1 and fields[0] == 'program': project.program_dir = fields[1] state = PROGRAM continue if len(fields) > 1 and fields[0] == 'binfile': project.binfile_dir = fields[1] state = BINFILE continue if len(fields) > 1 and fields[0] == 'gnt': project.gnt_dir = fields[1] state = GNT continue if len(fields) > 1 and fields[0] == 'cntl': project.cntl_dir = fields[1] state = CNTL continue if len(fields) > 1 and fields[0] == 'artifact': project.artifact_dir = fields[1] state = ARTIFACT continue if state == PROGRAM: for file in make_list(fields[0]): project.programs.append(file) continue if state == BINFILE: for file in make_list(fields[0]): project.binfiles.append(file) continue if state == GNT: for file in make_list(fields[0]): project.gnts.append(file) continue if state == CNTL: for file in make_list(fields[0]): project.cntls.append(file) continue if state == ARTIFACT: for file in make_list(fields[0]): project.artifacts.append((file, project.artifact_dir)) continue red('%s not used' % line) return project def main(): sourceFile = options.manifest_file project = parse_manifest(sourceFile) if project == None: red("Project not Created") return 1 source_missing = False blue('programs:', project.program_dir if len( project.programs) > 0 else 'None') for program in project.programs: if exists(program) == False: source_missing = True red("program source %s is missing" % (program)) blue('binfiles:', project.binfile_dir if len( project.binfiles) > 0 else 'None') for binfile in project.binfiles: if exists(binfile) == False: source_missing = True red("binfile source %s is missing" % (binfile)) blue('gnts:', project.gnt_dir if len(project.gnts) > 0 else 'None') for gnt in project.gnts: if exists(gnt) == False: source_missing = True red("gnt source %s is missing" % (gnt)) blue('cntls:', project.cntl_dir if len(project.cntls) > 0 else 'None') for cntl in project.cntls: if exists(cntl) == False: source_missing = True red("cntl source %s is missing" % (cntl)) for artifact, _ in project.artifacts: if exists(artifact) == False: source_missing = True red("artifact source %s is missing" % (artifact)) if source_missing == True: return 1 project.make_backup_shell() project.make_extract_shell() project.make_restore_shell() project.make_deploy_zip() if sys.platform != 'win32': project.run_build() return 0 if __name__ == '__main__': rc = main() exit(rc) <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-9 Performance Measurement.py ### 2-8-9 Performance Measurement ### # Some Python users develop a deep interest in knowing the relative performance of different approaches # to the same problem. Python provides a measurement tool that answers those questions immediately. # For example, it may be tempting to use the tuple packing and unpacking feature instead of the # traditional approach to swapping arguments. The timeit module quickly demonstrates a modest # performance advantage. from timeit import Timer print Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() # 0.0320846332396 print Timer('a,b = b,a', 'a=1; b=2').timeit() # 0.026504411628 # In contrast to timeit‘s fine level of granularity, the profile and pstats modules provide tools for # identifying time critical sections in larger blocks of code. <file_sep>/Day 1/1 - Coding Basics/1-7 Loops.py words = ['we', 'are', 'words', 'in', 'a', 'list'] for word in words: print word, len(word) # we 2 # are 3 # words 5 # in 2 # a 1 # list 4 for n, word in enumerate(words): print n, word # 0 we # 1 are # 2 words # 3 in # 4 a # 5 list for n, word in enumerate(sorted(words)): print n, word # 0 a # 1 are # 2 in # 3 list # 4 we # 5 words print range(10) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for n in range(len(words)): print n, words[n] # 0 we # 1 are # 2 words # 3 in # 4 a # 5 list for n in range(len(words)): if n == 3: continue if n > 4: break print n, words[n] # 0 we # 1 are # 2 words # 4 a for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' continue # 2 is a prime number # 3 is a prime number # 4 equals 2 * 2 # 5 is a prime number # 6 equals 2 * 3 # 7 is a prime number # 8 equals 2 * 4 # 9 equals 3 * 3 for num in range(2, 10): if num % 2 == 0: print "Found an even number", num continue print "Found a number", num # Found an even number 2 # Found a number 3 # Found an even number 4 # Found a number 5 # Found an even number 6 # Found a number 7 # Found an even number 8 # Found a number 9 i = 0 while i < 4: print i, i += 1 # 0 1 2 3 <file_sep>/Day 2/Excercises/cobblercsv/cobbler/cobbler.h #ifndef _COBBLER_H_ #define _COBBLER_H_ "$Revision: 47 $ $Date: 2009-01-15 10:22:38 +0200 (Thu, 15 Jan 2009) $" #include "versions.h" HEADER_VERSION(_COBBLER_H_); /* ************************************************************************** * * System : * * File : $URL: http://zug/Nedbank/MCCA/targsrc/c/util/cobbler.h $ * * Description : * * Created By : BB&D * * Date Created : * * $Author: rudolph $ * * $Revision: 47 $ * * $Date: 2009-01-15 10:22:38 +0200 (Thu, 15 Jan 2009) $ * * Change History : * * $Log: $ * ************************************************************************** */ #include "ti.h" #define xCobblerErrorName "xCobblerError" class tCobbler; class xCept; class xCobblerError : public xCept { public: enum eError { errCobOK , errCobInit , errCobShut , errCobMem , errCobWrit }; xCobblerError(pchar aFname, int aLine, eError aError,pchar aMsg1); xCobblerError(const xCobblerError& aX) : xCept(aX) {} }; #define XCobblerError(err,msg1) \ xCobblerError(__FILE__, __LINE__, xCobblerError::err,msg1) const char HIGH_VALUES[] = "\xFF"; const char LOW_VALUES[] = "\x00"; const char SPACES[] = " "; const char ZEROES[] = "0"; class tCobbler { public: void Write(int FileHandle); char* GetCStructure() {return CStructure;} int GetCStructSize() {return CStructSize;} protected: ~tCobbler(); tCobbler(int SSize); void moveG(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveN(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void move9(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void move9ts(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveX(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveA(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveS(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveL(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveD(double Data,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveDts(double Data,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); void moveE(char *SData,int SOffset,int SLen,int SScale,int SOccur = 0,int SMaxOccur = 1,int SEveryOccur = 0); private: char* CStructure; int CStructSize; tCobbler() {} }; #endif <file_sep>/Day 2/Excercises/cobblercsv/cobbler/neddf07.h #ifndef _NEDDF07_H_ #define _NEDDF07_H_ #include "cobbler.h" class tED007 : public tCobbler { public: tED007() : tCobbler(572){} void sCO (char *c) {moveX(c, 0, 2, 0);} void sINVESTOR (char *c) {moveN(c, 2, 10, 0);} void sINVESTMENT (char *c) {moveN(c, 12, 6, 0);} void sASSET_LIABILITY (char *c) {moveX(c, 18, 1, 0);} void sFNC_IND (char *c) {moveX(c, 19, 1, 0);} void sCLASS_CODE (char *c) {moveN(c, 20, 3, 0);} void sBRANCH (char *c) {moveN(c, 23, 4, 0);} void sEXPENSES_REGION (char *c) {moveN(c, 27, 4, 0);} void sTYPE (char *c) {moveN(c, 31, 1, 0);} void sPERIOD (char *c) {moveN(c, 32, 3, 0);} void sBA9_IND (char *c) {moveN(c, 35, 1, 0);} void sTERM (char *c) {moveN(c, 36, 1, 0);} void sME_TERM_IND (char *c) {moveN(c, 37, 1, 0);} void sRATE (char *c) {moveN(c, 38, 7, 4);} void sRATE_TYPE (char *c) {moveX(c, 45, 1, 0);} void sLINKED_RATE_TYPE (char *c) {moveN(c, 46, 12, 0);} void sCURRENCY (char *c) {moveX(c, 58, 3, 0);} void sCAPITAL (char *c) {moveN(c, 61, 15, 2);} void sDAILY_INT_SIGN (char *c) {moveX(c, 76, 1, 0);} void sDAILY_INT (char *c) {moveN(c, 77, 14, 6);} void sACCRUED_INT_SIGN (char *c) {moveX(c, 91, 1, 0);} void sACCRUED_INT (char *c) {moveN(c, 92, 14, 2);} void sENTRY_DATE (char *c) {moveN(c, 106, 8, 0);} void sEXPIRY_DATE (char *c) {moveN(c, 114, 8, 0);} void sNEXT_INT_DATE (char *c) {moveN(c, 122, 8, 0);} void sLAST_TRAN_DATE (char *c) {moveN(c, 130, 8, 0);} void sDROP_DATE (char *c) {moveN(c, 138, 8, 0);} void sINT_FREQ (char *c) {moveN(c, 146, 3, 0);} void sINT_PAYM_METHOD (char *c) {moveN(c, 149, 1, 0);} void sBLOCK_STATUS (char *c) {moveN(c, 150, 2, 0);} void sPLEDGED (char *c) {moveX(c, 152, 1, 0);} void sLIMIT (char *c) {moveN(c, 153, 13, 0);} void sDCAR (char *c) {moveN(c, 166, 5, 0);} void sTCIS_NO (char *c) {moveN(c, 171, 10, 0);} void sSARB_CODE (char *c) {moveX(c, 181, 4, 0);} void sFIN_BRANCH (char *c) {moveX(c, 185, 6, 0);} void sAVECAPOUT (char *c) {moveN(c, 191, 22, 2);} void sAVEUNCAPACCRINT (char *c) {moveN(c, 213, 22, 2);} void sSTARTINTRATE (char *c) {moveN(c, 235, 9, 6);} void sFILLER1 (char *c) {moveN(c, 244, 5, 0);} void sRUNDATE (char *c) {moveN(c, 249, 8, 0);} void sHOGANCISNO (char *c) {moveN(c, 257, 12, 0);} void sINTPAID (char *c) {moveN(c, 269, 14, 2);} void sINTREC (char *c) {moveN(c, 283, 14, 2);} void sSTATUS (char *c) {moveN(c, 297, 1, 0);} void sBACKDATED_INT_SIGN (char *c) {moveX(c, 298, 1, 0);} void sBACKDATED_INT (char *c) {moveN(c, 299, 14, 6);} void sBASERATE (char *c) {moveN(c, 313, 18, 6);} void sVARIANCEIND (char *c) {moveX(c, 331, 1, 0);} void sBANDDIFF (char *c) {moveN(c, 332, 18, 6);} void sSOURCESYSTEM (char *c) {moveX(c, 350, 4, 0);} void sAVAILABLEBALANCE (char *c) {moveN(c, 354, 22, 2);} void sNOTICEPERIOD (char *c) {moveN(c, 376, 8, 0);} void sORIGINVESTAMT_SIGN (char *c) {moveX(c, 384, 1, 0);} void sORIGINVESTAMT (char *c) {moveN(c, 385, 22, 2);} void sFIXEDAMT_SIGN (char *c) {moveX(c, 407, 1, 0);} void sFIXEDAMT (char *c) {moveN(c, 408, 22, 2);} void sACCESSPERC_SIGN (char *c) {moveX(c, 430, 1, 0);} void sACCESSPERC (char *c) {moveN(c, 431, 7, 2);} void sACCESSAMT_SIGN (char *c) {moveX(c, 438, 1, 0);} void sACCESSAMT (char *c) {moveN(c, 439, 22, 2);} void sACCESSCAP_SIGN (char *c) {moveX(c, 461, 1, 0);} void sACCESSCAP (char *c) {moveN(c, 462, 22, 2);} void sACCESSFLOOR_SIGN (char *c) {moveX(c, 484, 1, 0);} void sACCESSFLOOR (char *c) {moveN(c, 485, 22, 2);} void sWITHDRAWALBAL_SIGN (char *c) {moveX(c, 507, 1, 0);} void sWITHDRAWALBAL (char *c) {moveN(c, 508, 22, 2);} void sDEPOSITBAL_SIGN (char *c) {moveX(c, 530, 1, 0);} void sDEPOSITBAL (char *c) {moveN(c, 531, 22, 2);} void sPREVRESETDATE (char *c) {moveX(c, 553, 8, 0);} void sNEXTRESETDATE (char *c) {moveX(c, 561, 8, 0);} void sRESETFREQ (char *c) {moveX(c, 569, 2, 0);} void sRATEFLAG (char *c) {moveX(c, 571, 1, 0);} // void sPENALTYAMOUNT_SIGN (char *c) {moveX(c, 553, 1, 0);} // void sPENALTYAMOUNT (char *c) {moveN(c, 555, 22, 2);} // void sPENALTYCOMMENTS (char *c) {moveX(c, 577, 300, 0);} }; #endif <file_sep>/Day 1/1 - Coding Basics/1-6 Using Lists as Queues.py # It is also possible to use a list as a queue, where the first element added is he first element # retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While # appends and pops from the end of list are fast, doing inserts or pops from the beginning of a # list is slow (because all of the other elements have to be shifted by one). # To implement a queue, use collections.deque which was designed to have fast appends and pops # from both ends. For example: from collections import deque queue = deque(["Eric", "John", "Michael"]) queue.append("Terry") # Terry arrives queue.append("Graham") # Graham arrives print queue.popleft() # The first to arrive now leaves # 'Eric' print queue.popleft() # The second to arrive now leaves # 'John' print queue # Remaining queue in order of arrival #deque(['Michael', 'Terry', 'Graham']) <file_sep>/Day 1/1 - Coding Basics/1-9 Other Data Types.py # Sets amounts = [12.00, 15.12, 12.00, 6.25, 15.12] values = set(amounts) print values #set([6.25, 12.0, 15.12]) print sorted(values) #[6.25, 12.0, 15.12] for value in sorted(values): print value # 6.25 # 12.0 # 15.12 petrenella = set('petrenella') peterson = set('peterson') print petrenella #set(['a', 'e', 'l', 'n', 'p', 'r', 't']) print peterson #set(['e', 'o', 'n', 'p', 's', 'r', 't']) print petrenella - peterson #set(['a', 'l']) print petrenella | peterson #set(['a', 'e', 'l', 'o', 'n', 'p', 's', 'r', 't']) print petrenella & peterson #set(['p', 'r', 'e', 't', 'n']) print petrenella ^ peterson #set(['a', 's', 'l', 'o']) # List comprehension a = {x for x in peterson if x not in petrenella} print a #set(['s', 'o']) b = {x for x in peterson if x in petrenella} print b #set(['p', 'r', 'e', 't', 'n']) squares1 = [] for x in range(10): squares1.append(x**2) print squares1 #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares2 = [x**2 for x in range(10)] print squares2 #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] combs1 = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y] print combs1 #[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] combs2 = [] for x in [1, 2, 3]: for y in [3, 1, 4]: if x != y: combs2.append((x, y)) print combs2 #[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-5 Mathematics.py ### 2-8-5 Mathematics ### # The math module gives access to the underlying C library functions for floating point math. import math math.cos(math.pi / 4.0) # 0.7071067811865476 math.log(1024, 2) # 10 # The random module provides tools for making random selections. import random alist = ['banana', 'apple', 'blackberry'] random.choice(alist) random.random() random.randrange(6) <file_sep>/Day 2/2 - Advanced Concepts Cont/2-5 Object Oriented Programming.py # Extract from Python Tutorial. 9. Classes https://docs.python.org/2/tutorial/classes.html # “Compared with other programming languages, Python’s class mechanism adds classes with a # minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ # and Modula-3. Python classes provide all the standard features of Object Oriented Programming: # the class inheritance mechanism allows multiple base classes, a derived class can override any # methods of its base class or classes, and a method can call the method of a base class with the # same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes # partake of the dynamic nature of Python: they are created at runtime, and can be modified further # after creation.” # For futher reading see 9.1. A Word About Names and Objects and 9.2. Python Scopes and Namespaces <file_sep>/Koans/basic/README.md #Python Koans Python Koans is a port of Edgecase's "Ruby Koans" which can be found at (http://rubykoans.com/). (https://user-images.githubusercontent.com/2614930/28401740-ec6214b2-6cd0-11e7-8afd-30ed3102bfd6.png) Python Koans is an interactive tutorial for learning the Python programming language by making tests pass. Most tests are *fixed* by filling the missing parts of assert functions. Eg: self.assertEqual(__, 1+2) which can be fixed by replacing the __ part with the appropriate code: self.assertEqual(3, 1+2) Occasionally you will encounter some failing tests that are already filled out. In these cases you will need to finish implementing some code to progress. For example, there is an exercise for writing some code that will tell you if a triangle is equilateral, isosceles or scalene. As well as being a great way to learn some Python, it is also a good way to get a taste of Test Driven Development (TDD). ### Downloading Python Koans Python Koans is available through git on Github: (http://github.com/gregmalcolm/python_koans) It is also mirrored on bitbucket for Mercurial users: (http://bitbucket.org/gregmalcolm/python_koans) Either site will allow you to download the source as a zip/gz/bz2. ###Sniffer Support Sniffer allows you to run the tests continuously. If you modify any files files in the koans directory, it will rerun the tests. To set this up, you need to install sniffer:: pip install sniffer You should also run one of these libraries depending on your system. This will automatically trigger sniffer when a file changes, otherwise sniffer will have to poll to see if the files have changed. On Windows:: pip install pywin32 (If that failed, try:: pip install pypiwin32 ) Once it is set up, you just run:: ```bash sniffer ``` <file_sep>/Day 2/Excercises/cobblercsv/cobbler/cobblercsv.py import argparse def replace_with_spaces(line): for ch in '(){};,': line = line.replace(ch, ' ') return line def remove_comment(line): n = line.find('//') if n >= 0: line = '%s\n' % (line[:n]) return line class Record: 5 pass def get_ops(infile): cobble = Record() book = Record() cobble.infile = infile cobble.books = [] book.ops = [] file_in = open(infile, 'rt') lines = file_in.readlines() file_in.close() START, IN_CLASS = 0, 1 state = START for line in lines: line = remove_comment(line) if state == IN_CLASS: if line.find('};') == 0: state = START continue n = line.find('tCobbler(') if n > 0: cobble.size = int(line[n+9:].replace('){}', '')) continue n = line.find('{move') if n > 0: parts = replace_with_spaces(line).split() if parts[4].find('move') == 0: if int(parts[7]) == cobble.size: continue op = Record() book.ops.append(op) op.name = parts[1][1:] op.type = parts[4][4:] op.pos = parts[6:] else: op = Record() book.ops.append(op) op.name = parts[1][1:] op.type = parts[6][4:] op.pos = parts[8:] continue continue if line.find('class') == 0 and line.find('tCobbler') > 0: cobble.books.append(book) book.ops = [] parts = line.split() book.name = parts[1][1:] state = IN_CLASS continue return cobble def get_header(cobble, class_name, delim=','): result = '' tween = '' maximum = 0 if class_name == '': for b in cobble.books: no = len(b.ops) if no > maximum: book = b no = maximum if maximum == 0: for book in cobble.books: if book.name == class_name: break for op in book.ops: result += '%s%s' % (tween, op.name) tween = delim return result, book def display(cobble): print cobble.infile, cobble.size, len(cobble.books) for book in cobble.books: print '', book.name, len(book.ops) for op in book.ops: print '', '', op.name, op.type, op.pos def fix(data, oftype, scale): if oftype == 'X': data = data.rstrip() elif oftype == 'N' and scale > 0: while len(data) > scale+1 and data[0] == '0': data = data[1:] if scale > 0: n = len(data) - scale data = '%s.%s' % (data[:n], data[n:]) return data def check(data, delim): if len(data) > 0 and data[0] != '"' and delim in data: if delim != '"': return '"%s"' % (data) else: return "'%s'" % (data) return data def process_data(cobble, datafile, class_name, delim): header, book = get_header(cobble, class_name, delim) print header file_in = open(datafile, 'rt') lines = file_in.readlines() file_in.close() for line in lines: result = '' tween = '' for op in book.ops: if len(op.pos) >= 3: offset = int(op.pos[0]) size = int(op.pos[1]) scale = int(op.pos[2]) data = line[offset:offset+size] xx = fix(data, op.type, scale) result += '%s%s' % (tween, check(xx, delim)) tween = delim print result def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--delim', type=str, default=',') parser.add_argument('-c', '--class_name', type=str, default='', help='class-name-without-t') parser.add_argument('cobbler_header', help='cobbler.h filename') parser.add_argument('datafile', help='flat-datafile') args = parser.parse_args() cobbler_header = args.cobbler_header datafile = args.datafile class_name = args.class_name delim = args.delim cobble = get_ops(cobbler_header) process_data(cobble, datafile, class_name, delim) return 0 if __name__ == '__main__': rc = main() exit(rc) <file_sep>/Day 1/1 - Coding Basics/1-3 Lists.py # Lists are mutable vectors of zero or more elements and elements in a list can be # added, change or removed. They are denoted using square brackets. Tuples are # immutable vectors which cannot be modified. They are denoted using parenthesis # (round brackets). Strings are immutable so that individual characters cannot be # changed, the whole string must be replaced for changes. squares = [1, 4, 9, 16, 25] print squares [1, 4, 9, 16, 25] print squares[0], '# first element' # 1 # first element print squares[-1], '# last element' # 25 # last element print squares[1:2], '# new list of second element' # [4] # new list of second element print squares[-3:], '# new list of last three elements' # [9, 16, 25] # new list of last three elements print squares[:3], '# new list of first three elements' # [1, 4, 9] # new list of first three elements big_squares = squares + [36, 49, 64, 81, 100] print big_squares #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] cubes = [1, 8, 27, 65, 125] # something's wrong here print 4 ** 3 # the cube of 4 is 64, not 65! # 64 cubes[3] = 4 ** 3 print cubes #[1, 8, 27, 64, 125] cubes.append(6 ** 3) cubes.append(7 ** 3) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print letters #['a', 'b', 'c', 'd', 'e', 'f', 'g'] letters[2:5] = ['C', 'D', 'E'] print letters #['a', 'b', 'C', 'D', 'E', 'f', 'g'] letters[2:5] = [] print letters #['a', 'b', 'f', 'g'] letters[:] = [] print letters # [] letters = ['a', 'b', 'c', 'd'] print len(letters) # 4 mixed = [squares, cubes, letters] print mixed #[[1, 4, 9, 16, 25], [1, 8, 27, 64, 125, 216, 343], ['a', 'b', 'c', 'd']] print mixed[1] #[1, 8, 27, 64, 125, 216, 343] print mixed[0][3] # 16 <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library.py ### 2-8-1 Operating System Interface ### # The os module provides dozens of functions for interacting with the operating system. # These may differ from Windows to Linux or Mac. It is preferable to use import os and avoid # from os import *. import os # There is also a shutil module with a higher level interface simialr to the os module which # may be easier to use at times. import shutil ### 2-8-2 File Wildcards ### # The glob module provides a function for making file lists from directory wildcard searches. # This is very useful for writing utility scripts. import glob glob.glob('*.py') ### 2-8-3 Command Line Arguments ### # Common utility scripts often need to process command line arguments. These arguments are stored # in the sys module’s argv attribute as a list. Starting python with extra arguments, # say python - this is more than one. There are many treasures im module sys, for example stdout # or stderr could be used for writing info or errors. You could even use the dread exit to terminate # the session. In programs running using exception handling, exit is generally to be avoided. import sys print sys.argv sys.stdout.write('info\n') sys.stderr.write('error\n') sys.exit(1) ### 2-8-4 String Pattern Matching ### # The re module provides regular expression tools for advanced string processing. For complex matching # and manipulation, regular expressions offer succinct, optimized solutions. Unfortunately they are # quite often about as readable as an APL program. import re re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') # When only simple capabilities are needed, string methods are preferred because they are easier to # read and debug. 'cat in the the hat'.replace('the the', 'the') ### 2-8-5 Mathematics ### # The math module gives access to the underlying C library functions for floating point math. import math math.cos(math.pi / 4.0) # 0.7071067811865476 math.log(1024, 2) # 10 # The random module provides tools for making random selections. import random alist = ['banana', 'apple', 'blackberry'] random.choice(alist) random.random() random.randrange(6) ### 2-8-6 Internet Access ### # There are a number of modules for accessing the internet and processing internet protocols. # Two of the simplest are urllib2 for retrieving data from URLs and smtplib for sending mail. import urllib2 for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): if 'EST' in line or 'EDT' in line: print line # <BR>May. 14, 04:41:01 AM EDT Eastern Time # - (Note that this second example needs a mailserver running on localhost.) import smtplib server = smtplib.SMTP('localhost') server.sendmail('<EMAIL>', '<EMAIL>', """To: <EMAIL> From: <EMAIL> Beware the Ides of March. """) server.quit() ### 2-8-7 Date and Times ### # The datetime module supplies classes for manipulating dates and times in both simple and complex ways. # While date and time arithmetic is supported, the focus of the implementation is on efficient member # extraction for output formatting and manipulation. The module also supports objects that are timezone # aware. Here we will do a from datetime import date. from datetime import date now = date.today() print now now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") #'05-14-18. 14 May 2018 is a Monday on the 14 day of May.' birthday = date(1964, 7, 31) age = now - birthday print age.days ### 2-8-8 Data Compression ### # Common data archiving and compression formats are directly supported by modules including: zlib, # gzip, bz2, zipfile and tarfile. import zlib s = 'witch which has which witches wrist watch' print len(s) t = zlib.compress(s) print len(t) print zlib.decompress(t) # 226805979 ### 2-8-9 Performance Measurement ### # Some Python users develop a deep interest in knowing the relative performance of different approaches # to the same problem. Python provides a measurement tool that answers those questions immediately. # For example, it may be tempting to use the tuple packing and unpacking feature instead of the # traditional approach to swapping arguments. The timeit module quickly demonstrates a modest # performance advantage. from timeit import Timer print Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() # 0.0320846332396 print Timer('a,b = b,a', 'a=1; b=2').timeit() # 0.026504411628 # In contrast to timeit‘s fine level of granularity, the profile and pstats modules provide tools for # identifying time critical sections in larger blocks of code. ### 2-8-10 Quality Control ### # One approach for developing high quality software is to write tests for each function as it is # developed and to run those tests frequently during the development process. # The doctest module provides a tool for scanning a module and validating tests embedded in a # program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along # with its results into the docstring. This improves the documentation by providing the user with an # example and it allows the doctest module to make sure the code remains true to the documentation. def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests # The unittest module is not as effortless as the doctest module, but it allows a more comprehensive # set of tests to be maintained in a separate file. import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests ### 2-8-11 Batteries Included ### # Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust # capabilities of its larger packages. For example: # The xmlrpclib and SimpleXMLRPCServer modules make implementing remote procedure calls into an almost # trivial task. Despite the modules names, no direct knowledge or handling of XML is needed. # The email package is a library for managing email messages, including MIME and other RFC 2822-based # message documents. Unlike smtplib and poplib which actually send and receive messages, the email # package has a complete toolset for building or decoding complex message structures (including # attachments) and for implementing internet encoding and header protocols. # The xml.dom and xml.sax packages provide robust support for parsing this popular data interchange # format. Likewise, the csv module supports direct reads and writes in a common database format. # Together, these modules and packages greatly simplify data interchange between Python applications # and other tools. # Internationalization is supported by a number of modules including gettext, locale, and the codecs # package. <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-1 Operating System Interface.py ### 2-8-1 Operating System Interface ### # The os module provides dozens of functions for interacting with the operating system. # These may differ from Windows to Linux or Mac. It is preferable to use import os and avoid # from os import *. import os # There is also a shutil module with a higher level interface simialr to the os module which # may be easier to use at times. import shutil <file_sep>/External Excercises/Input Ex.py import math name = raw_input("What's your name? ") print ("Hello, " + name + "!") age = raw_input("How old are you today? ") print ("Ah, so you're at least " + str(int(age) * 365.25 * 24 * 60 * 60) + ' seconds old...') <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-3 Command Line Arguments.py ### 2-8-3 Command Line Arguments ### # Common utility scripts often need to process command line arguments. These arguments are stored # in the sys module’s argv attribute as a list. Starting python with extra arguments, # say python - this is more than one. There are many treasures im module sys, for example stdout # or stderr could be used for writing info or errors. You could even use the dread exit to terminate # the session. In programs running using exception handling, exit is generally to be avoided. import sys print sys.argv sys.stdout.write('info\n') sys.stderr.write('error\n') sys.exit(1) <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-7 Date and Times.py ### 2-8-7 Date and Times ### # The datetime module supplies classes for manipulating dates and times in both simple and complex ways. # While date and time arithmetic is supported, the focus of the implementation is on efficient member # extraction for output formatting and manipulation. The module also supports objects that are timezone # aware. Here we will do a from datetime import date. from datetime import date now = date.today() print now now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") #'05-14-18. 14 May 2018 is a Monday on the 14 day of May.' birthday = date(1964, 7, 31) age = now - birthday print age.days <file_sep>/Day 3/Excercises/Ex 1.py # Take this list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and print out all # the elements of the list that are less than 5. Instead of printing the elements # one by one, make a new list that has all the elements less than 5 from this list # in it and print out this new list. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] for num in a: if num < 5: b.append(num) print b <file_sep>/Day 1/1 - Coding Basics/1-10 Functions, Yield, and Lambda.py def fibonacci_looped(to_max): a, b = 0, 1 while b < to_max: print b, a, b = b, a+b print fibonacci_looped(40000) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 def fiboeven(to_max): sum_of = 0 p1 = 0 p2 = 1 p3 = p1 + p2 while sum_of + p1 < to_max: print p1, p2, p3, sum_of += p1 p1 = p2 + p3 p2 = p3 + p1 p3 = p1 + p2 print print 'sum of evens', sum_of fiboeven(40000) # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 # sum of evens 14328 def make_multiplier(n): def func(x): return x*n return func t4 = make_multiplier(4) t5 = make_multiplier(5) print 't4(11)*t5(17)', t4(11)*t5(17) # t4(11)*t5(17) 3740 def make_multiplier2(n): return lambda x: x * n t4 = make_multiplier2(4) t5 = make_multiplier2(5) print 't4(11)*t5(17)', t4(11)*t5(17) # t4(11)*t5(17) 3740 print '''\ Beware that default parameters are evaluated once def f(a, L=[]): L.append(a) return L ''' # Beware that default parameters are evaluated once # def f(a, L=[]): # L.append(a) # return L def f(a, L=[]): L.append(a) return L print 'f(1)', f(1) #f(1) [1] print 'f(2)', f(2) #f(2) [1, 2] print 'f(3)', f(3) #f(3) [1, 2, 3] def reverse(data): for i in range(len(data)-1, -1, -1): yield data[i] for char in reverse('pomelo'): print char # o # l # e # m # o # p <file_sep>/Day 3/Excercises/Ex 3.py # Given the dates '20180304', '20171031', '20160602', '19951223' # (dates in the format 'YYYYMMDD'), write a function to be able to # convert these dates to the form 1st January, 1901. The (st nd rd th) # is called the ordinal suffix, we want the day without leading zero # ending in its ordinal suffix, the written month with a comma and the # full year. dates = ['20180304', '20171031', '20160602', '19951223'] def convert_date(): formatted_dates = [] for date in dates: year = date[0:4] numeric_month = date[4:6] numeric_day = date[6:8] day = format_Day(numeric_day) month = format_month(numeric_month) newDateString = day + ' ' + month + ', ' + year formatted_dates.append(newDateString) return formatted_dates def format_Day(day): day = get_ordinal_suffix(day) if day[0] == '0': day = day.replace('0', '') return day def get_ordinal_suffix(day): if day[1] == '1': return day + 'st' elif day[1] == '2': return day + 'nd' elif day[1] == '3': return day + 'rd' else: return day + 'th' def format_month(month): Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return Months[int(month) - 1] newDates = convert_date() print newDates <file_sep>/Day 1/1 - Coding Basics/1-2 If.py x = 3 if x == 1: print 'x is 1' elif x == 2: pass elif x == 3: print "Hello There" else: print x # Hello There​ # Python equivalent of the C :- y = x == 3 ? 4 : 5; y = 4 if x == 3 else 5 a = 1 b = 2 c = 3 d = 4 if a == 1 and b == 2 and c == 3 and d == 4: print 'as above' # as above # You can set data with tuple syntax a, b, c, d = 1, 2, 3, 4 if a < c < d: print True # True # Comparing Sequences and Other Types print '''\ (1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) ''' #(1, 2, 3) < (1, 2, 4) #[1, 2, 3] < [1, 2, 4] #'ABC' < 'C' < 'Pascal' < 'Python' #(1, 2, 3, 4) < (1, 2, 4) #(1, 2) < (1, 2, -1) #(1, 2, 3) == (1.0, 2.0, 3.0) #(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) xx = (1, 2, 3) < (1, 2, 4) print xx # True xx = [1, 2, 3] < [1, 2, 4] print xx # True xx = 'ABC' < 'C' < 'Pascal' < 'Python' print xx # True xx = (1, 2, 3, 4) < (1, 2, 4) print xx # True xx = (1, 2) < (1, 2, -1) print xx # True xx = (1, 2, 3) == (1.0, 2.0, 3.0) print xx # True xx = (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) print xx # True <file_sep>/Day 1/1 - Coding Basics/1-4 More Lists.py # list.append(x)Add an item to the end of the list; equivalent to a[len(a):] = [x]. # list.extend(L)Extend the list by appending all the items in the given list; # equivalent to a[len(a):] = L. # list.insert(i, x)Insert an item at a given position. The first argument is the index of the # element before which to insert, so a.insert(0, x) inserts at the front of the list, # and a.insert(len(a), x) is equivalent to a.append(x). # list.remove(x)Remove the first item from the list whose value is x. It is an error if there is # no such item. # list.pop([i])Remove the item at the given position in the list, and return it. If no index is # specified, a.pop() removes and returns the last item in the list. (The square brackets around # the i in the method signature denote that the parameter is optional, not that you should type # square brackets at that position. You will see this notation frequently in the Python Library # Reference.) # list.index(x)Return the index in the list of the first item whose value is x. It is an error # if there is no such item. # list.count(x)Return the number of times x appears in the list. # list.sort(cmp=None, key=None, reverse=False)Sort the items of the list in place (the arguments # can be used for sort customization, see sorted() for their explanation). # list.reverse()Reverse the elements of the list, in place. a = [66.25, 333, 333, 1, 1234.5] print a.count(333), a.count(66.25), a.count('x') # 2 1 0 a.insert(2, -1) a.append(333) print a #[66.25, 333, -1, 333, 1, 1234.5, 333] print a.index(333) # 1 print a.remove(333) print a #[66.25, -1, 333, 1, 1234.5, 333] a.reverse() print a #[333, 1234.5, 1, 333, -1, 66.25] a.sort() print a #[-1, 1, 66.25, 333, 333, 1234.5] print a.pop() # 1234.5 print a #[-1, 1, 66.25, 333, 333] <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-11 Batteries Included.py ### 2-8-11 Batteries Included ### # Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust # capabilities of its larger packages. For example: # The xmlrpclib and SimpleXMLRPCServer modules make implementing remote procedure calls into an almost # trivial task. Despite the modules names, no direct knowledge or handling of XML is needed. # The email package is a library for managing email messages, including MIME and other RFC 2822-based # message documents. Unlike smtplib and poplib which actually send and receive messages, the email # package has a complete toolset for building or decoding complex message structures (including # attachments) and for implementing internet encoding and header protocols. # The xml.dom and xml.sax packages provide robust support for parsing this popular data interchange # format. Likewise, the csv module supports direct reads and writes in a common database format. # Together, these modules and packages greatly simplify data interchange between Python applications # and other tools. # Internationalization is supported by a number of modules including gettext, locale, and the codecs # package. <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-4 String Pattern Matching.py ### 2-8-4 String Pattern Matching ### # The re module provides regular expression tools for advanced string processing. For complex matching # and manipulation, regular expressions offer succinct, optimized solutions. Unfortunately they are # quite often about as readable as an APL program. import re re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') # When only simple capabilities are needed, string methods are preferred because they are easier to # read and debug. 'cat in the the hat'.replace('the the', 'the') <file_sep>/Day 1/2 - Advanced Concepts/2-1 Modules/2-1-4 Reading And Writing Files.py # There is a standard function open() which returns a file object, and is most commonly used with # two arguments: open(filename, mode). Due to the historical (hysterical) use of CRLF (carriage # return line feed) on Windows for textline endings opening a with the modes ‘r’ causes CRLF to be # translated to LF, this causes havoc when using binary data files like JPEG or EXE, the data in # these get corrupted. Text file with BOM (byte order marks) at the front also cause issues. These # BOM's unfortunately require two kinds of action when reading these files. # We will just be dealing with UTF8 containing ASCII mostly, here. f = open('workfile.txt', 'w') print f # <open file 'workfile', mode 'w' at ...> data = '''\ Mary had a little lamb it's fleece was white a snow and every where that Mary went the lamb was sure to go. ''' f.write(data) f.close() import sys stdout = sys.stdout stdout.write(data) f = open('workfile.txt', 'r') line = f.readline() stdout.write(line) # Mary had a little lamb for line in f: stdout.write(line) # it's fleece was white a snow # and every where that Mary went # the lamb was sure to go. f.close() f = open('workfile.txt', 'r') list(f) # Mary had a little lamb # it's fleece was white a snow # and every where that Mary went # the lamb was sure to go. f.seek(0) lines = f.readlines() for line in lines: stdout.write(line) # Mary had a little lamb # it's fleece was white a snow # and every where that Mary went # the lamb was sure to go. f.close() with open('workfile.txt', 'r') as f: list(f) # Mary had a little lamb # it's fleece was white a snow # and every where that Mary went # the lamb was sure to go. print f.closed # True # a little json import json f = open('workfile.txt', 'r') lines = f.readlines() json.dumps(lines) f.close() f = open('workfile.txt', 'w') json.dump(lines, f) f.close() f = open('workfile.txt', 'r') lines = json.load(f) f.close() <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-6 Internet Access.py ### 2-8-6 Internet Access ### # There are a number of modules for accessing the internet and processing internet protocols. # Two of the simplest are urllib2 for retrieving data from URLs and smtplib for sending mail. import urllib2 for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): if 'EST' in line or 'EDT' in line: print line # <BR>May. 14, 04:41:01 AM EDT Eastern Time # - (Note that this second example needs a mailserver running on localhost.) import smtplib server = smtplib.SMTP('localhost') server.sendmail('<EMAIL>', '<EMAIL>', """To: <EMAIL> From: <EMAIL> Beware the Ides of March. """) server.quit() <file_sep>/Day 3/Excercises/Ex 2.py # Create a list for the names of the months. Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] <file_sep>/Day 1/1 - Coding Basics/1-5 Using Lists as Stacks.py # The list methods make it very easy to use a list as a stack, where the last element added is # the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, # use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. # For example: stack = [3, 4, 5] stack.append(6) stack.append(7) print stack #[3, 4, 5, 6, 7] print stack.pop() # 7 print stack #[3, 4, 5, 6] print stack.pop() # 6 print stack.pop() # 5 print stack #[3, 4] <file_sep>/Day 1/Tester/tester.py # To run, in the cmd enter the following # python <filename>.py # OR # Navigate to the directory in the console # Run python, and Import <filename> # Then call <filename>.<function>(params) # Ex: # import tester # tester.xxx(12) def xxx(a): print 'I\'m going to lick these', a * \ 5, 'mother fucking snakes AND this mother fucking plane!' def main(): return xxx(12) if __name__ == '__main__': main() <file_sep>/Day 1/1 - Coding Basics/1-8 Dictionaries.py # Dictionaries are a (key, value) mapping type. They are denoted by braces (curly brackets.) # The keys must be unique and can be any immutable type; strings and number are generally used # but tuples can be keys if the do not contain mutable elements. course = {'VB6': 'Rory', 'JScript': 'Martin'} course['C++'] = "Craig" course['COBOL'] = None print course #{'JScript': 'Martin', 'COBOL': None, 'VB6': 'Rory', 'C++': 'Craig'} print sorted(course) # ['C++', 'COBOL', 'JScript', 'VB6'] for key in sorted(course): print key, course[key] #C++ Craig # COBOL None # JScript Martin # VB6 Rory print course.keys() # ['JScript', 'COBOL', 'VB6', 'C++'] kd = [] for key in course: kd.append((key, course[key])) print kd #[('JScript', 'Martin'), ('COBOL', None), ('VB6', 'Rory'), ('C++', 'Craig')] xyz = dict(kd) print xyz['COBOL'] # None if 'VB6' in xyz: print xyz['VB6'] # Rory <file_sep>/Day 2/2 - Advanced Concepts Cont/2-8 Tour of the Standard Library/2-8-2 File Wildcards.py ### 2-8-2 File Wildcards ### # The glob module provides a function for making file lists from directory wildcard searches. # This is very useful for writing utility scripts. import glob glob.glob('*.py')
3d1d7105a9613d216101b76b21856e706f2c3679
[ "Markdown", "Python", "C++" ]
41
Python
NickC148/Python_Bootcamp
485352408b4790722e4554ced71ff4091f0f68ab
c4510c15fa4ba4ece744771064c150d584f0b2e5
refs/heads/master
<file_sep>module Address module Io module ApiOperations module Retrieve def retrieve(postal_code=nil) return nil unless postal_code postal_code = "?postal_code=#{postal_code}" if postal_code.include? '@' api_request("#{url}/#{postal_code}", :get) end def self.included(base) base.extend(Retrieve) end end end end end<file_sep>module Address module Io module ApiOperations module List include ApiResource def list_all(params=nil) api_request(url, :get, params) end def self.included(base) base.extend(List) end end end end end<file_sep>require "rest-client" require "json" require "address/io/version" require "address/io/api_resource" require "address/io/api_operations/list" require "address/io/api_operations/retrieve" require "address/io/state" require "address/io/city" require "address/io/addresses" module Address module Io @@api_key = '' def self.api_key(api_key) @@api_key = api_key end def self.access_keys "#{@@api_key}" end end end <file_sep>module Address module Io VERSION = '2.0'.freeze end end <file_sep>require 'spec_helper' describe Address::Io do before(:each) do Address::Io.api_key(ENV['API_KEY']) end it 'has a version number' do expect(Address::Io::VERSION).not_to be nil end it 'should set api_key' do Address::Io.api_key(ENV['API_KEY']) expect(Address::Io.access_keys).to eq(ENV['API_KEY']) end it 'should call Adressio Api' do url = "/v1/states" method = :get response = Address::Io::State.api_request(url, method) expect(response.first.class).to eq(Hash) expect(response.first[:code]).to eq("12") expect(response.class).to eq(Array) expect(response.size).to eq(27) end it 'should get 27 states' do states = Address::Io::State.list_all expect(states.size).to eq(27) expect(states.first[:code]).to be_truthy end context 'get cities' do it 'should return null when state is null' do cities = Address::Io::City.list_all expect(cities).to eq(nil) end it 'should get 22 cities for state AC' do cities = Address::Io::City.list_all state: 'ac' expect(cities.size).to eq(22) end it 'should get all cities for state AP' do cities = Address::Io::City.list_all state: 'ap' expect(cities.size).to eq(16) end end context 'get address' do it 'should return null when postalCode is null' do address = Address::Io::Addresses.retrieve expect(address).to eq(nil) end it 'should return error message when postalCode is not valid' do address = Address::Io::Addresses.retrieve "invalid" expect(address).to eq("The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.") end it 'should return correct address when postalCode is 01311-300' do address = Address::Io::Addresses.retrieve "01311-300" expect(address).to include( postalCode: '01311-300', streetSuffix: 'Avenida', street: 'Paulista', district: 'Bela Vista', city: { code: '3550308', name: 'São Paulo' }, state: { abbreviation: 'SP' } ) end it 'should return correct address when postalCode is 01311300' do address = Address::Io::Addresses.retrieve "01311300" expect(address).to include( postalCode: '01311-300', streetSuffix: 'Avenida', street: 'Paulista', district: 'Bela Vista', city: { code: '3550308', name: 'São Paulo' }, state: { abbreviation: 'SP' } ) end end end <file_sep>module Address module Io class City include ApiResource def self.url "/v1/states/#{@state}/cities" end def url "#{self.class.url}/#{self.id}" end def self.list_all(params=nil) if params && params[:state] @state = params[:state] api_request(url, :get, params) else nil end end end end end<file_sep>module Address module Io class State include ApiResource include ApiOperations::List def self.url "/v1/states" end def url "#{self.class.url}/#{self.id}" end end end end<file_sep>module Address module Io class Addresses include ApiResource include ApiOperations::Retrieve BASE_URL = 'http://address.api.nfe.io' def self.url '/v2/addresses' end def url "#{self.class.url}/#{self.id}" end def self.api_request(url, method, params = nil) address = super(url, method, params) if address.is_a?(Hash) format_address(address[:address]) else legacy_url = 'http://open.nfe.io/v1/addresses' super(legacy_url, method, params) end rescue 'The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.' end def self.format_address(address) { postalCode: address[:postalCode], streetSuffix: address[:streetSuffix], street: address[:street], district: address[:district], city: { code: address[:city][:code], name: address[:city][:name] }, state: { abbreviation: address[:state] } } end end end end
0c5d0481a6cce5f5590200d62682da8ac5965855
[ "Ruby" ]
8
Ruby
PlugaDotCo/addresses-ruby
69fcd870e9fd2e1c79e9dd2b19a359b7bc58d0d2
88aa2f306b9e3860bce99dd164929ef20b89bdf8
refs/heads/master
<repo_name>SynapseFI/SynapsePy<file_sep>/synapsepy/endpoints.py paths = { 'oauth': '/oauth', 'client': '/client', 'users': '/users', 'trans': '/trans', 'nodes': '/nodes', 'subs': '/subscriptions', 'subn': '/subnets', 'inst': '/institutions', 'apple': '/applepay', 'atms': '/atms', 'cryptoq': '/crypto-quotes', 'cryptom': '/crypto-market-watch', 'dummy': '/dummy-tran', 'dispute': '/dispute', 'ubo': '/ubo', 'logs': '/logs', 'ship': '/ship', 'statem': '/statements', 'trade': '/trade-market-watch', 'barcode': '/barcode', 'chargeback': '/dispute-chargeback', 'types': '/types', 'doctypes': '/document-types', 'entypes': '/entity-types', 'enscopes': '/entity-scopes', 'verifyadd': '/address-verification', 'routnumver': '/routing-number-verification', 'push': '/push' }<file_sep>/synapsepy/__init__.py from .client import Client from .user import User, Users from .node import Node, Nodes from .subnet import Subnet, Subnets from .subscription import Subscription, Subscriptions from .transaction import Trans, Transactions<file_sep>/synapsepy/tests/client_tests.py import unittest from unittest import TestCase, mock from .. import errors as api_errors from .fixtures.user_fixtures import simple_response, users_resp from .fixtures.subscription_fixtures import subs_resp, subss_resp from .fixtures.node_fixtures import get_nodes_response from .fixtures.client_fixtures import verified_routing_number, verified_address from ..client import Client from ..user import User, Users from ..node import Node, Nodes from ..transaction import Trans, Transactions from ..subscription import Subscription, Subscriptions class ClientTests(TestCase): ''' TODO: need to add path/endpoint tests test all client methods ''' def setUp(self): self.client = Client( client_id='', client_secret='', fingerprint='', ip_address='', devmode=True, logging=False ) def test_client_init(self): # check if obj is Client self.assertIsInstance(self.client, Client) @mock.patch( 'synapsepy.http_client.HttpClient.post', return_value = simple_response, autospec = True ) def test_create_user(self, mock_request): # check if obj is User simple = self.client.create_user({},'CREATE_USER_IP',fingerprint='CREATE_USER_FP') self.assertIsInstance(simple, User) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = simple_response, autospec = True ) def test_get_user(self, mock_request): # check if obj is User simple = self.client.get_user('', ip='GET_USER_IP', fingerprint='GET_USER_FP') self.assertIsInstance(simple, User) @mock.patch( 'synapsepy.http_client.HttpClient.post', return_value = subs_resp, autospec = True ) def test_create_subs(self, mock_request): # check if obj is Subscription sub = self.client.create_subscription('', '') self.assertIsInstance(sub, Subscription) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = subs_resp, autospec = True ) def test_get_subs(self, mock_request): subs = self.client.get_subscription('') self.assertIsInstance(subs, Subscription) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_webhook_logs(self, mock_request): logs = self.client.webhook_logs() self.assertIsInstance(logs, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_crypto_quotes(self, mock_request): response = self.client.crypto_quotes() self.assertIsInstance(response, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_crypto_market_data(self, mock_request): response = self.client.crypto_market_data() self.assertIsInstance(response, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_trade_market_data(self, mock_request): response = self.client.trade_market_data('') self.assertIsInstance(response, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_locate_atms(self, mock_request): response = self.client.locate_atms() self.assertIsInstance(response, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {'public_key_obj':{}}, autospec = True ) def test_issue_pub_key(self, mock_request): # check if obj is dict key = self.client.issue_public_key([]) self.assertIsInstance(key, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = users_resp, autospec = True ) def test_get_users(self, mock_request): # check if obj is Users users = self.client.get_all_users() self.assertIsInstance(users, Users) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = subss_resp, autospec = True ) def test_get_subss(self, mock_request): # check if obj is Subscriptions subss = self.client.get_all_subs() self.assertIsInstance(subss, Subscriptions) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = get_nodes_response, autospec = True ) def test_get_nodes(self, mock_request): # check if obj is Nodes nodes = self.client.get_all_nodes() self.assertIsInstance(nodes, Nodes) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_get_inst(self, mock_request): # check if obj is JSON inst = self.client.get_all_inst() self.assertIsInstance(inst, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_get_node_types(self, mock_request): # check if obj is JSON node_types = self.client.get_node_types() self.assertIsInstance(node_types, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_get_user_document_types(self, mock_request): # check if obj is JSON user_document_types = self.client.get_user_document_types() self.assertIsInstance(user_document_types, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_get_user_entity_types(self, mock_request): # check if obj is JSON user_entity_types = self.client.get_user_entity_types() self.assertIsInstance(user_entity_types, dict) @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value = {}, autospec = True ) def test_get_user_entity_scopes(self, mock_request): # check if obj is JSON user_entity_scopes = self.client.get_user_entity_scopes() self.assertIsInstance(user_entity_scopes, dict) @mock.patch( 'synapsepy.http_client.HttpClient.post', return_value = verified_routing_number, autospec = True ) def test_verify_routing_number(self, mock_request): # check if obj is dictionary routing_num = self.client.verify_routing_number({ "type": 'ACH-US', "routing_num": "084008426" }) self.assertIsInstance(routing_num, dict) @mock.patch( 'synapsepy.http_client.HttpClient.post', return_value = verified_address, autospec = True ) def test_verify_address(self, mock_request): # check if obj is dictionary address = self.client.verify_address({ "address_street": "1 Market St. STE 500", "address_city": "San Francisco", "address_subdivision": "CA", "address_postal_code": "94105", "address_country_code": "US" }) self.assertIsInstance(address, dict) @mock.patch( 'synapsepy.http_client.HttpClient.patch', return_value = {}, autospec = True ) def test_dispute_chargeback(self, mock_request): chargeback = self.client.dispute_chargeback('', {}) self.assertIsInstance(chargeback, dict) if __name__ == '__main__': unittest.main()<file_sep>/synapsepy/tests/fixtures/error_fixtures.py from unittest.mock import Mock from requests.models import Response from requests.exceptions import HTTPError act_pend = Mock(spec=Response) act_pend.raise_for_status.side_effect = HTTPError act_pend.status_code = 202 act_pend.json.return_value = { "error": { "en": "Action Pending" }, "error_code": "10", "http_code": "202", "success": False } inc_cli_cred = Mock(spec=Response) inc_cli_cred.raise_for_status.side_effect = HTTPError inc_cli_cred.status_code = 400 inc_cli_cred.json.return_value = { "error": { "en": "Incorrect Client Credentials" }, "error_code": "100", "http_code": "400", "success": False } inc_user_cred = Mock(spec=Response) inc_user_cred.raise_for_status.side_effect = HTTPError inc_user_cred.status_code = 400 inc_user_cred.json.return_value = { "error": { "en": "Incorrect User Credentials" }, "error_code": "110", "http_code": "400", "success": False } unauth_fing = Mock(spec=Response) unauth_fing.raise_for_status.side_effect = HTTPError unauth_fing.status_code = 400 unauth_fing.json.return_value = { "error": { "en": "Unauthorized Fingerprint" }, "error_code": "120", "http_code": "400", "success": False } payload_err = Mock(spec=Response) payload_err.raise_for_status.side_effect = HTTPError payload_err.status_code = 400 payload_err.json.return_value = { "error": { "en": "Payload Error" }, "error_code": "200", "http_code": "400", "success": False } unauth_act = Mock(spec=Response) unauth_act.raise_for_status.side_effect = HTTPError unauth_act.status_code = 400 unauth_act.json.return_value = { "error": { "en": "Unauthorized Action" }, "error_code": "300", "http_code": "400", "success": False } inc_val = Mock(spec=Response) inc_val.raise_for_status.side_effect = HTTPError inc_val.status_code = 400 inc_val.json.return_value = { "error": { "en": "Incorrect Values" }, "error_code": "400", "http_code": "409", "success": False } obj_not_found = Mock(spec=Response) obj_not_found.raise_for_status.side_effect = HTTPError obj_not_found.status_code = 404 obj_not_found.json.return_value = { "error": { "en": "Object not found" }, "error_code": "404", "http_code": "404", "success": False } act_not_allow = Mock(spec=Response) act_not_allow.raise_for_status.side_effect = HTTPError act_not_allow.status_code = 400 act_not_allow.json.return_value = { "error": { "en": "Action not allowed" }, "error_code": "410", "http_code": "400", "success": False } too_many_req = Mock(spec=Response) too_many_req.raise_for_status.side_effect = HTTPError too_many_req.status_code = 400 too_many_req.json.return_value = { "error": { "en": "Too many requests" }, "error_code": "429", "http_code": "400", "success": False } idem_conf = Mock(spec=Response) idem_conf.raise_for_status.side_effect = HTTPError idem_conf.status_code = 400 idem_conf.json.return_value = { "error": { "en": "Idempotency conflict" }, "error_code": "450", "http_code": "400", "success": False } req_fail = Mock(spec=Response) req_fail.raise_for_status.side_effect = HTTPError req_fail.status_code = 400 req_fail.json.return_value = { "error": { "en": "Request failed" }, "error_code": "460", "http_code": "400", "success": False } serv_error = Mock(spec=Response) serv_error.raise_for_status.side_effect = HTTPError serv_error.status_code = 500 serv_error.json.return_value = { "error": { "en": "Server Error" }, "error_code": "500", "http_code": "500", "success": False } serv_unav = Mock(spec=Response) serv_unav.raise_for_status.side_effect = HTTPError serv_unav.status_code = 503 serv_unav.json.return_value = { "error": { "en": "Service Unavailable" }, "error_code": "503", "http_code": "503", "success": False } <file_sep>/synapsepy/tests/fixtures/subscription_fixtures.py subs_resp = { "_id": "5bfc80397e874a008afaa896", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/subscriptions/5bfc80397e874a008afaa896" } }, "_v": 2, "client_id": "5be38afd6a785e6bddfffe68", "is_active": True, "scope": [ "USERS|POST", "USER|PATCH", "NODES|POST", "NODE|PATCH", "TRANS|POST", "TRAN|PATCH" ], "url": "https://requestb.in/zvgnd0zv" } subss_resp = { "error_code": "0", "http_code": "200", "limit": 20, "page": 1, "page_count": 1, "subscriptions": [ { "_id": "5bfc80397e874a008afaa896", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/subscriptions/5bfc80397e874a008afaa896" } }, "_v": 2, "client_id": "5be38afd6a785e6bddfffe68", "is_active": True, "scope": [ "USERS|POST", "USER|PATCH", "NODES|POST", "NODE|PATCH", "TRANS|POST", "TRAN|PATCH" ], "url": "https://requestb.in/zvgnd0zv" } ], "subscriptions_count": 1, "success": True } webhook_url = "https://requestb.in/zp216zzp" sub_scope = [ "USERS|POST", "USER|PATCH", "NODES|POST", "NODE|PATCH", "TRANS|POST", "TRAN|PATCH" ] bad_scope = [ "USERS|POST", "USER|PATCH", "NODES|POST", "NODE|PATCH", "TRANS|POST", "TRAN|PATCH" ]<file_sep>/synapsepy/http_client.py import json import logging import requests import http.client as http_client from . import errors as api_errors class HttpClient(): """Handles HTTP requests (including headers) and API errors. """ def __init__(self, client_id, client_secret, fingerprint, ip_address, base_url, logging): self.client_id = client_id self.client_secret = client_secret self.fingerprint = fingerprint self.ip_address = ip_address self.base_url = base_url self.oauth_key = '' self.idempotency_key = None self.session = requests.Session() self.logger = self.get_log(logging) self.update_headers() def update_headers(self, **kwargs): """Update the supplied properties on self and in the header dictionary. """ self.logger.debug("updating headers") for header in kwargs.keys(): if kwargs.get(header) is not None: setattr(self, header, kwargs.get(header)) self.session.headers.update( { 'Content-Type': 'application/json', 'X-SP-LANG': 'en', 'X-SP-GATEWAY': self.client_id + '|' + self.client_secret, 'X-SP-USER': self.oauth_key + '|' + self.fingerprint, 'X-SP-USER-IP': self.ip_address } ) self.logger.debug(json.dumps(self.session.headers.__dict__, indent=2)) if self.idempotency_key: self.session.headers['X-SP-IDEMPOTENCY-KEY'] = self.idempotency_key return self.session.headers def get_headers(self): self.logger.debug("getting headers") return self.session.headers def get(self, path, **params): """Send a GET request to the API.""" url = self.base_url + path self.logger.debug("GET {}".format(url)) valid_params = [ 'query', 'page', 'per_page', 'type', 'is_credit', 'issue_public_key', 'show_refresh_tokens', 'subnet_id', 'subnetid', 'foreign_transaction', 'full_dehydrate', 'force_refresh', 'limit', 'ticker', 'currency', 'radius', 'scope', 'lat', 'lon', 'zip', 'filter', 'user_id' ] parameters = {} for param in valid_params: if params.get(param) is not None: parameters[param] = params[param] response = self.session.get(url, params=parameters) return self.parse_response(response) def post(self, path, payload, **kwargs): """Send a POST request to the API.""" url = self.base_url + path self.logger.debug("POST {}".format(url)) data = json.dumps(payload) if kwargs.get('idempotency_key') is not None: self.update_headers(idempotency_key=kwargs['idempotency_key']) response = self.session.post(url, data=data) return self.parse_response(response) def patch(self, path, payload, **params): """Send a PATCH request to the API.""" url = self.base_url + path self.logger.debug("PATCH {}".format(url)) parameters = {} valid_params = [ 'resend_micro', 'ship', 'reset' ] for param in valid_params: if params.get(param) is not None: parameters[param] = params[param] self.logger.debug("Params {}".format(parameters)) data = json.dumps(payload) response = self.session.patch(url, data=data, params=parameters) return self.parse_response(response) def delete(self, path): """Send a DELETE request to the API.""" url = self.base_url + path self.logger.debug("PATCH {}".format(url)) response = self.session.delete(url) return self.parse_response(response) def parse_response(self, response): """Convert successful response to dict or raise error.""" try: payload = response.json() except Exception as e: raise api_errors.GatewayTimeout(message="Request returned a non-JSON response due to a network timeout.", http_code=504, error_code="504", response=False) try: response.raise_for_status() except requests.exceptions.RequestException as e: raise api_errors.ErrorFactory.from_response(payload) from e if payload.get('error') and int(payload.get('error_code', 0)) == 10: # checks for unregistered fingerprint raise api_errors.ErrorFactory.from_response(payload) return response.json() def get_log(self, enable, debuglevel=1): """Log requests to stdout.""" # http_client.HTTPConnection.debuglevel = 1 if enable else 0 logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.disabled = not enable return logger <file_sep>/README.md # SynapseFI Python Library [![PyPI](https://img.shields.io/pypi/v/synapsepy.svg)](https://pypi.org/project/synapsepy/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/synapsepy.svg)](https://pypi.org/project/synapsepy/) [![PyPI - Status](https://img.shields.io/pypi/status/synapsepy.svg)](https://pypi.org/project/synapsepy/) Python wrapper for SynapseFI API ## Code Example Refer to [samples.md](samples.md) and our [API documentation](https://docs.synapsefi.com/) for examples. ## Installation ```bash $ pip install synapsepy ``` Clone repo ```bash $ git clone https://github.com/SynapseFI/SynapsePy.git ``` Install requirements ```bash $ cd SynapsePy $ pip install -r requirements.txt ``` ## USAGE ##### Import ```python import synapsepy ``` ## Development ### Package Deployment ##### 1. Install Requirements ```bash $ pip install twine ``` ##### 2. Setup Source Distribution Update version number in [setup.py](setup.py): ```python setup( name='synapsepy', ... version='0.0.15' # NEW VERSION NUMBER GOES HERE ... ) ``` Create the source distribution by running [setup.py](setup.py) using the following command: ```bash $ python setup.py sdist ``` ##### 3. Upload Distribution Replace `{{VERSION NUMBER}}` with the new version number in the following command then run: ```bash $ twine upload dist/synapsepy-{{VERSION NUMBER}}.tar.gz ``` ### Testing Run the following command from the root package directory ```bash $ python -m unittest discover -s synapsepy.tests -p '*tests.py' ``` <file_sep>/synapsepy/tests/fixtures/user_fixtures.py simple_user = { "logins": [ { "email": "<EMAIL>" } ], "phone_numbers": [ "901.111.1111" ], "legal_names": [ "<NAME>" ], "extra": { "supp_id": "my_user_id", "cip_tag":1, "is_business": False } } simple_response = { "_id": "4qnfFH98Ff390HYasd4fqftkk3", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/4qnfFH98Ff390HYasd4fqftkk3" } }, "client": { "id": "12351346161345", "name": "<NAME>" }, "doc_status": { "physical_doc": "MISSING|INVALID", "virtual_doc": "MISSING|INVALID" }, "documents": [], "emails": [], "extra": { "cip_tag": 1, "date_joined": 1544757747072, "extra_security": False, "is_business": False, "last_updated": 1544757747072, "public_note": None, "supp_id": "my_user_id" }, "is_hidden": False, "legal_names": [ "<NAME>" ], "logins": [ { "email": "<EMAIL>", "scope": "READ_AND_WRITE" } ], "permission": "UNVERIFIED", "phone_numbers": [ "901.111.1111" ], "photos": [], "refresh_token": "<PASSWORD>" } basedocs_user = { "logins": [ { "email": "<EMAIL>" } ], "phone_numbers": [ "901.111.1111" ], "legal_names": [ "<NAME>" ], "documents":[{ "email":"<EMAIL>", "phone_number":"901.111.1111", "ip":"::1", "name":"<NAME>", "alias":"Test", "entity_type":"M", "entity_scope":"Arts & Entertainment", "day":2, "month":5, "year":1989, "address_street":"1 Market St.", "address_city":"San Francisco", "address_subdivision":"CA", "address_postal_code":"94114", "address_country_code":"US", "virtual_docs":[{ "document_value":"111-111-2222", "document_type":"SSN" }], "physical_docs":[{ "document_value": "data:image/gif;base64,SUQs==", "document_type": "GOVT_ID" }], "social_docs":[{ "document_value":"https://www.facebook.com/valid", "document_type":"FACEBOOK" }] }], "extra": { "supp_id": "my_user_id", "cip_tag":1, "is_business": False } } users_resp = { "error_code": "0", "http_code": "200", "limit": 20, "page": 1, "page_count": 1, "success": True, "users": [ { "_id": "5c1323875596f200c41149dc", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c1323875596f200c41149dc" } }, "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "doc_status": { "physical_doc": "MISSING|INVALID", "virtual_doc": "MISSING|INVALID" }, "documents": [], "emails": [], "extra": { "cip_tag": 1, "date_joined": 1544758151570, "extra_security": False, "is_business": False, "last_updated": 1544758151570, "public_note": None, "supp_id": "my_user_id" }, "is_hidden": False, "legal_names": [ "<NAME>" ], "logins": [ { "email": "<EMAIL>", "scope": "READ_AND_WRITE" } ], "permission": "UNVERIFIED", "phone_numbers": [ "901.111.1111" ], "photos": [], "refresh_token": "<KEY>" }, { "_id": "5c1321f35596f200c616db1b", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c1321f35596f200c616db1b" } }, "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "doc_status": { "physical_doc": "MISSING|INVALID", "virtual_doc": "MISSING|INVALID" }, "documents": [], "emails": [], "extra": { "cip_tag": 1, "date_joined": 1544757747072, "extra_security": False, "is_business": False, "last_updated": 1544757747072, "public_note": None, "supp_id": "my_user_id" }, "is_hidden": False, "legal_names": [ "<NAME>" ], "logins": [ { "email": "<EMAIL>", "scope": "READ_AND_WRITE" } ], "permission": "UNVERIFIED", "phone_numbers": [ "901.111.1111" ], "photos": [], "refresh_token": "refresh_<PASSWORD>" } ], "users_count": 2 }<file_sep>/synapsepy/subscription.py class Subscription(): def __init__(self, response): self.id = response['_id'] self.url = response['url'] self.body = response class Subscriptions(): def __init__(self, response): self.page = response['page'] self.page_count = response['page_count'] self.limit = response['limit'] self.subscriptions_count = response['subscriptions_count'] self.list_of_subs = [ Subscription(sub_r) for sub_r in response['subscriptions']]<file_sep>/synapsepy/tests/fixtures/node_fixtures.py card_us_payload = { "type": "CARD-US", "info": { "nickname":"My Debit Card", "document_id":"2a4a5957a3a62aaac1a0dd0edcae96ea2cdee688ec6337b20745eed8869e3ac8" } } card_us_get_response = { "_id": "5c0af4e64f98b000bc81c6fd", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0af4e64f98b000bc81c6fd" } }, "allowed": "INACTIVE", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": { "access_token": "5c0af4eac3c43d7a63b1bc77" }, "supp_id": "" }, "info": { "balance": { "amount": 0, "currency": "USD" }, "card_hash": "0ce83962ea95688a3801c302b31c18cbd71d992ab050b6f32468fc280b31ce31", "card_number": "6340", "card_style_id": None, "document_id": "2a4a5957a3a62aaac1a0dd0edcae96ea2cdee688ec6337b20745eed8869e3ac8", "name_on_account": " ", "nickname": "My Debit Card", "preferences": { "allow_foreign_transactions": False, "atm_withdrawal_limit": 100, "pos_withdrawal_limit": 1000 } }, "is_active": True, "timeline": [ { "date": 1544221925385, "note": "Node created." }, { "date": 1544221937791, "note": "Card Created." } ], "type": "CARD-US", "user_id": "5c0abeb9970f8426abc8df67" } card_us_up_response = { "_id": "5c0af4e64f98b000bc81c6fd", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9<PASSWORD>426abc8df67/nodes/5c0af4e64f98b000bc81c6fd" } }, "allowed": "CREDIT-AND-DEBIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": { "access_token": "5c0af4eac3c43d7a63b1bc77" }, "supp_id": "" }, "info": { "balance": { "amount": 0, "currency": "USD" }, "card_hash": "0ce83962ea95688a3801c302b31c18cbd71d992ab050b6f32468fc280b31ce31", "card_number": "6340", "card_style_id": None, "document_id": "2a4a5957a3a62aaac1a0dd0edcae96ea2cdee688ec6337b20745eed8869e3ac8", "name_on_account": " ", "nickname": "My Debit Card", "preferences": { "allow_foreign_transactions": False, "atm_withdrawal_limit": 100, "pos_withdrawal_limit": 1000 } }, "is_active": True, "timeline": [ { "date": 1544221925385, "note": "Node created." }, { "date": 1544221937791, "note": "Card Created." } ], "type": "CARD-US", "user_id": "<KEY>" } get_nodes_response = { "error_code": "0", "http_code": "200", "limit": 20, "node_count": 3, "nodes": [ { "_id": "5c0b0ff74f98b000bd81f4af", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/<KEY>/nodes/5c0b0ff74f98b000bd81f4af" } }, "allowed": "CREDIT-AND-DEBIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": {}, "supp_id": "" }, "info": { "balance": { "amount": 0, "currency": "USD" }, "document_id": None, "name_on_account": " ", "nickname": "My Deposit Account" }, "is_active": True, "timeline": [ { "date": 1544228854825, "note": "Node created." } ], "type": "DEPOSIT-US", "user_id": "5c0abeb9<PASSWORD>26abc<PASSWORD>7" }, { "_id": "5c0b0cfd1cfe2300a0fe490f", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9<PASSWORD>6abc<PASSWORD>7/nodes/5c0b0cfd1cfe2300a0fe490f" } }, "allowed": "CREDIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": { "access_token": None, "updated_on": None }, "supp_id": "" }, "info": { "account_num": "2134", "address": "8001 VILLA PARK DRIVE, HENRICO, VA, US", "balance": { "amount": "0.00", "currency": "USD" }, "bank_logo": "https://cdn.synapsepay.com/bank_logos/new/bofa.png", "bank_long_name": "BANK OF AMERICA", "bank_name": "BANK OF AMERICA", "class": "CHECKING", "match_info": { "email_match": "not_found", "name_match": "not_found", "phonenumber_match": "not_found" }, "name_on_account": " ", "nickname": "Fake Account", "routing_num": "0017", "type": "PERSONAL" }, "is_active": True, "timeline": [ { "date": 1544228093046, "note": "Node created." }, { "date": 1544228096991, "note": "Micro deposits initiated." } ], "type": "ACH-US", "user_id": "5c0abeb9970f8426abc8df67" }, { "_id": "5c0af4e64f98b000bc81c6fd", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0af4e64f98b000bc81c6fd" } }, "allowed": "CREDIT-AND-DEBIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": { "access_token": "5c0af4eac3c43d7a63b1bc77" }, "supp_id": "" }, "info": { "balance": { "amount": 0, "currency": "USD" }, "card_hash": "0ce83962ea95688a3801c302b31c18cbd71d992ab050b6f32468fc280b31ce31", "card_style_id": None, "document_id": "2a4a5957a3a62aaac1a0dd0edcae96ea2cdee688ec6337b20745eed8869e3ac8", "name_on_account": " ", "nickname": "My Debit Card", "preferences": { "allow_foreign_transactions": False, "atm_withdrawal_limit": 100, "pos_withdrawal_limit": 1000 } }, "is_active": True, "timeline": [ { "date": 1544221925385, "note": "Node created." }, { "date": 1544221937791, "note": "Card Created." } ], "type": "CARD-US", "user_id": "5c0abeb9970f8426abc8df67" } ], "page": 1, "page_count": 1, "success": True } ach_mfa_resp = { "error_code": "10", "http_code": "202", "mfa": { "access_token": "fake_cd60680b9addc013ca7fb25b2b704be324d0295b34a6e3d14473e3cc65aa82d3", "message": "I heard you like questions so we put a question in your question?", "type": "question" }, "success": True } """ Everything below is technically unused or can be mocked """ ach_us_logins = { "type": "ACH-US", "info":{ "bank_id":"synapse_good", "bank_pw":"test1234", "bank_name":"fake" } } ach_us_acrt = { "type": "ACH-US", "info": { "nickname": "Fake Account", "account_num": "1232225674134", "routing_num": "051000017", "type": "PERSONAL", "class": "CHECKING" } } ach_us_payload = { "type": "ACH-US", "info": { "nickname": "Fake Account", "account_num": "12322134", "routing_num": "051000017", "type": "PERSONAL", "class": "CHECKING" } } ach_us_get_response = { "_id": "5c0b0cfd1cfe2300a0fe490f", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0b0cfd1cfe2300a0fe490f" } }, "allowed": "CREDIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": { "access_token": None, "updated_on": None }, "supp_id": "" }, "info": { "account_num": "2134", "address": "8001 VILLA PARK DRIVE, HENRICO, VA, US", "balance": { "amount": "0.00", "currency": "USD" }, "bank_logo": "https://cdn.synapsepay.com/bank_logos/new/bofa.png", "bank_long_name": "BANK OF AMERICA", "bank_name": "BANK OF AMERICA", "class": "CHECKING", "match_info": { "email_match": "not_found", "name_match": "not_found", "phonenumber_match": "not_found" }, "name_on_account": " ", "nickname": "Fake Account", "routing_num": "0017", "type": "PERSONAL" }, "is_active": True, "timeline": [ { "date": 1544228093046, "note": "Node created." }, { "date": 1544228096991, "note": "Micro deposits initiated." } ], "type": "ACH-US", "user_id": "5c0abeb<PASSWORD>abc<PASSWORD>" } debit_us_payload = { "type": "DEPOSIT-US", "info": { "nickname":"My Deposit Account" } } debit_us_get_response = { "_id": "5c0b0ff74f98b000bd81f4af", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5<PASSWORD>df67/nodes/5c0b0ff74f98b000bd81f4af" } }, "allowed": "CREDIT-AND-DEBIT", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "test user" }, "extra": { "note": None, "other": {}, "supp_id": "" }, "info": { "balance": { "amount": 0, "currency": "USD" }, "document_id": None, "name_on_account": " ", "nickname": "My Deposit Account" }, "is_active": True, "timeline": [ { "date": 1544228854825, "note": "Node created." } ], "type": "DEPOSIT-US", "user_id": "5c0abeb9970f8426abc8df67" } <file_sep>/synapsepy/tests/error_tests.py import unittest from ..client import Client from .. import errors as api_errors from .fixtures.error_fixtures import * class ErrorTests(unittest.TestCase): def setUp(self): self.client = Client( client_id='', client_secret='', fingerprint='', ip_address='', devmode=True, logging=False ) self.http = self.client.http def test_act_pend(self): self.assertRaises(api_errors.ActionPending, self.http.parse_response, act_pend) def test_inc_cli_cred(self): self.assertRaises(api_errors.IncorrectClientCredentials, self.http.parse_response, inc_cli_cred) def test_inc_user_cred(self): self.assertRaises(api_errors.IncorrectUserCredentials, self.http.parse_response, inc_user_cred) def test_unauth_fing(self): self.assertRaises(api_errors.UnauthorizedFingerprint, self.http.parse_response, unauth_fing) def test_payload_err(self): self.assertRaises(api_errors.PayloadError, self.http.parse_response, payload_err) def test_unauth_act(self): self.assertRaises(api_errors.UnauthorizedAction, self.http.parse_response, unauth_act) def test_inc_val(self): self.assertRaises(api_errors.IncorrectValues, self.http.parse_response, inc_val) def test_obj_not_found(self): self.assertRaises(api_errors.ObjectNotFound, self.http.parse_response, obj_not_found) def test_act_not_allow(self): self.assertRaises(api_errors.ActionNotAllowed, self.http.parse_response, act_not_allow) def test_too_many_req(self): self.assertRaises(api_errors.TooManyRequests, self.http.parse_response, too_many_req) def test_idem_conf(self): self.assertRaises(api_errors.IdempotencyConflict, self.http.parse_response, idem_conf) def test_req_fail(self): self.assertRaises(api_errors.RequestFailed, self.http.parse_response, req_fail) def test_serv_error(self): self.assertRaises(api_errors.ServerError, self.http.parse_response, serv_error) def test_serv_unav(self): self.assertRaises(api_errors.ServiceUnavailable, self.http.parse_response, serv_unav) if __name__ == '__main__': unittest.main()<file_sep>/synapsepy/client.py from .http_client import HttpClient from .user import User, Users from .node import Node, Nodes from .transaction import Trans, Transactions from .subscription import Subscription, Subscriptions from . import errors as api_errors from .endpoints import paths import sys import json import logging import requests class Client(): """ Client Record """ def __init__(self, client_id, client_secret, fingerprint, ip_address, devmode=False, logging=False): """ Args: client_id (str): API client id client_secret (str): API client secret fingerprint (str): device fingerprint ip_address (str): user IP address devmode (bool): (opt) switches between sandbox and production base url logging (bool): (opt) enables logger """ self.client_id = client_id self.client_secret = client_secret self.http = HttpClient( client_id=client_id, client_secret=client_secret, fingerprint=fingerprint, ip_address=ip_address, base_url= 'https://uat-api.synapsefi.com/v3.1' if devmode else 'https://api.synapsefi.com/v3.1', logging=logging ) self.logging = logging self.logger = self.get_log(logging) def update_headers(self, client_secret=None, fingerprint=None, ip_address=None, oauth_key=None, idempotency_key=None): '''Updates session headers Args: client_secret (str): (opt) API client secret fingerprint (str): (opt) device fingerprint ip_address (str): (opt) user IP address idempotency_key (str): (opt) idempotency key for safely retrying requests ''' self.http.update_headers( client_secret=client_secret, fingerprint=fingerprint, ip_address=ip_address, oauth_key=oauth_key, idempotency_key=idempotency_key ) def get_log(self, enable): '''Enables/Disables logs Args: enable (bool): enables if True, disables if False Returns: Logger: logging.Logger object used to debug ''' logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.disabled = not enable return logger def create_user(self, body, ip, fingerprint=None, idempotency_key=None): """Creates a User object containing a user's record Args: body (dict): user record ip (str): IP address of the user to create fingerprint (str) (opt): device fingerprint of the user idempotency_key (str): (opt) idempotency key for safely retrying requests Returns: user (User): object containing User record """ self.logger.debug("Creating a new user") path = paths['users'] if fingerprint: self.update_headers(fingerprint=fingerprint) self.update_headers(ip_address=ip) response = self.http.post( path, body, idempotency_key=idempotency_key ) return User(response, self.http, full_dehydrate=False, logging=self.logging) def get_user(self, user_id, ip=None, fingerprint=None, full_dehydrate=False): """Returns User object grabbed from API Args: user_id (str): identification for user ip (str) (opt): IP address of the user to create fingerprint (str) (opt): device fingerprint of the user full_dehydrate (bool) (opt): Full Dehydrate True will return back user's KYC info. Returns: user (User): object containing User record """ self.logger.debug("getting a user") if ip: self.update_headers(ip_address=ip) if fingerprint: self.update_headers(fingerprint=fingerprint) path = paths['users'] + '/' + user_id full_d = 'yes' if full_dehydrate else None response = self.http.get(path, full_dehydrate=full_d) return User(response, self.http, full_dehydrate=full_d, logging=self.logging) def create_subscription(self, webhook_url, scope, idempotency_key=None): '''Creates a webhook Args: webhook_url (str): subscription url scope (list of str): API call types to subscribe to Returns: dict: dictionary object containing json response ''' self.logger.debug("Creating a new subscription") path = paths['subs'] body = { 'scope': scope, 'url': webhook_url } response = self.http.post( path, body, idempotency_key=idempotency_key ) return Subscription(response) def get_subscription(self, sub_id): '''Returns Subscription object of webhook Args: sub_id (Str): subscription id Returns: Subscription Object ''' self.logger.debug("getting a subscription") path = paths['subs'] + '/' + sub_id response = self.http.get(path) return Subscription(response) def update_subscription(self, sub_id, body, idempotency_key=None): '''Updates a webhook Args: sub_id (str): subscription id body (JSON): update body Returns: (Subscription): object containing subscription record ''' self.logger.debug("updating subscription") path = paths['subs'] + '/' + sub_id response = self.http.patch(path, body) return Subscription(response) def webhook_logs(self): '''Returns all of the webhooks sent by SynapseFi ''' headers = self.http.get_headers() content_type = headers.pop('Content-Type') path = paths['subs'] + paths['logs'] response = self.http.get(path) headers['Content-Type'] = content_type return response def crypto_quotes(self): '''Gets quotes for crypto currencies Returns: dict: dictionary containing crypto quotes ''' path = paths['nodes'] + paths['cryptoq'] response = self.http.get(path) return response def crypto_market_data(self, limit=None, currency=None): '''Returns current market data for a particular crytpo-currency Args: limit (int): (opt) Number of days from today currency (str): (opt) crypto-currency to grab market data for Returns: dict: dictionary containing market data for crypto-currency ''' path = paths['nodes'] + paths['cryptom'] response = self.http.get( path, limit=limit, currency=currency ) return response def trade_market_data(self, ticker): '''Returns current market data for a particular crytpo-currency Args: limit (int): (opt) Number of days from today currency (str): (opt) crypto-currency to grab market data for Returns: dict: dictionary containing market data for crypto-currency ''' path = paths['nodes'] + paths['trade'] response = self.http.get( path, ticker=ticker ) return response def locate_atms(self, zip=None, lat=None, lon=None, rad=None, page=None, per_page=None): '''Returns atms closest to a particular coordinate Args: zip (str): (opt) Zip code for ATM locator lat (str): (opt) Latitude of the pin lon (str): (opt) Longitude of the pin radius (str): (opt) radius in miles page (int): (opt) Page number per_page (str): (opt) Number of Nodes per page Returns: dict: dictionary containing closest atms ''' path = paths['nodes'] + paths['atms'] response = self.http.get( path, zip=zip, lat=lat, lon=lon, radius=rad, page=page, per_page=per_page ) return response def issue_public_key(self, scope, user_id=None): '''Issues a public key for use with a UIaaS product Args: scope (list of str): Scopes that you wish to issue the public keys for Returns: dict: dictionary containing public key info ''' self.logger.debug("issuing a public key") path = paths['client'] if user_id: response = self.http.get( path, issue_public_key='YES', scope=scope, user_id=user_id ) else: response = self.http.get( path, issue_public_key='YES', scope=scope ) return response['public_key_obj'] def get_all_users(self, query=None, page=None, per_page=None, show_refresh_tokens=None): """Returns all user objects in a list Args: query (string): (opt) Name/Email of the user that you wish to search page (int): (opt) Page number per_page (int): (opt) How many users do you want us to return per page. show_refresh_tokens (bool): (opt) [yes/no] When dehydrating if the user object should have refresh tokens or not. Returns: (Users): object containing pagination info and list of User objects """ self.logger.debug("getting all users") path = paths['users'] response = self.http.get( path, query=query, page=page, per_page=per_page, show_refresh_tokens=show_refresh_tokens ) return Users(response, self.http) def get_all_trans(self, page=None, per_page=None): '''Gets all client transactions Args: page (int): (opt) Page number per_page (int): (opt) How many trans do you want us to return per page. Returns: (Transactions): object containing pagination info and list of Transaction objects ''' self.logger.debug("getting all transactions") path = paths['trans'] response = self.http.get( path, page=page, per_page=per_page ) return Transactions(response) def get_all_nodes(self, page=None, per_page=None, type=None): '''Gets all client nodes Args: page (int): (opt) Page number per_page (int): (opt) How many nodes do you want us to return per page. type (bool): (opt) Type of nodes you wish to see. (NOTE: deprecated in v3.2) Returns: (Nodes): object containing pagination info and list of Node objects ''' self.logger.debug("getting all nodes") path = paths['nodes'] response = self.http.get( path, page=page, per_page=per_page, type=type ) return Nodes(response) def get_all_subs(self, page=None, per_page=None): '''Gets all client webhooks Args: page (int): (opt) Page number per_page (int): (opt) How many subs do you want us to return per page. Returns: (Subscriptions): object containing pagination info and list of Subscription objects ''' self.logger.debug("getting all subscriptions") path = paths['subs'] response = self.http.get( path, page=page, per_page=per_page ) return Subscriptions(response) def get_all_inst(self): '''Gets all institutions Returns: dict: dictionary containing institutions ''' self.logger.debug("getting all institutions") path = paths['inst'] response = self.http.get(path) return response def dispute_chargeback(self, transaction_id, body): '''Dispute a transaction chargeback https://docs.synapsefi.com/api-references/transactions/dispute-chargebacks Only INTERCHANGE-US transactions that have been RETURNED within the last 14 days with return code of IR999 can be disputed. If dispute is won, the transaction will go back to SETTLED status. We recommend subscribing to our webhooks(https://docs.synapsefi.com/api-references/subscriptions)} to be notified. Args: trans_id (string): Unique ID for transaction body (JSON): Array of supporting docs converted into base 64 encoded strings Returns: (Transaction): a transaction object with an updated transaction.extra.other.chargeback_disputed field. Returns: dict: dictionary containing institutions ''' self.logger.debug("disputing chargeback") path = paths['trans'] + '/' + transaction_id + paths['chargeback'] response = self.http.patch(path, body) return response def verify_address(self, body): '''Verify address of a document owner https://docs.synapsefi.com/api-references/miscellaneous/verify-address ''' self.logger.debug("verifying address") path = paths['verifyadd'] response = self.http.post(path, body) return response def verify_routing_number(self, body): '''Verify routing numbers https://docs.synapsefi.com/api-references/miscellaneous/verify-routing-number ''' self.logger.debug("verify routing numbers") path = paths['routnumver'] response = self.http.post(path, body) return response def get_node_types(self): '''Fetches allowed node types https://docs.synapsefi.com/api-references/nodes/allowed-node-types returns: array: list of allowed node types ''' self.logger.debug("getting node types") path = paths['nodes'] + paths['types'] response = self.http.get(path) return response def get_user_document_types(self): '''Fetches allowed user document types https://docs.synapsefi.com/api-references/users/allowed-document-types returns: array: list of allowed user document types ''' self.logger.debug("getting user document types") path = paths['users'] + paths['doctypes'] response = self.http.get(path) return response def get_user_entity_types(self): '''Fetches allowed user entity types https://docs.synapsefi.com/api-references/users/allowed-entity-types returns: array: list of allowed user entity types ''' self.logger.debug("getting user entity types") path = paths['users'] + paths['entypes'] response = self.http.get(path) return response def get_user_entity_scopes(self): '''Fetches allowed user entity scopes https://docs.synapsefi.com/api-references/users/allowed-entity-scopes returns: array: list of allowed user entity scopes ''' self.logger.debug("getting user entity scopes") path = paths['users'] + paths['enscopes'] response = self.http.get(path) return response <file_sep>/synapsepy/tests/user_tests.py import unittest import warnings from unittest import TestCase, mock from .fixtures.user_fixtures import * from .fixtures.node_fixtures import * from .fixtures.trans_fixtures import * from .fixtures.subnet_fixtures import * from ..client import Client from ..user import User from ..node import Node, Nodes from ..transaction import Trans, Transactions from ..subnet import Subnet, Subnets from ..http_client import HttpClient @mock.patch( 'synapsepy.user.User._do_request', return_value={}, autospec=True ) class UserTests(TestCase): ''' TODO: need to add path/endpoint tests test all user methods ''' def setUp(self): self.client = Client( client_id='', client_secret='', fingerprint='', ip_address='', devmode=True, logging=False ) self.user = User(simple_response, self.client.http) self.card_us_id = card_us_get_response['_id'] self.card_us_type = card_us_get_response['type'] self.trans_id = trans_get_response['_id'] self.ach_us_id = ach_us_get_response['_id'] self.debit_us_id = debit_us_get_response['_id'] self.subnet_id = subnet_get_resp['_id'] self.nodes_page = get_nodes_response['page'] self.nodes_page_count = get_nodes_response['page_count'] self.nodes_limit = get_nodes_response['limit'] self.nodes_node_count = get_nodes_response['node_count'] self.node_trans_page = get_all_trans_resp['page'] self.node_trans_page_count = get_all_trans_resp['page_count'] self.node_trans_limit = get_all_trans_resp['limit'] self.node_trans_count = get_all_trans_resp['trans_count'] @mock.patch( 'synapsepy.http_client.HttpClient.get', return_value={'refresh_token':'1234'}, autospec=True ) def test_refresh(self, mock_get, mock_request): self.assertEqual( self.user.refresh(), mock_get.return_value['refresh_token'] ) @mock.patch( 'synapsepy.http_client.HttpClient.post', return_value={'oauth_key':'1234'}, autospec=True ) def test_oauth(self, mock_post, mock_request): self.assertEqual( self.user.oauth(), mock_post.return_value ) def test_update_info(self, mock_request): self.assertIsInstance( self.user.update_info({}), dict ) def test_create_node(self, mock_request): mock_request.return_value = get_nodes_response self.assertIsInstance( self.user.create_node(card_us_payload), Nodes ) mock_request.return_value = ach_mfa_resp self.assertIsInstance( self.user.create_node(ach_us_logins), dict ) def test_get_node(self, mock_request): mock_request.return_value = card_us_get_response test_node = self.user.get_node(self.card_us_id) self.assertIsInstance(test_node, Node) self.assertEqual(test_node.id, self.card_us_id) self.assertEqual(test_node.type, self.card_us_type) self.assertEqual( test_node.body, card_us_get_response ) def test_get_node_statements(self, mock_request): statem = self.user.get_node_statements('') self.assertIsInstance(statem, dict) def test_update_node(self, mock_request): mock_request.return_value = card_us_up_response test_node = self.user.update_node( self.card_us_id, {} ) self.assertIsInstance(test_node, Node) self.assertEqual(test_node.id, self.card_us_id) self.assertEqual(test_node.type, self.card_us_type) self.assertNotEqual( test_node.body, card_us_get_response ) self.assertEqual( test_node.body, card_us_up_response ) def test_ach_mfa(self, mock_request): mock_request.return_value = get_nodes_response self.assertIsInstance(self.user.ach_mfa({}), Nodes) mock_request.return_value = ach_mfa_resp self.assertIsInstance( self.user.ach_mfa({}), dict ) def test_verify_micro(self, mock_request): mock_request.return_value = ach_us_get_response self.assertIsInstance( self.user.verify_micro(self.ach_us_id,{}), Node ) def test_reinit_micro(self, mock_request): self.assertEqual( self.user.reinit_micro(self.ach_us_id), mock_request.return_value ) def test_ship_card_node(self, mock_request): warnings.simplefilter("ignore") self.assertEqual( self.user.ship_card_node(self.card_us_id, {}), mock_request.return_value ) def test_reset_card_node(self, mock_request): warnings.simplefilter("ignore") self.assertEqual( self.user.reset_card_node(self.debit_us_id), mock_request.return_value ) def test_generate_apple_pay(self, mock_request): self.assertEqual( self.user.generate_apple_pay( self.card_us_id, {} ), mock_request.return_value ) def test_dummy_tran(self, mock_request): self.assertEqual( self.user.dummy_tran(self.card_us_id), mock_request.return_value ) def test_delete_node(self, mock_request): self.assertEqual( self.user.delete_node(self.card_us_id), mock_request.return_value ) def test_create_trans(self, mock_request): mock_request.return_value = trans_get_response test_trans = self.user.create_trans( self.card_us_id, {} ) self.assertIsInstance(test_trans, Trans) self.assertEqual(test_trans.id, self.trans_id) self.assertEqual( test_trans.body, trans_get_response ) def test_get_trans(self, mock_request): mock_request.return_value = trans_get_response test_trans = self.user.get_trans( self.card_us_id, self.trans_id ) self.assertIsInstance(test_trans, Trans) self.assertEqual(test_trans.id, self.trans_id) self.assertEqual( test_trans.body, trans_get_response ) def test_comment_trans(self, mock_request): self.assertEqual( self.user.comment_trans( self.card_us_id, self.trans_id, '' ), mock_request.return_value ) def test_cancel_trans(self, mock_request): self.assertEqual( self.user.cancel_trans( self.card_us_id, self.trans_id ), mock_request.return_value ) def test_create_subnet(self, mock_request): mock_request.return_value = subnet_get_resp test_subnet = self.user.create_subnet( '', {} ) self.assertIsInstance(test_subnet, Subnet) def test_get_subnet(self, mock_request): mock_request.return_value = subnet_get_resp test_subnet = self.user.get_subnet('', '') self.assertIsInstance(test_subnet, Subnet) def test_update_subnet(self, mock_request): mock_request.return_value = subnet_get_resp test_subnet = self.user.update_subnet('','',{}) self.assertIsInstance(test_subnet, Subnet) def test_ship_card(self, mock_request): test_response = self.user.ship_card('','',{}) self.assertEqual(test_response, {}) def test_get_all_nodes(self, mock_request): mock_request.return_value = get_nodes_response test_nodes = self.user.get_all_nodes() self.assertIsInstance(test_nodes, Nodes) self.assertEqual(test_nodes.page, self.nodes_page) self.assertEqual( test_nodes.page_count, self.nodes_page_count ) self.assertEqual(test_nodes.limit, self.nodes_limit) self.assertEqual( test_nodes.node_count, self.nodes_node_count ) for node in test_nodes.list_of_nodes: self.assertIsInstance(node, Node) def test_get_all_node_trans(self, mock_request): mock_request.return_value = get_all_trans_resp test_node_trans = self.user.get_all_node_trans('') self.assertIsInstance(test_node_trans, Transactions) self.assertEqual( test_node_trans.page, self.node_trans_page ) self.assertEqual( test_node_trans.page_count, self.node_trans_page_count ) self.assertEqual( test_node_trans.limit, self.node_trans_limit ) self.assertEqual( test_node_trans.trans_count, self.node_trans_count ) for trans in test_node_trans.list_of_trans: self.assertIsInstance(trans, Trans) def test_get_all_trans(self, mock_request): mock_request.return_value = get_all_trans_resp test_node_trans = self.user.get_all_trans() self.assertIsInstance(test_node_trans, Transactions) def test_get_all_subnets(self, mock_request): mock_request.return_value = subnet_get_all_resp test_get_all_subn = self.user.get_all_subnets('') self.assertIsInstance(test_get_all_subn, Subnets) def test_get_statements(self, mock_request): statem = self.user.get_statements() self.assertIsInstance(statem, dict) if __name__ == '__main__': unittest.main() <file_sep>/synapsepy/errors.py """Custom errors for handling HTTP and API errors.""" class SynapseError(Exception): """Custom class for handling HTTP and API errors.""" def __init__(self, message, http_code, error_code, response): self.message = message self.http_code = http_code self.error_code = error_code self.response = response super(SynapseError, self).__init__(message) def __repr__(self): return '{0}(code={1},message={2})'.format(self.__class__, self.error_code, self.message) class ActionPending(SynapseError): """ raised on ERROR_CODE 10 Accepted, but action pending """ pass class IncorrectClientCredentials(SynapseError): """ raised on ERROR_CODE 100 Incorrect Client Credentials """ pass class IncorrectUserCredentials(SynapseError): """ raised on ERROR_CODE 110 Incorrect User Credentials """ pass class UnauthorizedFingerprint(SynapseError): """ raised on ERROR_CODE 120 Unauthorized Fingerprint """ pass class PayloadError(SynapseError): """ raised on ERROR_CODE 200 Error in Payload (Error in payload formatting) Supplied address is invalid / Unable to verify address """ pass class UnauthorizedAction(SynapseError): """ raised on ERROR_CODE 300 Unauthorized action (User/Client not allowed to perform this action) """ pass class IncorrectValues(SynapseError): """ raised on ERROR_CODE 400 Incorrect Values Supplied (eg. Insufficient balance, wrong MFA response, incorrect micro deposits) """ pass class ObjectNotFound(SynapseError): """ raised on ERROR_CODE 404 Object not found """ pass class ActionNotAllowed(SynapseError): """ raised on ERROR_CODE 410 Action Not Allowed on the object (either you do not have permissions or the action on this object is not supported) """ class TooManyRequests(SynapseError): """ raised on ERROR_CODE 429 Too many requests hit the API too quickly. """ pass class IdempotencyConflict(SynapseError): """ raised on ERROR_CODE 450 Idempotency key already in use """ pass class RequestFailed(SynapseError): """ raised on ERROR_CODE 460 Request Failed but not due to server error """ pass class ServerError(SynapseError): """ raised on ERROR_CODE 500 Server Error """ pass class ServiceUnavailable(SynapseError): """ raised on ERROR_CODE 503 Service Unavailable. The server is currently unable to handle the request due to a temporary overload or scheduled maintenance. """ pass class GatewayTimeout(SynapseError): """ raised on ERROR_CODE 504 Gateway Timeout. The request did not get a response in time from the server that it needed in order to complete the request. """ pass class ErrorFactory(): """Determines which error to raise based on status code. """ ERRORS = { "10" : ActionPending, "100" : IncorrectClientCredentials, "110" : IncorrectUserCredentials, "120" : UnauthorizedFingerprint, "200" : PayloadError, "300" : UnauthorizedAction, "400" : IncorrectValues, "404" : ObjectNotFound, "410" : ActionNotAllowed, "429" : TooManyRequests, "450" : IdempotencyConflict, "460" : RequestFailed, "500" : ServerError, "503" : ServiceUnavailable, "504": GatewayTimeout } @classmethod def from_response(cls, response): """Return the corresponding error from a response.""" # import pdb; pdb.set_trace() # message = response.get('mfa', {}).get('message', response.get('message', response['error'])['en']) message = response.get('error', {}).get('en', "") http_code = response['http_code'] error_code = response['error_code'] klass = cls.ERRORS.get(error_code) return klass(message=message, http_code=http_code, error_code=error_code, response=response) <file_sep>/synapsepy/tests/fixtures/subnet_fixtures.py subnet_payload = { "nickname":"Test AC/RT" } subnet_get_resp = { "_id": "5c1151d32a3d440028193353", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb<KEY>/nodes/5c0b0ff74f98b000bd81f4af/subnets/5c1151d32a3d440028193353" } }, "account_class": "CHECKING", "account_num": "9826249105", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "<NAME>" }, "nickname": "Test AC/RT", "node_id": "5c0b0ff74f98b000bd81f4af", "routing_num": { "ach": "084106768", "wire": "084106768" }, "user_id": "5c0abeb9970f8426abc8df67" } subnet_get_all_resp = { "error_code": "0", "http_code": "200", "limit": 20, "page": 1, "page_count": 1, "subnets": [ { "_id": "5c1151d32a3d440028193353", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0b0ff74f98b000bd81f4af/subnets/5c1151d32a3d440028193353" } }, "account_class": "CHECKING", "account_num": "9826249105", "client": { "id": "5be38afd6a785e6bddfffe68", "name": "<NAME>" }, "nickname": "Test AC/RT", "node_id": "5c0b0ff74f98b000bd81f4af", "routing_num": { "ach": "084106768", "wire": "084106768" }, "user_id": "5c0abeb9970f8426abc8df67" } ], "subnets_count": 1, "success": True }<file_sep>/synapsepy/tests/fixtures/trans_fixtures.py trans_payload = { "to": { "type": "DEPOSIT-US", "id": "5c0b0ff74f98b000bd81f4af" }, "amount": { "amount": 300, "currency": "USD" }, "extra": { "ip": "192.168.0.1", "note": "Test transaction" } } trans_get_response = { "_id": "5c0b1562905a4e00cb631470", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0b0cfd1cfe2300a0fe490f/trans/5c0b1562905a4e00cb631470" } }, "_v": 2, "amount": { "amount": 300, "currency": "USD" }, "client": { "id": "5be38afd6a785e6bddfffe68", "name": "* <NAME>" }, "extra": { "asset": None, "created_on": 1544230242087, "encrypted_note": "", "group_id": None, "ip": "192.168.0.1", "latlon": "0,0", "note": "Test transaction", "process_on": 1544230242087, "same_day": False, "supp_id": "" }, "fees": [ { "fee": 0, "note": "Facilitator Fee", "to": { "id": "None" } } ], "from": { "id": "5c0b0cfd1cfe2300a0fe490f", "nickname": "Fake Account", "type": "ACH-US", "user": { "_id": "<KEY>", "legal_names": [ "Test User" ] } }, "recent_status": { "date": 1544230242087, "note": "Transaction Created.", "status": "CREATED", "status_id": "1" }, "timeline": [ { "date": 1544230242087, "note": "Transaction Created.", "status": "CREATED", "status_id": "1" } ], "to": { "id": "5c0b0ff74f98b000bd81f4af", "nickname": "My Deposit Account", "type": "DEPOSIT-US", "user": { "_id": "<KEY>", "legal_names": [ "Test User" ] } } } get_all_trans_resp = { "error_code": "0", "http_code": "200", "limit": 20, "page": 1, "page_count": 1, "success": True, "trans": [ { "_id": "5c0b1562905a4e00cb631470", "_links": { "self": { "href": "https://uat-api.synapsefi.com/v3.1/users/5c0abeb9970f8426abc8df67/nodes/5c0b0ff74f98b000bd81f4af/trans/5c0b1562905a4e00cb631470" } }, "_v": 2, "amount": { "amount": 300, "currency": "USD" }, "client": { "id": "5be38afd6a785e6bddfffe68", "name": "<NAME>" }, "extra": { "asset": None, "created_on": 1544230242087, "encrypted_note": "", "group_id": None, "ip": "192.168.0.1", "latlon": "0,0", "note": "Test transaction", "process_on": 1544230242087, "same_day": False, "supp_id": "" }, "fees": [ { "fee": 0.2, "note": "Synapse Facilitator Fee", "to": { "id": "55b3f8c686c2732b4c4e9df6" } } ], "from": { "id": "5c0b0cfd1cfe2300a0fe490f", "nickname": "Fake Account", "type": "ACH-US", "user": { "_id": "5c0abeb9970f8426abc8df67", "legal_names": [ "Test User" ] } }, "recent_status": { "date": 1544230251191, "note": "Unable to settle transaction from 5c0b0cfd1cfe2300a0fe490f, since the node 'allowed' is CREDIT.", "status": "CANCELED", "status_id": "5" }, "timeline": [ { "date": 1544230242087, "note": "Transaction Created.", "status": "CREATED", "status_id": "1" }, { "date": 1544230251191, "note": "Unable to settle transaction from 5c0b0cfd1cfe2300a0fe490f, since the node 'allowed' is CREDIT.", "status": "CANCELED", "status_id": "5" } ], "to": { "id": "5c0b0ff74f98b000bd81f4af", "nickname": "My Deposit Account", "type": "DEPOSIT-US", "user": { "_id": "5c0abeb9970f8426abc8df67", "legal_names": [ "Test User" ] } } } ], "trans_count": 1 } <file_sep>/synapsepy/transaction.py class Trans(): def __init__(self, response): self.id = response['_id'] self.body = response class Transactions(): def __init__(self, response): self.page = response['page'] self.page_count = response['page_count'] self.limit = response['limit'] self.trans_count = response['trans_count'] self.list_of_trans = [ Trans(trans_r) for trans_r in response['trans'] ]<file_sep>/synapsepy/subnet.py class Subnet(): def __init__(self, response): self.id = response['_id'] self.user_id = response['user_id'] self.node_id = response['node_id'] self.body = response class Subnets(): def __init__(self, response): self.page = response['page'] self.page_count = response['page_count'] self.limit = response['limit'] self.subnets_count = response['subnets_count'] self.list_of_subnets = [Subnet(sub_r) for sub_r in response['subnets']]<file_sep>/synapsepy/node.py class Node(): def __init__(self, response, full_dehydrate=False): self.id = response['_id'] self.type = response['type'] self.full_dehydrate = full_dehydrate self.body = response class Nodes(): def __init__(self, response): self.page = response.get('page', 1) self.page_count = response['page_count'] self.limit = response['limit'] self.node_count = response['node_count'] self.list_of_nodes = [ Node(node_r) for node_r in response['nodes'] ]<file_sep>/samples.md # Table of Contents - [Client](#client) * [Initialize Client](#initialize-client) * [Update Headers](#update-headers) * [Create User](#create-user) * [Get User](#get-user) * [Create Subscription](#create-subscription) * [Get Subscription](#get-subscription) * [Update Subscription](#update-subscription) * [Get All Users](#get-all-users) * [Get All Client Transactions](#get-all-client-transactions) * [Get All Client Nodes](#get-all-client-nodes) * [Get All Client Institutions](#get-all-client-institutions) * [Get All Client Subscriptions](#get-all-client-subscriptions) * [Get All Client Subscription Logs](#get-all-client-subscription-logs) * [Issue Public Key](#issue-public-key) * [View Crypto Quotes](#view-crypto-quotes) * [View Crypto Market Data](#view-crypto-market-data) * [Locate ATMs](#locate-atms) - [User](#user) * [Get New Oauth](#get-new-oauth) * [Register New Fingerprint](#register-new-fingerprint) * [Update User or Update/Add Documents](#update-user-or-updateadd-documents) * [Generate UBO](#generate-ubo) * [Get All User Nodes](#get-all-user-nodes) * [Get All User Transactions](#get-all-user-transactions) * [Get All User Statements](#get-all-user-statements) + [Nodes](#nodes) * [Create Node](#create-node) * [Get Node](#get-node) * [Get All User Nodes](#get-all-user-nodes-1) * [Update Node](#update-node) * [Ship Card Node](#ship-card-node) * [Reset Debit](#reset-card-node) * [Verify Micro Deposit](#verify-micro-deposit) * [Reinitiate Micro Deposit](#reinitiate-micro-deposit) * [Generate Apple Pay](#generate-apple-pay) * [Delete Node](#delete-node) * [Get All Node Subnets](#get-all-node-subnets) * [Get All Node Transactions](#get-all-node-transactions) * [Get All Node Statements](#get-all-node-statements) + [Subnets](#subnets) * [Create Subnet](#create-subnet) * [Get Subnet](#get-subnet) * [Update Subnet](#update-subnet) * [Ship Card](#ship-card) * [Get All Card Shipments](#get-all-card-shipments) * [Get Card Shipment](#get-card-shipment) * [Delete Card Shipment](#delete-card-shipment) + [Transactions](#transactions) * [Create Transaction](#create-transaction) * [Get Transaction](#get-transaction) * [Comment on Status](#comment-on-status) * [Dispute Transaction](#dispute-transaction) * [Cancel/Delete Transaction](#cancel-deletetransaction) * [Trigger Dummy Transactions](#trigger-dummy-transactions) # Client ##### Initialize Client [Getting Started - Creating a Client](https://docs.synapsefi.com/#setting-up-your-sandbox) ```python client = Client( client_id='client_id_1239ABCdefghijk1092312309', client_secret='client_secret_<KEY>', fingerprint='1023918209480asdf8341098', ip_address='172.16.17.32', devmode=True ) ``` ##### Update Headers ```python client.update_headers( client_secret='client_secret_1239ABCdefghijk1092312309', fingerprint='1023918209480asdf8341098', ip_address='172.16.17.32', oauth_key='<KEY>', idempotency_key='1234567' ) ``` ##### Create User [Creating a User](https://docs.synapsefi.com/api-references/users/create-user) ```python ip = '172.16.17.32' fingerprint = '<PASSWORD>' body = { "logins": [ { "email": "<EMAIL>" } ], "phone_numbers": [ "901.111.1111", "<EMAIL>" ], "legal_names": [ "<NAME>" ], ... } client.create_user(body, ip, fingerprint=fingerprint) ``` ##### Get User [Get User](https://docs.synapsefi.com/api-references/users/view-user) ```python user_id = '594e0fa2838454002ea317a0' ip = '172.16.17.32' fingerprint = '<PASSWORD>' client.get_user(user_id, ip=ip, fingerprint=fingerprint, full_dehydrate=True) ``` ##### Create Subscription [Create Subscription](https://docs.synapsefi.com/api-references/subscriptions/create-subscription) ```python body = { "scope": [ "USERS|POST", "USER|PATCH", "NODES|POST", "NODE|PATCH", "TRANS|POST", "TRAN|PATCH" ], "url": "https://requestb.in/zp216zzp" } subs = client.create_subscription(body) ``` ##### Get Subscription [Get Subscription](https://docs.synapsefi.com/api-references/subscriptions/view-subscription) ```python subs_id = '589b6adec83e17002122196c' subs = client.get_subscription(subs_id) ``` ##### Update Subscription [Update Subscription](https://docs.synapsefi.com/api-references/subscriptions/update-subscription) ```python body = { 'url': 'https://requestb.in/zp216zzp' 'scope': [ "USERS|POST", "USER|PATCH", "NODES|POST", ... ] } subs = client.update_subscription(body) ``` ##### Get All Users [Get All Users](https://docs.synapsefi.com/api-references/users/view-all-users-paginated) ```python allusers = client.get_all_users(show_refresh_tokens=True) ``` ##### Get All Client Transactions ```python alltrans = client.get_all_trans() ``` ##### Get All Client Nodes ```python allnodes = client.get_all_nodes() ``` ##### Get All Client Institutions ```python allinst = client.get_all_inst() ``` ##### Get All Client Subscriptions [Get All Client Subscriptions](https://docs.synapsefi.com/api-references/subscriptions/view-all-subscriptions) ```python allsubs = client.get_all_subs() ``` ##### Get All Client Subscription Logs [Get All Client Subcription Webhook Logs](https://docs.synapsefi.com/api-references/subscriptions/view-subscription-logs) ```python allsublogs = client.webhook_logs() ``` ##### Issue Public Key ```python scope = [ "USERS|POST", "USER|PATCH", "NODES|POST", ... ] pubkey = client.issue_public_key(scope) ``` ##### View Crypto Quotes [View Crypto Quotes](https://docs.synapsefi.com/api-references/nodes/view-crypto-quotes) ```python crypto_quotes = client.crypto_quotes() ``` ##### View Crypto Market Data ```python market_data = client.crypto_market_data(limit=5, currency='BTC') ``` ##### Locate ATMs [Locate ATMs](https://docs.synapsefi.com/api-references/nodes/view-atms) ```python market_data = client.locate_atms(zip='94114', lat=None, rad=None, page=None, per_page=None) ``` # User ##### Get New Oauth [Get New OAuth](https://docs.synapsefi.com/api-references/oauth/oauth-via-refresh-token) ```python body = { "refresh_token":"<KEY>", "scope":[ "USER|PATCH", "USER|GET", ... ] } user.oauth(body) ``` ##### Register New Fingerprint 1. Supply the new fingerprint: ```python client.update_headers(fingerprint='<PASSWORD>') user.oauth() ``` 2. Supply 2FA device from the list ```python user.select_2fa_device('<EMAIL>') ``` 3. Verify the pin sent to the 2FA device ```python user.confirm_2fa_pin('594230') ``` ##### Update User or Update/Add Documents [Update User](https://docs.synapsefi.com/api-references/users/update-user) ```python body = { "update":{ "login":{ "email":"<EMAIL>" }, "remove_login":{ "email":"<EMAIL>" }, "phone_number":"901-111-2222", "remove_phone_number":"901.111.1111" } } user.update_info(body) ``` ##### Generate UBO [Generate UBO](https://docs.synapsefi.com/api-references/users/generate-ubo-doc) ```python body = { "entity_info": { "cryptocurrency": True, "msb": { "federal": True, "states": ["AL"] }, "public_company": False, "majority_owned_by_listed": False, "registered_SEC": False, "regulated_financial": False, "gambling": False, "document_id": "2a4a5957a3a62aaac1a0dd0edcae96ea2cdee688ec6337b20745eed8869e3ac8" ... } user.create_ubo(body) ``` ##### Get duplicate users [Get Duplicate Users](https://docs.synapsefi.com/api-references/users/manage-duplicates) ```python user.get_duplicate_users() ``` ##### Swap duplicate users [Swap Duplicate Users](https://docs.synapsefi.com/api-references/users/manage-duplicates#example-request-1) ```python body = { "swap_to_user_id": "5ddc57cb3c4e2800756baa97" } user.swap_duplicate_user(body) ``` ##### Get All User Nodes [Get Nodes](https://docs.synapsefi.com/api-references/nodes/view-all-user-nodes) ```python user.get_all_nodes(page=4, per_page=10, type='DEPOSIT-US') ``` ##### Get All User Transactions [Get Transactions](https://docs.synapsefi.com/api-references/transactions/view-all-user-transactions) ```python user.get_all_trans(page=4, per_page=10) ``` ##### Get All User Statements [Get All Users Statements](https://docs.synapsefi.com/api-references/statements/view-all-user-statements) ```python user.get_statements(page=4, per_page=10) ``` ### Nodes ##### Create Node [Create Node](https://docs.synapsefi.com/api-references/nodes/create-node) Refer to the following docs for how to setup the payload for a specific Node type: - [Direct Deposit Accounts](https://docs.synapsefi.com/api-references/nodes/create-node#create-deposit-account) - [Issue Card](https://docs.synapsefi.com/api-references/subnets/create-subnet#issue-card) - [ACH-US with Logins](https://docs.synapsefi.com/api-references/nodes/create-node#create-ach-account) - [ACH-US with AC/RT](https://docs.synapsefi.com/api-references/nodes/create-node#create-ach-account) - [INTERCHANGE-US](https://docs.synapsefi.com/api-references/nodes/create-node#create-interchange-account) - [CHECK-US](https://docs.synapsefi.com/api-references/nodes/create-node#create-check-account) - [WIRE-US](https://docs.synapsefi.com/api-references/nodes/create-node#create-wire-account) - [WIRE-INT](https://docs.synapsefi.com/api-references/nodes/create-node#create-swift-account) ```python body = { "type": "DEPOSIT-US", "info":{ "nickname":"My Checking" } } user.create_node(body, idempotency_key='123456') ``` ##### Get Node [Get Node](https://docs.synapsefi.com/api-references/nodes/view-node) ```python node_id = '594e606212e17a002f2e3251' node = user.get_node(node_id, full_dehydrate=True, force_refresh=True) ``` ##### Get All User Nodes [Get All User Nodes](https://docs.synapsefi.com/api-references/nodes/view-all-user-nodes) ```python nodes = user.get_nodes(page=1, per_page=5, type='ACH-US') ``` ##### Update Node [Update Node](https://docs.synapsefi.com/api-references/nodes/update-node) ```python node_id = '5ba05ed620b3aa005882c52a' body = { "supp_id":"new_supp_id_1234" } nodes = user.update_node(node_id, body) ``` ##### Ship Card Node ```python node_id = '5ba05ed620b3aa005882c52a' body = { "fee_node_id":"5ba05e7920b3aa006482c5ad", "expedite":True } nodes = user.ship_card_node(node_id, body) ``` ##### Reset Card Node ```python node_id = '5ba05ed620b3aa005882c52a' nodes = user.reset_card_node(node_id) ``` ##### Verify Micro Deposit [Verify Micro Deposit](https://docs.synapsefi.com/api-references/nodes/update-node#verify-micro-deposits) ```python node_id = '5ba05ed620b3aa005882c52a' body = { "micro":[0.1,0.1] } nodes = user.verify_micro(node_id, body) ``` ##### Reinitiate Micro Deposit [Reinitiate Micro Deposit](https://docs.synapsefi.com/api-references/nodes/update-node#resend-micro-deposits) ```python node_id = '5ba05ed620b3aa005882c52a' nodes = user.reinit_micro(node_id) ``` ##### Generate Apple Pay [Generate Apple Pay](https://docs.synapsefi.com/api-references/subnets/push-to-wallet) ```python node_id = '5ba05ed620b3aa005882c52a' body = { "certificate": "your applepay cert", "nonce": "9c02xxx2", "nonce_signature": "4082f883ae62d0700c283e225ee9d286713ef74" } nodes = user.generate_apple_pay(node_id) ``` ##### Delete Node [Delete Node](https://docs.synapsefi.com/api-references/nodes/update-node) ```python node_id = '594e606212e17a002f2e3251' user.delete_node(node_id) ``` ##### Get All Node Subnets [Get All Subnets](https://docs.synapsefi.com/api-references/subnets/view-all-node-subnets) ```python node_id = '594e606212e17a002f2e3251' user.get_all_subnets(node_id, page=4, per_page=10) ``` ##### Get All Node Transactions [Get All Node Transactions](https://docs.synapsefi.com/api-references/transactions/view-all-node-transactions) ```python node_id = '594e606212e17a002f2e3251' user.get_all_node_trans(node_id, page=4, per_page=10) ``` ##### Get All Node Statements [Get All Node Statements](https://docs.synapsefi.com/api-references/statements/view-all-node-statements) ```python node_id = '594e606212e17a002f2e3251' user.get_statements(node_id, page=4, per_page=10) ``` ### Subnets ##### Create Subnet [Create Subnet](https://docs.synapsefi.com/api-references/subnets/create-subnet) ```python node_id = '594e606212e17a002f2e3251' body = { "nickname":"Test AC/RT" } user.create_subnet(node_id, body) ``` ##### Get Subnet [Get Subnet](https://docs.synapsefi.com/api-references/subnets/view-subnet) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' user.get_subnet(node_id, subn_id) ``` ##### Update Subnet [Update Subnet](https://docs.synapsefi.com/api-references/subnets/update-subnet) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' body = { "status": "ACTIVE", "card_pin": "1234", "preferences": { "allow_foreign_transactions": True, "daily_atm_withdrawal_limit": 10, "daily_transaction_limit": 1000 } } user.update(node_id, subn_id) ``` ##### Ship Card [Ship Card](https://docs.synapsefi.com/api-references/shipments/create-shipment) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' body = { "fee_node_id":"5bba781485411800991b606b", "expedite":False, "card_style_id":"555" } user.ship_card(node_id, subn_id, body) ``` #### Get All Card Shipments [Get All Card Shipments](https://docs.synapsefi.com/api-references/shipments/view-all-subnet-shipments) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' page = 1 per_page = 10 user.view_all_card_shipments(node_id,subn_id,per_page=per_page,page=page) ``` #### Get Card Shipment [Get Card Shipment](https://docs.synapsefi.com/api-references/shipments/view-shipment) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' ship_id = '6101f4062846db14581f19e6' user.view_card_shipment(node_id,subn_id,ship_id) ``` #### Delete Card Shipment [Delete Card Shipment](https://docs.synapsefi.com/api-references/shipments/cancel-shipment) ```python node_id = '594e606212e17a002f2e3251' subn_id = '59c9f77cd412960028b99d2b' ship_id = '6101f4062846db14581f19e6' user.cancel_card_shipment(node_id,subn_id,ship_id) ``` ### Transactions ##### Create Transaction [Create Transaction](https://docs.synapsefi.com/api-references/transactions/create-transaction) ```python node_id = '594e606212e17a002f2e3251' body = { "to": { "type": "ACH-US", "id": "594e6e6c12e17a002f2e39e4" }, "amount": { "amount": 20.1, "currency": "USD" }, "extra": { "ip": "192.168.0.1" } } user.create_trans(node_id, body) ``` ##### Get Transaction [Get Transaction](https://docs.synapsefi.com/api-references/transactions/view-transaction) ```python node_id = '594e606212e17a002f2e3251' trans_id = '594e72124599e8002fe62e4f' user.get_trans(node_id, trans_id) ``` ##### Comment on Status ```python node_id = '594e606212e17a002f2e3251' trans_id = '594e72124599e8002fe62e4f' user.comment_status(node_id, trans_id, 'Pending verification...') ``` ##### Dispute Transaction [Dispute Transaction](https://docs.synapsefi.com/api-references/transactions/dispute-transaction) ```python node_id = '594e606212e17a002f2e3251' trans_id = '594e72124599e8002fe62e4f' dispute_reason = 'Chargeback...' dispute_meta = { "type_of_merchandise_or_service": "groceries", "merchant_contacted": true, "contact_method": "phone", "contact_date": 1563474864000 } certification_date = 1579308186000 dispute_attachments = [ "data:image/gif;base64,SUQs==" ] user.dispute_trans(node_id, trans_id, dispute_reason, dispute_meta, certification_date, dispute_attachments) ``` ##### Cancel/Delete Transaction [Cancel Transaction](https://docs.synapsefi.com/api-references/transactions/cancel-transaction) ```python node_id = '594e606212e17a002f2e3251' trans_id = '594e72124599e8002fe62e4f' user.cancel_trans(node_id, trans_id) ``` ##### Trigger Dummy Transactions [Trigger Dummy Transactions](https://docs.synapsefi.com/api-references/miscellaneous/dummy-transactions) ```python node_id = '594e606212e17a002f2e3251' subnet_id = '594e606212e17a002f2e3251' user.dummy_tran(node_id, subnet_id=subnet_id, type='INTERCHANGE', foreign_transaction=False, is_credit=True) ``` <file_sep>/synapsepy/user.py from .endpoints import paths from .node import Node, Nodes from .subnet import Subnet, Subnets from .transaction import Trans, Transactions from functools import partial import json import logging import requests import warnings from . import errors as api_errors class User(): """ User Record """ def __init__(self, response, http, full_dehydrate=False, logging=False): """Initializes the User by parsing response from API """ self.id = response['_id'] self.body = response self.full_dehydrate = full_dehydrate self.http = http self.logger = self.get_log(logging) def refresh(self): '''gets a new refresh token by getting user Args: user (JSON): json response for user record with old_refresh_token Returns: dict: dict response of user record with new refresh_token ''' self.logger.debug("Getting new User and refresh_token") path = paths['users'] + '/' + self.id self.body = self.http.get(path, full_dehydrate=self.full_dehydrate) return self.body['refresh_token'] def oauth(self, payload=None): '''Gets new OAuth for user and updates the headers Args: payload (:obj:dict, optional): (opt) Returns: OAuth (str): newly created OAuth within scope ''' self.logger.debug("Getting new OAuth for user") path = paths['oauth'] + '/' + self.id body = {'refresh_token': self.body['refresh_token']} if payload: body.update(payload) try: response = self.http.post(path, body) except api_errors.IncorrectValues as e: self.refresh() body['refresh_token'] = self.body['refresh_token'] response = self.http.post(path, body) self.http.update_headers( oauth_key=response['oauth_key'] ) return response def select_2fa_device(self, device): '''Sends MFA pin to specific device Args: device (str): device to send pin to Returns: dict: dictionary containing API response ''' self.logger.debug("Sending chosen 2FA device") path = paths['oauth'] + '/' + self.id body = { 'refresh_token': self.body['refresh_token'], 'phone_number': device } response = self.http.post(path, body) return response def confirm_2fa_pin(self, pin): '''Confirms pin sent to device Args: pin (str): validation_pin sent to user's device Returns: dict: dictionary containing API response ''' self.logger.debug("Confirming 2FA Pin") path = paths['oauth'] + '/' + self.id body = { 'refresh_token': self.body['refresh_token'], 'validation_pin': pin } response = self.http.post(path, body) self.http.update_headers( oauth_key=response['oauth_key'] ) return response def _do_request(self, req_func, path, body={}, **params): '''Single point of access for user methods in the event of an invalid OAuth ''' self.logger.debug( "{} request on {}".format(req_func.__name__, path) ) self.logger.debug(json.dumps(body, indent=2)) req_dict = { "get": partial(req_func, path, **params), "post": partial(req_func, path, body, **params), "patch": partial(req_func, path, body, **params), "delete": partial(req_func, path) } try: response = req_dict[req_func.__name__]() except (requests.exceptions.HTTPError, api_errors.UnauthorizedAction, api_errors.IncorrectUserCredentials) as e: self.logger.debug( "user's oauth expired. re-authenticatng" ) self.oauth() self.logger.debug( "Retrying {} request on {}".format( req_func.__name__, path ) ) self.logger.debug(body) response = req_dict[req_func.__name__]() return response def update_info(self, body): '''Updates user information in database Args: body (dict): user information to update Returns: response (User): User object containing updated info ''' self.logger.debug("Updating user info") path = paths['users'] + '/' + self.id response = self._do_request(self.http.patch, path, body) self.body = response return response def create_node(self, body, idempotency_key=None): '''Creates a new Node for User Args: body (dict): dictionary containing new Node information idempotency_key: (opt) Idempotency key for safely retrying requests ''' self.logger.debug("Creating {} Node".format(body.get('type'))) path = paths['users'] + '/' + self.id + paths['nodes'] response = self._do_request( self.http.post, path, body, idempotency_key=idempotency_key ) if response.get('mfa'): return response return Nodes(response) def get_node(self, node_id, full_dehydrate=False, force_refresh=False): '''Gets Node from database Args: node_id (str): Node ID for the Node you are trying to get full_dehydrate (bool): (opt) Full Dehydrate True will return all the node info, including decrypted account/routing number, transaction history, etc. force_refresh (bool): (opt) If the node was created with bank logins, force refresh 'yes' will attempt updating the account balance and transactions Returns: Node: Node object containing node info ''' self.logger.debug("Retrieving Node") path = ( paths['users'] + '/' + self.id + paths['nodes'] +'/' + node_id ) full_d = 'yes' if full_dehydrate else 'no' force_r = 'yes' if force_refresh else 'no' response = self._do_request( self.http.get, path, full_dehydrate=full_d, force_refresh=force_r ) return Node(response, full_dehydrate=full_dehydrate) def get_node_statements(self, node_id, page=None, per_page=None): '''Retrieves all Statements for a User's Node Args: node_id (str): Node ID page (int): (opt) Page number per_page (int): (opt) How many nodes do you want us to return per page. Returns: dict: dictionary response of the collection of statements for User ''' self.logger.debug("Retrieving all statements for User") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['statem'] ) response = self._do_request( self.http.get, path, page=page, per_page=per_page ) return response def update_node(self, node_id, body): '''Updates a node's info in the database Args: node_id (str): ID of the Node to update body (dict): dictionary containing updated info Returns: Node: Node object with updated info ''' self.logger.debug("Updating Node info") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request(self.http.patch, path, body) return Node(response) def generate_ecash_barcode(self, node_id, body): '''Allows you to generate a barcode for Greendot's eCash feature Args: node_id (str): ID of the node used to create barcode body (dict): dictionary containing updating info Returns: barcode (dict): a body describing a barcode https://docs.synapsefi.com/api-references/nodes/generate-ecash-barcode ''' self.logger.debug("Generating ecash barcode") path = paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['barcode'] response = self._do_request(self.http.post, path, body) return response def ach_mfa(self, body): '''MFA to add user to database through bank logins Args: body (dict): dictionary containing access_token and mfa_answer Returns: Nodes: Nodes object containing aggregated accounts or dict: dictionary response if another MFA flow is needed ''' self.logger.debug("Sending MFA flow information") path = paths['users'] + '/' + self.id + paths['nodes'] response = self._do_request(self.http.post, path, body) if response.get('mfa'): return response return Nodes(response) def verify_micro(self, node_id, body): '''Verifies micro transactions for adding ACH-US Node with AC/RT Args: node_id (str): ID of the Node to verify body (dict): dictionary containing micro (list of micro-deposit amounts) Returns: Node: Node object containing node info ''' self.logger.debug("Verifying micro-transactions") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request(self.http.patch, path, body) return Node(response) def reinit_micro(self, node_id): '''Reinitiates micro-deposit for an ACH-US Node Args: node_id (str): ID of the Node object to reinitiate micro deposits for Returns: dict: dictionary of response from API ''' self.logger.debug( "reinitiating micro transaction for node_id: {}".format( node_id ) ) path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request( self.http.patch, path, {}, resend_micro='YES' ) return response def ship_card_node(self, node_id, body): '''DEPRECATED - Ship physical debit card to user Args: node_id (str): ID of the Node object to reinitiate micro deposits for body (dict): dictionary containing Node and shipping information Returns: dict: dictionary of response from API ''' self.logger.debug("Shipping debit card") warnings.warn( ( "CARD-US Nodes have been deprecated and replaced by Subnet Cards." + "\nPlease migrate to Subnet based card issuance." + "\nSee: https://docs.synapsefi.com/docs/issue-a-card-number-1" ), DeprecationWarning ) path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request( self.http.patch, path, body, ship='YES' ) return response def reset_card_node(self, node_id): '''DEPRECATED - Resets the debit card number, card cvv, and expiration date Args: node_id (str): ID of the Node object to reset card info for Returns: dict: dictionary of response from API ''' self.logger.debug("Resetting debit card") warnings.warn( ( "CARD-US Nodes have been deprecated and replaced by Subnet Cards." + "\nPlease migrate to Subnet based card issuance." + "\nSee: https://docs.synapsefi.com/docs/issue-a-card-number-1" ), DeprecationWarning ) path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request( self.http.patch, path, {}, reset='YES' ) return response def generate_apple_pay(self, node_id, body): '''Generates an ApplePay token (currently not working in API) ''' self.logger.debug("Generating apple pay token") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['apple'] ) response = self._do_request(self.http.patch, path, body) return response def create_ubo(self, body): '''Generates an UBO and REG GG form Args: body (dict): dictionary containing relevent document and user info needed to generate UBO Returns: dict: dictionary of response from API ''' self.logger.debug("Generating UBO and REG GG form") path = paths['users'] +'/'+ self.id + paths['ubo'] response = self._do_request(self.http.patch, path, body) return response def delete_node(self, node_id): '''Deletes a Node from the API Args: node_id (str): ID of the Node to delete Returns: dict: dictionary of response from API ''' self.logger.debug("Deleting Node") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id ) response = self._do_request(self.http.delete, path) return response def create_trans(self, node_id, body, idempotency_key=None): '''Create a transaction Args: node_id (str): ID of the from Node body (dict): dictionary containing relevent transaction details idempotency_key: (opt) Idempotency key for safely retrying requests Returns: Trans: Trans object containing transaction record ''' self.logger.debug("Creating transaction") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['trans'] ) response = self._do_request( self.http.post, path, body, idempotency_key=idempotency_key ) return Trans(response) def batch_trans(self, node_id, body): '''allows you to create up-to 500 transactions (100 in sandbox) from one node at once. https://docs.synapsefi.com/api-references/transactions/create-batch-transactions Args: node_id (str): ID of the from Node body (dict): dictionary containing relevant list of transactions Returns: Transactions: an array of Trans object containing transaction record ''' self.logger.debug("Creating batched transactions") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + 'batch-trans' ) response = self._do_request( self.http.post, path, body ) return Transactions(response) def get_trans(self, node_id, trans_id): '''Retrieves a transaction record from the API Args: node_id (str): ID of the from Node trans_id (str): ID of the transaction Returns: Trans: Trans object containing transaction record ''' self.logger.debug("Retrieving Transaction") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['trans'] + '/' + trans_id ) response = self._do_request(self.http.get, path) return Trans(response) def comment_trans(self, node_id, trans_id, comment): '''Comment on a Transaction Args: node_id (str): ID of the from Node trans_id (str): ID of the transaction comment (str): Comment you wish to add for the transaction status Returns: dict: dictionary of response from API ''' self.logger.debug("Commenting on Transaction") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['trans'] + '/' + trans_id ) body = {'comment': comment} response = self._do_request(self.http.patch, path, body) return response def dispute_trans(self, node_id, trans_id, dispute_reason, dispute_meta={}, certification_date=False, dispute_attachments=[]): '''Disputes a transaction Args: node_id (str): ID of the from Node trans_id (str): ID of the transaction dispute_reason (str): Reason for disputing the transaction dispute_meta (dict): Additional information about dispute dispute_attachments (list): Additional attachements certification_date (int): Epoch timestamp of certification Returns: dict: dictionary of response from API ''' self.logger.debug("Disputing Transaction") path = ( paths['users'] + '/' + self.id + paths['nodes'] +'/' + node_id + paths['trans'] + '/' + trans_id + paths['dispute'] ) body = { 'dispute_reason': dispute_reason } if dispute_meta: body['dispute_meta'] = dispute_meta if certification_date: body['certification_date'] = certification_date if dispute_attachments: body['dispute_attachments'] = dispute_attachments response = self._do_request(self.http.patch, path, body) return response def cancel_trans(self, node_id, trans_id): '''Cancels/Deletes a transaction Args: node_id (str): ID of the from Node trans_id (str): ID of the transaction Returns: dict: dictionary of response from API ''' self.logger.debug("Cancelling Transaction") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['trans'] + '/' + trans_id ) response = self._do_request(self.http.delete, path) return response def dummy_tran(self, node_id, subnet_id=None, type=None, is_credit=False, foreign_transaction=False): '''Trigger external dummy transactions on deposit or card accounts Args: node_id (str): ID of the from Node is_credit (str): (opt) If the transaction is a credit or debit Returns: dict: dictionary of response from API ''' self.logger.debug("Triggering dummy Transactions for Node") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['dummy'] ) credit = 'YES' if is_credit else 'NO' foreign = 'YES' if foreign_transaction else 'NO' response = self._do_request( self.http.get, path, subnetid=subnet_id, type=type, is_credit=credit, foreign_transaction=foreign ) return response def create_subnet(self, node_id, body, idempotency_key=None): '''Creates account and routing number on an account Args: node_id (str): ID of the from Node nickname (str): Any nickname/common name given to the node idempotency_key: (opt) Idempotency key for safely retrying requests Returns: Subnet: Subnet object containing Subnet record ''' self.logger.debug("Creating Subnet\n" + json.dumps(body, indent=2)) path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] ) response = self._do_request(self.http.post, path, body, idempotency_key=idempotency_key) return Subnet(response) def get_subnet(self, node_id, subnet_id): '''Retrieves the account and routing numbers on an account Args: node_id (str): ID of the from Node subnet_id (str): ID of the Subnet Returns: Subnet: Subnet object containing Subnet record ''' self.logger.debug("Retrieving Subnet info") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id ) response = self._do_request(self.http.get, path) return Subnet(response) def update_subnet(self, node_id, subnet_id, body): '''Updates the subnet's prefrences Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet body (dict): dictionary containing preference updates Returns: Subnet: Subnet object containing Subnet record ''' self.logger.debug("Updating Subnet info") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id ) response = self._do_request(self.http.patch, path, body) return Subnet(response) def ship_card(self, node_id, subnet_id, body): '''Ship physical debit card to user Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet body (dict): dictionary containing fee Node and card information Returns: dict: dictionary of response from API ''' self.logger.debug("Processing card shipment data") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id + paths['ship'] ) response = self._do_request(self.http.patch, path, body) return response def push_to_mobile_wallet(self, node_id, subnet_id, body): '''generate a token to push card to digital wallet. https://docs.synapsefi.com/api-references/subnets/push-to-wallet Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet body (dict): relevant wallet data including nonce, certificates and type Returns: dict: dictionary of response with wallet tokens ''' self.logger.debug("Generate a token to push card to digital wallet.") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id + paths['push'] ) response = self._do_request(self.http.post, path, body) return response def view_all_card_shipments(self, node_id, subnet_id, per_page = 10, page = 1): '''View all card shipments for a subnet Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet per_page (int): Number of card shipments retrieved per page, maximum is 20 page (int): Page number of card shipments returned Returns: dict: dictionary of response from API ''' self.logger.debug("View card shipments data") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id + paths['ship'] ) response = self._do_request(self.http.get,path,per_page=per_page,page=page) return response def view_card_shipment(self, node_id, subnet_id, shipment_id): '''View a single card shipment for a subnet by shipment ID Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet shipment_id (str): ID of the Shipment Returns: dict: dictionary of response from API ''' self.logger.debug("View card shipment data") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id + paths['ship'] + '/' + shipment_id ) response = self._do_request(self.http.get,path) return response def cancel_card_shipment(self, node_id, subnet_id, shipment_id): '''Delete a single card shipment for a subnet by shipment ID Args: node_id (str): ID of the Node subnet_id (str): ID of the Subnet shipment_id (str): ID of the Shipment Returns: dict: dictionary of response from API ''' self.logger.debug("Deleting card shipment data") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] + '/' + subnet_id + paths['ship'] + '/' + shipment_id ) response = self._do_request(self.http.delete,path) return response def get_all_nodes(self, page=None, per_page=None, type=None): '''Retrieves all Nodes for a User Args: page (int): (opt) Page number per_page (int): (opt) How many nodes do you want us to return per page. type (str): (opt) Type of Node to filter Returns: Nodes: Nodes object containing paginated info and Node records ''' self.logger.debug("Retrieving all Nodes for User") path = paths['users'] + '/' + self.id + paths['nodes'] response = self._do_request( self.http.get, path, page=page, per_page=per_page, type=type ) return Nodes(response) def get_all_node_trans(self, node_id, page=None, per_page=None): '''Retrieves all Transactions for a Node Args: node_id (str): ID of the Node page (int): (opt) Page number per_page (int): (opt) How many transactions do you want us to return per page. Returns: Transactions: Transactions object containing paginated info and Trans records ''' self.logger.debug("Retrieving all Transactions for Node") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['trans'] ) response = self._do_request( self.http.get,path, page=page, per_page=per_page ) return Transactions(response) def get_all_trans(self, page=None, per_page=None): '''Retrieves all Transactions for a User Args: page (int): (opt) Page number per_page (int): (opt) How many transactions do you want us to return per page. Returns: Transactions: Transactions object containing paginated info and Trans records ''' self.logger.debug("Retrieving all Transactions for User") path = paths['users'] + '/' + self.id + paths['trans'] response = self._do_request( self.http.get, path, page=page, per_page=per_page ) return Transactions(response) def get_all_subnets(self, node_id, page=None, per_page=None): '''Retrieves all Subnets for a Node Args: node_id (str): ID of the Node page (int): (opt) Page number per_page (int): (opt) How many transactions do you want us to return per page. Returns: Subnets: Subnets object containing paginated info and Subnet records ''' self.logger.debug("Retrieving all Subnets for Node") path = ( paths['users'] + '/' + self.id + paths['nodes'] + '/' + node_id + paths['subn'] ) response = self._do_request( self.http.get, path, page=page, per_page=per_page ) return Subnets(response) def get_log(self, enable): '''Creates logger ''' logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.disabled = not enable return logger def get_statements(self, page=None, per_page=None): '''Retrieves all Statements for a User Args: page (int): (opt) Page number per_page (int): (opt) How many nodes do you want us to return per page. Returns: dict: dictionary response of the collection of statements for User ''' self.logger.debug("Retrieving all statements for User") path = paths['users'] + '/' + self.id + paths['statem'] response = self._do_request( self.http.get, path, page=page, per_page=per_page ) return response def get_duplicate_users(self): self.logger.debug("getting duplicate users") path = paths['users'] + '/' + self.id + '/get-duplicates' response = self._do_request(self.http.get, path) self.body = response return response def swap_duplicate_user(self, body): self.logger.debug("swapping duplicate users") path = paths['users'] + '/' + self.id + '/swap-duplicate-users' response = self._do_request(self.http.patch, path, body) self.body = response return response class Users(): def __init__(self, response, http): '''Initializes a Users object containing pagination info and User Records ''' self.page = response['page'] self.page_count = response['page_count'] self.limit = response['limit'] self.users_count = response['users_count'] self.list_of_users = [ User(user_r, http) for user_r in response['users'] ]
1cbe0d976ceb6a4eda53afd0071fc2f068bfad0a
[ "Markdown", "Python" ]
21
Python
SynapseFI/SynapsePy
a6937530cb2892da1f498c6501033b54835fb803
7d503c837084aa13a72c60b878d2fa7d6f20b9c1
refs/heads/master
<repo_name>ihexon/doVim<file_sep>/uninstall.sh #!/bin/bash rm -rf ~/.vim rm -rf ~/.vimplus echo "Uninstall Done!" <file_sep>/install.sh #!/bin/bash # Get currect VIM version function get_vim_info(){ declare -r VIM_VERSION="$(vim --version | head -n1 | cut -d ' ' -f 5)"; declare -r VIM_PATCH="$(vim --version| sed '2!d' | cut -f 3 -d ' '|cut -f2 -d '-' )"; } # 获取平台类型,mac还是linux平台 function get_platform_type() { echo $(uname) } # 获取linux平台类型,ubuntu还是centos function get_linux_platform_type() { if which apt-get > /dev/null ; then echo "ubuntu" # debian ubuntu系列 elif which yum > /dev/null ; then echo "centos" # centos redhat系列 elif which pacman > /dev/null; then echo "archlinux" # archlinux系列 else echo "invaild" fi } # 判断是否是ubuntu16.04LTS版本 function is_ubuntu1604() { version=$(cat /etc/lsb-release | grep "DISTRIB_RELEASE") if [ ${version} == "DISTRIB_RELEASE=16.04" ]; then echo 1 else echo 0 fi } # Compile Vim from source function compile_vim_on_ubuntu() { sudo apt-get install -y libncurses5-dev libgnome2-dev libgnomeui-dev \ libgtk2.0-dev libatk1.0-dev libbonoboui2-dev \ libcairo2-dev libx11-dev libxpm-dev libxt-dev python-dev python3-dev ruby-dev lua5.1 lua5.1-dev rm -rf /tmp/vim_src && git clone https://github.com/vim/vim.git /tmp/vim_src cd /tmp/vim_src ./configure --enable-fail-if-missing \ --enable-luainterp=dynamic \ --enable-mzschemeinterp \ --enable-perlinterp=dynamic \ --enable-pythoninterp=dynamic \ --enable-python3interp=dynamic \ --enable-tclinterp=dynamic \ --enable-rubyinterp=dynamic \ --enable-cscope --enable-terminal \ --enable-multibyte --enable-autoservername \ --enable-gui=auto --with-features=huge \ --with-python-command=python2 \ --with-python3-command=python3 \ --with-tclsh=tclsh8.6 \ --with-compiledby=ZhuZhiHao \ --enable-fontset \ --with-modified-by=ZhuZhiHao \ --enable-channel --without-local-dir \ --enable-selinux --enable-netbeans --enable-smack \ --prefix=""${HOME}"/vim_bins" if [ "${?}" != 0 ];then make make install cd "${HOME}"/.vimplus fi } # 在centos上源代码安装vim function compile_vim_on_centos() { sudo rm -rf /usr/bin/vi sudo rm -rf /usr/bin/vim* sudo rm -rf /usr/local/bin/vim* sudo rm -rf /usr/share/vim/vim* sudo rm -rf /usr/local/share/vim/vim* rm -rf ~/vim sudo yum install -y ruby ruby-devel lua lua-devel luajit \ luajit-devel ctags git python python-devel \ python34 python34-devel tcl-devel \ perl perl-devel perl-ExtUtils-ParseXS \ perl-ExtUtils-XSpp perl-ExtUtils-CBuilder \ perl-ExtUtils-Embed libX11-devel ncurses-devel git clone https://github.com/vim/vim.git ~/vim cd ~/vim ./configure --with-features=huge \ --enable-multibyte \ --with-tlib=tinfo \ --enable-rubyinterp=yes \ --enable-pythoninterp=yes \ --with-python-config-dir=/usr/local/python-2.7.14/lib/python2.7/config \ --enable-perlinterp=yes \ --enable-luainterp=yes \ --enable-gui=gtk2 \ --enable-cscope \ --prefix=/usr make sudo make install cd - } # 安装mac平台必要软件 function install_prepare_software_on_mac() { brew install vim gcc cmake ctags-exuberant curl ack } # 安装centos发行版必要软件 function install_prepare_software_on_centos() { sudo yum install -y ctags automake gcc gcc-c++ kernel-devel cmake python-devel python3-devel curl fontconfig ack compile_vim_on_centos } # 安装ubuntu发行版必要软件 function install_prepare_software_on_ubuntu() { sudo apt-get install -y ctags build-essential cmake python-dev python3-dev fontconfig curl libfile-next-perl ack-grep ubuntu_1604=`is_ubuntu1604` echo ${ubuntu_1604} if [ ${ubuntu_1604} == 1 ]; then echo "ubuntu 16.04 LTS" compile_vim_on_ubuntu else echo "not ubuntu 16.04 LTS" sudo apt-get install -y vim fi } # Install vim and other utils in need function install_prepare_software_on_archlinux() { sudo pacman -S --needed --noconfirm gvim ctags automake gcc cmake python3 python2 curl ack } # Backup old file and copy new file function copy_files() { backupdir="vim_old_config_"$(date +"%Y%m%d%k%M%S")""; printf "%s" "Backup dir : "~/${backupdir}""; mkdir -p ~/${backupdir}; mv "~/.vimrc" "~/${backupdir}" &> /tmp/log_install mv "~/.vimrc.local" "~/${backupdir}" &> /tmp/log_install mv "~/.ycm_extra_conf.py" "~/${backupdir}" &> /tmp/log_install mv "~/.vim" "~/${backupdir}" &> /tmp/log_install cp ${PWD}/.vimrc.local ~ ln -s ${PWD}/.ycm_extra_conf.py ~ mkdir -p ~/.vim HOMEDIR=$(echo ~) ln -s ${PWD}/colors ${HOMEDIR}/.vim ln -s ${PWD}/ftplugin ${HOMEDIR}/.vim ln -s ${PWD}/config ${HOMEDIR}/.vim ln -s ${PWD}/autoload ${HOMEDIR}/.vim ln -s ${PWD}/temp ${HOMEDIR}/.vim ln -s ${PWD}/vimrc ${HOMEDIR}/.vim } # 安装mac平台字体 function install_fonts_on_mac() { rm -rf ~/Library/Fonts/Droid\ Sans\ Mono\ Nerd\ Font\ Complete.otf cp ./fonts/Droid\ Sans\ Mono\ Nerd\ Font\ Complete.otf ~/Library/Fonts } # 安装linux平台字体 function install_fonts_on_linux() { mkdir -p ~/.fonts rm -rf ~/.fonts/Droid\ Sans\ Mono\ Nerd\ Font\ Complete.otf cp ./fonts/Droid\ Sans\ Mono\ Nerd\ Font\ Complete.otf ~/.fonts fc-cache -vf ~/.fonts } # 下载插件管理软件vim-plug function download_vim_plug() { curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim } # 安装vim插件 function install_vim_plugin() { vim -c "PlugInstall" -c "q" -c "q" } # linux编译ycm插件 function compile_ycm_on_linux() { cd ~/.vim/plugged/YouCompleteMe ./install.py --clang-completer --system-libclang --clang-tidy --enable-coverage \ --system-boost --enable-debug } # mac编译ycm插件 function compile_ycm_on_mac() { cd ~/.vim/plugged/YouCompleteMe ./install.py --clang-completer --system-libclang --clang-tidy --enable-coverage \ --system-boost --enable-debug } # print logo function print_logo(){ color="$(tput setaf 6)" normal="$(tput sgr0)" printf "${color}" echo ' /$$ /$$ /$$ ' echo ' |__/ | $$ | $$ ' echo ' /$$ /$$ /$$ /$$$$$$/$$$$ /$$$$$$ | $$ /$$ /$$ /$$$$$$$ /$$$$$$ | $$ /$$ /$$ /$$$$$$$' echo '| $$ /$$/| $$| $$_ $$_ $$ /$$__ $$| $$| $$ | $$ /$$_____/ /$$__ $$| $$| $$ | $$ /$$_____/' echo ' \ $$/$$/ | $$| $$ \ $$ \ $$| $$ \ $$| $$| $$ | $$| $$$$$$ | $$ \ $$| $$| $$ | $$| $$$$$$ ' echo ' \ $$$/ | $$| $$ | $$ | $$| $$ | $$| $$| $$ | $$ \____ $$| $$ | $$| $$| $$ | $$ \____ $$' echo ' \ $/ | $$| $$ | $$ | $$| $$$$$$$/| $$| $$$$$$/ /$$$$$$$/| $$$$$$$/| $$| $$$$$$/ /$$$$$$$/' echo ' \_/ |__/|__/ |__/ |__/| $$____/ |__/ \______/ |_______/ | $$____/ |__/ \______/ |_______/ ' echo ' | $$ | $$ ' echo ' | $$ | $$ ' echo ' |__/ |__/ ' echo 'Now install finish.' echo 'Please report bug and issue' echo 'https://github.com/ihexon/dovim' printf "${normal}" } # 在mac平台安装vimplus function install_vimplus_on_mac() { install_prepare_software_on_mac copy_files install_fonts_on_mac download_vim_plug install_vim_plugin compile_ycm_on_mac print_logo } function begin_install_vimplus() { copy_files #install_fonts_on_linux download_vim_plug install_vim_plugin compile_ycm_on_linux print_logo } # 在ubuntu发行版安装vimplus function install_vimplus_on_ubuntu() { install_prepare_software_on_ubuntu begin_install_vimplus } # 在centos发行版安装vimplus function install_vimplus_on_centos() { install_prepare_software_on_centos begin_install_vimplus } # 在archlinux发行版安装vimplus function install_vimplus_on_archlinux() { install_prepare_software_on_archlinux begin_install_vimplus } # 在linux平台安装vimplus function install_vimplus_on_linux() { type=`get_linux_platform_type` echo "linux platform type: "${type} if [ ${type} == "ubuntu" ]; then install_vimplus_on_ubuntu elif [ ${type} == "centos" ]; then install_vimplus_on_centos elif [ ${type} == "archlinux" ]; then install_vimplus_on_archlinux else echo "not support this linux platform type: "${type} fi } # main函数 function main() { type=`get_platform_type` echo "platform type: "${type} if [ ${type} == "Darwin" ]; then install_vimplus_on_mac elif [ ${type} == "Linux" ]; then install_vimplus_on_linux else echo "not support platform type: "${type} fi } # 调用main函数 main
2fc7e2735e36d33fa21c5c5a0ba23dc271905451
[ "Shell" ]
2
Shell
ihexon/doVim
26bbf3c0b1a3e7dd03fa5253ae5387c023b869f7
5504f2c64193b620a0bff68bc2e1c9f0624939ab
refs/heads/master
<repo_name>friendly/DDAR<file_sep>/pages/Rcode/ch06.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch06") .locals$ch06 <- NULL .pkgs$ch06 <- NULL ## ----ca-haireye1, R.options=list(digits=4)------------------------------- haireye <- margin.table(HairEyeColor, 1 : 2) library(ca) (haireye.ca <- ca(haireye)) ## ----ca-haireye2, output.lines=9----------------------------------------- summary(haireye.ca) ## ----ca-haireye3--------------------------------------------------------- # standard coordinates Phi (Eqn 6.4) and Gamma (Eqn 6.5) (Phi <- haireye.ca$rowcoord) (Gamma <- haireye.ca$colcoord) # demonstrate orthogonality of std coordinates Dr <- diag(haireye.ca$rowmass) zapsmall(t(Phi) %*% Dr %*% Phi) Dc <- diag(haireye.ca$colmass) zapsmall(t(Gamma) %*% Dc %*% Gamma) ## ----ca-haireye-plot, echo=2, h=5.53, w=7, out.width='.8\\textwidth', cap='Correspondence analysis solution for the hair color and eye color data.'---- op <- par(cex=1.4, mar=c(5,4,1,2)+.1) res <- plot(haireye.ca) par(op) ## ----ca-haireye4--------------------------------------------------------- res ## ----ca-mental1---------------------------------------------------------- data("Mental", package="vcdExtra") mental.tab <- xtabs(Freq ~ ses + mental, data = Mental) ## ----ca-mental2, output.lines=9------------------------------------------ mental.ca <- ca(mental.tab) summary(mental.ca) ## ----ca-mental-plot, echo=2:4, h=4, w=6, out.width='.9\\textwidth', cap='Correspondence analysis solution for the Mental health data.'---- op <- par(cex=1.3, mar=c(5,4,1,1)+.1) res <- plot(mental.ca, ylim = c(-.2, .2)) lines(res$rows, col = "blue", lty = 3) lines(res$cols, col = "red", lty = 4) par(op) ## ----ca-victims1, output.lines=13---------------------------------------- data("RepVict", package = "vcd") victim.ca <- ca(RepVict) summary(victim.ca) ## ----ca-victims2--------------------------------------------------------- chisq.test(RepVict) (chisq <- sum(RepVict) * sum(victim.ca$sv^2)) ## ----ca-victims-plot, echo=2:4, h=6, w=6, out.width='.65\\textwidth', cap='2D CA solution for the repeat victimization data. Lines connect the category points for first and second occurrence to highlight these relations.', fig.pos='!htb'---- op <- par(cex=1.3, mar=c(4,4,1,1)+.1) res <- plot(victim.ca, labels = c(2, 0)) segments(res$rows[,1], res$rows[,2], res$cols[,1], res$cols[,2]) legend("topleft", legend = c("First", "Second"), title = "Occurrence", col = c("blue", "red"), pch = 16 : 17, bg = "gray90") par(op) ## ----RVsym, fig.show='hide'---------------------------------------------- RVsym <- (RepVict + t(RepVict)) / 2 RVsym.ca <- ca(RVsym) res <- plot(RVsym.ca) all.equal(res$rows, res$cols) ## ----TV2-1--------------------------------------------------------------- data("TV", package = "vcdExtra") TV2 <- margin.table(TV, c(1, 3)) TV2 ## ----TV2-ca-results, output.lines=5-------------------------------------- TV.ca <- ca(TV2) TV.ca ## ----TV2-ca, eval=FALSE-------------------------------------------------- ## res <- plot(TV.ca) ## segments(0, 0, res$cols[,1], res$cols[,2], col = "red", lwd = 2) ## ----TV2-mosaic, eval=FALSE---------------------------------------------- ## days.order <- order(TV.ca$rowcoord[,1]) ## mosaic(t(TV2[days.order,]), shade = TRUE, legend = FALSE, ## labeling = labeling_residuals, suppress=0) ## ----stacking-demo------------------------------------------------------- set.seed(1234) dim <- c(3, 2, 2, 2) tab <- array(rpois(prod(dim), 15), dim = dim) dimnames(tab) <- list(Pet = c("dog", "cat", "bird"), Age = c("young", "old"), Color = c("black", "white"), Sex = c("male", "female")) ## ----stacking-demo1------------------------------------------------------ ftable(Pet + Age ~ Color + Sex, tab) ## ----stacking-demo2, R.options=list(width=96)---------------------------- (pet.mat <- as.matrix(ftable(Pet + Age ~ Color + Sex, tab), sep = '.')) ## ----stacking-demo3, results='hide'-------------------------------------- tab.df <- as.data.frame(as.table(tab)) tab.df <- within(tab.df, {Pet.Age = interaction(Pet, Age) Color.Sex = interaction(Color, Sex) }) xtabs(Freq ~ Color.Sex + Pet.Age, data = tab.df) ## ----ca-suicide1--------------------------------------------------------- data("Suicide", package = "vcd") # interactive coding of sex and age.group Suicide <- within(Suicide, { age_sex <- paste(age.group, toupper(substr(sex, 1, 1))) }) ## ----ca-suicide2--------------------------------------------------------- suicide.tab <- xtabs(Freq ~ age_sex + method2, data = Suicide) suicide.tab ## ----ca-suicide3, output.lines=13---------------------------------------- suicide.ca <- ca(suicide.tab) summary(suicide.ca) ## ----ca-suicide-plot, echo=2, h=6, w=6, out.width='.7\\textwidth', cap='2D CA solution for the stacked [AgeSex][Method] table of the suicide data.', scap='2D CA solution for the stacked AgeSex, Method table of the suicide data.'---- op <- par(cex=1.3, mar=c(4,4,1,1)+.1) plot(suicide.ca) par(op) ## ----ca-suicide4--------------------------------------------------------- suicide.tab3 <- xtabs(Freq ~ sex + age.group + method2, data = Suicide) ## ----ca-suicide5--------------------------------------------------------- # methods, ordered as in the table suicide.ca$colnames # order of methods on CA scores for Dim 1 suicide.ca$colnames[order(suicide.ca$colcoord[,1])] # reorder methods by CA scores on Dim 1 suicide.tab3 <- suicide.tab3[, , order(suicide.ca$colcoord[,1])] # delete "other" suicide.tab3 <- suicide.tab3[,, -5] ftable(suicide.tab3) ## ----ca-suicide-mosaic, h=6, w=6, out.width='.7\\textwidth', cap='Mosaic display showing deviations from the model [AgeSex][Method] for the suicide data.', scap='Mosaic display showing deviations from the model AgeSex Method for the suicide data', fig.pos='!htb'---- library(vcdExtra) mosaic(suicide.tab3, shade = TRUE, legend = FALSE, expected = ~ age.group * sex + method2, labeling_args = list(abbreviate_labs = c(FALSE, FALSE, 5)), rot_labels = c(0, 0, 0, 90)) ## ----ca-suicide6--------------------------------------------------------- # two way, ignoring sex suicide.tab2 <- xtabs(Freq ~ age.group + method2, data = Suicide) suicide.tab2 suicide.ca2 <- ca(suicide.tab2) ## ----ca-suicide7--------------------------------------------------------- # relation of sex and method suicide.sup <- xtabs(Freq ~ sex + method2, data = Suicide) suicide.tab2s <- rbind(suicide.tab2, suicide.sup) ## ----ca-suicide8, output.lines=11---------------------------------------- suicide.ca2s <- ca(suicide.tab2s, suprow = 6 : 7) summary(suicide.ca2s) ## ----ca-suicide-sup, echo=2:3, h=3, w=6, out.width='.65\\textwidth', cap='2D CA solution for the [Age] [Method] marginal table. Category points for Sex are shown as supplementary points.', scap='2D CA solution for the Age Method marginal table.', fig.pos="H"---- op <- par(cex=1.3, mar=c(4,4,1,1)+.1) res <- plot(suicide.ca2s, pch = c(16, 15, 17, 24)) lines(res$rows[6 : 7,]) par(op) ## ----mca-indicator1------------------------------------------------------ haireye.df <- cbind( as.data.frame(haireye), model.matrix(Freq ~ Hair + Eye, data=haireye, contrasts.arg=list(Hair=diag(4), Eye=diag(4)))[,-1] ) haireye.df ## ----mca-indicator2------------------------------------------------------ Z <- expand.dft(haireye.df)[,-(1:2)] vnames <- c(levels(haireye.df$Hair), levels(haireye.df$Eye)) colnames(Z) <- vnames dim(Z) ## ----mca-indicator3------------------------------------------------------ (N <- t(as.matrix(Z[,1:4])) %*% as.matrix(Z[,5:8])) ## ----mca-haireye0, fig.keep='none'--------------------------------------- Z.ca <- ca(Z) res <- plot(Z.ca, what = c("none", "all")) ## ----mca-haireye1, echo=FALSE, h=6, w=8, out.width='.8\\textwidth', cap='Correspondence analysis of the indicator matrix Z for the hair color--eye color data. The category points are joined separately by lines for the hair color and eye color categories.', fig.pos="t"---- # customized plot res <- plot(Z.ca, what=c("none", "all"), labels = 0, pch = ".", xpd = TRUE) # extract factor names and levels coords <- data.frame(res$cols) coords$factor <- rep(c("Hair", "Eye"), each = 4) coords$levels <- rownames(res$cols) coords # sort by Dim 1 coords <- coords[ order(coords[,"factor"], coords[,"Dim1"]), ] cols <- c("blue", "red") nlev <- c(4,4) text(coords[,1:2], coords$levels, col=rep(cols, nlev), pos=2, cex=1.2) points(coords[,1:2], pch=rep(16:17, nlev), col=rep(cols, nlev), cex=1.2) lines(Dim2 ~ Dim1, data=coords, subset=factor=="Eye", lty=1, lwd=2, col=cols[1]) lines(Dim2 ~ Dim1, data=coords, subset=factor=="Hair", lty=1, lwd=2, col=cols[2]) ## ----Burt1--------------------------------------------------------------- Burt <- t(as.matrix(Z)) %*% as.matrix(Z) rownames(Burt) <- colnames(Burt) <- vnames Burt ## ----Burt2, fig.keep='none'---------------------------------------------- Burt.ca <- ca(Burt) plot(Burt.ca) ## ----presex-mca2, output.lines=10---------------------------------------- data("PreSex", package = "vcd") PreSex <- aperm(PreSex, 4:1) # order variables G, P, E, M presex.mca <- mjca(PreSex, lambda = "Burt") summary(presex.mca) ## ----presex-mca3, fig.keep='none', results='hide'------------------------ plot(presex.mca) ## ----presex-mca-plot, h=6, w=6, out.width='.7\\textwidth', cap='MCA plot of the Burt matrix for the PreSex data. The category points are joined separately by lines for the factor variables.', fig.pos='!htb', out.extra='trim=0 10 20 60', fig.pos="H"---- # plot, but don't use point labels or points res <- plot(presex.mca, labels = 0, pch = ".", cex.lab = 1.2) # extract factor names and levels coords <- data.frame(res$cols, presex.mca$factors) nlev <- presex.mca$levels.n fact <- unique(as.character(coords$factor)) cols <- c("blue", "red", "brown", "black") points(coords[,1:2], pch=rep(16:19, nlev), col=rep(cols, nlev), cex=1.2) text(coords[,1:2], label=coords$level, col=rep(cols, nlev), pos=3, cex=1.2, xpd=TRUE) lwd <- c(2, 2, 2, 4) for(i in seq_along(fact)) { lines(Dim2 ~ Dim1, data = coords, subset = factor==fact[i], lwd = lwd[i], col = cols[i]) } legend("bottomright", legend = c("Gender", "PreSex", "ExtraSex", "Marital"), title = "Factor", title.col = "black", col = cols, text.col = cols, pch = 16:19, bg = "gray95", cex = 1.2) ## ----titanic-mca1-------------------------------------------------------- titanic.mca <- mjca(Titanic) ## ----titanic-mca2, output.lines=9---------------------------------------- summary(titanic.mca) ## ----titanic-mca3, fig.keep='none', results='hide', echo=FALSE----------- res <- plot(titanic.mca) ## ----titanic-mca-plot, echo=FALSE, h=6, w=6, out.width='.8\\textwidth', cap='MCA plot of the Titanic data. The category points are joined separately by lines for the factor variables.', fig.pos='!htb'---- # plot, but don't use point labels or points res <- plot(titanic.mca, labels=0, pch='.', cex.lab=1.2) # extract factor names and levels coords <- data.frame(res$cols, titanic.mca$factors) cols <- c("blue", "red", "brown", "black") nlev <- c(4,2,2,2) points(coords[,1:2], pch=rep(16:19, nlev), col=rep(cols, nlev), cex=1.2) pos <- c(3,1,1,3) text(coords[,1:2], labels=coords$level, col=rep(cols, nlev), pos=rep(pos,nlev), cex=1.1, xpd=TRUE) coords <- coords[ order(coords[,"factor"], coords[,"Dim1"]), ] lines(Dim2 ~ Dim1, data=coords, subset=factor=="Class", lty=1, lwd=2, col="blue") lines(Dim2 ~ Dim1, data=coords, subset=factor=="Sex", lty=1, lwd=2, col="red") lines(Dim2 ~ Dim1, data=coords, subset=factor=="Age", lty=1, lwd=2, col="brown") lines(Dim2 ~ Dim1, data=coords, subset=factor=="Survived", lty=1, lwd=2, col="black") legend("topleft", legend=c("Class", "Sex", "Age", "Survived"), title="Factor", title.col="black", col=cols, text.col=cols, pch=16:19, bg="gray95", cex=1.2) ## ----suicide-ca---------------------------------------------------------- suicide.tab <- xtabs(Freq ~ age_sex + method2, data = Suicide) suicide.ca <- ca(suicide.tab) ## ----ca-suicide-biplot, echo=2, h=6, w=6, out.width='.8\\textwidth', cap='CA biplot of the suicide data using the contribution biplot scaling. Associations between the age--sex categories and the suicide methods can be read as the projections of the points on the vectors. The lengths of the vectors for the suicide categories reflect their contributions to this representation in a 2D plot. ', fig.pos='!htb'---- op <- par(cex=1.3, mar=c(4,4,1,1)+.1, lwd=2) plot(suicide.ca, map = "colgreen", arrows = c(FALSE, TRUE)) par(op) ## ----cabipl-suicide, eval=FALSE------------------------------------------ ## library(UBbipl) ## cabipl(as.matrix(suicide.tab), ## axis.col = gray(.4), ax.name.size = 1, ## ca.variant = "PearsonResA", ## markers = FALSE, ## row.points.size = 1.5, ## row.points.col = rep(c("red", "blue"), 4), ## plot.col.points = FALSE, ## marker.col = "black", marker.size = 0.8, ## offset = c(2, 2, 0.5, 0.5), ## offset.m = rep(-0.2, 14), ## output = NULL) ## ----biplot-soccer1------------------------------------------------------ data("UKSoccer", package = "vcd") dimnames(UKSoccer) <- list(Home = paste0("H", 0:4), Away = paste0("A", 0:4)) ## ----biplot-soccer2------------------------------------------------------ soccer.pca <- prcomp(log(UKSoccer + 1), center = TRUE, scale. = FALSE) ## ----biplot-soccer-plot, echo=1:2, h=6, w=6, out.width='.7\\textwidth', cap='Biplot for the biadditive representation of independence for the UK soccer scores. The row and column categories are independent in this plot when they appear as points on approximately orthogonal lines.', fig.pos='!htb'---- biplot(soccer.pca, scale = 0, var.axes = FALSE, col = c("blue", "red"), cex = 1.2, cex.lab = 1.2, xlab = "Dimension 1", ylab = "Dimension 2") # get the row and column scores rscores <- soccer.pca$x[,1:2] cscores <- soccer.pca$rotation[,1:2] # means, excluding A2 and H2 rmean <- colMeans(rscores[-3,])[2] cmean <- colMeans(cscores[-3,])[1] abline(h = rmean, col = "blue", lwd = 2) abline(v = cmean, col = "red", lwd = 2) abline(h = 0, lty = 3, col = "gray") abline(v = 0, lty = 3, col = "gray") ## ----biplot-soccer3, eval=FALSE------------------------------------------ ## # get the row and column scores ## rscores <- soccer.pca$x[, 1 : 2] ## cscores <- soccer.pca$rotation[, 1 : 2] ## # means, excluding A2 and H2 ## rmean <- colMeans(rscores[-3,])[2] ## cmean <- colMeans(cscores[-3,])[1] ## ## abline(h = rmean, col = "blue", lwd = 2) ## abline(v = cmean, col = "red", lwd = 2) ## abline(h = 0, lty = 3, col = "gray") ## abline(v = 0, lty = 3, col = "gray") <file_sep>/README.md # DDAR Development for the **Discrete Data Analysis with R** web site ## Requirements ## PHP 5.3.10 or greater (5.4+ preferred) Web server (e.g. Apache) ## Overview ## This is a simple custom php/html framework. A high-level overview of how it works, as follows: > All site URLs are routed to the `index.php` file. Based on the URL's path, > the routing mechanism determines which static .html files > to serve and loads it in place inside an outer html wrapper page. ## Installation ## ### Apache Web Server ### As described above, all URLs are routed to the `index.php` file. Apache needs a few things in place to make this happen: #### Step 1 #### You will need to enable **url rewriting** in your Apache `httpd.conf` file, or add it via a rewriting package. #### Step 2 #### If you are using a ``` <VirtualHost>``` directive to define your web site, make sure it resembles the following. *Note*, the ``` <Directory>``` block. This allows the project to define an `.htaccess` file that sets up URL rewriting. ``` apacheconf <VirtualHost *:80> DocumentRoot "/path/to/your/web/directory" ServerName web <Directory "/path/to/your/web/directory"> AllowOverride All Options FollowSymLinks </Directory> </VirtualHost> ``` If you are not using a virtual host file and are serving a single web site, then look for the ``` apacheconf <Directory>``` block in Apache's `httpd.conf` file. Update as follows: ``` apacheconf AllowOverride All Options FollowSymLinks ``` #### .htaccess #### You will also need to add an `.htaccess` file to your site root. This will setup URL rewriting. ``` apacheconf RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php [L] ``` **Note:** If you are using an `Alias` directive, you will need to add a `RewriteBase` directive to the `.htaccess` file that points to the URL-path of your Alias. ### Directory permissions ### After installing the website, please make both the `/scripts/bootstrap` and `/styles/bootstrap` directories writable by the web server. ## Composer package dependencies ## ### External Libraries ### - [AltoRouter](http://altorouter.com) - [Bootstrap](http://getbootstrap.com/) - [DotEnv](https://github.com/vlucas/phpdotenv) This project requires [Composer](https://getcomposer.org/) to set up project dependencies. ### To install composer: ### ``` bash curl -sS https://getcomposer.org/installer | php -- --filename=composer ``` `composer` is then executable (by php) in the current directory. #### On project installation #### Run the following composer commands to install the dependencies: ``` bash composer install composer run-script compile ``` #### On project updates #### Run the following composer commands to update the dependencies: ``` bash composer update composer run-script compile ``` **Note:** `run-script compile` copies Bootstrap files to `{styles,scripts}/bootstrap`. ## Environment variable ## You will need to create a `.env` file in the project's root directory with the following environment variable that defines which sub directory your site lives in. The following example defined the site being served from the root directory. ``` bash BASEPATH="/" ``` If you are serving this project from a subdirectory of the website's root, change the above to point to the location of the subdirectory from the web root, i.e. ``` bash BASEPATH="/subdirectory" ``` **Important:** Do not include a trailing slash if you are declaring a sub directory. **Note:** If you are serving images in .html files, you will need to manually update their paths to be relative to the sub directory. ## Site Map ## This site is made up of the following initial files: ``` - index.php - images/ - pages/ - chapters/ - ch01.html - ch01/ - authors.html - error.html - home.html - other.html - using.html - scripts/ - src/ - styles/ ``` ## Usage ## ### index.php ### > This is the main framework entry point. This file handles the setup of the > html document, including the navigation and dynamic inclusion of the pages > and chapters. > > **Note:** All static files in this file, are served via a `urlfor` helper > function. This helper sets the basepath for any scripts or pages linked to > from this page. If you plan on adding any files or pages, you will need to > use this helper as well. ### images/ ### > This directory contains the global site images ### pages/ ### > This directory contains the main pages and the chapter pages. The main pages > in this directory can be updated when needed. They are however hard-coded > into the navigation in the index.php page. So adding any new pages will > require you to add them to the index.php navigation markup. ### pages/chapters/ ### > This directory contains the chapter files. This part of the navigation is > dynamically generated by the `index.php` file. When listing chapters, the > `index.php` script scans the `pages/chapters/` directory, looks for any files > of the form (e.g.) `ch01.html`, and then adds that to the chapter list in the > chapter navigation drop down menu. ### /pages/chapters/*.html ### > This directory is where you would store all the images and assets for the any > chapter files. Ideally you would keep assets for the chapters contained in > this way so that there would be a `ch01.html` file and its corresponding > `ch01/` directory where its assets would live. > The idea here is that you will continue to render the chapter files from > markdown using whatever process you have in place. The only caveat is that > the rendered .html files should ideally not contain `<html>`, `<head>`, or > `<body>` tags. They should only contain the markup inside the `<body>` tag. ### scripts/ ### > This directory contains the global site javascript files ### src/ ### > This directory contains any php libraries or helper functions used in the > `lindex.php` page. It contains a custom URL Router and some helpers. ### styles/ ### > This directory contains a `main.css` file which is used for the global > styles. It also contains a `page.css` file (where you should put > page-specific css styles), and a `chapters.css` file (where you should put > chapter-specific css styles). > You can change the markup of any of the pages to suit. Keep in mind that since > this site uses the Bootstrap framework, you should use Bootstrap markup and > classes wherever possible. Its not imperative that you do, but highly > suggested since using the Bootstrap styles will keep the content responsive. > > Read the Bootstrap documentation for full details: > [http://getbootstrap.com/](http://getbootstrap.com/) <file_sep>/src/helpers.php <?php /** * Get the BASEPATH env var * @return string */ function basepath() { $path = getenv('BASEPATH'); if (empty($path)) { return ''; } return rtrim($path, '/'); } /** * Build a url for the static path * @param string $path * @return string */ function urlfor($path) { return basepath() . $path; } /** * Build the chapter navigation sub pages * @param string $path * @return string */ function renderChapterNavigation($path) { $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST ); $items = array(); foreach ($objects as $o) { $filename = $o->getFileName(); $re = '/ch([0-9]{1,2})\.html/'; preg_match($re, $filename, $matches); if (count($matches) == 2) { $filename = basename($filename, '.html'); $filepath = '/' . $path . '/' . $filename; $items[$matches[1]] = $filepath; } } ksort($items); $html = ''; foreach ($items as $num=>$href) { $href = basepath() . $href; $html .= '<li>' . '<a class="page chapter"' . ' href="' . $href . '">' . 'Chapter ' . $num . '</a>' . '</li>' . PHP_EOL; } return $html; } <file_sep>/pages/Rcode/ch03.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch03", fig.pos = 'tb') require(vcdExtra, quietly = TRUE, warn.conflicts = FALSE) .locals$ch03 <- NULL .pkgs$ch03 <- NULL ## ----arbuthnot1, echo=-1, h=4, w=7, out.width=".75\\textwidth", fig.pos='t', cap="Arbuthnot's data on male/female sex ratios in London, 1629--1710, together with a (loess) smoothed curve (blue) over time and the mean Pr(Male).", scap="Arbuthnot's data on male/female sex ratios"---- op <- par(mar = c(4,4,1,1) + .1, cex.lab = 1.25) data("Arbuthnot", package = "HistData") with(Arbuthnot, { prob = Males / (Males + Females) plot(x = Year, y = prob, type = "b", ylim = c(0.5, 0.54), ylab = "Pr (Male)") abline(h = 0.5, col = "red", lwd = 2) abline(h = mean(prob), col = "blue") lines(loess.smooth(Year, prob), col = "blue", lwd = 2) text(x = 1640, y = 0.5, expression(H[0]: "Pr(Male)=0.5"), pos = 3, col = "red") }) ## ----saxony-barplot, echo=-1, w=8, h=4, out.width=".75\\textwidth", cap="Number of males in Saxony families of size 12."---- spar() data("Saxony", package = "vcd") barplot(Saxony, xlab = "Number of males", ylab = "Number of families", col = "lightblue", cex.lab = 1.5) ## ----dice, w=8, h=4, out.width=".75\\textwidth", cap="Weldon's dice data, frequency distribution of 5s and 6s in throws of 12 dice."---- data("WeldonDice", package = "vcd") dimnames(WeldonDice)$n56[11] <- "10+" barplot(WeldonDice, xlab = "Number of 5s and 6s", ylab = "Frequency", col = "lightblue", cex.lab = 1.5) ## ----horsekicks, w=8, h=4, out.width=".75\\textwidth", cap="HorseKicks data, distribution of the number of deaths in 200 corps-years."---- data("HorseKicks", package = "vcd") barplot(HorseKicks, xlab = "Number of deaths", ylab = "Frequency", col = "lightblue", cex.lab = 1.5) ## ----federalist, w=8, h=4, out.width=".75\\textwidth", cap="Federalist Papers data, distribution of the uses of the word \\emph{may}.", scap="Federalist Papers data"---- data("Federalist", package = "vcd") barplot(Federalist, xlab = "Occurrences of 'may'", ylab = "Number of blocks of text", col = "lightgreen", cex.lab = 1.5) ## ----cyclists1----------------------------------------------------------- data("CyclingDeaths", package = "vcdExtra") CyclingDeaths.tab <- table(CyclingDeaths$deaths) CyclingDeaths.tab ## ----cyclists2, w=8, h=4, out.width=".75\\textwidth", cap="Frequencies of number of cyclist deaths in two-week periods in London, 2005--2012."---- barplot(CyclingDeaths.tab, xlab = "Number of deaths", ylab = "Number of fortnights", col = "pink", cex.lab = 1.5) ## ----butterfly, w=10, h=4, out.width=".9\\textwidth", cap="Butterfly species in Malaya."---- data("Butterfly", package = "vcd") barplot(Butterfly, xlab = "Number of individuals", ylab = "Number of species", cex.lab = 1.5) ## ----dbinom12, w=8, h=4, out.width=".75\\textwidth", cap="Binomial distribution for $k=0,\\dots,12$ successes in 12 trials and $p$=1/3."---- k <- 0 : 12 Pk <- dbinom(k, 12, 1/3) b <- barplot(Pk, names.arg = k, xlab = "Number of successes", ylab = "Probability") lines(x = b, y = Pk, col = "red") ## ----weldon-dbinom------------------------------------------------------- Weldon_df <- as.data.frame(WeldonDice) # convert to data frame k <- 0 : 12 # same as seq(0, 12) Pk <- dbinom(k, 12, 1/3) # binomial probabilities Pk <- c(Pk[1:10], sum(Pk[11:13])) # sum values for 10+ Exp <- round(26306 * Pk, 5) # expected frequencies Diff <- Weldon_df$Freq - Exp # raw residuals Chisq <- Diff^2 / Exp data.frame(Weldon_df, Prob = round(Pk, 5), Exp, Diff, Chisq) ## ------------------------------------------------------------------------ p <- c(1/6, 1/3, 1/2, 2/3) k <- 0 : 12 Prob <- outer(k, p, function(k, p) dbinom(k, 12, p)) str(Prob) ## ----dbinom2-plot2, echo=-1, w=8, h=4, out.width=".75\\textwidth", cap="Binomial distributions for $k=0, \\dots, 12$ successes in $n=12$ trials, and four values of $p$."---- op <- par(mar = c(5,4,1,1) + .1) col <- palette()[2:5] matplot(k, Prob, type = "o", pch = 15 : 17, col = col, lty = 1, xlab = "Number of Successes", ylab = "Probability") legend("topright", legend = c("1/6","1/3","1/2","2/3"), pch = 15 : 17, lty = 1, col = col, title = "Pr(Success)") ## ----soccer-stats1------------------------------------------------------- data("UKSoccer", package = "vcd") soccer.df <- as.data.frame(UKSoccer, stringsAsFactors = FALSE) soccer.df <- within(soccer.df, { Home <- as.numeric(Home) # make numeric Away <- as.numeric(Away) # make numeric Total <- Home + Away # total goals }) str(soccer.df) ## ----soccer-stats2------------------------------------------------------- soccer.df <- expand.dft(soccer.df) # expand to ungrouped form apply(soccer.df, 2, FUN = function(x) c(mean = mean(x), var = var(x))) ## ----cyclists2-1--------------------------------------------------------- with(CyclingDeaths, c(mean = mean(deaths), var = var(deaths), ratio = mean(deaths) / var(deaths))) ## ----cyclists2-2--------------------------------------------------------- mean.deaths <- mean(CyclingDeaths$deaths) ppois(5, mean.deaths, lower.tail = FALSE) ## ----dpois1-------------------------------------------------------------- KL <- expand.grid(k = 0 : 20, lambda = c(1, 4, 10)) pois_df <- data.frame(KL, prob = dpois(KL$k, KL$lambda)) pois_df$lambda = factor(pois_df$lambda) str(pois_df) ## ----dpois-xyplot1, h=4, w=9, out.width="\\textwidth", cap="Poisson distributions for $\\lambda$ = 1, 4, 10, in a multi-panel display."---- library(lattice) xyplot(prob ~ k | lambda, data = pois_df, type = c("h", "p"), pch = 16, lwd = 4, cex = 1.25, layout = c(3, 1), xlab = list("Number of events (k)", cex = 1.25), ylab = list("Probability", cex = 1.25)) ## ----dpois-xyplot2, h=4, w=8, out.width=".8\\textwidth", cap="Poisson distributions for $\\lambda$ = 1, 4, 10, using direct labels."---- mycol <- palette()[2:4] plt <- xyplot(prob ~ k, data = pois_df, groups = lambda, type = "b", pch = 15 : 17, lwd = 2, cex = 1.25, col = mycol, xlab = list("Number of events (k)", cex = 1.25), ylab = list("Probability", cex = 1.25), ylim = c(0, 0.4)) library(directlabels) direct.label(plt, list("top.points", cex = 1.5, dl.trans(y = y + 0.1))) ## ----dpois-ggplot1------------------------------------------------------- library(ggplot2) gplt <- ggplot(pois_df, aes(x = k, y = prob, colour = lambda, shape = lambda)) + geom_line(size = 1) + geom_point(size = 3) + xlab("Number of events (k)") + ylab("Probability") ## ----dpois-ggplot2, h=4, w=8, out.width=".8\\textwidth", cap="Poisson distributions for $\\lambda$ = 1, 4, 10, using \\pkg{ggplot2}."---- gplt + theme(legend.position = c(0.8, 0.8)) + # manually move legend theme(axis.text = element_text(size = 12), axis.title = element_text(size = 14, face = "bold")) ## ----dnbin1-------------------------------------------------------------- k <- 2 n <- 2 : 4 p <- 0.2 dnbinom(k, n, p) (mu <- n * (1 - p) / p) dnbinom(k, n, mu = mu) ## ----dnbin2-------------------------------------------------------------- XN <- expand.grid(k = 0 : 20, n = c(2, 4, 6), p = c(0.2, 0.3, 0.4)) nbin_df <- data.frame(XN, prob = dnbinom(XN$k, XN$n, XN$p)) nbin_df$n <- factor(nbin_df$n) nbin_df$p <- factor(nbin_df$p) str(nbin_df) ## ----dnbin3, h=8, w=8, out.width=".8\\textwidth", cap="Negative binomial distributions for $n = 2, 4, 6$ and $p=0.2, 0.3, 0.4$, using \\func{xyplot}.", fig.pos='!htb'---- xyplot(prob ~ k | n + p, data = nbin_df, xlab = list("Number of failures (k)", cex = 1.25), ylab = list("Probability", cex = 1.25), type = c("h", "p"), pch = 16, lwd = 2, strip = strip.custom(strip.names = TRUE) ) ## ----dnbin5-------------------------------------------------------------- n <- c(2, 4, 6) p <- c(0.2, 0.3, 0.4) NP <- outer(n, p, function(n, p) n * (1 - p) / p) dimnames(NP) <- list(n = n, p = p) NP ## ----horse-gof1---------------------------------------------------------- # goodness-of-fit test tab <- as.data.frame(HorseKicks, stringsAsFactors = FALSE) colnames(tab) <- c("nDeaths", "Freq") str(tab) (lambda <- weighted.mean(as.numeric(tab$nDeaths), w = tab$Freq)) ## ----horse-gof2---------------------------------------------------------- phat <- dpois(0 : 4, lambda = lambda) exp <- sum(tab$Freq) * phat chisq <- (tab$Freq - exp)^2 / exp GOF <- data.frame(tab, phat, exp, chisq) GOF ## ----horse-gof3---------------------------------------------------------- sum(chisq) # chi-square value pchisq(sum(chisq), df = nrow(tab) - 2, lower.tail = FALSE) ## ----sax.fit------------------------------------------------------------- data("Saxony", package = "vcd") Sax_fit <- goodfit(Saxony, type = "binomial") unlist(Sax_fit$par) # estimated parameters ## ----sax.fit1------------------------------------------------------------ names(Sax_fit) # components of "goodfit" objects Sax_fit # print method summary(Sax_fit) # summary method ## ----dice.fit------------------------------------------------------------ data("WeldonDice", package = "vcd") dice_fit <- goodfit(WeldonDice, type = "binomial", par = list(size = 12)) unlist(dice_fit$par) ## ----dice.fit1----------------------------------------------------------- print(dice_fit, digits = 0) summary(dice_fit) ## ----HF.fit-------------------------------------------------------------- data("HorseKicks", package = "vcd") HK_fit <- goodfit(HorseKicks, type = "poisson") HK_fit$par HK_fit ## ----HF.fit1------------------------------------------------------------- summary(HK_fit) ## ----Fedfit1------------------------------------------------------------- data("Federalist", package = "vcd") Fed_fit0 <- goodfit(Federalist, type = "poisson") unlist(Fed_fit0$par) Fed_fit0 ## ----Fedfit2------------------------------------------------------------- summary(Fed_fit0) ## ----Fedfit3------------------------------------------------------------- Fed_fit1 <- goodfit(Federalist, type = "nbinomial") unlist(Fed_fit1$par) summary(Fed_fit1) ## ----Fed0-plots1, h=6, w=6, out.width='.48\\textwidth', cap='Plots for the Federalist Papers data, fitting the Poisson model. Each panel shows the observed frequencies as bars and the fitted frequencies as a smooth curve. Left: raw frequencies; right: plotted on a square-root scale to emphasize smaller frequencies.'---- plot(Fed_fit0, scale = "raw", type = "standing") plot(Fed_fit0, type = "standing") ## ----Fed0-plots2, h=6, w=6, out.width='.48\\textwidth', cap='Plots for the Federalist Papers data, fitting the Poisson model. Left: hanging rootogram; Right: deviation rootogram. Color reflects the sign and magnitude of the contributions to lack of fit.'---- plot(Fed_fit0, type = "hanging", shade = TRUE) plot(Fed_fit0, type = "deviation", shade = TRUE) ## ----Fed0-Fed1, h=5, w=6, out.width='.48\\textwidth', cap='Hanging rootograms for the Federalist Papers data, comparing the Poisson and negative binomial models.', fig.pos="!b"---- plot(Fed_fit0, main = "Poisson", shade = TRUE, legend = FALSE) plot(Fed_fit1, main = "Negative binomial", shade = TRUE, legend = FALSE) ## ----But-fit, h=5, w=6, out.width='.48\\textwidth', cap='Hanging rootograms for the Butterfly data, comparing the Poisson and negative binomial models. The lack of fit for both is readily apparent.'---- data("Butterfly", package = "vcd") But_fit1 <- goodfit(Butterfly, type = "poisson") But_fit2 <- goodfit(Butterfly, type = "nbinomial") plot(But_fit1, main = "Poisson", shade = TRUE, legend = FALSE) plot(But_fit2, main = "Negative binomial", shade = TRUE, legend = FALSE) ## ----ordplot1, h=6, w=6, out.width='.5\\textwidth', cap='Ord plot for the Butterfly data. The slope and intercept in the plot correctly diagnoses the log-series distribution.'---- ord <- Ord_plot(Butterfly, main = "Butterfly species collected in Malaya", gp = gpar(cex = 1), pch = 16) ord ## ----ord-horse----------------------------------------------------------- data("HorseKicks", package = "vcd") nk <- as.vector(HorseKicks) k <- as.numeric(names(HorseKicks)) nk1 <- c(NA, nk[-length(nk)]) y <- k * nk / nk1 weight <- sqrt(pmax(nk, 1) - 1) (ord_df <- data.frame(k, nk, nk1, y, weight)) coef(lm(y ~ k, weights = weight, data = ord_df)) ## ----ordplot2, h=6, w=6, out.width='.5\\textwidth', cap='Ord plot for the HorseKicks data. The plot correctly diagnoses the Poisson distribution.'---- Ord_plot(HorseKicks, main = "Death by horse kicks", gp = gpar(cex = 1), pch = 16) ## ----ordplot3, h=6, w=6, out.width='.48\\textwidth', fig.keep="none"----- Ord_plot(Federalist, main = "Instances of 'may' in Federalist Papers", gp = gpar(cex = 1), pch = 16) ## ----ordplot3plot, h=6, w=6, out.width='.48\\textwidth', cap='Ord plots for the Federalist (left) and WomenQueue (right) data sets.', echo=FALSE, fig.pos="!b"---- Ord_plot(Federalist, main = "Instances of 'may' in Federalist Papers", gp=gpar(cex=1), pch=16) Ord_plot(WomenQueue, main = "Women in queues of length 10", gp=gpar(cex=1), pch=16) ## ----queues-------------------------------------------------------------- data("WomenQueue", package = "vcd") WomenQueue ## ----ordplot4, h=6, w=6, out.width='.48\\textwidth', fig.keep="none"----- Ord_plot(WomenQueue, main = "Women in queues of length 10", gp = gpar(cex = 1), pch = 16) ## ----distplot1, w=6, h=6, fig.show='hide'-------------------------------- data("HorseKicks", package = "vcd") dp <- distplot(HorseKicks, type = "poisson", xlab = "Number of deaths", main = "Poissonness plot: HorseKicks data") print(dp, digits = 4) ## ----distplot2, w=6, h=6, fig.show='hide'-------------------------------- # leveled version, specifying lambda distplot(HorseKicks, type = "poisson", lambda = 0.61, xlab = "Number of deaths", main = "Leveled Poissonness plot") ## ----distplot3, h=6, w=6, out.width=".49\\textwidth", cap='Diagnostic plots for males in Saxony families. Left: \\func{goodfit} plot; right: \\func{distplot} plot. Both plots show heavier tails than in a binomial distribution.'---- plot(goodfit(Saxony, type = "binomial", par = list(size=12)), shade=TRUE, legend=FALSE, xlab = "Number of males") distplot(Saxony, type = "binomial", size = 12, xlab = "Number of males") ## ----distplot5, h=6, w=6, out.width=".49\\textwidth", cap='Diagnostic plots for the Federalist Papers data. Left: Poissonness plot; right: negative binomialness plot.'---- distplot(Federalist, type = "poisson", xlab = "Occurrences of 'may'") distplot(Federalist, type = "nbinomial", xlab = "Occurrences of 'may'") ## ----sax-glm1------------------------------------------------------------ data("Saxony", package = "vcd") Males <- as.numeric(names(Saxony)) Families <- as.vector(Saxony) Sax.df <- data.frame(Males, Families) ## ----sax-glm2------------------------------------------------------------ # fit binomial (12, p) as a glm Sax.bin <- glm(Families ~ Males, offset = lchoose(12, 0:12), family = poisson, data = Sax.df) # brief model summaries LRstats(Sax.bin) coef(Sax.bin) ## ----sax-glm3------------------------------------------------------------ # double binomial, (12, p, psi) Sax.df$YlogitY <- Males * log(ifelse(Males == 0, 1, Males)) + (12-Males) * log(ifelse(12-Males == 0, 1, 12-Males)) Sax.dbin <- glm(Families ~ Males + YlogitY, offset = lchoose(12,0:12), family = poisson, data = Sax.df) coef(Sax.dbin) LRstats(Sax.bin, Sax.dbin) ## ----sax-glm4------------------------------------------------------------ results <- data.frame(Sax.df, fit.bin = fitted(Sax.bin), res.bin = rstandard(Sax.bin), fit.dbin = fitted(Sax.dbin), res.dbin = rstandard(Sax.dbin)) print(results, digits = 2) ## ----sax-glm5, eval=FALSE, h=6, w=6, out.width=".6\\textwidth", cap='Rootogram for the double binomial model for the Saxony data. This now fits well in the tails of the distribution.'---- ## with(results, vcd::rootogram(Families, fit.dbin, Males, ## xlab = "Number of males")) ## ----phdpubs0-1---------------------------------------------------------- data("PhdPubs", package = "vcdExtra") table(PhdPubs$articles) ## ----phdpubs-rootogram, h=5, w=6, out.width='.48\\textwidth', cap='Hanging rootograms for publications by PhD candidates, comparing the Poisson and negative binomial models. The Poisson model clearly does not fit. The the negative binomial is better, but still has significant lack of fit.'---- library(vcd) plot(goodfit(PhdPubs$articles), xlab = "Number of Articles", main = "Poisson") plot(goodfit(PhdPubs$articles, type = "nbinomial"), xlab = "Number of Articles", main = "Negative binomial") ## ----phdpubs0-2---------------------------------------------------------- summary(goodfit(PhdPubs$articles, type = "nbinomial")) <file_sep>/pages/Rcode/ch02.R ### SECTION ### 2. Working with Categorical Data ### SECTION ### 2.1. Working with R data: vectors, matrices, arrays, and data frames ### SECTION ### 2.1.1. Vectors library(vcdExtra) ## ceating simple vectors c(17, 20, 15, 40) c("female", "male", "female", "male") c(TRUE, TRUE, FALSE, FALSE) ## storing vectors count <- c(17, 20, 15, 40) # assign count # print (sex <- c("female", "male", "female", "male")) # both (passed <- c(TRUE, TRUE, FALSE, FALSE)) ## (repeated) sequences seq(10, 100, by = 10) # give interval seq(0, 1, length.out = 11) # give length (sex <- rep(c("female", "male"), times = 2)) (sex <- rep(c("female", "male"), length.out = 4)) # same (passed <- rep(c(TRUE, FALSE), each = 2)) ### SECTION ### 2.1.2. Matrices ## creating matrices (matA <- matrix(1:8, nrow = 2, ncol = 4)) (matB <- matrix(1:8, nrow = 2, ncol = 4, byrow = TRUE)) (matC <- matrix(1:4, nrow = 2, ncol = 4)) ## dimension attribute and labels for matrices dim(matA) str(matA) dimnames(matA) <- list(c("M", "F"), LETTERS[1:4]) matA str(matA) ## names for dimension names dimnames(matA) <- list(sex = c("M", "F"), group = LETTERS[1:4]) ## or: names(dimnames(matA)) <- c("Sex", "Group") matA str(matA) ## adding rows and columns to matrices rbind(matA, c(10, 20)) cbind(matA, c(10, 20)) ## transposing matrices t(matA) ## calculations with matrices 2 * matA / 100 ### SECTION ### 2.1.3. Arrays ## creating arrays dims <- c(2, 4, 2) (arrayA <- array(1:16, dim = dims)) # 2 rows, 4 columns, 2 layers str(arrayA) (arrayB <- array(1:16, dim = c(2, 8))) # 2 rows, 8 columns str(arrayB) ## labels for arrays dimnames(arrayA) <- list(sex = c("M", "F"), group = letters[1:4], time = c("Pre", "Post")) arrayA str(arrayA) ### SECTION ### 2.1.4. data frames ## creating data frames set.seed(12345) # reproducibility n <- 100 A <- factor(sample(c("a1", "a2"), n, replace = TRUE)) B <- factor(sample(c("b1", "b2"), n, replace = TRUE)) sex <- factor(sample(c("M", "F"), n, replace = TRUE)) age <- round(rnorm(n, mean = 30, sd = 5)) mydata <- data.frame(A, B, sex, age) head(mydata, 5) str(mydata) ## subsetting data frames mydata[1,2] mydata$sex #same as: mydata[,"sex"] or mydata[,3] ## Example 2.1.: Arthritis Treatment library(vcd) # create data file for this example write.table(Arthritis, file = "Arthritis.csv", quote = FALSE, sep = ",") path <- "Arthritis.csv" # set path # for convenience, use path <- file.choose() to retrieve a path # then, use file.show(path) to inspect the data format Arthritis <- read.table(path, header = TRUE, sep = ",") str(Arthritis) ## make Improved an ordered factor levels(Arthritis$Improved) Arthritis$Improved <- ordered(Arthritis$Improved, levels = c("None", "Some", "Marked")) ### SECTION ### 2.2. Forms of categorical data: case form, frequency form, and table form ### SECTION ### 2.2.1. Case Form ## Example 2.2.: Arthritis Treatment data("Arthritis", package = "vcd") # load the data names(Arthritis) # show the variables str(Arthritis) # show the structure head(Arthritis, 5) # first 5 observations, same as Arthritis[1:5,] ## Example 2.3.: General social survey ## creating GSS data in frequency form tmp <- expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")) tmp GSS <- data.frame(tmp, count = c(279, 165, 73, 47, 225, 191)) GSS names(GSS) str(GSS) sum(GSS$count) ### SECTION ### 2.2.3. Table form ## Example 2.4.: Hair and Eye color data("HairEyeColor", package = "datasets") # load the data str(HairEyeColor) # show the structure dim(HairEyeColor) # table dimension sizes dimnames(HairEyeColor) # variable and level names sum(HairEyeColor) # number of cases ## GSS data as a matrix GSS.tab <- matrix(c(279, 73, 225, 165, 47, 191), nrow = 2, ncol = 3, byrow = TRUE) dimnames(GSS.tab) <- list(sex = c("female", "male"), party = c("dem", "indep", "rep")) GSS.tab ## transforming a matrix to a table GSS.tab <- as.table(GSS.tab) str(GSS.tab) ## Example 2.5.: Job Satisfaction JobSat <- matrix(c(1, 2, 1, 0, 3, 3, 6, 1, 10, 10, 14, 9, 6, 7, 12, 11), nrow = 4, ncol = 4) dimnames(JobSat) <- list(income = c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction = c("VeryD", "LittleD", "ModerateS", "VeryS")) JobSat <- as.table(JobSat) JobSat ### SECTION ### 2.3. Ordered factors and reordered tables ## Assigning numeric values as labels dimnames(JobSat)$income <- c(7.5, 20, 32.5, 60) dimnames(JobSat)$satisfaction <- 1:4 ## Assigning a prefix to labels dimnames(JobSat)$income <- paste(1:4, dimnames(JobSat)$income, sep = ":") dimnames(JobSat)$satisfaction <- paste(1:4, dimnames(JobSat)$satisfaction, sep = ":") ## Permuting labels data("HairEyeColor", package = "datasets") HEC <- HairEyeColor[, c(1, 3, 4, 2), ] str(HEC) ## Permuting dimensions str(UCBAdmissions) # vary along the 2nd, 1st, and 3rd dimension in UCBAdmissions UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)$Admit <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admitted", "Department") str(UCB) ### SECTION ### 2.4. Generating tables with table() and xtabs() ## Creating sample data set.seed(12345) # reproducibility n <- 100 A <- factor(sample(c("a1", "a2"), n, replace = TRUE)) B <- factor(sample(c("b1", "b2"), n, replace = TRUE)) sex <- factor(sample(c("M", "F"), n, replace = TRUE)) age <- round(rnorm(n, mean = 30, sd = 5)) mydata <- data.frame(A, B, sex, age) ### SECTION ### 2.4.1. table() ## Creating a 2-Way Frequency Table table(mydata$A, mydata$B) # A will be rows, B will be columns # same: with(mydata, table(A, B)) (mytab <- table(mydata[,1:2])) # same ## marginal sums margin.table(mytab) # sum over A & B margin.table(mytab, 1) # A frequencies (summed over B) margin.table(mytab, 2) # B frequencies (summed over A) addmargins(mytab) # show all marginal totals ## proportions prop.table(mytab) # cell proportions prop.table(mytab, 1) # row proportions prop.table(mytab, 2) # column proportions ## 3-Way Frequency Table mytab <- table(mydata[,c("A", "B", "sex")]) ftable(mytab) ### SECTION ### 2.4.2. xtabs() ## 3-Way Frequency Table mytable <- xtabs(~ A + B + sex, data = mydata) ftable(mytable) # print table summary(mytable) # chi-squared test of independence ## Pretabulated data (GSStab <- xtabs(count ~ sex + party, data = GSS)) summary(GSStab) ### SECTION ### 2.5. Printing tables with structable() and ftable() ### SECTION ### 2.5.1. Text output ## ftable() ftable(UCB) # default #ftable(UCB, row.vars = 1:2) # same result ftable(Admitted + Sex ~ Department, data = UCB) # formula method ## structable() library(vcd) structable(HairEyeColor) # show the table: default structable(Hair + Sex ~ Eye, HairEyeColor) # specify col ~ row variables ### SECTION ### 2.6. Subsetting data ### SECTION ### 2.6.1. Subsetting tables ## Extracting female data from HairEyeColor data HairEyeColor[,,"Female"] ##same using index: HairEyeColor[,,2] ## Applying functions to subsets of the data apply(HairEyeColor, 3, sum) ## Subsetting with more than one level HairEyeColor[c("Black", "Brown"), c("Hazel", "Green"),] ### SECTION ### 2.6.2. Subsetting structables hec <- structable(Eye ~ Sex + Hair, data = HairEyeColor) hec hec["Male",] hec[["Male",]] ## Subsetting with more than one level hec[[c("Male", "Brown"),]] ### SECTION ### 2.6.3. Subsetting data frames ## subsetting using indexes rows <- Arthritis$Sex == "Female" & Arthritis$Age > 68 cols <- c("Treatment", "Improved") Arthritis[rows, cols] ## subsetting using subset subset(Arthritis, Sex == "Female" & Age > 68, select = c(Treatment, Improved)) ## removing columns using subset subset(Arthritis, Sex == "Female" & Age > 68, select = -c(Age, ID)) ### SECTION ### 2.7. Collapsing tables ### SECTION ### 2.7.1. Collapsing over factor tables ## Example 2.6.: Dayton survey data("DaytonSurvey", package = "vcdExtra") str(DaytonSurvey) head(DaytonSurvey) ## data in frequency form: collapse over sex and race Dayton_ACM_df <- aggregate(Freq ~ cigarette + alcohol + marijuana, data = DaytonSurvey, FUN = sum) Dayton_ACM_df ## convert to table form Dayton_tab <- xtabs(Freq ~ cigarette + alcohol + marijuana + sex + race, data = DaytonSurvey) structable(cigarette + alcohol + marijuana ~ sex + race, data = Dayton_tab) ## collapse over sex and race Dayton_ACM_tab <- apply(Dayton_tab, MARGIN = 1:3, FUN = sum) Dayton_ACM_tab <- margin.table(Dayton_tab, 1:3) # same result structable(cigarette + alcohol ~ marijuana, data = Dayton_ACM_tab) ## using the plyr package library(plyr) Dayton_ACM_df <- ddply(DaytonSurvey, .(cigarette, alcohol, marijuana), summarise, Freq = sum(Freq)) ### SECTION ### 2.7.2. Collapsing table levels ## Example 2.8.: Collapsing categories ## create some sample data in frequency form set.seed(12345) # reproducibility sex <- c("Male", "Female") age <- c("10-19", "20-29", "30-39", "40-49", "50-59", "60-69") education <- c("low", "med", "high") dat <- expand.grid(sex = sex, age = age, education = education) counts <- rpois(36, 100) # random Poisson cell frequencies dat <- cbind(dat, counts) # make it into a 3-way table tab1 <- xtabs(counts ~ sex + age + education, data = dat) structable(tab1) ## collapse age to 3 levels, education to 2 levels tab2 <- collapse.table(tab1, age = c("10-29", "10-29", "30-49", "30-49", "50-69", "50-69"), education = c("<high", "<high", "high")) structable(tab2) ### SECTION ### 2.8. Converting among frequency tables and data frames ### SECTION ### 2.8.1. Table form to frequency form ## Example 2.9.: General social survey as.data.frame(GSStab) ## Example 2.10.: Death by horse kick str(as.data.frame(HorseKicks)) ## coercing table names to numbers ... horse.df <- data.frame(nDeaths = as.numeric(names(HorseKicks)), Freq = as.vector(HorseKicks)) str(horse.df) horse.df ## ... and applying weighted.mean() weighted.mean(horse.df$nDeaths, weights=horse.df$Freq) ### SECTION ### 2.8.2. Case form to table form ## Example 2.11. Arthritis treatment Art.tab <- table(Arthritis[,c("Treatment", "Sex", "Improved")]) str(Art.tab) ftable(Art.tab) ### SECTION ### 2.8.3. Table form to case form ## Example 2.12.: Arthritis treatment library(vcdExtra) Art.df <- expand.dft(Art.tab) str(Art.df) ### SECTION ### 2.8.4. Publishing tables to LaTeX or HTML ## the horsekicks data data("HorseKicks", package = "vcd") HorseKicks ## using xtable() library(xtable) xtable(HorseKicks) ## modified output using xtable() tab <- as.data.frame(HorseKicks) colnames(tab) <- c("nDeaths", "Freq") print(xtable(tab), include.rownames = FALSE, include.colnames = TRUE) ## Table 2.2.: horsekicks data in transposed form using xtable() horsetab <- t(as.data.frame(addmargins(HorseKicks))) rownames(horsetab) <- c( "Number of deaths", "Frequency" ) horsetab <- xtable(horsetab, digits = 0, label="tab:xtable5", caption = "von Bortkiewicz's data on deaths by horse kicks", align = paste0("l|", paste(rep("r", ncol(horsetab)), collapse = "")) ) print(horsetab, include.colnames=FALSE, caption.placement="top") ### SECTION ### 2.9. A complex example: TV viewing data ### SECTION ### 2.9.1. Creating data frames and arrays ## reading in the data tv_data <- read.table(system.file("doc", "extdata", "tv.dat", package = "vcdExtra")) str(tv_data) head(tv_data, 5) ## tv_data <- read.table("C:/R/data/tv.dat") ## tv_data <- read.table(file.choose()) ## creating factors within the data frame TV_df <- tv_data colnames(TV_df) <- c("Day", "Time", "Network", "State", "Freq") TV_df <- within(TV_df, { Day <- factor(Day, labels = c("Mon", "Tue", "Wed", "Thu", "Fri")) Time <- factor(Time) Network <- factor(Network) State <- factor(State) }) ## reshaping the table into a 4-way table TV <- array(tv_data[,5], dim = c(5, 11, 5, 3)) dimnames(TV) <- list(c("Mon", "Tue", "Wed", "Thu", "Fri"), c("8:00", "8:15", "8:30", "8:45", "9:00", "9:15", "9:30", "9:45", "10:00", "10:15", "10:30"), c("ABC", "CBS", "NBC", "Fox", "Other"), c("Off", "Switch", "Persist")) names(dimnames(TV)) <- c("Day", "Time", "Network", "State") ## Creating the table using xtabs() TV <- xtabs(V5 ~ ., data = tv_data) dimnames(TV) <- list(Day = c("Mon", "Tue", "Wed", "Thu", "Fri"), Time = c("8:00", "8:15", "8:30", "8:45", "9:00", "9:15", "9:30", "9:45", "10:00", "10:15", "10:30"), Network = c("ABC", "CBS", "NBC", "Fox", "Other"), State = c("Off", "Switch", "Persist")) ### SECTION ### 2.9.2. Subsetting and collapsing ## subsetting data TV <- TV[,,1:3,] # keep only ABC, CBS, NBC TV <- TV[,,,3] # keep only Persist -- now a 3 way table structable(TV) ## collapsing time labels TV2 <- collapse.table(TV, Time = c(rep("8:00-8:59", 4), rep("9:00-9:59", 4), rep("10:00-10:44", 3))) structable(Day ~ Time + Network, TV2) <file_sep>/pages/Rcode/ch07.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch07") .locals$ch07 <- NULL .pkgs$ch07 <- NULL library(ggplot2) theme_set(theme_bw()) # set default ggplot theme ## ----odds---------------------------------------------------------------- library(MASS) p <- c(.05, .10, .25, .50, .75, .90, .95) odds <- p / (1 - p) data.frame(p, odds = as.character(fractions(odds)), logit = log(odds)) ## ----arth-age0, echo=FALSE----------------------------------------------- data("Arthritis", package = "vcd") Arthritis$Better <- as.numeric(Arthritis$Improved > "None") ## ----arth-logi-hist, h=5, w=6, out.width='.6\\textwidth', cap='Plot of the Arthritis treatment data, showing the conditional distributions of the 0/1 observations of the Better response by histograms and boxplots.', echo=-1---- source("functions/logi.hist.plot.R") with(Arthritis, logi.hist.plot(Age, Improved > "None", type = "hist", counts = TRUE, ylabel = "Probability (Better)", xlab = "Age", col.cur = "blue", col.hist = "lightblue", col.box = "lightblue") ) ## ----arth-age1----------------------------------------------------------- data("Arthritis", package = "vcd") Arthritis$Better <- as.numeric(Arthritis$Improved > "None") ## ----arth-age2----------------------------------------------------------- arth.logistic <- glm(Better ~ Age, data = Arthritis, family = binomial) ## ----arth-age2a---------------------------------------------------------- library(lmtest) coeftest(arth.logistic) ## ----arth-age3----------------------------------------------------------- exp(coef(arth.logistic)) exp(10 * coef(arth.logistic)["Age"]) ## ----arth-age4----------------------------------------------------------- arth.lm <- glm(Better ~ Age, data = Arthritis) coef(arth.lm) ## ----arth-test1---------------------------------------------------------- anova(arth.logistic, test = "Chisq") ## ----arth-test2---------------------------------------------------------- library(vcdExtra) LRstats(arth.logistic) ## ----arthritis-age2, echo=FALSE, h=6, w=6, out.width='.6\\textwidth', cap='A version of plot of the Arthritis treatment data (\\figref{fig:arthritis-age}) produced with \\R base graphics, showing logistic, linear regression and lowess fits.', scap='A version of plot of the Arthritis treatment data produced with R base graphics', fig.pos="!b"---- plot(jitter(Better, .1) ~ Age, data = Arthritis, xlim = c(15, 85), pch = 16, ylab = "Probability (Better)") xvalues <- seq(15, 85, 5) pred.logistic <- predict(arth.logistic, newdata=data.frame(Age=xvalues), type="response", se.fit=TRUE) upper <- pred.logistic$fit + 1.96*pred.logistic$se.fit lower <- pred.logistic$fit - 1.96*pred.logistic$se.fit polygon(c(xvalues, rev(xvalues)), c(upper, rev(lower)), col=rgb(0,0,1,.2), border=NA) lines(xvalues, pred.logistic$fit, lwd = 4 , col = "blue") abline(arth.lm, lwd=2) lines(lowess(Arthritis$Age, Arthritis$Better, f = .9), col = "red", lwd = 2) ## ----arth-plot1, eval=FALSE---------------------------------------------- ## plot(jitter(Better, .1) ~ Age, data = Arthritis, ## xlim = c(15, 85), pch = 16, ## ylab="Probability (Better)") ## ----arth-plot2, eval=FALSE---------------------------------------------- ## xvalues <- seq(15, 85, 5) ## pred.logistic <- predict(arth.logistic, ## newdata = data.frame(Age = xvalues), ## type = "response", se.fit = TRUE) ## ----arth-plot3, eval=FALSE---------------------------------------------- ## upper <- pred.logistic$fit + 1.96 * pred.logistic$se.fit ## lower <- pred.logistic$fit - 1.96 * pred.logistic$se.fit ## ----arth-plot4, eval=FALSE---------------------------------------------- ## polygon(c(xvalues, rev(xvalues)), ## c(upper, rev(lower)), ## col = rgb(0, 0, 1, .2), border = NA) ## lines(xvalues, pred.logistic$fit, lwd=4 , col="blue") ## ----arth-plot5, eval=FALSE---------------------------------------------- ## abline(arth.lm, lwd = 2) ## lines(lowess(Arthritis$Age, Arthritis$Better, f = .9), ## col = "red", lwd = 2) ## ----arth-gg1, eval=FALSE------------------------------------------------ ## library(ggplot2) ## # basic logistic regression plot ## gg <- ggplot(Arthritis, aes(x = Age, y = Better)) + ## xlim(5, 95) + ## geom_point(position = position_jitter(height = 0.02, width = 0)) + ## stat_smooth(method = "glm", family = binomial, ## alpha = 0.1, fill = "blue", size = 2.5, fullrange = TRUE) ## ----arth-gg2, eval=FALSE------------------------------------------------ ## # add linear model and loess smoothers ## gg <- gg + stat_smooth(method = "lm", se = FALSE, ## size = 1.2, color = "black", fullrange = TRUE) ## gg <- gg + stat_smooth(method = "loess", se = FALSE, ## span = 0.95, colour = "red", size = 1.2) ## gg # show the plot ## ----nasa-temp1---------------------------------------------------------- data("SpaceShuttle", package = "vcd") shuttle.mod <- glm(cbind(nFailures, 6 - nFailures) ~ Temperature, data = SpaceShuttle, na.action = na.exclude, family = binomial) ## ----nasa-temp2---------------------------------------------------------- SpaceShuttle$trials <- 6 shuttle.modw <- glm(nFailures / trials ~ Temperature, weight = trials, data = SpaceShuttle, na.action = na.exclude, family = binomial) ## ------------------------------------------------------------------------ all.equal(coef(shuttle.mod), coef(shuttle.modw)) ## ------------------------------------------------------------------------ # testing, vs. null model anova(shuttle.mod, test = "Chisq") ## ----nasa-temp-ggplot, h=6, w=8, out.width='.7\\textwidth', cap='Space shuttle data, with fitted logistic regression model.', eval=FALSE---- ## library(ggplot2) ## ggplot(SpaceShuttle, aes(x = Temperature, y = nFailures / trials)) + ## xlim(30, 81) + ## xlab("Temperature (F)") + ## ylab("O-Ring Failure Probability") + ## geom_point(position=position_jitter(width = 0, height = 0.01), ## aes(size = 2)) + ## theme(legend.position = "none") + ## geom_smooth(method = "glm", family = binomial, fill = "blue", ## aes(weight = trials), fullrange = TRUE, alpha = 0.2, ## size = 2) ## ----arth2-glm----------------------------------------------------------- arth.logistic2 <- glm(Better ~ I(Age-50) + Sex + Treatment, data = Arthritis, family = binomial) ## ----arth2-glm2---------------------------------------------------------- coeftest(arth.logistic2) ## ----arth2-glm3, R.options=list(digits=4)-------------------------------- exp(cbind(OddsRatio = coef(arth.logistic2), confint(arth.logistic2))) ## ----arth-cond1, h=4, w=6, out.width='.6\\textwidth', cap='Conditional plot of Arthritis data showing separate points and fitted curves stratified by Treatment. A separate fitted curve is shown for the two treatment conditions, ignoring Sex.'---- library(ggplot2) gg <- ggplot(Arthritis, aes(Age, Better, color = Treatment)) + xlim(5, 95) + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", family = binomial, alpha = 0.2, aes(fill = Treatment), size = 2.5, fullrange = TRUE) gg # show the plot ## ----arth-cond2, h=4, w=8, out.width='.8\\textwidth', cap='Conditional plot of Arthritis data, stratified by Treatment and Sex. The unusual patterns in the panel for Males signals a problem with this data.', out.extra='clip'---- gg + facet_wrap(~ Sex) ## ----arth-margins-------------------------------------------------------- addmargins(xtabs(~Sex + Treatment, data = Arthritis), 2) ## ----arth-binreg0, fig.keep='none'--------------------------------------- library(vcd) binreg_plot(arth.logistic2, type = "link") ## ----arth-binreg1, h=6, w=6, out.width='.49\\textwidth', cap='Full-model plot of Arthritis data, showing fitted logits by Treatment and Sex.', out.extra='clip'---- binreg_plot(arth.logistic2, type = "link", subset = Sex == "Female", main = "Female", xlim=c(25, 75), ylim = c(-3, 3)) binreg_plot(arth.logistic2, type = "link", subset = Sex == "Male", main = "Male", xlim=c(25, 75), ylim = c(-3, 3)) ## ----arth-binreg2, h=6, w=6, out.width='.49\\textwidth', cap='Full-model plot of Arthritis data, showing fitted probabilities by Treatment and Sex.', out.extra='clip'---- binreg_plot(arth.logistic2, subset = Sex == "Female", main = "Female", xlim = c(25, 75)) binreg_plot(arth.logistic2, subset = Sex == "Male", main = "Male", xlim = c(25, 75)) ## ----arth-eff1----------------------------------------------------------- library(effects) arth.eff2 <- allEffects(arth.logistic2, partial.residuals = TRUE) names(arth.eff2) ## ------------------------------------------------------------------------ arth.eff2[["Sex"]] arth.eff2[["Sex"]]$model.matrix ## ----arth-effplot1, h=4, w=9, out.width='\\textwidth', cap='Plot of all effects in the main effects model for the Arthritis data. Partial residuals and their loess smooth are also shown for the continuous predictor, Age.', echo=FALSE, fig.pos="H"---- plot(arth.eff2, rows = 1, cols = 3, type="response", residuals.pch = 15) ## ----arth-effplot1-code, h=4, w=9, out.width='\\textwidth', cap='Plot of all effects in the main effects model for the Arthritis data. Partial residuals and their loess smooth are also shown for the continuous predictor, Age.', eval=FALSE, fig.keep='none'---- ## plot(arth.eff2, rows = 1, cols = 3, ## type="response", residuals.pch = 15) ## ----arth-full----------------------------------------------------------- arth.full <- Effect(c("Age", "Treatment", "Sex"), arth.logistic2) ## ----arth-effplot2, h=4, w=8, out.width='.8\\textwidth', cap='Full-model plot of the effects of all predictors in the main effects model for the Arthritis data, plotted on the logit scale.'---- plot(arth.full, multiline = TRUE, ci.style = "bands", colors = c("red", "blue"), lwd = 3, ticks = list(at = c(.05, .1, .25, .5, .75, .9, .95)), key.args = list(x = .52, y = .92, columns = 1), grid = TRUE) ## ----arth-effplot3, h=4, w=8, out.width='.8\\textwidth', cap='Full-model plot of the effects of all predictors in the main effects model for the Arthritis data, plotted on the probability scale.'---- plot(arth.full, multiline = TRUE, ci.style = "bands", type="response", colors = c("red", "blue"), lwd = 3, key.args = list(x = .52, y = .92, columns = 1), grid = TRUE) ## ----donner1-ex, child="ch07/donner1.Rnw"-------------------------------- ## ----donner11, echo=-1--------------------------------------------------- set.seed(1235) data("Donner", package = "vcdExtra") # load the data library(car) # for some() and Anova() some(Donner, 8) ## ----donner12------------------------------------------------------------ Donner$survived <- factor(Donner$survived, labels = c("no", "yes")) ## ----donner13------------------------------------------------------------ xtabs(~ family, data = Donner) ## ----donner14------------------------------------------------------------ # collapse small families into "Other" fam <- Donner$family levels(fam)[c(3, 4, 6, 7, 9)] <- "Other" # reorder, putting Other last fam = factor(fam,levels(fam)[c(1, 2, 4:6, 3)]) Donner$family <- fam xtabs(~family, data=Donner) ## ----donner15------------------------------------------------------------ xtabs(~ survived + family, data = Donner) ## ----donner1-spineplot, h=4, w=8, out.width='.8\\textwidth', cap='Spineplot of survival in the Donner Party by family.'---- plot(survived ~ family, data = Donner, col = c("pink", "lightblue")) ## ----donner1-gpairs, h=6, w=6, out.width='.7\\textwidth', cap='Generalized pairs plot for the Donner data.'---- library(gpairs) library(vcd) gpairs(Donner[,c(4, 2, 3, 1)], diag.pars = list(fontsize = 20, hist.color = "gray"), mosaic.pars = list(gp = shading_Friendly), outer.rot = c(45, 45) ) ## ----donner1-cond1, h=4, w=6, out.width='.7\\textwidth', cap='Conditional plot of the Donner data, showing the relationship of survival to age and sex. The smoothed curves and confidence bands show the result of fitting separate linear logistic regressions on age for males and females.'---- # basic plot: survived vs. age, colored by sex, with jittered points gg <- ggplot(Donner, aes(age, as.numeric(survived=="yes"), color = sex)) + ylab("Survived") + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) # add conditional linear logistic regressions gg + stat_smooth(method = "glm", family = binomial, formula = y ~ x, alpha = 0.2, size = 2, aes(fill = sex)) ## ----donner1-cond3, h=5, w=6, out.width='.5\\textwidth', cap='Conditional plots of the Donner data, showing the relationship of survival to age and sex. Left: The smoothed curves and confidence bands show the result of fitting separate quadratic logistic regressions on age for males and females. Right: Separate loess smooths are fit to the data for males and females.'---- # add conditional quadratic logistic regressions gg + stat_smooth(method = "glm", family = binomial, formula = y ~ poly(x,2), alpha = 0.2, size = 2, aes(fill = sex)) # add loess smooth gg + stat_smooth(method = "loess", span=0.9, alpha = 0.2, size = 2, aes(fill = sex)) + coord_cartesian(ylim = c(-.05,1.05)) ## ----donner1-mod1-------------------------------------------------------- donner.mod1 <- glm(survived ~ age + sex, data = Donner, family =binomial) Anova(donner.mod1) donner.mod2 <- glm(survived ~ age * sex, data = Donner, family = binomial) Anova(donner.mod2) ## ----donner1-mod3-------------------------------------------------------- donner.mod3 <- glm(survived ~ poly(age, 2) + sex, data = Donner, family = binomial) donner.mod4 <- glm(survived ~ poly(age, 2) * sex, data = Donner, family = binomial) Anova(donner.mod4) ## ----donner1-summarise, R.options=list(digits=5)------------------------- library(vcdExtra) LRstats(donner.mod1, donner.mod2, donner.mod3, donner.mod4) ## ----donner1-LR, R.options=list(digits=4)-------------------------------- mods <- list(donner.mod1, donner.mod2, donner.mod3, donner.mod4) LR <- sapply(mods, function(x) x$deviance) LR <- matrix(LR, 2, 2) rownames(LR) <- c("additive", "non-add") colnames(LR) <- c("linear", "non-lin") LR <- cbind(LR, diff = LR[,1] - LR[,2]) LR <- rbind(LR, diff = c(LR[1,1:2] - LR[2,1:2], NA)) ## ----donner-mod5--------------------------------------------------------- library(splines) donner.mod5 <- glm(survived ~ ns(age,2) * sex, data = Donner, family = binomial) Anova(donner.mod5) donner.mod6 <- glm(survived ~ ns(age,4) * sex, data = Donner, family = binomial) Anova(donner.mod6) LRstats(donner.mod4, donner.mod5, donner.mod6) ## ----donner-effect, h=5, w=8, out.width='.8\\textwidth', cap='Effect plot for the spline model \\code{donner.mod6} fit to the Donner data.', scap='Effect plot for the spline model donner.mod6 fit to the Donner data'---- library(effects) donner.eff6 <- allEffects(donner.mod6, xlevels = list(age=seq(0, 50, 5))) plot(donner.eff6, ticks = list(at=c(0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.999))) ## ----arrests, child="ch07/arrests.Rnw"----------------------------------- ## ----arrests1, echo=-1--------------------------------------------------- set.seed(12345) library(effects) data("Arrests", package = "effects") Arrests[sample(nrow(Arrests), 6),] ## ----arrests2------------------------------------------------------------ Arrests$year <- as.factor(Arrests$year) arrests.mod <- glm(released ~ employed + citizen + checks + colour*year + colour*age, family = binomial, data = Arrests) ## ----arrests3------------------------------------------------------------ library(car) Anova(arrests.mod) ## ----arrests4, size='footnotesize', R.options=list(digits=4)------------- coeftest(arrests.mod) ## ----arrests-eff1, h=6, w=6, out.width='.6\\textwidth', cap='Effect plot for the main effect of skin color in the Arrests data.', fig.pos="H"---- plot(Effect("colour", arrests.mod), lwd = 3, ci.style = "bands", main = "", xlab = list("Skin color of arrestee", cex = 1.25), ylab = list("Probability(released)", cex = 1.25) ) ## ----arrests-eff2, h=8, w=8, out.width='.49\\textwidth', cap='Effect plots for the interactions of color with age (left) and year (right) in the Arrests data.'---- # colour x age interaction plot(Effect(c("colour", "age"), arrests.mod), lwd = 3, multiline = TRUE, ci.style = "bands", xlab = list("Age", cex = 1.25), ylab = list("Probability(released)", cex = 1.25), key.args = list(x = .05, y = .99, cex = 1.2, columns = 1) ) # colour x year interaction plot(Effect(c("colour", "year"), arrests.mod), lwd = 3, multiline = TRUE, xlab = list("Year", cex = 1.25), ylab = list("Probability(released)", cex = 1.25), key.args = list(x = .7, y = .99, cex = 1.2, columns = 1) ) ## ----arrests-all, h=8, w=12, out.width='\\textwidth', cap='Effect plot for all high-order terms in the model for the Arrests data.'---- arrests.effects <- allEffects(arrests.mod, xlevels = list(age = seq(15, 45, 5))) plot(arrests.effects, ylab = "Probability(released)", ci.style = "bands", ask = FALSE) ## ----icu-ex, child="ch07/icu1.Rnw"--------------------------------------- ## ----icu11--------------------------------------------------------------- data("ICU", package = "vcdExtra") names(ICU) ICU <- ICU[,-c(4, 20)] # remove redundant race, coma ## ----icu1-full, R.options=list(digits=4)--------------------------------- icu.full <- glm(died ~ ., data = ICU, family = binomial) summary(icu.full) ## ----icu1-lrtest--------------------------------------------------------- LRtest <- function(model) c(LRchisq = (model$null.deviance - model$deviance), df = (model$df.null - model$df.residual)) (LR <- LRtest(icu.full)) (pvalue <- 1 - pchisq(LR[1], LR[2])) ## ----icu-full1, size='footnotesize'-------------------------------------- icu.full1 <- update(icu.full, . ~ . - renal - fracture) anova(icu.full1, icu.full, test = "Chisq") ## ----icu1-lrm1----------------------------------------------------------- library(rms) dd <- datadist(ICU[,-1]) options(datadist = "dd") icu.lrm1 <- lrm(died ~ ., data = ICU) icu.lrm1 <- update(icu.lrm1, . ~ . - renal - fracture) ## ----icu1-odds-ratios, eval=FALSE---------------------------------------- ## sum.lrm1 <- summary(icu.lrm1) ## plot(sum.lrm1, log = TRUE, main = "Odds ratio for 'died'", cex = 1.25, ## col = rgb(0.1, 0.1, 0.8, alpha = c(0.3, 0.5, 0.8))) ## ----icu1-step1---------------------------------------------------------- library(MASS) icu.step1 <- stepAIC(icu.full1, trace = FALSE) icu.step1$anova ## ----icu1-step2---------------------------------------------------------- icu.step2 <- stepAIC(icu.full, trace = FALSE, k = log(200)) icu.step2$anova ## ----icu1-coef----------------------------------------------------------- coeftest(icu.step2) ## ----icu1-anova---------------------------------------------------------- anova(icu.step2, icu.step1, test = "Chisq") ## ----icu1-glm3----------------------------------------------------------- icu.glm3 <- update(icu.step2, . ~ . - age + ns(age, 3) + (cancer + admit + uncons) ^ 2) anova(icu.step2, icu.glm3, test = "Chisq") ## ----icu1-glm4----------------------------------------------------------- icu.glm4 <- update(icu.step2, . ~ . + age * (cancer + admit + uncons)) anova(icu.step2, icu.glm4, test = "Chisq") ## ----lrm-nomogram, eval=FALSE-------------------------------------------- ## icu.lrm2 <- lrm(died ~ age + cancer + admit + uncons, data = ICU) ## plot(nomogram(icu.lrm2), cex.var = 1.2, lplabel = "Log odds death") ## ----icu-recode---------------------------------------------------------- levels(ICU$cancer) <- c("-", "Cancer") levels(ICU$admit) <- c("-","Emerg") levels(ICU$uncons) <- c("-","Uncons") icu.glm2 <- glm(died ~ age + cancer + admit + uncons, data = ICU, family = binomial) ## ----icu1-binreg-plot, h=8, w=8, out.width='.65\\textwidth', cap='Fitted log odds of death in the ICU data for the model \\code{icu.glm2}. Each line shows the relationship with age, for patients having various combinations of risk factors and 1 standard error confidence bands.', scap='Fitted log odds of death in the ICU data for the model icu.glm2', fig.pos="!htb"---- binreg_plot(icu.glm2, type = "link", conf_level = 0.68, legend = FALSE, labels = TRUE, labels_just = c("right", "bottom"), cex = 0, point_size = 0.8, pch = 15:17, ylab = "Log odds (died)", ylim = c(-7, 4)) ## ----cleanup-rms, echo=FALSE--------------------------------------------- options(datadist = NULL) detach(package:rms) detach(package:Hmisc) ## ----donner2, child="ch07/donner2.Rnw"----------------------------------- ## ----donner2-inflmeasures------------------------------------------------ infl <- influence.measures(donner.mod3) names(infl) ## ----donner2-inflmeasures2, size="scriptsize", R.options=list(width=95)---- summary(infl) ## ----donner2-inflplot, echo=-2, h=6, w=8, out.width='.75\\textwidth', cap="Influence plot (residual vs. leverage) for the Donner data model, showing Cook's D as the size of the bubble symbol. Horizontal and vertical reference lines show typical cutoff values for noteworthy residuals and leverage."---- op <- par(mar = c(5, 4, 1, 1) + .1, cex.lab = 1.2) library(car) res <- influencePlot(donner.mod3, id.col = "blue", scale = 8, id.n = 2) k <- length(coef(donner.mod3)) n <- nrow(Donner) text(x = c(2, 3) * k / n, y = -1.8, c("2k/n", "3k/n"), cex = 1.2) ## ----donner2-res, R.options=list(digits=4)------------------------------- # show data together with diagnostics for influential cases idx <- which(rownames(Donner) %in% rownames(res)) cbind(Donner[idx,2:4], res) ## ----donner2-indexinfl, h=6, w=8, out.width='.8\\textwidth', cap="Index plots of influence measures for the Donner data model. The four most extreme observations on each measure are labeled."---- influenceIndexPlot(donner.mod3, vars=c("Cook", "Studentized", "hat"), id.n=4) ## ----icu2, child="ch07/icu2.Rnw"----------------------------------------- ## ----icu2-glm2, eval=FALSE----------------------------------------------- ## icu.glm2 <- glm(died ~ age + cancer + admit + uncons, ## data = ICU, family = binomial) ## ----icu2-inflplot, h=5.5, w=8, out.width='.7\\textwidth', cap='Influence plot for the main effects model for the ICU data.',fig.pos="!tb"---- library(car) res <- influencePlot(icu.glm2, id.col = "red", scale = 8, id.cex = 1.5, id.n = 3) ## ----icu2-res, R.options=list(digits=4)---------------------------------- idx <- which(rownames(ICU) %in% rownames(res)) cbind(ICU[idx, c("died", "age", "cancer", "admit", "uncons")], res) ## ----icu2-infl-index, h=5.5, w=8, out.width='.8\\textwidth', cap="Index plots of influence measures for the ICU data model. The four most extreme observations on each measure are labeled.", fig.pos="!htb"---- influenceIndexPlot(icu.glm2, vars = c("Cook", "Studentized", "hat"), id.n = 4) ## ----icu2-dfbetas, R.options=list(digits=4)------------------------------ infl <- influence.measures(icu.glm2) dfbetas <- data.frame(infl$infmat[,2:5]) colnames(dfbetas) <- c("dfb.age", "dfb.cancer", "dfb.admit", "dfb.uncons") head(dfbetas) ## ----icu2-dbage, h=6, w=9, out.width='.8\\textwidth', cap='Index plot for DFBETA (Age) in the ICU data model. The observations are colored blue or red according to whether the patient lived or died.'---- op <- par(mar = c(5, 5, 1, 1) + .1) cols <- ifelse(ICU$died == "Yes", "red", "blue") plot(dfbetas[,1], type = "h", col = cols, xlab = "Observation index", ylab = expression(Delta * beta[Age]), cex.lab = 1.3) points(dfbetas[,1], col = cols) # label some points big <- abs(dfbetas[,1]) > .25 idx <- 1 : nrow(dfbetas) text(idx[big], dfbetas[big, 1], label = rownames(dfbetas)[big], cex = 0.9, pos = ifelse(dfbetas[big, 1] > 0, 3, 1), xpd = TRUE) abline(h = c(-.25, 0, .25), col = "gray") par(op) ## ----icu2-dbscatmat, h=8, w=8, out.width='.85\\textwidth', cap= 'Scatterplot matrix for DFBETAs from the model for the ICU data. Those who lived or died are shown with blue circles and red triangles, respectively. The diagonal panels show histograms of each variable.', fig.pos='!b'---- scatterplotMatrix(dfbetas, smooth = FALSE, id.n = 2, ellipse = TRUE, levels = 0.95, robust = FALSE, diagonal = "histogram", groups = ICU$died, col = c("blue", "red")) ## ----donner3-mods, eval=FALSE-------------------------------------------- ## donner.mod1 <- glm(survived ~ age + sex, ## data = Donner, family = binomial) ## donner.mod3 <- glm(survived ~ poly(age, 2) + sex, ## data = Donner, family = binomial) ## ----donner-cr1, h=6, w=8, out.width='.6\\textwidth', cap='Component-plus-residual plot for the simple additive linear model, \\code{donner.mod1}. The dashed red line shows the slope of age in the full model; the smoothed green curve shows a loess fit with span = 0.5.', scap='Component-plus-residual plot for the simple additive linear model',fig.pos='htb'---- crPlots(donner.mod1, ~age, id.n=2) ## ----donner-cr2, h=6, w=8, out.width='.6\\textwidth', cap='Component-plus-residual plot for the nonlinear additive model, \\code{donner.mod3}.', scap='Component-plus-residual plot for the nonlinear additive model'---- crPlots(donner.mod3, ~poly(age,2), id.n=2) ## ----donner4-avp0, eval=FALSE, fig.show='hide'--------------------------- ## col <- ifelse(Donner$survived == "yes", "blue", "red") ## pch <- ifelse(Donner$sex == "Male", 16, 17) ## avPlots(donner.mod1, id.n = 2, ## col = col, pch = pch, col.lines = "darkgreen") ## ----donner4-avp, echo=FALSE, h=7, w=6, out.width='.5\\textwidth', cap='Added-variable plots for age (left) and sex (right) in the Donner Party main effects model. Those who survived are shown in blue; those who died in red. Men are plotted with filled circles; women with filled triangles. '---- col <- ifelse(Donner$survived == "yes", "blue", "red") pch <- ifelse(Donner$sex == "Male", 16, 17) avPlot(donner.mod1, "age", id.n = 2, pch = pch, col = col, col.lines = "darkgreen", cex.lab = 1.2) text(30, -0.4, expression(beta[age]*" = -0.034"), pos = 4, cex = 1.25, col = "darkgreen") avPlot(donner.mod1, "sexMale", id.n = 2, pch = pch, col = col, col.lines = "darkgreen", cex.lab = 1.2) text(0, 0.1, expression(beta[sexMale]*" = -1.21"), pos = 4, cex = 1.25, col = "darkgreen") ## ----icu3-marginal, echo=1:5, h=6, w=8, out.width='.8\\textwidth', cap='Marginal plots of the response \\code{died} against each of the predictors in the model \\code{icu.glm2} for the \\data{ICU} data.', scap='Marginal plots of the response died against each of the predictors in the model icu.glm2 for the ICU data'---- op <- par(mfrow = c(2, 2), mar = c(4, 4, 1, 2.5) + .1, cex.lab = 1.4) plot(died ~ age, data = ICU, col = c("lightblue", "pink")) plot(died ~ cancer, data = ICU, col = c("lightblue", "pink")) plot(died ~ admit, data = ICU, col = c("lightblue", "pink")) plot(died ~ uncons, data = ICU, col = c("lightblue", "pink")) par(op) ## ----icu3-avp1, h=6, w=6, out.width='.8\\textwidth', cap='Added-variable plots for the predictors in the model for the ICU data. Those who died and survived are shown by triangles ($\\triangle$) and circles (\\small{$\\bigcirc$}), respectively.', scap='Added-variable plots for the predictors in the model for the ICU data.', fig.pos='!htb'---- pch <- ifelse(ICU$died=="No", 1, 2) avPlots(icu.glm2, id.n=2, pch=pch, cex.lab=1.3) ## ----icu3-glm2a---------------------------------------------------------- icu.glm2a <- glm(died ~ age + cancer + admit + uncons + systolic, data = ICU, family = binomial) anova(icu.glm2, icu.glm2a, test = "Chisq") ## ----icu3-avp2, h=6, w=6, out.width='.6\\textwidth', cap='Added-variable plot for the effect of adding systolic blood pressure to the main effects model for the ICU data.'---- avPlot(icu.glm2a, "systolic", id.n = 3, pch = pch) <file_sep>/pages/other.html <!-- generator: rmarkdown::render("other.md") --> <div class="contents"> <h2 id="updates">Updates</h2> <p>Updates to the code examples in the book will be posted here.</p> <ul> <li> <p><strong><code>ca</code></strong> package: There are now several enhancements for graphics for correspondence analysis (Chapter 6) in the <code>ca</code> package, v. 0.64. All examples in the book still work, but some can be simplified.</p> <ul> <li> The <code>ca</code> package now includes <code>cacoords()</code> extracting coordinate from CA/MCA solutions with various scaling options. </li> <li> A <code>multilines()</code> function facilitates drawing CA/MCA solutions connecting factor levels with lines. </li> <li> The <strong><code>vcdExtra</code></strong> package, v. 0.7, now includes a function <code>mcaplot()</code> for MCA plots in the style used in the book. </li> </ul> </li> <li><p><strong><code>ggplot2</code></strong> changes: In the latest major release, <code>ggplot2_2.0.0</code>, calls to <code>stat_smooth(method=&quot;glm&quot;)</code> now require the <code>family</code> argument to be specified as, for example, <code>method.args = list(family = binomial)</code> rather than <code>family = binomial</code>. This affects numerous figures in Chapter 7, starting with Figure 7.2 in Example 7.3.</p> </li> </ul> <h2 id="errata">Errata</h2> <p>Readers are invited to send an email related to typos or errors in the book to <code>friendly AT yorku DOT ca</code>. Please give specific section, page, figure or equation references, and use <code>DDAR: errata</code> in the subject line.</p> <ul> <li><a href="extra/errata.pdf">Errata for the book, Jan. 22, 2016</a></li> </ul> <h2 id="additional-vignettes-and-case-studies">Additional vignettes and case studies</h2> <p>Several examples and topics did not make it into the printed book</p> <ul> <li><a href="extra/titanic-glm-ex.pdf">Visualizing GLMs for binary outcomes</a> R code <a href="extra/titanic-glm-ex.R"> <img height=20 src="../images/Rfile.png"> </li> <li><a href="extra/titanic-tree-ex.pdf">Classification and regression trees</a> R code <a href="extra/titanic-tree-ex.R"> <img height=20 src="../images/Rfile.png"> </li> </ul> <h2 id="reviews">Reviews</h2> <blockquote> <p>"This is an excellent book, nearly encyclopedic in its coverage. I personally find it very useful and expect that many other readers will as well. The book can certainly serve as a reference. It could also serve as a supplementary text in a course on categorical data analysis that uses R for computation or, because so much statistical detail is provided, even as the main text for a course on the topic that emphasizes graphical methods." <strong><em><NAME>, McMaster University</em></strong></p> <p>"For many years, Prof. Friendly has been the most effective promoter in Statistics of graphical methods for categorical data. We owe thanks to Friendly and Meyer for promoting graphical methods and showing how easy it is to implement them in R. This impressive book is a very worthy addition to the library of anyone who spends much time analyzing categorical data." <strong><NAME>, <em>Biometrics</em>, June, 2016</strong></p> </blockquote> <h2 id="citations">Citations</h2> <p>If you use this book or the materials contained on this web site in research papers, you can cite that use as follows with BibTeX:</p> <pre><code>@Book{FriendlyMeyer:2016:DDAR, title = {Discrete Data Analysis with R: Visualization and Modeling Techniques for Categorical and Count Data}, year = {2016}, author = {<NAME> and <NAME>}, publisher = {Chapman \&amp; Hall/CRC}, address = {Boca Raton, FL}, isbn = {978-1-4987-2583-5}, } </code></pre> <p>A text version of this citation is:</p> <p><NAME>. &amp; <NAME>. (2016). <em>Discrete Data Analysis with R: Visualization and Modeling Techniques for Categorical and Count Data</em>. Boca Raton, FL: Chapman &amp; Hall/CRC.</p> </div> <file_sep>/pages/Rcode/ch05.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch05") .locals$ch05 <- NULL .pkgs$ch05 <- NULL library(MASS) ## ----haireye-mos1, h=6, w=6, out.width='.6\\textwidth', cap='Basic mosaic display for hair color and eye color data. The area of each rectangle is proportional to the observed frequency in that cell, shown as numbers.', echo=FALSE---- library(vcd) library(vcdExtra) data("HairEyeColor", package = "datasets") haireye <- margin.table(HairEyeColor, 1:2) mosaic(haireye, pop = FALSE) labeling_cells(text = haireye, gp_text = gpar(fontface = 2), clip = FALSE)(haireye) ## ----haireye-mos2, fig.show='hide', fig.keep='none'---------------------- data("HairEyeColor", package = "datasets") haireye <- margin.table(HairEyeColor, 1 : 2) mosaic(haireye, labeling = labeling_values) ## ----haireye-mos3-------------------------------------------------------- (hair <- margin.table(haireye, 1)) prop.table(hair) ## ----haireye-mos5-------------------------------------------------------- expected <- rep(sum(hair) / 4, 4) names(expected) <- names(hair) expected ## ------------------------------------------------------------------------ (residuals <- (hair - expected) / sqrt(expected)) ## ----haireye-mos7-------------------------------------------------------- round(addmargins(prop.table(haireye, 1), 2), 3) ## ----haireye-mos8, h=6, w=6, out.width='.6\\textwidth', cap='Second step in constructing the mosaic display. Each rectangle for hair color is subdivided in proportion to the relative frequencies of eye color, and the tiles are shaded in relation to residuals from the model of independence.',echo=FALSE,results="hide"---- mosaic(haireye, shade=TRUE, suppress=0, labeling=labeling_residuals, gp_text=gpar(fontface=2)) ## ----echo=FALSE,fig.show='hide',fig.keep='none'-------------------------- mosaic(haireye, shade = TRUE, labeling = labeling_residuals) ## ------------------------------------------------------------------------ exp <- independence_table(haireye) resids <- (haireye - exp) / sqrt(exp) round(resids, 2) ## ----he-chisq------------------------------------------------------------ (chisq <- sum(resids ^ 2)) (df <- prod(dim(haireye) - 1)) pchisq(chisq, df, lower.tail = FALSE) ## ----he-chisqtest-------------------------------------------------------- chisq.test(haireye) round(residuals(chisq.test(haireye)), 2) ## ----haireye-mos9, h=6, w=6, out.width='.6\\textwidth', cap='Two-way mosaic for hair color and eye color, reordered. The eye colors were reordered from dark to light, enhancing the interpretation.'---- # re-order eye colors from dark to light haireye2 <- as.table(haireye[, c("Brown", "Hazel", "Green", "Blue")]) mosaic(haireye2, shade = TRUE) ## ----HE-fill1, h=6, w=6, fig.show='hide'--------------------------------- # color by hair color fill_colors <- c("brown4", "#acba72", "green", "lightblue") (fill_colors_mat <- t(matrix(rep(fill_colors, 4), ncol = 4))) mosaic(haireye2, gp = gpar(fill = fill_colors_mat, col = 0)) ## ----shadingMarimekko,fig.show="hide"------------------------------------ mosaic(haireye2, gp = shading_Marimekko(haireye2)) ## ----HE-fill2, h=6, w=6, fig.show='hide'--------------------------------- # toeplitz designs library(colorspace) toeplitz(1 : 4) fill_colors <- rainbow_hcl(8)[1 + toeplitz(1 : 4)] mosaic(haireye2, gp = gpar(fill = fill_colors, col = 0)) ## ----HE-fill, h=6, w=6, echo=FALSE, out.width='.49\\textwidth', cap='Mosaic displays for the \\texttt{haireye2} data, using custom colors to fill the tiles. Left: Marimekko chart, using colors to reflect the eye colors; right: Toeplitz-based colors, reflecting the diagonal strips in a square table.'---- fill_colors <- c("brown4", "#acba72", "green", "lightblue") fill_colors_mat <- t(matrix(rep(fill_colors, 4), ncol=4)) mosaic(haireye2, gp = gpar(fill = fill_colors_mat, col = 0)) library(colorspace) #toeplitz(1:4) fill_colors <- rainbow_hcl(8)[1+toeplitz(1:4)] mosaic(haireye2, gp = gpar(fill = fill_colors, col = 0)) ## ----shadingDiagonal,fig.show="hide"------------------------------------- mosaic(haireye2, gp = shading_diagonal(haireye2)) ## ----HE-fill3, eval=FALSE------------------------------------------------ ## mosaic(haireye2, highlighting = "Eye", highlighting_fill = fill_colors) ## mosaic(Eye ~ Hair, data = haireye2, highlighting_fill = fill_colors) ## ----HE-interp, h=6, w=6, out.width='.49\\textwidth', cap='Interpolation options for shading levels in mosaic displays. Left: four shading levels; right: continuous shading.'---- # more shading levels mosaic(haireye2, shade = TRUE, gp_args = list(interpolate = 1 : 4)) # continuous shading interp <- function(x) pmin(x / 6, 1) mosaic(haireye2, shade = TRUE, gp_args = list(interpolate = interp)) ## ----HE-shading, h=6, w=6, out.width='.49\\textwidth', cap="Shading functions for mosaic displays. Left: \\code{shading\\_Friendly} using fixed cutoffs and the ``Friendly'' color scheme and an alternative legend style (\\code{legend\\_fixed}); right: \\code{shading\\_max}, using a permutation-based test to determine significance of residuals."---- mosaic(haireye2, gp = shading_Friendly, legend = legend_fixed) set.seed(1234) mosaic(haireye2, gp = shading_max) ## ----art-setup----------------------------------------------------------- art <- xtabs(~ Treatment + Improved, data = Arthritis, subset = Sex == "Female") names(dimnames(art))[2] <- "Improvement" ## ----arth-mosaic, h=6, w=6, out.width='.49\\textwidth', cap="Mosaic plots for the female patients in the \\code{Arthritis} data. Left: Fixed shading levels via \\code{shading\\_Friendly}; right: shading levels determined by significant maximum residuals via \\code{shading\\_max}."---- mosaic(art, gp = shading_Friendly, margin = c(right = 1), labeling = labeling_residuals, suppress = 0, digits = 2) set.seed(1234) mosaic(art, gp = shading_max, margin = c(right = 1)) ## ----arth-residuals------------------------------------------------------ residuals(chisq.test(art)) ## ----arth-max------------------------------------------------------------ set.seed(1243) art_max <- coindep_test(art) art_max ## ----arth-quantiles------------------------------------------------------ art_max$qdist(c(0.90, 0.99)) ## ----soccer-chisq-------------------------------------------------------- data("UKSoccer", package = "vcd") CMHtest(UKSoccer) ## ----UKsoccer-mosaic, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for UK soccer scores, highlighting one cell that stands out for further attention.'---- set.seed(1234) mosaic(UKSoccer, gp = shading_max, labeling = labeling_residuals, digits = 2) ## ----HEC-mos1b, h=6, w=6, out.width='.7\\textwidth', cap='Three-way mosaic for hair color, eye color, and sex.', fig.pos='!htb'---- HEC <- HairEyeColor[, c("Brown", "Hazel", "Green", "Blue"),] mosaic(HEC, rot_labels = c(right = -45)) ## ----ch5-loglm1, eval=FALSE---------------------------------------------- ## loglin(mytable, margin = list(1, 2)) ## ----ch5-loglm2, eval=FALSE---------------------------------------------- ## loglin(mytable, margin = list(c(1, 2))) ## ----ch5-loglm3, eval=FALSE---------------------------------------------- ## loglm(~ A + B, data = mytable) ## ----ch5-loglm4, eval=FALSE---------------------------------------------- ## loglm(~ A + B + A : B, data = mytable) ## loglm(~ A * B, data = mytable) ## ------------------------------------------------------------------------ loglm(~ Hair + Eye, data = haireye) ## ------------------------------------------------------------------------ HE_S <- loglm(~ Hair * Eye + Sex, data = HairEyeColor) HE_S ## ----eval=FALSE---------------------------------------------------------- ## residuals(HE_S, type = "pearson") ## ----HEC-mos1, h=6, w=6, out.width='.7\\textwidth', cap='Three-way mosaic for hair color, eye color, and sex. Residuals from the model of joint independence, [HE][S] are shown by shading.', fig.pos='!htb'---- HEC <- HairEyeColor[, c("Brown", "Hazel", "Green", "Blue"),] mosaic(HEC, expected = ~ Hair * Eye + Sex, labeling = labeling_residuals, digits = 2, rot_labels = c(right = -45)) ## ----HEC-mos2, h=6, w=6, out.width='.49\\textwidth', cap="Mosaic displays for other models fit to the data on hair color, eye color, and sex. Left: Mutual independence model; right: Conditional independence of hair color and eye color given sex."---- abbrev <- list(abbreviate = c(FALSE, FALSE, 1)) mosaic(HEC, expected = ~ Hair + Eye + Sex, labeling_args = abbrev, main = "Model: ~ Hair + Eye + Sex") mosaic(HEC, expected = ~ Hair * Sex + Eye * Sex, labeling_args = abbrev, main="Model: ~ Hair*Sex + Eye*Sex") ## ----HEC-loglm1---------------------------------------------------------- library(MASS) # three types of independence: mod1 <- loglm(~ Hair + Eye + Sex, data = HEC) # mutual mod2 <- loglm(~ Hair * Sex + Eye * Sex, data = HEC) # conditional mod3 <- loglm(~ Hair * Eye + Sex, data = HEC) # joint LRstats(mod1, mod2, mod3) ## ----HEC-loglm2---------------------------------------------------------- anova(mod1) anova(mod1, mod2, mod3, test = "chisq") ## ----HEC-seq1, h=6, w=6, echo=FALSE, fig.show='hide'--------------------- mosaic(HEC, expected = ~ Hair + Eye + Sex, legend = FALSE, labeling_args = abbrev, main = "Mutual") ## ----HEC-seq2, h=6, w=6, echo=FALSE, fig.show='hide'--------------------- mosaic(~ Hair + Eye, data = HEC, shade = TRUE, legend = FALSE, main = "Marginal") ## ----HEC-seq3, h=6, w=6, echo=FALSE, fig.show='hide'--------------------- mosaic(HEC, expected = ~ Hair * Eye + Sex, legend = FALSE, labeling_args = abbrev, main = "Joint") ## ----seq-functions------------------------------------------------------- for(nf in 2 : 5) { print(loglin2string(joint(nf, factors = LETTERS[1:5]))) } for(nf in 2 : 5) { print(loglin2string(conditional(nf, factors = LETTERS[1:5]), sep = "")) } for(nf in 2 : 5) { print(loglin2formula(conditional(nf, factors = LETTERS[1:5]))) } ## ----seq-functions2------------------------------------------------------ loglin2formula(joint(3, table = HEC)) loglin2string(joint(3, table = HEC)) ## ------------------------------------------------------------------------ HEC.mods <- seq_loglm(HEC, type = "joint") LRstats(HEC.mods) ## ----presex1------------------------------------------------------------- data("PreSex", package = "vcd") structable(Gender + PremaritalSex + ExtramaritalSex ~ MaritalStatus, data = PreSex) ## ----presex-reorder------------------------------------------------------ PreSex <- aperm(PreSex, 4 : 1) # order variables G, P, E, M ## ----presex2, h=6, w=6, out.width='.49\\textwidth', cap='Mosaic displays for the first two marginal tables in the PreSex data. Left: Gender and premarital sex; right: fitting the model of joint independence with extramarital sex, [GP][E].'---- # (Gender Pre) mosaic(margin.table(PreSex, 1 : 2), shade = TRUE, main = "Gender and Premarital Sex") ## (Gender Pre)(Extra) mosaic(margin.table(PreSex, 1 : 3), expected = ~ Gender * PremaritalSex + ExtramaritalSex, main = "Gender*Pre + ExtramaritalSex") ## ----presex-odds--------------------------------------------------------- loddsratio(margin.table(PreSex, 1 : 3), stratum = 1, log = FALSE) ## ----presex3, h=6, w=6, out.width='.49\\textwidth', cap='Four-way mosaics for the PreSex data. The left panel fits the model [GPE][M]. The pattern of residuals suggests other associations with marital status. The right panel fits the model [GPE][PEM].'---- ## (Gender Pre Extra)(Marital) mosaic(PreSex, expected = ~ Gender * PremaritalSex * ExtramaritalSex + MaritalStatus, main = "Gender*Pre*Extra + MaritalStatus") ## (GPE)(PEM) mosaic(PreSex, expected = ~ Gender * PremaritalSex * ExtramaritalSex + MaritalStatus * PremaritalSex * ExtramaritalSex, main = "G*P*E + P*E*M") ## ----employ1, size = "footnotesize"-------------------------------------- data("Employment", package = "vcd") structable(Employment) ## ----employ2------------------------------------------------------------- loglm(~ EmploymentStatus + EmploymentLength * LayoffCause, data = Employment) ## ----employ-mos1, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for the employment status data, fitting the baseline model of joint independence.'---- # baseline model [A][BC] mosaic(Employment, shade = TRUE, expected = ~ EmploymentStatus + EmploymentLength * LayoffCause, main = "EmploymentStatus + Length * Cause") ## ----employ3------------------------------------------------------------- loglm(~ EmploymentStatus * LayoffCause + EmploymentLength * LayoffCause, data = Employment) ## ----employ-mos2, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for the employment status data, fitting the model of conditional independence, [AC][BC].', scap='Mosaic display for the employment status data, fitting the model of conditional independence'---- mosaic(Employment, shade = TRUE, gp_args = list(interpolate = 1 : 4), expected = ~ EmploymentStatus * LayoffCause + EmploymentLength * LayoffCause, main = "EmploymentStatus * Cause + Length * Cause") ## ----employ4------------------------------------------------------------- mods.list <- apply(Employment, "LayoffCause", function(x) loglm(~ EmploymentStatus + EmploymentLength, data = x)) mods.list ## ----employ-mos3, h=6, w=6, out.width='.49\\textwidth', cap='Mosaic displays for the employment status data, with separate panels for cause of layoff.', fig.pos="htb"---- mosaic(Employment[,,"Closure"], shade = TRUE, gp_args = list(interpolate = 1 : 4), margin = c(right = 1), main = "Layoff: Closure") mosaic(Employment[,,"Replaced"], shade = TRUE, gp_args = list(interpolate = 1 : 4), margin = c(right = 1), main = "Layoff: Replaced") ## ----punish1------------------------------------------------------------- data("Punishment", package = "vcd") str(Punishment, vec.len = 2) ## ----punish2------------------------------------------------------------- pun <- xtabs(Freq ~ memory + attitude + age + education, data = Punishment) dimnames(pun) <- list( Memory = c("yes", "no"), Attitude = c("no", "moderate"), Age = c("15-24", "25-39", "40+"), Education = c("Elementary", "Secondary", "High")) ## ----punish3------------------------------------------------------------- (mod.cond <- loglm(~ Memory * Age * Education + Attitude * Age * Education, data = pun)) ## ----punish4------------------------------------------------------------- set.seed(1071) coindep_test(pun, margin = c("Age", "Education"), indepfun = function(x) sum(x ^ 2), aggfun = sum) ## ----punish-cond1-bis, h=8, w=8, out.width='.95\\textwidth', cap='Conditional mosaic plot of the Punishment data for the model of conditional independence of attitude and memory, given age and education. Shading of tiles is based on the sum of squares statistic.', echo=FALSE, fig.pos='hbt'---- set.seed(1071) pun_cotab <- cotab_coindep(pun, condvars = 3 : 4, type = "mosaic", varnames = FALSE, margins = c(2, 1, 1, 2), test = "sumchisq", interpolate = 1 : 2) cotabplot(~ Memory + Attitude | Age + Education, data = pun, panel = pun_cotab) ## ------------------------------------------------------------------------ mods.list <- apply(pun, c("Age", "Education"), function(x) loglm(~ Memory + Attitude, data = x)$pearson) ## ----punish-cond1, h=8, w=8, out.width='.95\\textwidth', cap='Conditional mosaic plot of the Punishment data for the model of conditional independence of attitude and memory, given age and education. Shading of tiles is based on the sum of squares statistic.', eval=FALSE---- ## set.seed(1071) ## pun_cotab <- cotab_coindep(pun, condvars = 3 : 4, type = "mosaic", ## varnames = FALSE, margins = c(2, 1, 1, 2), ## test = "sumchisq", interpolate = 1 : 2) ## cotabplot(~ Memory + Attitude | Age + Education, ## data = pun, panel = pun_cotab) ## ----punish-cond2, h=8, w=8, out.width='.8\\textwidth', cap='Conditional mosaic plot of the Punishment data for the model of conditional independence of attitude and memory, given age and education. This plot explicitly shows the total frequencies in the cells of age and education by the areas of the main blocks for these variables.', fig.pos='!htb'---- mosaic(~ Memory + Attitude | Age + Education, data = pun, shade = TRUE, gp_args = list(interpolate = 1 : 4)) ## ----bartlett-pairs, h=8, w=8, out.width='.8\\textwidth', cap='Mosaic pairs plot for the Bartlett data. Each panel shows the bivariate marginal relation between the row and column variables.', fig.pos='!htb'---- pairs(Bartlett, gp = shading_Friendly2) ## ----marital-pairs,h=8, w=8, out.width='.8\\textwidth', cap='Mosaic pairs plot for the PreSex data. Each panel shows the bivariate marginal relation between the row and column variables.', fig.pos='!htb'---- data("PreSex", package = "vcd") pairs(PreSex, gp = shading_Friendly2, space = 0.25, gp_args = list(interpolate = 1 : 4), diag_panel_args = list(offset_varnames = -0.5)) ## ----berk-pairs1, h=8, w=8, out.width='.8\\textwidth', cap='Mosaic matrix of the UCBAdmissions data showing bivariate marginal relations.', fig.pos='htb'---- largs <- list(labeling = labeling_border(varnames = FALSE, labels = c(T, T, F, T), alternate_labels = FALSE)) dargs <- list(gp_varnames = gpar(fontsize = 20), offset_varnames = -1, labeling = labeling_border(alternate_labels = FALSE)) pairs(UCBAdmissions, shade = TRUE, space = 0.25, diag_panel_args = dargs, upper_panel_args = largs, lower_panel_args = largs) ## ----berk-pairs2, h=8, w=8, out.width='.8\\textwidth', cap='Generalized mosaic matrix of the UCBAdmissions data. The above-diagonal plots fit models of joint independence; below-diagonal plots fit models of mutual independence.', fig.pos='!htb'---- pairs(UCBAdmissions, space = 0.2, lower_panel = pairs_mosaic(type = "joint"), upper_panel = pairs_mosaic(type = "total")) ## ----berk-pairs3, eval=FALSE--------------------------------------------- ## pairs(UCBAdmissions, type = "conditional", space = 0.2) ## ----arth-gpairs, h=8, w=8, out.width='.9\\textwidth', cap='Generalized pairs plot of the Arthritis data. Combinations of categorical and quantitative variables can be rendered in various ways.', fig.pos='!htb'---- library(gpairs) data("Arthritis", package = "vcd") gpairs(Arthritis[,c(5, 2, 3, 4)], diag.pars = list(fontsize = 20), mosaic.pars = list(gp = shading_Friendly, gp_args = list(interpolate = 1 : 4))) ## ----mos3d1, eval=FALSE-------------------------------------------------- ## mosaic3d(Bartlett) ## ----struc1-------------------------------------------------------------- struc <- array(c(6, 10, 312, 44, 37, 31, 192, 76), dim = c(2, 2, 2), dimnames = list(Age = c("Young", "Old"), Sex = c("F", "M"), Disease = c("No", "Yes")) ) struc <- as.table(struc) structable(struc) ## ----struc-mos1, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for the data on age, sex, and disease. Observed frequencies are shown in the plot, and residuals reflect departure from the model of mutual independence.', fig.pos="!b"---- mosaic(struc, shade = TRUE) ## ----struc-mos2, h=6, w=6, out.width='.5\\textwidth', cap='Mosaic display for the data on age, sex, and disease, using expected frequencies under mutual independence.'---- mosaic(struc, type = "expected") ## ----struc2-------------------------------------------------------------- mutual <- loglm(~ Age + Sex + Disease, data = struc, fitted = TRUE) fit <- as.table(fitted(mutual)) structable(fit) ## ----struc-mos3, h=8, w=8, out.width='.8\\textwidth', cap='Mosaic matrix for fitted values under mutual independence. In all panels the joint frequencies conform to the one-way margins.', fig.pos='!htb'---- pairs(fit, gp = shading_Friendly2, type = "total") ## ----code-mos3d1, eval=FALSE--------------------------------------------- ## mosaic3d(fit) ## ----struc3-------------------------------------------------------------- joint <- loglm(~ Age * Sex + Disease, data = struc, fitted = TRUE) fit <- as.table(fitted(joint)) structable(fit) ## ----struc-mos4, h=8, w=8, out.width='.7\\textwidth', cap='Mosaic matrix for fitted values under joint independence for the model [Age Sex][Disease].', scap='Mosaic matrix for fitted values under joint independence.', fig.pos='!htb'---- pairs(fit, gp = shading_Friendly2) ## ----sec-related, child='ch05/related.Rnw'------------------------------- ## ----berkeley-doubledecker, w=10, h=4, out.width='\\textwidth', cap='Doubledecker plot for the UCBAdmissions data.', fig.pos='htb'---- doubledecker(Admit ~ Dept + Gender, data = UCBAdmissions[2:1, , ]) ## ----titanic-doubledecker, w=12, h=4, out.width='\\textwidth', cap='Doubledecker plot for the Titanic data.'---- doubledecker(Survived ~ Class + Age + Sex, Titanic) ## ----pun1, R.options=list(digits=3)-------------------------------------- data("Punishment", package = "vcd") pun_lor <- loddsratio(Freq ~ memory + attitude | age + education, data = Punishment) ## ----pun2, R.options=list(digits=3)-------------------------------------- pun_lor_df <- as.data.frame(pun_lor) ## ----pun-lor-plot, h=4, w=5, out.width='.7\\textwidth', cap='Log odds ratio for the association between attitude and memory of corporal punishment, stratified by age and education. Error bars show $\\pm 1$ standard error.', scap='Log odds ratio for the association between attitude and memory of corporal punishment, stratified by age and education', fig.pos="H"---- plot(pun_lor) ## ----pun-anova0, echo=FALSE---------------------------------------------- pun_lor_df <- transform(pun_lor_df, age = as.numeric(age), education = as.numeric(education)) ## ----pun-anova----------------------------------------------------------- pun_mod <- lm(LOR ~ age * education, data = pun_lor_df, weights = 1 / ASE^2) anova(pun_mod) ## ----titanic-lor1-------------------------------------------------------- Titanic2 <- Titanic[, , 2:1, 2:1] Titanic2["Crew", , "Child", ] <- NA titanic_lor1 <- loddsratio(~ Survived + Age | Class + Sex, data = Titanic2) titanic_lor1 ## ----titanic-lor2-------------------------------------------------------- titanic_lor2 <- loddsratio(~ Survived + Sex | Class + Age, data = Titanic2) titanic_lor2 ## ----titanic-lor-plot, echo=FALSE, h=6, w=6, out.width='0.49\\textwidth', cap='Log odds ratio plots for the Titanic data. Left: Odds ratios for survival and age, by sex and class. Right: for survival and sex, by age and class. Error bars show $\\pm 1$ standard error.', scap='Log odds ratio plots for the Titanic data.'---- plot(titanic_lor1) plot(titanic_lor2) <file_sep>/index.php <?php require 'vendor/autoload.php'; require 'src/router.php'; require 'src/helpers.php'; try { $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); } catch(Exception $e) { //assumes sys ENV instead } $router = new DDARRouter(basepath()); $router->load(); ?> <!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"> <title>DDAR</title> <link rel="stylesheet" href="<?php echo urlfor('/styles/bootstrap/bootstrap.min.css'); ?>"/> <link rel="stylesheet" href="<?php echo urlfor('/styles/bootstrap/bootstrap-theme.min.css'); ?>"/> <link rel="stylesheet" href="<?php echo urlfor('/styles/fancybox/jquery.fancybox.css?v=2.1.5'); ?>" /> <link rel="stylesheet" href="<?php echo urlfor('/styles/main.css'); ?>"/> <link rel="stylesheet" href="<?php echo urlfor('/styles/pages.css'); ?>"/> <link rel="stylesheet" href="<?php echo urlfor('/styles/chapters.css'); ?>"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="<?php echo urlfor('/scripts/bootstrap/bootstrap.min.js'); ?>"></script> <script src="<?php echo urlfor('/scripts/fancybox/jquery.fancybox.js?v=2.1.5'); ?>"></script> <script src="<?php echo urlfor('/scripts/main.js'); ?>"></script> </head> <body data-basepath="<?php echo $router->getBasepath(); ?>"> <div class="jumbotron"> <div class="container"></div> </div> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a class="page" href="<?php echo urlfor('/pages/home'); ?>">Home</a></li> <li class="dropdown"> <a href="#" class="content-page dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Content<span class="caret"></span></a> <ul class="dropdown-menu"> <?php $path = 'pages/chapters'; echo renderChapterNavigation($path); ?> </ul> </li> <li class="dropdown"> <a href="#" class="content-page dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Using<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a class="page" href="<?php echo urlfor('/pages/using'); ?>#r-packages">R Packages</a></li> <li><a class="page" href="<?php echo urlfor('/pages/using'); ?>#data-sets-by-package">Data Sets by Package</a></li> <li><a class="page" href="<?php echo urlfor('/pages/using'); ?>#r-code">R Code</a></li> </ul> </li> <li><a class="page" href="<?php echo urlfor('/pages/other'); ?>">Other materials</a></li> <li><a class="page" href="<?php echo urlfor('/pages/authors'); ?>">Authors</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <div class="container"> <div class="row"> <div class="page-content col-md-12"> <?php echo $router->match(); ?> </div> </div> </div> </body> </html> <file_sep>/pages/extra/titanic-tree-ex.R ## ----parent, include=FALSE----------------------------------------------- set_parent("example-template.Rnw") ## ----rp0,out.width='0.55\\linewidth', fig.cap='Classification tree for passengers on the \\emph{Titanic}, using \\var{pclass} and \\var{age}.'---- # fit a simple tree, using only pclass and age library(rpart) library(rpart.plot) data(Titanicp, package="vcdExtra") rp0 <- rpart(survived ~ pclass + age, data=Titanicp) rpart.plot(rp0, type=0, extra=2, cex=1.5) ## ----rp0-print----------------------------------------------------------- rp0 ## ----partition-map1, echo=FALSE, out.width='0.7\\linewidth', fig.cap='Partition map for the tree in \\figref{fig:rp0}. Those in the shaded region are predicted to have died; observations are shown by red circles (died) and blue squares (survived)', fig.scap=''---- with(Titanicp, { class <- as.numeric(pclass) class.jitter <- jitter(class) op <- par(mar=c(4,4,0,0)+.2) plot(age ~ class.jitter,xlim=c(.6,3.4), type="n", xlab="Class (jittered)", ylab="Age", xaxt="n", cex.lab=1.5) axis(1, at=1:3, cex.axis=1.5) abline(v=1.5, col="gray") abline(v=2.5, col="gray") abline(h=16, col="gray") points(age[survived=="died"] ~ class.jitter[survived=="died"],pch=15, cex=1.1, col="red") points(age[survived=="survived"] ~ class.jitter[survived=="survived"],pch=16, cex=1.1, col="blue") rect(1.5,16,2.5,89,col=rgb(0.5,0.5,0.5,1/4)) rect(2.5,-5,3.61,89,col=rgb(0.5,0.5,0.5,1/4)) rect(0.48,60,1.5,89, col=rgb(0.5,0.5,0.5,1/4) ) text(3, 76, "predict: died", cex=1.5, col="red") text(1, 8, "predict: survived", cex=1.5, col="blue") par(op) }) ## ----rp-plotmo1, out.width='0.7\\linewidth', fig.cap='\\func{plotmo} plot for the tree in \\figref{fig:rp0}. Shading level is proportional to the predicted probability of survival.', fig.scap=''---- library(plotmo) plotmo(rp0, nresponse="survived", degree1=0, type2="image", col.image=gray(seq(.6, 1,.05)), col.response=ifelse(Titanicp$survived=="died", "red", "blue"), pch=ifelse(Titanicp$survived=="died", 15, 16)) ## ----rp-plotmo2, fig.show='hold', out.width='0.32\\linewidth', fig.cap='Other \\func{plotmo} plots: one-way and two-way effects'---- # one-way plots plotmo(rp0, nresponse="survived", degree1=1, degree2=0, trace=-1, do.par=FALSE) plotmo(rp0, nresponse="survived", degree1=2, degree2=0, trace=-1, do.par=FALSE) # two-way, 3D persp plot plotmo(rp0, nresponse="survived", degree1=0, trace=-1) ## ----printcp-rp0--------------------------------------------------------- printcp(rp0) ## ----plotcp-rp0,out.width='0.6\\linewidth', fig.cap='Plot of complexity and error statistics. The dashed horizontal line is drawn 1 SE above the minimum of the curve.'---- plotcp(rp0, lty=2, col="red", lwd=2) ## ----rp0-pruned,out.width='0.6\\linewidth', fig.cap='Classification tree for passengers on the Titanic, pruned'---- rp0.pruned <- prune(rp0, cp=.05) rpart.plot(rp0.pruned, type=0, extra=2, cex=1.5, under=TRUE, box.col=c("pink", "lightblue")[rp0.pruned$frame$yval]) ## ----titanic-rp1--------------------------------------------------------- rp1 = rpart(survived ~ pclass + sex + age + sibsp, data=Titanicp) ## ----cptable------------------------------------------------------------- printcp(rp1) ## ----rp1, out.width='.7\\linewidth', fig.cap='Plot of the extended \\func{rpart} tree for four predictors'---- rpart.plot(rp1, type=4, extra=2, faclen=0, under=TRUE, cex=1.1, box.col=c("pink", "lightblue")[rp1$frame$yval]) ## ----ctree--------------------------------------------------------------- library(party) titanic.ctree = ctree(survived ~ pclass + sex + age, data=Titanicp) titanic.ctree ## ----titanic-ctree, out.width='\\linewidth', fig.height=6, fig.width=11, fig.cap='A conditional inference tree for survival on the Titanic. The barplots below each leaf node highlight the proportion of survivors in each branch.'---- plot(titanic.ctree, tp_args = list(fill = c("blue", "lightgray")), ip_args = list(fill = c("lightgreen")) ) ## ----wrapup, include=FALSE, eval=TRUE------------------------------------ pkglist <- setdiff(.packages(), c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base")) write_bib(pkglist, "ex-packages.bib") <file_sep>/pages/extra/titanic-glm-ex.R ## ----parent, include=FALSE----------------------------------------------- set_parent("example-template.Rnw") ## ----setup, include=FALSE------------------------------------------------ library(vcdExtra) library(car) # data(Titanicp) ## ----load-data----------------------------------------------------------- data(Titanicp, package="vcdExtra") Titanicp <- Titanicp[!is.na(Titanicp$age),] ## ----titanic-glm-ggp1, out.width='.6\\linewidth', fig.height=4, fig.pos='hbt!', fig.cap='Survival on the Titanic, by age and sex, with a \\code{loess} smooth and 95\\% confidence band'---- require(ggplot2) ggplot(Titanicp, aes(age, as.numeric(survived)-1, color=sex)) + stat_smooth(method="loess", formula=y~x, alpha=0.2, size=2, aes(fill=sex)) + geom_point(position=position_jitter(height=0.03, width=0)) + xlab("Age") + ylab("Pr (survived)") ## ----titanic-glm-ggp2, out.width='.6\\linewidth', fig.height=4, fig.pos='hb', fig.cap='Survival on the Titanic, by age and sex, with a \\code{glm} smooth and 95\\% confidence band'---- ggplot(Titanicp, aes(age, as.numeric(survived)-1, color=sex)) + stat_smooth(method="glm", family=binomial, formula=y~x, alpha=0.2, size=2, aes(fill=sex)) + geom_point(position=position_jitter(height=0.03, width=0)) + xlab("Age") + ylab("Pr (survived)") ## ----titanic-glm-ggp-logit, out.width='.6\\linewidth', fig.height=4, fig.pos='hb', fig.cap='Survival on the Titanic, by age and sex plotted on the log odds scale where they are linear'---- logit <- function(x) log(x)/log(1-x) ggplot(Titanicp, aes(age, as.numeric(survived)-1, color=sex)) + stat_smooth(method="glm", family=binomial, formula=y~x, alpha=0.2, size=2, aes(fill=sex)) + scale_y_continuous(breaks=c(.10, .25, .50, .75, .90)) + coord_trans(y="logit") + xlab("Age") + ylab("Pr (survived)") ## ----titanic-glm-ggp3, out.width='\\linewidth', fig.height=3.5, fig.pos='hb', fig.cap='Survival on the Titanic, by age and sex, with panels for passenger class'---- p <- ggplot(Titanicp, aes(age, as.numeric(survived)-1, color=sex)) + stat_smooth(method="glm", family=binomial, formula=y~x, alpha=0.2, size=2, aes(fill=sex)) + geom_point(position=position_jitter(height=0.03, width=0)) + xlab("Age") + ylab("Pr (survived)") # facet by pclass p + facet_grid(. ~ pclass) ## ----eval=FALSE---------------------------------------------------------- ## # add plot collapsed over pclass ## p + facet_grid(. ~ pclass, margins=TRUE) ## ## ----titanic-glm-ggp4, out.width='\\linewidth', fig.height=3.5, fig.cap='Survival on the Titanic, by age and passenger class, with panels for passenger sex'---- # facet by sex, curves by class p <- ggplot(Titanicp, aes(age, as.numeric(survived)-1, color=pclass)) + stat_smooth(method="glm", family=binomial, formula=y~x, alpha=0.2, size=2, aes(fill=pclass)) + geom_point(position=position_jitter(height=0.03, width=0)) + xlab("Age") + ylab("Pr (survived)") # facet by sex p + facet_grid(. ~ sex) ## ----glm-models---------------------------------------------------------- titanic.glm1 <- glm(survived ~ pclass + sex + age, data=Titanicp, family=binomial) titanic.glm2 <- glm(survived ~ (pclass + sex + age)^2, data=Titanicp, family=binomial) titanic.glm3 <- glm(survived ~ (pclass + sex + age)^3, data=Titanicp, family=binomial) anova(titanic.glm1, titanic.glm2, titanic.glm3, test="Chisq") ## ------------------------------------------------------------------------ vcdExtra::LRstats(glmlist(titanic.glm1, titanic.glm2, titanic.glm3)) ## ----summary-titanic-glm2------------------------------------------------ summary(titanic.glm2) ## ----contrasts-pclass---------------------------------------------------- contrasts(Titanicp$pclass) ## ----Anova-titanic-glm2-------------------------------------------------- Anova(titanic.glm2) ## ----titanic-eff2-------------------------------------------------------- library(effects) titanic.eff2 <- allEffects(titanic.glm2) names(titanic.eff2) ## ----titanic-eff2a------------------------------------------------------- titanic.eff2a <- allEffects(titanic.glm2, typical=median, given.values=c(pclass2nd=1/3, pclass3rd=1/3, sexmale=0.5) ) ## ----titanic-eff2-menu, eval=FALSE--------------------------------------- ## plot(titanic.eff2, ask=TRUE, ...) ## ----titanic-eff2-1,out.width = '.5\\linewidth'-------------------------- ticks <- list(at=c(.01, .05, seq(.1, .9, by=.2), .95, .99)) plot(titanic.eff2[1], ticks=ticks, multiline=TRUE, ci.style="bars", key=list(x=.7, y=.95)) ## ----titanic-eff2-2, fig.show='hide'------------------------------------- plot(titanic.eff2[2], ticks=ticks, multiline=TRUE, ci.style="bars", key=list(x=.7, y=.95)) ## ----titanic-eff2-3, fig.show='hide'------------------------------------- plot(titanic.eff2[3], ticks=ticks, multiline=TRUE, ci.style="bars", key=list(x=.7, y=.95)) ## ----wrapup, include=FALSE, eval=TRUE------------------------------------ pkglist <- setdiff(.packages(), c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base")) #write_bib(pkglist, "ex-packages.bib") <file_sep>/pages/other.md --- output: html_fragment: self_contained: false smart: false --- <!-- generator: rmarkdown::render("other.md") --> <div class="contents"> ## Updates Updates to the code examples in the book will be posted here. * __`ca`__ package: There are now several enhancements for graphics for correspondence analysis (Chapter 6) in the `ca` package, v. 0.64. All examples in the book still work, but some can be simplified. * __`ggplot2`__ changes: In the latest major release, `ggplot2_2.0.0`, calls to `stat_smooth(method="glm")` now require the `family` argument to be specified as, for example, `method.args = list(family = binomial)` rather than `family = binomial`. This affects numerous figures in Chapter 7, starting with Figure 7.2 in Example 7.3. ## Errata Readers are invited to send an email related to typos or errors in the book to `friendly AT yorku DOT ca`. Please give specific section, page, figure or equation references, and use `DDAR: errata` in the subject line. * [Errata for the book, Jan. 11, 2016](extra/errata.pdf) ## Additional vignettes and case studies Several examples and topics did not make it into the printed book * [Visualizing GLMs for binary outcomes](extra/titanic-glm-ex.pdf) * [Classification and regression trees](extra/titanic-tree-ex.pdf) ## Reviews >This is an excellent book, nearly encyclopedic in its coverage. I personally find it very useful and expect that many other readers will as well. The book can certainly serve as a reference. It could also serve as a supplementary text in a course on categorical data analysis that uses R for computation or, because so much statistical detail is provided, even as the main text for a course on the topic that emphasizes graphical methods. ___<NAME>, McMaster University___ ## Citations If you use this book or the materials contained on this web site in research papers, you can cite that use as follows with BibTeX: ``` @Book{FriendlyMeyer:2016:DDAR, title = {Discrete Data Analysis with R: Visualization and Modeling Techniques for Categorical and Count Data}, year = {2016}, author = {<NAME> and <NAME>}, publisher = {Chapman \& Hall/CRC}, address = {Boca Raton, FL}, isbn = {978-1-4987-2583-5}, } ``` A text version of this citation is: <NAME>. & <NAME>. (2016). *Discrete Data Analysis with R: Visualization and Modeling Techniques for Categorical and Count Data*. Boca Raton, FL: Chapman & Hall/CRC. </div> <file_sep>/pages/Rcode/ch10.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch10") library(vcdExtra) .locals$ch10 <- NULL .pkgs$ch10 <- NULL ## ----ordinal, child='ch10/ordinal.Rnw'---------------------------------- ## ----lodds, R.options=list(digits=3)------------------------------------- library(vcd) data("Mental", package = "vcdExtra") (mental.tab <- xtabs(Freq ~ mental + ses, data=Mental)) (LMT <- loddsratio(mental.tab)) ## ----mental-lorplot-plot, eval=FALSE------------------------------------- ## library(corrplot) ## corrplot(as.matrix(LMT), method = "square", is.corr = FALSE, ## tl.col = "black", tl.srt = 0, tl.offset = 1) ## ----lodds1-------------------------------------------------------------- mean(LMT$coefficients) ## ----mental-glm1--------------------------------------------------------- indep <- glm(Freq ~ mental + ses, data = Mental, family = poisson) LRstats(indep) ## ----mental-indep, h=6, w=7, out.width='.7\\textwidth', cap='Mosaic display of the independence model for the mental health data.'---- long.labels <- list(set_varnames = c(mental="Mental Health Status", ses="Parent SES")) mosaic(indep, gp=shading_Friendly, residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, suppress=1, main="Mental health data: Independence") ## ----mental-glm2--------------------------------------------------------- Cscore <- as.numeric(Mental$ses) Rscore <- as.numeric(Mental$mental) ## ----mental-glm3--------------------------------------------------------- linlin <- update(indep, . ~ . + Rscore:Cscore) roweff <- update(indep, . ~ . + mental:Cscore) coleff <- update(indep, . ~ . + Rscore:ses) rowcol <- update(indep, . ~ . + Rscore:ses + mental:Cscore) ## ----mental-glm4, R.options=list(digits=6)------------------------------- LRstats(indep, linlin, roweff, coleff, rowcol) ## ----mental-glm5--------------------------------------------------------- anova(indep, linlin, roweff, test = "Chisq") anova(indep, linlin, coleff, test = "Chisq") ## ----mental-glm6--------------------------------------------------------- # interpret linlin association parameter coef(linlin)[["Rscore:Cscore"]] exp(coef(linlin)[["Rscore:Cscore"]]) ## ----mental-lodds-roweff------------------------------------------------- roweff.fit <- matrix(fitted(roweff), 4, 6, dimnames=dimnames(mental.tab)) round(as.matrix(loddsratio(roweff.fit)), 3) ## ----mental-lodds-coleff------------------------------------------------- coleff.fit <- matrix(fitted(coleff), 4, 6, dimnames = dimnames(mental.tab)) round(as.matrix(loddsratio(coleff.fit)), 3) ## ----mental-lodds-plots, echo=FALSE, h=5, w=5, out.width='.33\\textwidth', cap='Log odds ratio plots for the R (left), C (middle), and R+C (right) models fit to the mental health data.'---- plot(t(loddsratio(roweff.fit)), confidence = FALSE, legend_pos="bottomright", ylim = c(-.2, .3), main = "log odds ratios for ses and mental, R model") plot(t(loddsratio(coleff.fit)), confidence = FALSE, legend_pos = "bottomright", ylim = c(-.2, .3), main="log odds ratios for ses and mental, C model") rowcol.fit <- matrix(fitted(rowcol), 4, 6, dimnames = dimnames(mental.tab)) plot(t(loddsratio(rowcol.fit)), confidence = FALSE, legend_pos = "bottomright", ylim = c(-.2, .3), main = "log odds ratios for ses and mental, R+C model") ## ----mental-gnm1--------------------------------------------------------- library(gnm) contrasts(Mental$mental) <- contr.treatment contrasts(Mental$ses) <- contr.treatment indep <- gnm(Freq ~ mental + ses, data = Mental, family = poisson) RC1 <- update(indep, . ~ . + Mult(mental, ses), verbose = FALSE) RC2 <- update(indep, . ~ . + instances(Mult(mental, ses), 2), verbose = FALSE) ## ----mental-gnm2, R.options=list(digits=6)------------------------------- LRstats(indep, linlin, roweff, coleff, RC1, RC2) ## ----mental-gnm3--------------------------------------------------------- anova(linlin, RC1, RC2, test = "Chisq") ## ----mental-gnm4--------------------------------------------------------- rowProbs <- with(Mental, tapply(Freq, mental, sum) / sum(Freq)) colProbs <- with(Mental, tapply(Freq, ses, sum) / sum(Freq)) mu <- getContrasts(RC1, pickCoef(RC1, "[.]mental"), ref = rowProbs, scaleWeights = rowProbs) nu <- getContrasts(RC1, pickCoef(RC1, "[.]ses"), ref = colProbs, scaleWeights = colProbs) ## ----mental-gnm5--------------------------------------------------------- (alpha <- mu$qvframe) (beta <- nu$qvframe) ## ----mental-gnm6, R.options=list(digits=3)------------------------------- scores <- rbind(alpha, beta) scores <- cbind(scores, factor = c(rep("mental", 4), rep("ses", 6)) ) rownames(scores) <- c(levels(Mental$mental), levels(Mental$ses)) scores$lower <- scores[,1] - scores[,2] scores$upper <- scores[,1] + scores[,2] scores ## ----mental-RC1-plot, h=6, w=8, echo=2, fig.show='hide'------------------ op <- par(mar=c(5, 4, 1, 1) + .1) with(scores, { dotchart(Estimate, groups = factor, labels = rownames(scores), cex = 1.2, pch = 16, xlab = "RC1 Score", xlim = c(min(lower), max(upper))) arrows(lower, c(8 + (1 : 4), 1 : 6), upper, c(8 + (1 : 4), 1 : 6), col = "red", angle = 90, length = .05, code = 3, lwd = 2) }) par(op) ## ----mental-gnm7--------------------------------------------------------- alpha <- coef(RC2)[pickCoef(RC2, "[.]mental")] alpha <- matrix(alpha, ncol=2) rownames(alpha) <- levels(Mental$mental) colnames(alpha) <- c("Dim1", "Dim2") alpha beta <- coef(RC2)[pickCoef(RC2, "[.]ses")] beta <- matrix(beta, ncol=2) rownames(beta) <- levels(Mental$ses) colnames(beta) <- c("Dim1", "Dim2") beta ## ----mental-logmult1, eval=FALSE----------------------------------------- ## library(logmult) ## rc1 <- rc(mental.tab, verbose = FALSE, weighting = "marginal", ## se = "jackknife") ## rc2 <- rc(mental.tab, verbose = FALSE, weighting = "marginal", nd = 2, ## se = "jackknife") ## ----mental-logmult2, eval=FALSE, fig.show='hide'------------------------ ## coords <- plot(rc2, conf.ellipses = 0.68, cex = 1.5, ## rev.axes = c(TRUE, FALSE)) ## ----mental-logmult3, eval=FALSE----------------------------------------- ## scores <- rbind(coords$row, coords$col) ## lines(scores[1 : 4,], col = "blue", lwd = 2) ## lines(scores[-(1 : 4),], col = "red", lwd = 2) ## ----square, child='ch10/square.Rnw'------------------------------------- ## ----vision-glm1--------------------------------------------------------- data("VisualAcuity", package="vcd") women <- subset(VisualAcuity, gender=="female", select=-gender) ## ----vision-glm2--------------------------------------------------------- #library(vcdExtra) indep <- glm(Freq ~ right + left, data = women, family = poisson) quasi <- update(indep, . ~ . + Diag(right, left)) symm <- glm(Freq ~ Symm(right, left), data = women, family = poisson) qsymm <- update(symm, . ~ right + left + .) ## ----vision-glm4--------------------------------------------------------- LRstats(indep, quasi, symm, qsymm) ## ----vision-mosaics, h=6, w=6, out.width='.49\\textwidth', cap='Mosaic displays comparing the models of quasi-independence and quasi-symmetry for visual acuity in women.'---- labs <- c("High", "2", "3", "Low") largs <- list(set_varnames = c(right = "Right eye grade", left = "Left eye grade"), set_labels=list(right = labs, left = labs)) mosaic(quasi, ~ right + left, residuals_type = "rstandard", gp = shading_Friendly, labeling_args = largs, main = "Quasi-Independence (women)") mosaic(qsymm, ~ right + left, residuals_type = "rstandard", gp = shading_Friendly, labeling_args = largs, main = "Quasi-Symmetry (women)") ## ----vision-glm5--------------------------------------------------------- anova(symm, qsymm, test = "Chisq") ## ----hauser1------------------------------------------------------------- data("Hauser79", package = "vcdExtra") structable(~ Father + Son, data = Hauser79) ## ----hauser-lor, R.options=list(digits=3)-------------------------------- hauser.tab <- xtabs(Freq ~ Father + Son, data = Hauser79) (lor.hauser <- loddsratio(hauser.tab)) ## ----hauser-lor-plot, h=6, w=7, out.width='.6\\textwidth', cap='Plot of observed local log odds ratios in the Hauser79 data. The dotted horizontal line at zero shows local independence; the solid black horizontal line shows the mean.'---- plot(lor.hauser, confidence = FALSE, legend_pos = "topleft", xlab = "Father's status comparisons") m <- mean(lor.hauser$coefficients) # mean LOR grid.lines(x = unit(c(0, 1), "npc"), y = unit(c(m, m), "native")) ## ----hauser2------------------------------------------------------------- hauser.indep <- gnm(Freq ~ Father + Son, data = Hauser79, family = poisson) hauser.quasi <- update(hauser.indep, ~ . + Diag(Father, Son)) LRstats(hauser.indep, hauser.quasi) ## ----hauser-mosaic1, h=6, w=6, out.width='.49\\textwidth', cap='Mosaic displays for the Hauser79 data. Left: independence model; right:quasi-independence model.'---- mosaic(hauser.indep, ~ Father + Son, main = "Independence model", gp = shading_Friendly) mosaic(hauser.quasi, ~ Father + Son, main = "Quasi-independence model", gp = shading_Friendly) ## ----hauser-qsymm-------------------------------------------------------- hauser.qsymm <- update(hauser.indep, ~ . + Diag(Father, Son) + Symm(Father, Son)) LRstats(hauser.qsymm) ## ----hauser-mosaic2, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for the model of quasi-symmetry fit to the Hauser79 data.'---- mosaic(hauser.qsymm, ~ Father + Son, main = "Quasi-symmetry model", gp = shading_Friendly, residuals_type = "rstandard") ## ----hauser-topo1-------------------------------------------------------- levels <- matrix(c( 2, 4, 5, 5, 5, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 1 ), 5, 5, byrow = TRUE) ## ----hauser-topo2-------------------------------------------------------- hauser.topo <- update(hauser.indep, ~ . + Topo(Father, Son, spec = levels)) LRstats(hauser.topo) ## ----hauser-topo3-------------------------------------------------------- as.vector((coef(hauser.topo)[pickCoef(hauser.topo, "Topo")])) ## ----hauser-summary------------------------------------------------------ LRstats(hauser.indep, hauser.quasi, hauser.qsymm, hauser.topo) ## ----hauser2-ord1-------------------------------------------------------- Fscore <- as.numeric(Hauser79$Father) # numeric scores Sscore <- as.numeric(Hauser79$Son) # numeric scores # uniform association hauser.UA <- update(hauser.indep, ~ . + Fscore * Sscore) # row effects model hauser.roweff <- update(hauser.indep, ~ . + Father * Sscore) # RC model hauser.RC <- update(hauser.indep, ~ . + Mult(Father, Son), verbose = FALSE) ## ----hauser2-ord2-------------------------------------------------------- LRstats(hauser.indep, hauser.UA, hauser.roweff, hauser.RC) ## ----hauser-ord3--------------------------------------------------------- hauser.UAdiag <- update(hauser.UA, ~ . + Diag(Father, Son)) anova(hauser.UA, hauser.UAdiag, test = "Chisq") ## ----hauser2-ord3-------------------------------------------------------- coef(hauser.UAdiag)[["Fscore:Sscore"]] ## ----hauser2-CR1--------------------------------------------------------- hauser.CR <- update(hauser.indep, ~ . + Crossings(Father, Son)) hauser.CRdiag <- update(hauser.CR, ~ . + Diag(Father, Son)) LRstats(hauser.CR, hauser.CRdiag) ## ----hauser2-CR2--------------------------------------------------------- nu <- coef(hauser.CRdiag)[pickCoef(hauser.CRdiag, "Crossings")] names(nu) <- gsub("Crossings(Father, Son)C", "nu", names(nu), fixed = TRUE) nu ## ----hauser-mosaic3, h=6, w=6, out.width='.6\\textwidth', cap='Mosaic display for the quasi-crossings model fit to the Hauser79 data.'---- mosaic(hauser.CRdiag, ~ Father + Son, gp = shading_Friendly, residuals_type = "rstandard", main = "Crossings() + Diag()") ## ----hauser-sumry1------------------------------------------------------- modlist <- glmlist(hauser.indep, hauser.roweff, hauser.UA, hauser.UAdiag, hauser.quasi, hauser.qsymm, hauser.topo, hauser.RC, hauser.CR, hauser.CRdiag) LRstats(modlist, sortby = "BIC") ## ----hauser-sumry-plot, h=6, w=7, out.width='.7\\textwidth', cap='Model comparison plot for the models fit to the Hauser79 data.'---- sumry <- LRstats(modlist) mods <- substring(rownames(sumry), 8) with(sumry, { plot(Df, BIC, cex = 1.3, pch = 19, xlab = "Degrees of freedom", ylab = "BIC (log scale)", log = "y", cex.lab = 1.2) pos <- ifelse(mods == "UAdiag", 1, 3) text(Df, BIC + 55, mods, pos = pos, col = "red", xpd = TRUE, cex = 1.2) }) ## ----ord3way, child='ch10/ord3way.Rnw'----------------------------------- ## ----vision2-kway0, eval=FALSE------------------------------------------- ## Freq ~ 1 ## Freq ~ right + left + gender ## Freq ~ (right + left + gender)^2 ## Freq ~ (right + left + gender)^3 ## ----vision2-kway-------------------------------------------------------- vis.kway <- Kway(Freq ~ right + left + gender, data = VisualAcuity) LRstats(vis.kway) ## ----vision2-glm1-------------------------------------------------------- vis.indep <- glm(Freq ~ right + left + gender, data = VisualAcuity, family = poisson) vis.quasi <- update(vis.indep, . ~ . + Diag(right, left)) vis.qsymm <- update(vis.indep, . ~ . + Diag(right, left) + Symm(right, left)) LRstats(vis.indep, vis.quasi, vis.qsymm) ## ----vision2-qsymm, h=6, w=6, out.width='.7\\textwidth', cap='Mosaic display for the model of homogeneous quasi-symmetry fit to the VisualAcuity data.', fig.pos='!htb'---- mosaic(vis.qsymm, ~ gender + right + left, condvars = "gender", residuals_type = "rstandard", gp = shading_Friendly, labeling_args = largs, rep = FALSE, main = "Homogeneous quasi-symmetry") ## ----vision2-glm2-------------------------------------------------------- vis.hetdiag <- update(vis.indep, . ~ . + gender * Diag(right, left) + Symm(right, left)) vis.hetqsymm <- update(vis.indep, . ~ . + gender * Diag(right, left) + gender * Symm(right, left)) LRstats(vis.qsymm, vis.hetdiag, vis.hetqsymm) ## ----vision2-hetqsymm, h=6, w=6, out.width='.7\\textwidth', cap='Mosaic display for the model of heterogeneous quasi-symmetry fit to the VisualAcuity data.', fig.pos='!htb'---- mosaic(vis.hetqsymm, ~ gender + right + left, condvars="gender", residuals_type = "rstandard", gp = shading_Friendly, labeling_args = largs, rep = FALSE, main="Heterogeneous quasi-symmetry") ## ----multiv, child='ch10/multiv.Rnw'------------------------------------- ## ----coalminers-ex, child='ch10/coalminers.Rnw'-------------------------- ## ----cm1----------------------------------------------------------------- data("CoalMiners", package = "vcd") coalminers <- data.frame(t(matrix(aperm(CoalMiners, c(2, 1, 3)), 4, 9))) colnames(coalminers) <- c("BW", "Bw", "bW", "bw") coalminers$age <- c(22, 27, 32, 37, 42, 47, 52, 57, 62) coalminers ## ----blogits2------------------------------------------------------------ logitsCM <- blogits(coalminers[, 1 : 4], add = 0.5) colnames(logitsCM)[1:2] <- c("logitB", "logitW") logitsCM ## ----cm-blogits, h=6, w=7, out.width='.8\\textwidth', cap='Empirical logits and log odds ratio for breathlessness and wheeze in the CoalMiners data. The lines show separate linear regressions for each function. The right vertical axis shows equivalent probabilities for the logits.', fig.pos='!htb'---- col <- c("blue", "red", "black") pch <- c(15, 17, 16) age <- coalminers$age op <- par(mar = c(4, 4, 1, 4)+.2) matplot(age, logitsCM, type = "p", col = col, pch = pch, cex = 1.2, cex.lab = 1.25, xlab = "Age", ylab = "Log Odds or Odds Ratio") abline(lm(logitsCM[,1] ~ age), col = col[1], lwd = 2) abline(lm(logitsCM[,2] ~ age), col = col[2], lwd = 2) abline(lm(logitsCM[,3] ~ age), col = col[3], lwd = 2) # right probability axis probs <- c(.01, .05, .10, .25, .5) axis(4, at = qlogis(probs), labels = probs) mtext("Probability", side = 4, cex = 1.2, at = -2, line = 2.5) # curve labels text(age[2], logitsCM[2, 1] + .5, "Breathlessness", col = col[1], pos = NULL, cex = 1.2) text(age[2], logitsCM[2, 2] + .5, "Wheeze", col = col[2], pos = NULL, cex = 1.2) text(age[2], logitsCM[2, 3] - .5, "log OR\n(B|W)/(B|w)", col = col[3], pos = 1, cex = 1.2) par(op) ## ----cm-glm1------------------------------------------------------------- CM <- as.data.frame(CoalMiners) colnames(CM)[1:2] <- c("B", "W") head(CM) ## ----cm-glm2------------------------------------------------------------- cm.glm0 <- glm(Freq ~ B + W + Age, data = CM, family = poisson) cm.glm1 <- glm(Freq ~ B * W + Age, data = CM, family = poisson) LRstats(cm.glm0, cm.glm1) ## ----cm-mosaic1, h=6, w=7, out.width='.7\\textwidth', cap='Mosaic display for the baseline model, [BW][Age], fit to the CoalMiners data.', scap='Mosaic display for the baseline model, BW Age, fit to the CoalMiners data.'---- vnames <- list(set_varnames = c(B = "Breathlessness", W = "Wheeze")) lnames <- list(B=c("B", "b"), W = c("W", "w")) mosaic(cm.glm1, ~ Age + B + W, labeling_args = vnames, set_labels = lnames) ## ----cm-glm3------------------------------------------------------------- cm.glm2 <- glm(Freq ~ B * W + (B + W) * Age, data = CM, family = poisson) LRstats(cm.glm1, cm.glm2) ## ----cm-glm4------------------------------------------------------------- library(car) Anova(cm.glm2) ## ----cm-glm5------------------------------------------------------------- CM$age <- rep(seq(22, 62, 5), each = 4) ## ----cm-glm6------------------------------------------------------------- CM$ageOR <- (CM$B == "B") * (CM$W == "W") * CM$age cm.glm3 <- update(cm.glm2, . ~ . + ageOR) LRstats(cm.glm0, cm.glm1, cm.glm2, cm.glm3) ## ----cm.glm7------------------------------------------------------------- anova(cm.glm2, cm.glm3, test = "Chisq") ## ----cm-vglm0------------------------------------------------------------ coalminers <- transform(coalminers, agec = (age - 42) / 5) coalminers$Age <- dimnames(CoalMiners)[[3]] coalminers ## ----cm-vglm1------------------------------------------------------------ library(VGAM) # 00 01 10 11 cm.vglm1 <- vglm(cbind(bw, bW, Bw, BW) ~ agec, binom2.or(zero = NULL), data = coalminers) cm.vglm1 ## ------------------------------------------------------------------------ (G2 <- deviance(cm.vglm1)) # test residual deviance 1-pchisq(deviance(cm.vglm1), cm.vglm1@df.residual) ## ----cm-vglm1-coef------------------------------------------------------- coef(cm.vglm1, matrix = TRUE) exp(coef(cm.vglm1, matrix = TRUE)) ## ----cm-vglm1-plot1------------------------------------------------------ age <- coalminers$age P <- fitted(cm.vglm1) colnames(P) <- c("bw", "bW", "Bw", "BW") head(P) Y <- depvar(cm.vglm1) ## ----cm-vglm1-plot2, eval=FALSE, fig.show='hide', size='footnotesize'---- ## col <- c("red", "blue", "red", "blue") ## pch <- c(1, 2, 16, 17) ## ## op <- par(mar = c(5, 4, 1, 1) + .1) ## matplot(age, P, type = "l", ## col = col, ## lwd = 2, cex = 1.2, cex.lab = 1.2, ## xlab = "Age", ylab = "Probability", ## xlim = c(20,65)) ## matpoints(age, Y, pch = pch, cex = 1.2, col = col) ## # legend ## text(64, P[9,]+ c(0,.01, -.01, 0), labels = colnames(P), col = col, cex = 1.2) ## text(20, P[1,]+ c(0,.01, -.01, .01), labels = colnames(P), col = col, cex = 1.2) ## par(op) ## ----cm-lP, eval=FALSE--------------------------------------------------- ## lP <- qlogis(P) ## lY <- qlogis(Y) ## ----cm-blogitsP, eval=FALSE--------------------------------------------- ## # blogits, but for B and W ## logitsP <- blogits(P[, 4 : 1]) ## logitsY <- blogits(Y[, 4 : 1]) ## ----cm-vglm2------------------------------------------------------------ cm.vglm2 <- vglm(cbind(bw, bW, Bw, BW) ~ poly(agec, 2), binom2.or(zero = NULL), data = coalminers) ## ----cm-vglm2-LR--------------------------------------------------------- (LR <- deviance(cm.vglm1) - deviance(cm.vglm2)) 1 - pchisq(LR, <EMAIL> - <EMAIL>) ## ----tox-ex, child='ch10/toxaemia.Rnw'----------------------------------- ## ----tox1, size='footnotesize'------------------------------------------- data("Toxaemia", package = "vcdExtra") str(Toxaemia) tox.tab <- xtabs(Freq ~ class + smoke + hyper + urea, Toxaemia) ftable(tox.tab, row.vars = 1) ## ----tox-mosaic1, h=6, w=6, out.width='.5\\textwidth', cap='Mosaic displays for Toxaemia data: Predictor and response associations.'---- mosaic(~ smoke + class, data = tox.tab, shade = TRUE, main = "Predictors", legend = FALSE) mosaic(~ hyper + urea, data = tox.tab, shade = TRUE, main = "Responses", legend = FALSE) ## ----tox-mosaic2, h=4, w=12, out.width='1.1\\textwidth', cap='Toxaemia data: Response association conditioned on smoking level.'---- cotabplot(~ hyper + urea | smoke, tox.tab, shade = TRUE, legend = FALSE, layout = c(1, 3)) ## ----tox-mosaic3, h=4, w=20, out.width='1.1\\textwidth', cap='Toxaemia data: Response association conditioned on social class.'---- cotabplot(~ hyper + urea | class, tox.tab, shade = TRUE, legend = FALSE, layout = c(1, 5)) ## ----tox-fourfold, eval=FALSE-------------------------------------------- ## fourfold(aperm(tox.tab), fontsize = 16) ## ----tox-margins--------------------------------------------------------- margin.table(tox.tab, 2 : 1) ## ----tox-LOR0------------------------------------------------------------ (LOR <- loddsratio(urea ~ hyper | smoke + class, data = tox.tab)) ## ----tox-LOR, h=6, w=9, out.width='.75\\textwidth', cap='Log odds ratios for protein urea given hypertension, by social class and level of maternal smoking.'---- plot(t(LOR), confidence = FALSE, legend_pos = "bottomright", xlab = "Social class of mother") ## ----tox-logits---------------------------------------------------------- tox.hyper <- glm(hyper == "High" ~ class * smoke, weights = Freq, data = Toxaemia, family = binomial) tox.urea <- glm(urea == "High" ~ class * smoke, weights = Freq, data = Toxaemia, family = binomial) ## ----tox-effplots, h=6, w=6, out.width='.5\\textwidth', cap='Effect plots for hypertension and urea, by social class of mother and smoking.'---- library(effects) plot(allEffects(tox.hyper), ylab = "Probability (hypertension)", xlab = "Social class of mother", main = "Hypertension: class*smoke effect plot", colors = c("blue", "black", "red"), lwd=3, multiline = TRUE, key.args = list(x = 0.05, y = 0.2, cex = 1.2, columns = 1) ) plot(allEffects(tox.urea), ylab = "Probability (Urea)", xlab = "Social class of mother", main = "Urea: class*smoke effect plot", colors = c("blue", "black", "red"), lwd=3, multiline = TRUE, key.args = list(x = 0.65, y = 0.2, cex = 1.2, columns = 1) ) ## ----tox-prep------------------------------------------------------------ tox.tab <- xtabs(Freq~class + smoke + hyper + urea, Toxaemia) toxaemia <- t(matrix(aperm(tox.tab), 4, 15)) colnames(toxaemia) <- c("hu", "hU", "Hu", "HU") rowlabs <- expand.grid(smoke = c("0", "1-19", "20+"), class = factor(1:5)) toxaemia <- cbind(toxaemia, rowlabs) head(toxaemia) ## ----tox-vglm1----------------------------------------------------------- tox.vglm1 <- vglm(cbind(hu, hU, Hu, Hu) ~ class + smoke, binom2.or(zero = 3), data = toxaemia) coef(tox.vglm1, matrix=TRUE) ## ----tox-glms1----------------------------------------------------------- # null model tox.glm0 <- glm(Freq ~ class*smoke + hyper + urea, data = Toxaemia, family = poisson) # baseline model: no association between predictors and responses tox.glm1 <- glm(Freq ~ class*smoke + hyper*urea, data = Toxaemia, family = poisson) ## ----tox-glms2, size='footnotesize'-------------------------------------- tox.glm2 <- update(tox.glm1, . ~ . + smoke*hyper + class*urea) tox.glm3 <- glm(Freq ~ (class + smoke + hyper + urea)^2, data=Toxaemia, family=poisson) tox.glm4 <- glm(Freq ~ class*smoke*hyper + hyper*urea + class*urea, data=Toxaemia, family=poisson) tox.glm5 <- update(tox.glm4, . ~ . + smoke*urea) tox.glm6 <- update(tox.glm4, . ~ . + class*smoke*urea) tox.glm7 <- update(tox.glm6, . ~ . + smoke*hyper*urea) tox.glm8 <- glm(Freq ~ (class + smoke + hyper + urea)^3, data = Toxaemia, family = poisson) tox.glm9 <- glm(Freq ~ (class + smoke + hyper + urea)^4, data = Toxaemia, family = poisson) ## ----tox-glms3, size='footnotesize'-------------------------------------- library(lmtest) lmtest::lrtest(tox.glm1, tox.glm2, tox.glm3, tox.glm4, tox.glm5) ## ----tox-logits1--------------------------------------------------------- # reshape to 15 x 4 table of frequencies tox.tab <- xtabs(Freq ~ class + smoke + hyper + urea, Toxaemia) toxaemia <- t(matrix(aperm(tox.tab), 4, 15)) colnames(toxaemia) <- c("hu", "hU", "Hu", "HU") rowlabs <- expand.grid(smoke = c("0", "1-19", "20+"), class = factor(1:5)) toxaemia <- cbind(toxaemia, rowlabs) ## ----tox-logits2--------------------------------------------------------- # observed logits and log odds ratios logitsTox <- blogits(toxaemia[,4:1], add=0.5) colnames(logitsTox)[1:2] <- c("logitH", "logitU") logitsTox <- cbind(logitsTox, rowlabs) head(logitsTox) ## ----tox-logits3--------------------------------------------------------- # fitted frequencies, as a 15 x 4 table Fit <- t(matrix(predict(tox.glm2, type = "response"), 4, 15)) colnames(Fit) <- c("HU", "Hu", "hU", "hu") Fit <- cbind(Fit, rowlabs) logitsFit <- blogits(Fit[, 1 : 4], add=0.5) colnames(logitsFit)[1 : 2] <- c("logitH", "logitU") logitsFit <- cbind(logitsFit, rowlabs) ## ----tox-logits4--------------------------------------------------------- matrix(logitsFit$logOR, 3, 5, dimnames = list(smoke = c("0", "1-19", "20+"), class = 1 : 5)) ## ----tox-glmplot1, eval=FALSE-------------------------------------------- ## ggplot(logitsFit, aes(x = as.numeric(class), y = logitH, ## color = smoke)) + ## theme_bw() + ## geom_line(size = 1.2) + ## scale_color_manual(values = c("blue", "black", "red")) + ## ylab("log odds (Hypertension)") + ## xlab("Social class of mother") + ## ggtitle("Hypertension") + ## theme(axis.title = element_text(size = 16)) + ## geom_point(data = logitsTox, ## aes(x = as.numeric(class), y = logitH, color = smoke), ## size = 3) + ## theme(legend.position = c(0.85, .6)) <file_sep>/scripts/main.js // jQuery // Document ready $(function() { var basepath = $('body').data('basepath') || ''; // highlight the selected nav item var pathname = window.location.pathname; // strip trailing slash pathname = pathname.replace(/\/$/,''); if (!pathname.length || pathname == basepath) { pathname = basepath + '/pages/home'; } $('a.page').each(function(index) { var el = $(this); if (el.attr('href') == pathname) { el.addClass('selected'); // highlight its parent nav item if it has one var closest = el.closest('li.dropdown'); if (closest) { closest.children().first().addClass('selected'); } } }); // init fancybox $(".fancybox").fancybox(); }); <file_sep>/src/router.php <?php require 'vendor/autoload.php'; /** * A custom router built on top of AltoRouter * * @author <NAME> <<EMAIL>> * @version 1.0 */ class DDARRouter { private $router; private $basepath; /** * Constructor * @param string $basepath */ public function __construct($basepath) { $this->basepath = $basepath; $this->router = new AltoRouter(); } /** * Get the BASEPATH * @return string */ public function getBasepath() { return $this->basepath; } /** * Load the router and its routes */ public function load() { if (!empty($this->basepath)) { $this->router->setBasePath($this->basepath); } //set catch-all route $this->router->map('GET', '/[*:path]', function(){}); } /** * Perform a routing match and load the content * @return string */ public function match() { $match = $this->router->match(); return $this->getPageContent($match); } /** * Get the page content as a string * @param object $match * @return string */ private function getPageContent($match) { $params = $match['params']; $path = rtrim($params['path'], '/'); if (empty($path)) { //home $page = 'pages/home.html'; } else { $page = $path . '.html'; if (!is_file($page)) { //error $page = 'pages/error.html'; } } return file_get_contents($page); } } <file_sep>/pages/Rcode/ch04.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch04") .locals$ch04 <- NULL .pkgs$ch04 <- NULL library(vcd) library(vcdExtra) ## ----results="hide",fig.keep="none"-------------------------------------- hec <- margin.table(HairEyeColor, 2:1) barplot(hec, beside = TRUE, legend = TRUE) ## ----bartile, h=6, w=6, out.width='.49\\textwidth', cap="Two basic displays for the Hair-color Eye-color data. Left: grouped barchart; right: tile plot.", echo=FALSE---- hec <- margin.table(HairEyeColor, 2:1) barplot(hec, beside = TRUE, legend = TRUE, args.legend = list(x = "top")) tile(hec) ## ----results="hide",fig.keep="none"-------------------------------------- tile(hec) ## ----spineplot,w=6,h=6,out.width="0.7\\textwidth",cap="Spineplot of the Mental data."---- data("Mental", package = "vcdExtra") mental <- xtabs(Freq ~ ses + mental, data = Mental) spineplot(mental) ## ----berk-table---------------------------------------------------------- Berkeley <- margin.table(UCBAdmissions, 2:1) library(gmodels) CrossTable(Berkeley, prop.chisq = FALSE, prop.c = FALSE, format = "SPSS") ## ----odds-logoods-------------------------------------------------------- p <- c(0.05, .1, .25, .50, .75, .9, .95) odds <- p / (1 - p) logodds <- log(odds) data.frame(p, odds, logodds) ## ------------------------------------------------------------------------ data("UCBAdmissions") UCB <- margin.table(UCBAdmissions, 1:2) (LOR <- loddsratio(UCB)) (OR <- loddsratio(UCB, log = FALSE)) ## ------------------------------------------------------------------------ summary(LOR) ## ------------------------------------------------------------------------ confint(OR) confint(LOR) ## ------------------------------------------------------------------------ fisher.test(UCB) ## ----arth-assocstats1---------------------------------------------------- data("Arthritis", package = "vcd") Art <- xtabs(~ Treatment + Improved, data = Arthritis) Art round(100 * prop.table(Art, margin = 1), 2) ## ----arth-assocstats2---------------------------------------------------- assocstats(Art) ## ------------------------------------------------------------------------ data("Mental", package = "vcdExtra") mental <- xtabs(Freq ~ ses + mental, data = Mental) assocstats(mental) # standard chisq tests CMHtest(mental) # CMH tests ## ----chmdemo-prep, results='hide', echo=FALSE---------------------------- # general association cmhdemo1 <- read.table(header=TRUE, sep="", text=" b1 b2 b3 b4 b5 a1 0 15 25 15 0 a2 5 20 5 20 5 a3 20 5 5 5 20 ") cmhdemo1 <- as.matrix(cmhdemo1) # linear association cmhdemo2 <- read.table(header=TRUE, sep="", text=" b1 b2 b3 b4 b5 a1 2 5 8 8 8 a2 2 8 8 8 5 a3 5 8 8 8 2 a4 8 8 8 5 2 ") cmhdemo2 <- as.matrix(cmhdemo2) ## ----cmhdemo-test1------------------------------------------------------- CMHtest(cmhdemo1) ## ----cmhdemo, h=6, w=6, out.width='.49\\textwidth', cap='Sieve diagrams for two patterns of association: Left: general association; right: linear association.',echo=FALSE, fig.pos="tp"---- sieve(cmhdemo1, shade=TRUE, main="General association", gp = shading_sieve(interpolate = 0, lty = c("solid", "longdash"))) sieve(cmhdemo2, shade=TRUE, main="Linear association", gp = shading_sieve(interpolate = 0, lty = c("solid", "longdash"))) ## ----cmhdemo-test2------------------------------------------------------- CMHtest(cmhdemo2) ## ----arth-strat1--------------------------------------------------------- Art2 <- xtabs(~ Treatment + Improved + Sex, data = Arthritis) Art2 ## ----arth-strat2--------------------------------------------------------- assocstats(Art2) ## ----arth-strat3--------------------------------------------------------- CMHtest(Art2) apply(Art2, 3, sum) ## ----berk-woolf---------------------------------------------------------- woolf_test(UCBAdmissions) ## ----art-homogeneity----------------------------------------------------- woolf_test(Art2) ## ----art-homogeneity2---------------------------------------------------- library(MASS) loglm(~ (Treatment + Improved + Sex)^2, data = Art2) ## ----berk-fourfold1, h=6, w=6, out.width='.49\\textwidth', cap='Fourfold displays for the Berkeley admission data. Left: unstandardized; right: equating the proportions of males and females.'---- fourfold(Berkeley, std = "ind.max") # unstandardized fourfold(Berkeley, margin = 1) # equating gender ## ----berk-fourfold3, h=6, w=6, out.width='.6\\textwidth', cap='Fourfold display for Berkeley admission data with margins for gender and admission equated. The area of each quadrant shows the standardized frequency in each cell.'---- fourfold(Berkeley) # standardize both margins ## ------------------------------------------------------------------------ summary(loddsratio(Berkeley)) exp(.6103 + c(-1, 1) * qnorm(.975) * 0.06398) confint(loddsratio(Berkeley, log = FALSE)) ## ----berk-fourfold4, h=6, w=9, out.width='.95\\textwidth', cap='Fourfold displays for Berkeley admissions data, stratified by department. The more intense shading for Dept. A indicates a significant association.', out.extra='trim=80 50 80 50'---- # fourfold display UCB <- aperm(UCBAdmissions, c(2, 1, 3)) fourfold(UCB, mfrow = c(2, 3)) ## ----coalminer0---------------------------------------------------------- data("CoalMiners", package = "vcd") CM <- CoalMiners[, , 2 : 9] structable(. ~ Age, data = CM) ## ----coalminer1, h=5, w=10, out.width='\\textwidth', cap='Fourfold display for CoalMiners data, both margins equated.', out.extra='trim=120 80 120 80'---- fourfold(CM, mfcol = c(2, 4)) ## ----coalminer2---------------------------------------------------------- loddsratio(CM) loddsratio(CM, log = FALSE) ## ----coalminer3, h=6, w=6, out.width='.6\\textwidth', cap='Log odds plot for the CoalMiners data. The smooth curve shows a quadratic fit to age.'---- lor_CM <- loddsratio(CM) plot(lor_CM, bars=FALSE, baseline=FALSE, whiskers=.2) lor_CM_df <- as.data.frame(lor_CM) age <- seq(25, 60, by = 5) + 2 lmod <- lm(LOR ~ poly(age, 2), weights = 1 / ASE^2, data = lor_CM_df) grid.lines(seq_along(age), fitted(lmod), gp = gpar(col = "red", lwd = 2), default.units = "native") ## ----coalminer4---------------------------------------------------------- summary(lmod) ## ----HE-expected--------------------------------------------------------- haireye <- margin.table(HairEyeColor, 1:2) expected = independence_table(haireye) round(expected, 1) ## ----HE-sieve-simple, eval=FALSE, echo=FALSE----------------------------- ## sieve(haireye, shade=TRUE, sievetype="expected", ## main="Expected frequencies") ## sieve(haireye, shade=TRUE, ## main="Observed frequencies") ## ----HE-sieve, h=6, w=6, out.width='.49\\textwidth', cap="Sieve diagrams for the \\data{HairEyeColor} data. Left: expected frequencies shown in cells as numbers and the number of boxes; right: observed frequencies shown in cells.", echo=FALSE, fig.pos="tb"---- sieve(haireye, sievetype = "expected", shade = TRUE, main="Expected frequencies", labeling = labeling_values, value_type = "expected", gp_text = gpar(fontface = 2), gp = shading_sieve(interpolate = 0, line_col="darkgrey",eps=Inf,lty="dashed")) sieve(haireye, shade = TRUE, main="Observed frequencies", labeling = labeling_values, value_type = "observed", gp_text = gpar(fontface = 2)) ## ----VA.tab-------------------------------------------------------------- # re-assign names/dimnames data("VisualAcuity", package = "vcd") VA <- xtabs(Freq ~ right + left + gender, data = VisualAcuity) dimnames(VA)[1:2] <- list(c("high", 2, 3, "low")) names(dimnames(VA))[1:2] <- paste(c("Right", "Left"), "eye grade") structable(aperm(VA)) ## ----VA-sieve2, h=6, w=6, out.width='.7\\textwidth', cap='Vision classification for 7,477 women in Royal Ordnance factories. The high frequencies in the diagonal cells indicate the main association, but a subtler pattern also appears in the symmetric off-diagonal cells.', fig.pos='H'---- sieve(VA[, , "female"], shade = TRUE) ## ----sieve3, eval=FALSE-------------------------------------------------- ## sieve(Freq ~ right + left, data = VisualAcuity, shade = TRUE) ## ----VA-sieve3, h=6, w=6, out.width='.7\\textwidth', cap='Sieve diagram for the three-way table of VisualAcuity, conditioned on gender.'---- sieve(Freq ~ right + left | gender, data = VisualAcuity, shade = TRUE, set_varnames = c(right = "Right eye grade", left = "Left eye grade")) ## ----VA-cotabsieve3, h=6, w=12, out.width='\\textwidth', cap='Conditional Sieve diagram for the three-way table of VisualAcuity, conditioned on gender.'---- cotabplot(VA, cond = "gender", panel = cotab_sieve, shade = TRUE) ## ----berkeley-sieve, h=6, w=6, out.width='.49\\textwidth', cap='Sieve diagrams for the three-way table of the Berkeley admissions data. Left: Admit by Dept, conditioned on Gender; right: Dept re-ordered as the first splitting variable.'---- # conditioned on gender sieve(UCBAdmissions, shade = TRUE, condvar = 'Gender') # three-way table, Department first, with cell labels sieve(~ Dept + Admit + Gender, data = UCBAdmissions, shade = TRUE, labeling = labeling_values, gp_text = gpar(fontface = 2), abbreviate_labs = c(Gender = TRUE)) ## ----berkeley-cotabsieve, h=6, w=12, out.width='\\textwidth', cap='Conditional Sieve diagram for the three-way table of the Berkeley data, conditioned on gender.'---- cotabplot(UCBAdmissions, cond = "Gender", panel = cotab_sieve, shade = TRUE) ## ----berkeley-cotabsieve2, h=8, w=12, out.width='\\textwidth', cap='Conditional Sieve diagram for the three-way table of the Berkeley data, conditioned on department.'---- cotabplot(UCBAdmissions, cond = "Dept", panel = cotab_sieve, shade = TRUE, labeling = labeling_values, gp_text = gpar(fontface = "bold")) ## ----berkeley-sieve2, h=6, w=6, out.width='.6\\textwidth', cap='Sieve diagram for the Berkeley admissions data, fitting the model of joint independence, Admit * Gender + Dept.'---- UCB2 <- aperm(UCBAdmissions, c(3, 2, 1)) sieve(UCB2, shade = TRUE, expected = ~ Admit * Gender + Dept, split_vertical = c(FALSE, TRUE, TRUE)) ## ----eval=FALSE---------------------------------------------------------- ## assoc(~ Hair + Eye, data = HairEyeColor, shade = TRUE) ## assoc(HairEyeColor, shade = TRUE) ## ----HE-assoc, h=6, w=6, out.width='0.5\\textwidth', cap='Association plot for the hair-color eye-color data. Left: marginal table, collapsed over gender; right: full table.',echo=FALSE---- assoc(~ Hair + Eye, data = HairEyeColor, shade = TRUE, gp_axis = gpar(lty = 5)) assoc(HairEyeColor, shade = TRUE, gp_axis = gpar(lty = 5)) ## ----sexisfun------------------------------------------------------------ data("SexualFun", package = "vcd") SexualFun ## ----ms1----------------------------------------------------------------- MSPatients[, , "Winnipeg"] MSPatients[, , "New Orleans"] apply(MSPatients, 3, sum) # show sample sizes ## ----sexfun-kappa-------------------------------------------------------- Kappa(SexualFun) confint(Kappa(SexualFun)) ## ----sexfun-agree, echo=2:3, h=6, w=6, out.width='.48\\textwidth', cap="Agreement charts for husbands' and wives' sexual fun. Left: unweighted chart, showing only exact agreement; right: weighted chart, using weight $w_1 = 8/9$ for a one-step disagreement.", fig.pos="hbt"---- op <- par(mar=c(4,3,4,1)+.1) agreementplot(SexualFun, main = "Unweighted", weights = 1) agreementplot(SexualFun, main = "Weighted") par(op) ## ----sexfun-agree1, fig.keep='none'-------------------------------------- B <- agreementplot(SexualFun) unlist(B)[1 : 2] ## ----mammograms1, echo=2:3, h=6, w=6, out.width='.6\\textwidth', cap='Agreement plot for the Mammograms data.'---- op <- par(mar = c(4, 3, 4, 1) + .1) data("Mammograms", package = "vcdExtra") B <- agreementplot(Mammograms, main = "Mammogram ratings") par(op) ## ----mammograms2--------------------------------------------------------- unlist(B)[1 : 2] ## ----MS-agree, h=7, w=12, out.width='\\textwidth', cap='Weighted agreement charts for both patient samples in the MSPatients data. Departure of the middle rectangles from the diagonal indicates lack of marginal homogeneity.'---- cotabplot(MSPatients, cond = "Patients", panel = cotab_agreementplot, text_gp = gpar(fontsize = 18), xlab_rot=20) ## ----MS-agree-stats, fig.keep='none'------------------------------------- agr1 <- agreementplot(MSPatients[, , "Winnipeg"]) agr2 <- agreementplot(MSPatients[, , "New Orleans"]) rbind(Winnipeg = unlist(agr1), NewOrleans = unlist(agr2))[, 1 : 2] ## ----tripdemo2, h=6, w=6, out.width='.6\\textwidth', cap='A trilinear plot showing three points, for variables A, B, C.', out.extra='trim=20 20 20 20,clip',echo=FALSE, fig.pos="!b"---- library(ggtern) DATA <- data.frame( A = c(40, 20, 10), B = c(30, 60, 10), C = c(30, 20, 80), id = c("1", "2", "3")) ggtern(data = DATA, mapping = aes(x=C, y=A, z=B, colour = id)) + geom_point(size=4) + geom_text(vjust=-.5, size=8, aes(label=id), show_guide=FALSE) + theme_rgbw() + theme(plot.margin=unit(c(0,0,0,0),"mm")) ## ----eval=FALSE---------------------------------------------------------- ## library(ggtern) ## DATA <- data.frame( ## A = c(40, 20, 10), ## B = c(30, 60, 10), ## C = c(30, 20, 80), ## id = c("1", "2", "3")) ## ## aesthetic_mapping <- aes(x = C, y = A, z = B, colour = id) ## ggtern(data = DATA, mapping = aesthetic_mapping) + ## geom_point(size = 4) + ## theme_rgbw() ## ----eval=FALSE---------------------------------------------------------- ## data("Lifeboats", package = "vcd") ## # label boats with more than 10% men ## Lifeboats$id <- ifelse(Lifeboats$men / Lifeboats$total > .1, ## as.character(Lifeboats$boat), "") ## ## AES <- aes(x = women, y = men, z = crew, colour = side, shape = side, ## label = id) ## ggtern(data = Lifeboats, mapping = AES) + ## geom_text() + ## geom_point(size=2) + ## geom_smooth_tern(method = "lm", alpha = 0.2) ## ----lifeboats1, h=6, w=6, out.width='.7\\textwidth', cap='Lifeboats on the \\emph{Titanic}, showing the composition of each boat. Boats with more than 10\\% male passengers are labeled.', scap='Lifeboats on the Titanic', out.extra='clip,trim=0 20 0 20',echo=FALSE---- data("Lifeboats", package="vcd") # label boats with more than 10% men Lifeboats$id <- ifelse(Lifeboats$men/Lifeboats$total > .1, as.character(Lifeboats$boat), "") ggtern(data = Lifeboats, mapping = aes(x = women, y = men, z = crew, colour=side, shape=side, label=id)) + theme_rgbw() + geom_point(size=2) + labs(title = "Lifeboats on the Titanic") + labs(T="Women and children") + geom_smooth_tern(method="lm", size=1.5, alpha=.2, aes(fill=side)) + geom_text(vjust=1, color="black") + theme(legend.position=c(.85, .85), axis.tern.vshift=unit(5,"mm")) ## ----eval=FALSE---------------------------------------------------------- ## AES <- aes(x = launch, y = total, colour = side, label = boat) ## ggplot(data = Lifeboats, mapping = AES) + ## geom_text() + ## geom_smooth(method = "lm", aes(fill = side), size = 1.5) + ## geom_smooth(method = "loess", aes(fill = side), se = FALSE, ## size = 1.2) ## ----lifeboats2, h=5, w=9, out.width='.8\\textwidth', cap='Number of people loaded on lifeboats on the Titanic vs. time of launch, by side of boat. The plot annotations show the linear regression and loess smooth.',echo=FALSE---- ggplot(data = Lifeboats, aes(x=launch, y=total, colour=side, label=boat)) + geom_smooth(method="lm", aes(fill=side), size=1.5) + geom_smooth(method="loess", aes(fill=side), se=FALSE, size=1.2) + geom_point() + ylim(c(0,100)) + geom_text(vjust=-.5, color="black") + labs(y="Total loaded", x="Launch time") <file_sep>/pages/Rcode/ch11.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch11") .locals$ch11 <- NULL .pkgs$ch11 <- NULL library(ggplot2) library(vcdExtra) theme_set(theme_bw()) # set default ggplot theme ## ----count-data, child='ch11/count.Rnw'---------------------------------- ## ----phdpubs1-1---------------------------------------------------------- data("PhdPubs", package = "vcdExtra") with(PhdPubs, c(mean = mean(articles), var = var(articles), ratio = var(articles) / mean(articles))) ## ----art.tab, size='footnotesize', R.options=list(width=90)-------------- art.fac <- factor(PhdPubs$articles, levels = 0 : 19) # include zero frequencies art.tab <- table(art.fac) art.tab ## ----phdpubs-barplot1, eval=FALSE---------------------------------------- ## barplot(art.tab, xlab = "Number of articles", ylab = "Frequency", ## col = "lightblue") ## abline(v = mean(PhdPubs$articles), col = "red", lwd = 3) ## ci <- mean(PhdPubs$articles) + c(-1, 1) * sd(PhdPubs$articles) ## lines(x = ci, y = c(-4, -4), col = "red", lwd = 3, xpd = TRUE) ## ----phdpubs-barplot2, eval=FALSE---------------------------------------- ## barplot(art.tab + 1, ylab = "log(Frequency+1)", ## xlab = "Number of articles", col = "lightblue", log = "y") ## ----phdpubs-logplots, h=6, w=6, out.width='.49\\textwidth', cap='Exploratory plots for the number of articles in the PhdPubs data. Left: boxplots for married (1) vs.\ non-married (0); right: jittered scatterplot vs.\ mentor publications with a lowess smoothed curve.'---- boxplot(articles + 1 ~ married, data = PhdPubs, log = "y", varwidth = TRUE, ylab = "log(articles + 1)", xlab = "married", cex.lab = 1.25) plot(jitter(articles + 1) ~ mentor, data = PhdPubs, log = "y", ylab="log(articles + 1)", cex.lab = 1.25) lines(lowess(PhdPubs$mentor, PhdPubs$articles + 1), col = "blue", lwd = 3) ## ----phdpubs-ggplot, eval=FALSE------------------------------------------ ## ggplot(PhdPubs, aes(mentor, articles + 1)) + ## geom_jitter(position = position_jitter(h = 0.05)) + ## stat_smooth(method = "loess", size = 2, fill = "blue", alpha = 0.25) + ## stat_smooth(method = "lm", color = "red", size = 1.25, se = FALSE) + ## scale_y_log10(breaks = c(1, 2, 5, 10, 20)) + ## labs(y = "log(articles + 1)", x = "Mentor publications") ## ----phdpubs1-factors---------------------------------------------------- PhdPubs <- within(PhdPubs, { female <- factor(female) married <- factor(married) }) ## ----phdpubs1-pois, size='footnotesize'---------------------------------- phd.pois <- glm(articles ~ ., data = PhdPubs, family = poisson) summary(phd.pois) ## ----phdpubs1-coef------------------------------------------------------- round(cbind(beta = coef(phd.pois), expbeta = exp(coef(phd.pois)), pct = 100 * (exp(coef(phd.pois)) - 1)), 3) ## ----phdpubs1-effpois, h=5, w=10, out.width='\\textwidth', cap='Effect plots for the predictors in the Poisson regression model for the PhdPubs data. Jittered values of the continuous predictors are shown at the bottom as rug-plots.'---- library(effects) plot(allEffects(phd.pois), band.colors = "blue", lwd = 3, ylab = "Number of articles", main = "") ## ----phdpubs1-effpois1, eval=FALSE--------------------------------------- ## plot(allEffects(phd.pois), band.colors = "blue", ylim = c(0, log(10))) ## ----crabs1, child='ch11/crabs1.Rnw'------------------------------------- ## ----crabs1-gpairs, h=8, w=8, out.width='.8\\textwidth', cap='Generalized pairs plot for the CrabSatellites data.', echo=FALSE, fig.pos="!b"---- data("CrabSatellites", package = "countreg") library(vcd) library(gpairs) gpairs(CrabSatellites[, 5 : 1], diag.pars = list(fontsize = 16)) ## ----crabs1-str, size="footnotesize"------------------------------------- data("CrabSatellites", package = "countreg") str(CrabSatellites) ## ----crabs1-gpairs-bis, h=8, w=8, out.width='.8\\textwidth', cap='Generalized pairs plot for the CrabSatellites data.', eval=FALSE---- ## library(vcd) ## library(gpairs) ## gpairs(CrabSatellites[, 5 : 1], ## diag.pars = list(fontsize = 16)) ## ----crabs1-scats, h=5, w=6, echo=2:5, out.width='.49\\textwidth', cap='Scatterplots of number of satellites vs.\ width and weight, with lowess smooths.',size="footnotesize"---- op <- par(mar=c(4,4,1,1)+.1) plot(jitter(satellites) ~ width, data = CrabSatellites, ylab = "Number of satellites (jittered)", xlab = "Carapace width", cex.lab = 1.25) with(CrabSatellites, lines(lowess(width, satellites), col = "red", lwd = 2)) plot(jitter(satellites) ~ weight, data = CrabSatellites, ylab = "Number of satellites (jittered)", xlab = "Weight", cex.lab = 1.25) with(CrabSatellites, lines(lowess(weight, satellites), col = "red", lwd = 2)) par(op) ## ----cutfac, size='footnotesize', include=FALSE-------------------------- cutfac <- function(x, breaks = NULL, q = 10) { if(is.null(breaks)) breaks <- unique(quantile(x, (0 : q) / q)) x <- cut(x, breaks, include.lowest = TRUE, right = FALSE) levels(x) <- paste(breaks[-length(breaks)], ifelse(diff(breaks) > 1, c(paste("-", breaks[-c(1, length(breaks))] - 1, sep = ""), "+"), ""), sep = "") return(x) } ## ----crabs1-boxplots, h=4, w=5, echo=2:3, out.width='.49\\textwidth', cap='Boxplots of number of satellites vs.\ width and weight.'---- op <- par(mar=c(4,4,1,1)+.1) plot(satellites ~ cutfac(width), data = CrabSatellites, ylab = "Number of satellites", xlab = "Carapace width (deciles)") plot(satellites ~ cutfac(weight), data = CrabSatellites, ylab = "Number of satellites", xlab = "Weight (deciles)") par(op) ## ----crabs1-pois6-------------------------------------------------------- crabs.pois <- glm(satellites ~ ., data = CrabSatellites, family = poisson) summary(crabs.pois) ## ----crabs1-eff1, h=6, w=9, out.width='\\textwidth', cap='Effect plots for the predictors in the Poisson regression model for the CrabSatellites data.'---- plot(allEffects(crabs.pois), main = "") ## ----crabs1-pois1, size='footnotesize'----------------------------------- CrabSatellites1 <- transform(CrabSatellites, color = as.numeric(color)) crabs.pois1 <- glm(satellites ~ weight + color, data = CrabSatellites1, family = poisson) summary(crabs.pois1) ## ------------------------------------------------------------------------ LRstats(crabs.pois, crabs.pois1) ## ----phdpubs2-phi-------------------------------------------------------- with(phd.pois, deviance / df.residual) sum(residuals(phd.pois, type = "pearson")^2) / phd.pois$df.residual ## ----phdpubs2-quasi------------------------------------------------------ phd.qpois <- glm(articles ~ ., data = PhdPubs, family = quasipoisson) ## ----phdpubs2-phi2------------------------------------------------------- (phi <- summary(phd.qpois)$dispersion) ## ----crabs-nbin---------------------------------------------------------- library(MASS) crabs.nbin <- glm.nb(satellites ~ weight + color, data = CrabSatellites1) crabs.nbin$theta ## ----crabs-nbin1--------------------------------------------------------- crabs.nbin1 <- glm(satellites ~ weight + color, data = CrabSatellites1, family = negative.binomial(1)) ## ----phdpubs-nbin, echo=FALSE-------------------------------------------- library(MASS) phd.nbin <- glm.nb(articles ~ ., data = PhdPubs) ## ----phdpubs3-fitted----------------------------------------------------- fit.pois <- fitted(phd.pois, type = "response") fit.nbin <- fitted(phd.nbin, type = "response") ## ----cutq---------------------------------------------------------------- cutq <- function(x, q = 10) { quantile <- cut(x, breaks = quantile(x, probs = (0 : q) / q), include.lowest = TRUE, labels = 1 : q) quantile } ## ----qdat1--------------------------------------------------------------- group <- cutq(fit.nbin, q = 20) qdat <- aggregate(PhdPubs$articles, list(group), FUN = function(x) c(mean = mean(x), var = var(x))) qdat <- data.frame(qdat$x) qdat <- qdat[order(qdat$mean),] ## ----qdat2--------------------------------------------------------------- phi <- summary(phd.qpois)$dispersion qdat$qvar <- phi * qdat$mean qdat$nbvar <- qdat$mean + (qdat$mean^2) / phd.nbin$theta head(qdat) ## ----phd-mean-var-plot, h=6, w=9, out.width='.75\\textwidth', cap='Mean--variance functions for the PhdPubs data. Points show the observed means and variances for 20 quantile groups based on the fitted values in the negative-binomial model. The labeled lines and curves show the variance functions implied by various models.'---- with(qdat, { plot(var ~ mean, xlab = "Mean number of articles", ylab = "Variance", pch = 16, cex = 1.2, cex.lab = 1.2) abline(h = mean(PhdPubs$articles), col = gray(.40), lty = "dotted") lines(mean, qvar, col = "red", lwd = 2) lines(mean, nbvar, col = "blue", lwd = 2) lines(lowess(mean, var), lwd = 2, lty = "dashed") text(3, mean(PhdPubs$articles), "Poisson", col = gray(.40)) text(3, 5, "quasi-Poisson", col = "red") text(3, 6.7, "negbin", col = "blue") text(3, 8.5, "lowess") }) ## ----phdpubs3-SE--------------------------------------------------------- library(sandwich) phd.SE <- sqrt(cbind( pois = diag(vcov(phd.pois)), sand = diag(sandwich(phd.pois)), qpois = diag(vcov(phd.qpois)), nbin = diag(vcov(phd.nbin)))) round(phd.SE, 4) ## ----phd-disptest-------------------------------------------------------- library(AER) dispersiontest(phd.pois) dispersiontest(phd.pois, 2) ## ----phdpubs4-rootogram, w=6, h=4, out.width='.49\\textwidth', cap='Hanging rootograms for the PhdPubs data.'---- library(countreg) countreg::rootogram(phd.pois, max = 12, main = "PhDPubs: Poisson") countreg::rootogram(phd.nbin, max = 12, main = "PhDPubs: Negative-Binomial") ## ----crabs2-rootogram, w=6, h=4, out.width='.49\\textwidth', cap='Hanging rootograms for the CrabSatellites data.'---- countreg::rootogram(crabs.pois, max = 15, main = "CrabSatellites: Poisson") countreg::rootogram(crabs.nbin, max = 15, main = "CrabSatellites: Negative-Binomial") ## ----zeros, child='ch11/zeros.Rnw'--------------------------------------- ## ----zipois1------------------------------------------------------------- library(VGAM) set.seed(1234) data1 <- rzipois(200, 3, 0) data2 <- rzipois(200, 3, .3) ## ----zipois-plot, h=6, w=6, out.width='.49\\textwidth', cap='Bar plots of simulated data from Poisson and zero-inflated Poisson distributions.'---- tdata1 <- table(data1) barplot(tdata1, xlab = "Count", ylab = "Frequency", main = "Poisson(3)") tdata2 <- table(data2) barplot(tdata2, xlab = "Count", ylab = "Frequency", main = expression("ZI Poisson(3, " * pi * "= .3)")) ## ----detach-vgam, echo=FALSE--------------------------------------------- detach(package:VGAM) ## ----crabs-fix-color, include=FALSE-------------------------------------- CrabSatellites <- transform(CrabSatellites, color = as.numeric(color)) ## ----crabs-zero-spinogram, h=4, w=10, echo=2:3, out.width='\\textwidth', cap='Spinograms for the CrabSatellites data. The variables weight (left) and color (right) have been made discrete using quantiles of their distributions.'---- op <- par(cex.lab=1.2, mfrow = c(1, 2)) plot(factor(satellites == 0) ~ weight, data = CrabSatellites, breaks = quantile(weight, probs = seq(0,1,.2)), ylevels = 2:1, ylab = "No satellites") plot(factor(satellites == 0) ~ color, data = CrabSatellites, breaks = quantile(color, probs = seq(0,1,.33)), ylevels = 2:1, ylab = "No satellites") par(op) ## ----crabs-zero-cdplot, h=4, w=10, echo=2:3, out.width='\\textwidth', cap='Conditional density plots for the CrabSatellites data. The region shaded below shows the conditional probability density estimate for a count of zero.'---- op <- par(cex.lab = 1.2, mfrow = c(1, 2)) cdplot(factor(satellites == 0) ~ weight, data = CrabSatellites, ylevels = 2:1, ylab = "No satellites") cdplot(factor(satellites == 0) ~ color, data = CrabSatellites, ylevels = 2:1, , ylab = "No satellites") par(op) ## ----cod1, child='ch11/cod1.Rnw'----------------------------------------- ## ----cod-prevalence, eval=FALSE------------------------------------------ ## CodParasites$prevalence <- ## ifelse(CodParasites$intensity == 0, "no", "yes") ## ----cod1-1, size='footnotesize', R.options=list(width=80)--------------- data("CodParasites", package = "countreg") summary(CodParasites[, c(1 : 4, 7)]) ## ----cod1-gpairs, h=8, w=8, out.width='.8\\textwidth', cap='Generalized pairs plot for the CodParasites data.', fig.pos='htb!'---- library(vcd) library(gpairs) gpairs(CodParasites[, c(1 :4, 7)], diag.pars = list(fontsize = 16), mosaic.pars = list(gp = shading_Friendly)) ## ----cod1-tab------------------------------------------------------------ cp.tab <- xtabs(~ area + year + factor(is.na(prevalence) | prevalence == "yes"), data = CodParasites) dimnames(cp.tab)[3] <- list(c("No", "Yes")) names(dimnames(cp.tab))[3] <- "prevalence" ## ----cod1-doubledecker, h=5, w=10, out.width='.9\\textwidth', cap='Doubledecker plot for prevalence against area and year in the CodParasites data. The cases of infected fish are highlighted.'---- doubledecker(prevalence ~ area + year, data = cp.tab, margins = c(1, 5, 3, 1)) ## ----cod1-mosaic, h=5, w=10, out.width='.9\\textwidth', cap='Mosaic plot for prevalence against area and year in the CodParasites data, in the doubledecker format. Shading reflects departure from a model in which prevalence is independent of area and year jointly.'---- doubledecker(prevalence ~ area + year, data = cp.tab, gp = shading_hcl, expected = ~ year:area + prevalence, margins = c(1, 5, 3, 1)) ## ----cod1-length-prevalence, h=5, w=7, out.width='.6\\textwidth', cap='Jittered scatterplot of prevalence against length of fish, with loess smooth.'---- library(ggplot2) ggplot(CodParasites, aes(x = length, y = as.numeric(prevalence) - 1)) + geom_jitter(position = position_jitter(height = .05), alpha = 0.25) + geom_rug(position = "jitter", sides = "b") + stat_smooth(method = "loess", color = "red", fill = "red", size = 1.5) + labs(y = "prevalence") ## ----cod1-boxplot-bis, h=5, w=10, out.width='.9\\textwidth', cap='Notched boxplots for log (intensity) of parasites by area and year in the CodParasites data. Significant differences in the medians are signaled when the notches of two groups do not overlap.', eval=FALSE---- ## # plot only positive values of intensity ## CPpos <- subset(CodParasites, intensity > 0) ## ggplot(CPpos, aes(x = year, y = intensity)) + ## geom_boxplot(outlier.size = 3, notch = TRUE, aes(fill = year), ## alpha = 0.2) + ## geom_jitter(position = position_jitter(width = 0.1), alpha = 0.25) + ## facet_grid(. ~ area) + ## scale_y_log10(breaks = c(1, 2, 5, 10, 20, 50, 100, 200)) + ## theme(legend.position = "none") + ## labs(y = "intensity (log scale)") ## ----CPpos-kludge, echo=FALSE-------------------------------------------- CPpos <- subset(CodParasites, intensity > 0) ## ----cod1-length-scat, h=5, w=7, out.width='.6\\textwidth', cap='Jittered scatterplot of log (intensity) for the positive counts against length of fish, with loess smooth and linear regression line.'---- ggplot(CPpos, aes(x = length, y = intensity)) + geom_jitter(position = position_jitter(height = .1), alpha = 0.25) + geom_rug(position = "jitter", sides = "b") + scale_y_log10(breaks = c(1, 2, 5, 10, 20, 50, 100, 200)) + stat_smooth(method = "loess", color = "red", fill = "red", size = 2) + stat_smooth(method = "lm", size = 1.5) ## ----cod2-mod1----------------------------------------------------------- library(MASS) library(countreg) cp_p <- glm(intensity ~ length + area * year, data = CodParasites, family = poisson) cp_nb <- glm.nb(intensity ~ length + area * year, data = CodParasites) ## ----cod2-mod2----------------------------------------------------------- cp_hp <- hurdle(intensity ~ length + area * year, data = CodParasites, dist = "poisson") cp_hnb <- hurdle(intensity ~ length + area * year, data = CodParasites, dist = "negbin") cp_zip <- zeroinfl(intensity ~ length + area * year, data = CodParasites, dist = "poisson") cp_znb <- zeroinfl(intensity ~ length + area * year, data = CodParasites, dist = "negbin") ## ----cod2-rootograms, h=8, w=6, echo=2:7, out.width='.8\\textwidth', cap='Rootograms for six models fit to the CodParasites data.', fig.pos="!t"---- op <- par(mfrow = c(3, 2)) countreg::rootogram(cp_p, max = 50, main = "Poisson") countreg::rootogram(cp_nb, max = 50, main = "Negative Binomial") countreg::rootogram(cp_hp, max = 50, main = "Hurdle Poisson") countreg::rootogram(cp_hnb, max = 50, main = "Hurdle Negative Binomial") countreg::rootogram(cp_zip, max = 50, main = "Zero-inflated Poisson") countreg::rootogram(cp_znb, max = 50, main = "Zero-inflated Negative Binomial") par(op) ## ----cod2-summarise------------------------------------------------------ LRstats(cp_p, cp_nb, cp_hp, cp_hnb, cp_zip, cp_znb, sortby = "BIC") ## ----cod2-lrtest--------------------------------------------------------- library(lmtest) lrtest(cp_hp, cp_hnb) ## ----cod2-vuong---------------------------------------------------------- library(pscl) vuong(cp_nb, cp_hnb) # nb vs. hurdle nb vuong(cp_hnb, cp_znb) # hurdle nb vs znb ## ----cod2-summary, size='footnotesize', R.options=list(width=80)--------- summary(cp_hnb) ## ----cod2-hnb1----------------------------------------------------------- cp_hnb1 <- hurdle(intensity ~ length + area * year | area * year, data = CodParasites, dist = "negbin") ## ------------------------------------------------------------------------ lrtest(cp_hnb, cp_hnb1) vuong(cp_hnb, cp_hnb1) ## ----detach, echo=FALSE-------------------------------------------------- detach(package:pscl) ## ----cod3-eff1, h=6, w=6, out.width='.49\\textwidth', cap='Effect plots for total intensity of parasites from the negative-binomial model.'---- library(effects) eff.nb <- allEffects(cp_nb) plot(eff.nb[1], type = "response", ylim = c(0,30), main ="NB model: length effect") plot(eff.nb[2], type = "response", ylim = c(0,30), multiline = TRUE, ci.style = "bars", key.args = list(x = .05, y = .95, columns = 1), colors = c("black", "red", "blue") , symbols = 15 : 17, cex = 2, main = "NB model: area*year effect") ## ------------------------------------------------------------------------ cp_zero <- glm(prevalence ~ length + area * year, data = CodParasites, family = binomial) cp_nzero <- glm.nb(intensity ~ length + area * year, data = CodParasites, subset = intensity > 0) ## ----cod3-eff2, h=6, w=6, out.width='.49\\textwidth', cap='Effect plots for prevalence of parasites analogous to the hurdle negative-binomial model, fitted using a binomial GLM model.'---- eff.zero <- allEffects(cp_zero) plot(eff.zero[1], ylim=c(-2.5, 2.5), main="Hurdle zero model: length effect") plot(eff.zero[2], ylim=c(-2.5, 2.5), multiline=TRUE, key.args=list(x=.05, y=.95, columns=1), colors=c("black", "red", "blue"), symbols=15:17, cex=2, main="Hurdle zero model: area*year effect") ## ----nmes1, child='ch11/nmes1.Rnw'--------------------------------------- ## ----nmes1-data---------------------------------------------------------- data("NMES1988", package = "AER") nmes <- NMES1988[, c(1, 6:8, 13, 15, 18)] ## ----nmes-visits, h=6, w=6, out.width='.49\\textwidth', cap='Frequency distributions of the number of physician office visits.'---- plot(table(nmes$visits), xlab = "Physician office visits", ylab = "Frequency") plot(log(table(nmes$visits)), xlab = "Physician office visits", ylab = "log(Frequency)") ## ----nmes-mean-var------------------------------------------------------- with(nmes, c(mean = mean(visits), var = var(visits), ratio = var(visits) / mean(visits))) ## ----nmes-boxplots, h=4, w=9, echo=2:4, out.width='\\textwidth', cap='Number of physician office visits plotted against some of the predictors.'---- op <-par(mfrow=c(1, 3), cex.lab=1.4) plot(log(visits + 1) ~ cutfac(chronic), data = nmes, ylab = "Physician office visits (log scale)", xlab = "Number of chronic conditions", main = "chronic") plot(log(visits + 1) ~ health, data = nmes, varwidth = TRUE, ylab = "Physician office visits (log scale)", xlab = "Self-perceived health status", main = "health") plot(log(visits + 1) ~ cutfac(hospital, c(0:2, 8)), data = nmes, ylab = "Physician office visits (log scale)", xlab = "Number of hospital stays", main = "hospital") par(op) ## ----nmes-school, h=5, w=6, out.width='.6\\textwidth', cap='Jittered scatterplot of physician office visits against number of years of education, with nonparametric (loess) smooth.'---- library(ggplot2) ggplot(nmes, aes(x = school, y = visits + 1)) + geom_jitter(alpha = 0.25) + stat_smooth(method = "loess", color = "red", fill = "red", size = 1.5, alpha = 0.3) + labs(x = "Number of years of education", y = "log(Physician office visits + 1)") + scale_y_log10(breaks = c(1, 2, 5, 10, 20, 50, 100)) ## ----nmes2-initial------------------------------------------------------- nmes.pois <- glm(visits ~ ., data = nmes, family = poisson) nmes.nbin <- glm.nb(visits ~ ., data = nmes) ## ----nmes2-lrtest1------------------------------------------------------- library(lmtest) lrtest(nmes.pois, nmes.nbin) ## ----nmes2-nbin-summary-------------------------------------------------- summary(nmes.nbin) ## ----nmes2-add1---------------------------------------------------------- add1(nmes.nbin, . ~ .^2, test = "Chisq") ## ----nmes2-nbin2--------------------------------------------------------- nmes.nbin2 <- update(nmes.nbin, . ~ . + (health + chronic + hospital)^2 + health : school) ## ----nmes2-lrtest2------------------------------------------------------- lrtest(nmes.nbin, nmes.nbin2) ## ----nmes2-eff1, h=5, w=9, out.width='\\textwidth', cap='Effect plots for the main effects of each predictor in the negative binomial model nmes.nbin.'---- library(effects) plot(allEffects(nmes.nbin), ylab = "Office visits") ## ----eff-nbin2----------------------------------------------------------- eff_nbin2 <- allEffects(nmes.nbin2, xlevels = list(hospital = c(0 : 3, 6, 8), chronic = c(0:3, 6, 8), school = seq(0, 20, 5))) ## ------------------------------------------------------------------------ names(eff_nbin2) ## ----nmes2-eff2, h=5, w=12, out.width='\\textwidth', cap='Effect plot for the interaction of health and number of chronic conditions in the model nmes.nbin2.'---- plot(eff_nbin2, "health:chronic", layout = c(3, 1), ylab = "Office visits", colors = "blue") ## ----nmes2-eff3, h=6, w=6, out.width='.49\\textwidth', cap='Effect plots for the interactions of chronic conditions and hospital stays with perceived health status in the model nmes.nbin2.'---- plot(eff_nbin2, "health:chronic", multiline = TRUE, ci.style = "bands", ylab = "Office visits", xlab ="# Chronic conditions", key.args = list(x = 0.05, y = .80, corner = c(0, 0), columns = 1)) plot(eff_nbin2, "hospital:health", multiline = TRUE, ci.style = "bands", ylab = "Office visits", xlab = "Hospital stays", key.args = list(x = 0.05, y = .80, corner = c(0, 0), columns = 1)) ## ----nmes2-eff4, h=6, w=6, out.width='.49\\textwidth', cap='Effect plots for the interactions of chronic conditions and hospital stays and for health status with years of education in the model nmes.nbin2.'---- plot(eff_nbin2, "hospital:chronic", multiline = TRUE, ci.style = "bands", ylab = "Office visits", xlab = "Hospital stays", key.args = list(x = 0.05, y = .70, corner = c(0, 0), columns = 1)) plot(eff_nbin2, "health:school", multiline = TRUE, ci.style = "bands", ylab = "Office visits", xlab = "Years of education", key.args = list(x = 0.65, y = .1, corner = c(0, 0), columns = 1)) ## ----nmes3-nbin3--------------------------------------------------------- nmes.nbin3 <- update(nmes.nbin2, . ~ . + I(chronic^2) + I(hospital^2)) ## ----nmes3-nbin3a, eval=FALSE-------------------------------------------- ## nmes.nbin3 <- glm.nb(visits ~ poly(hospital, 2) + poly(chronic, 2) + ## insurance + school + gender + ## (health + chronic + hospital)^2 + health : school, ## data = nmes) ## ----fm_anova------------------------------------------------------------ ret <- anova(nmes.nbin, nmes.nbin2, nmes.nbin3) ret$Model <- c("nmes.nbin", "nmes.nbin2", "nmes.nbin3") ret LRstats(nmes.nbin, nmes.nbin2, nmes.nbin3) ## ----nmes3-eff1, h=5, w=12, out.width='\\textwidth', cap='Effect plot for the interaction of health and number of chronic conditions in the quadratic model nmes.nbin3.'---- eff_nbin3 <- allEffects(nmes.nbin3, xlevels = list(hospital = c(0 : 3, 6, 8), chronic = c (0 : 3, 6, 8), school = seq(0, 20, 5))) plot(eff_nbin3, "health : chronic", layout = c(3, 1)) ## ----nmes3-gamnb--------------------------------------------------------- library(mgcv) nmes.gamnb <- gam(visits ~ s(hospital, k = 3) + s(chronic, k = 3) + insurance + school + gender + (health + chronic + hospital)^2 + health : school, data = nmes, family = nb()) ## ----nmes3-rsm, h=6, w=6, out.width='.5\\textwidth', cap='Fitted response surfaces for the relationships among chronic conditions, number of hospital stays, and years of education to office visits in the generalized additive model, nmes.gamnb.', echo=FALSE, fig.pos="hbt"---- library(rsm) library(colorspace) persp(nmes.gamnb, hospital ~ chronic, zlab = "log Office visits", col = rainbow_hcl(30), contour = list(col = "colors", lwd = 2), at = list(school = 10, health = "average"), theta = -60) persp(nmes.gamnb, school ~ chronic, zlab = "log Office visits", col = rainbow_hcl(30), contour = list(col = "colors", lwd = 2, z = "top"), at = list(hospital = 0.3, health = "average"), theta = -60) ## ----nmes3-rsm-bis, h=6, w=6, out.width='.5\\textwidth', cap='Fitted response surfaces for the relationships among chronic conditions, number of hospital stays, and years of education to office visits in the generalized additive model, nmes.gamnb.', eval=FALSE---- ## library(rsm) ## library(colorspace) ## persp(nmes.gamnb, hospital ~ chronic, zlab = "log Office visits", ## col = rainbow_hcl(30), contour = list(col = "colors", lwd = 2), ## at = list(school = 10, health = "average"), theta = -60) ## ## persp(nmes.gamnb, school ~ chronic, zlab = "log Office visits", ## col = rainbow_hcl(30), ## contour = list(col = "colors", lwd = 2, z = "top"), ## at = list(hospital = 0.3, health = "average"), theta = -60) ## ----phdpubs5-plot, h=8, w=8, echo=2, out.width='.7\\textwidth', cap='Default diagnostic plots for the negative-binomial model fit to the PhdPubs data.'---- op <- par(mfrow=c(2,2), mar=c(4,4,2,1)+.1, cex.lab=1.2) plot(phd.nbin) par(op) ## ----phdpubs5-resplot1, h=6, w=6, out.width='.5\\textwidth', cap='Plots of residuals against the linear predictor using residualPlot(). The right panel shows that the diagonal bands correspond to different values of the discrete response.'---- library(car) residualPlot(phd.nbin, type = "rstandard", col.smooth = "red", id.n = 3) residualPlot(phd.nbin, type = "rstandard", groups = PhdPubs$articles, key = FALSE, linear = FALSE, smoother = NULL) ## ----phdpubs5-resplot2, h=6, w=6, out.width='.5\\textwidth', cap='Plots of residuals against two predictors in the phd.nbin model. Such plots should show no evidence of a systematic trend for a good-fitting model.'---- residualPlot(phd.nbin, "mentor", type = "rstudent", quadratic = TRUE, col.smooth = "red", col.quad = "blue", id.n = 3) residualPlot(phd.nbin, "phdprestige", type = "rstudent", quadratic = TRUE, col.smooth = "red", col.quad = "blue", id.n = 3) ## ----phdpubs5-influenceplot, h=6, w=8, out.width='.7\\textwidth', cap="Influence plot showing leverage, studentized residuals, and Cook's distances for the negative-binomial model fit to the PhdPubs data. Conventional cutoffs for studentized residuals are shown by dashed horizontal lines at $\\pm 2$; vertical lines show 2 and 3 times the average hat-value."---- influencePlot(phd.nbin) ## ----phdpubs-outlierTest------------------------------------------------- outlierTest(phd.nbin) ## ----phdpubs6-qqplot, h=6, w=6, out.width='.5\\textwidth', cap='Normal QQ plot of the studentized residuals from the NB model for the PhdPubs data. The normal-theory reference line and confidence envelope are misleading here.'---- qqPlot(rstudent(phd.nbin), id.n = 3, xlab = "Normal quantiles", ylab = "Studentized residuals") ## ----phdpubs6-obs, eval=FALSE-------------------------------------------- ## observed <- sort(abs(rstudent(phd.nbin))) ## n <- length(observed) ## expected <- qnorm((1:n + n - 1/8) / (2*n + 1/2)) ## ----phdpubs6-sims, eval=FALSE------------------------------------------- ## S <- 100 ## sims <- simulate(phd.nbin, nsim = S) ## simdat <- cbind(PhdPubs, sims) ## ----phdpubs6-simres, eval=FALSE----------------------------------------- ## # calculate residuals for one simulated data set ## resids <- function(y) ## rstudent(glm.nb(y ~ female + married + kid5 + phdprestige + mentor, ## data=simdat, start=coef(phd.nbin))) ## # do them all ... ## simres <- matrix(0, nrow(simdat), S) ## for(i in 1:S) { ## simres[,i] <- sort(abs(resids(dat[,paste("sim", i, sep="_")]))) ## } ## ----phdpubs6-env, eval=FALSE-------------------------------------------- ## envelope <- 0.95 ## mean <- apply(simres, 1, mean) ## lower <- apply(simres, 1, quantile, prob = (1 - envelope) / 2) ## upper <- apply(simres, 1, quantile, prob = (1 + envelope) / 2) ## ----phdpubs6-hnp, eval=FALSE-------------------------------------------- ## plot(expected, observed, ## xlab = "Expected value of half-normal order statistic", ## ylab = "Absolute value of studentized residual") ## lines(expected, mean, lty = 1, lwd = 2, col = "blue") ## lines(expected, lower, lty = 2, lwd = 2, col = "red") ## lines(expected, upper, lty = 2, lwd = 2, col = "red") ## identify(expected, observed, labels = names(observed), n = 3) ## ----phdpubs6-res-plots, h=6, w=6, out.width='.5\\textwidth', cap='Further plots of studentized residuals. Left: density plot; right: residuals against log(articles+1).'---- # examine distribution of residuals res <- rstudent(phd.nbin) plot(density(res), lwd = 2, col = "blue", main = "Density of studentized residuals") rug(res) # why the bimodality? plot(jitter(log(PhdPubs$articles + 1), factor = 1.5), res, xlab = "log (articles + 1)", ylab = "Studentized residual") ## ----multiv, child='ch11/multiv.Rnw'------------------------------------- ## ----nmes-multiv, child='ch11/nmes-multiv.Rnw'--------------------------- ## ----nmes4-data---------------------------------------------------------- data("NMES1988", package = "AER") nmes2 <- NMES1988[, c(1 : 4, 6 : 8, 13, 15, 18)] names(nmes2)[1 : 4] # responses names(nmes2)[-(1 : 4)] # predictors ## ----nmes4-mlm----------------------------------------------------------- clog <- function(x) log(x + 1) nmes.mlm <- lm(clog(cbind(visits, nvisits, ovisits, novisits)) ~ ., data = nmes2) ## ----nmes4-hepairs, h=8, w=8, out.width='.8\\textwidth', cap='Pairwise HE plots for all responses in the nmes2 data.', fig.pos='!htb'---- library(heplots) vlabels <- c("Physician\noffice visits", "Non-physician\n office visits", "Physician\nhospital visits", "Non-physician\nhospital visits") pairs(nmes.mlm, factor.means = "health", fill = TRUE, var.labels = vlabels) ## ----nmes4-reshape------------------------------------------------------- vars <- colnames(nmes2)[1 : 4] nmes.long <- reshape(nmes2, varying = vars, v.names = "visit", timevar = "type", times = vars, direction = "long", new.row.names = 1 : (4 * nrow(nmes2))) ## ----nmes4-long, size='footnotesize'------------------------------------- nmes.long <- nmes.long[order(nmes.long$id),] nmes.long <- transform(nmes.long, practitioner = ifelse(type %in% c("visits", "ovisits"), "physician", "nonphysician"), place = ifelse(type %in% c("visits", "nvisits"), "office", "hospital"), hospf = cutfac(hospital, c(0 : 2, 8)), chronicf = cutfac(chronic)) ## ------------------------------------------------------------------------ xtabs(visit ~ practitioner + place, data = nmes.long) ## ----nmes4-fourfold1, h=6, w=6, out.extra='trim=0 130 0 130,clip', out.width='\\textwidth', cap='Fourfold displays for the association between practitioner and place in the nmes.long data, conditioned on health status.'---- library(vcdExtra) fourfold(xtabs(visit ~ practitioner + place + health, data = nmes.long), mfrow=c(1,3)) loddsratio(xtabs(visit ~ practitioner + place + health, data = nmes.long)) ## ----nmes4-fourfold2, h=8, w=8, out.width='\\textwidth', cap='Fourfold displays for the association between practitioner and place in the nmes.long data, conditioned on gender, insurance, and number of chronic conditions. Rows are levels of chronic; columns are the combinations of gender and insurance.', fig.pos='!htb'---- tab <- xtabs(visit ~ practitioner + place + gender + insurance + chronicf, data = nmes.long) fourfold(tab, mfcol=c(4,4), varnames=FALSE) ## ----nmes4-loddsratio, h=5, w=9, out.width='.85\\textwidth', cap='Plot of log odds ratios with 1 standard error bars for the association between practitioner and place, conditioned on gender, insurance, and number of chronic conditions. The horizontal lines show the null model (longdash) and the mean (dot--dash) of the log odds ratios.'---- lodds.df <- as.data.frame(loddsratio(tab)) library(ggplot2) ggplot(lodds.df, aes(x = chronicf, y = LOR, ymin = LOR - 1.96 * ASE, ymax = LOR + 1.96 * ASE, group = insurance, color = insurance)) + geom_line(size = 1.2) + geom_point(size = 3) + geom_linerange(size = 1.2) + geom_errorbar(width = 0.2) + geom_hline(yintercept = 0, linetype = "longdash") + geom_hline(yintercept = mean(lodds.df$LOR), linetype = "dotdash") + facet_grid(. ~ gender, labeller = label_both) + labs(x = "Number of chronic conditions", y = "log odds ratio (physician|place)") + theme_bw() + theme(legend.position = c(0.1, 0.9)) ## ----nmes4-lodds-mod----------------------------------------------------- lodds.mod <- lm(LOR ~ (gender + insurance + chronicf)^2, weights = 1 / ASE^2, data = lodds.df) anova(lodds.mod) ## ----load-VGAM, echo=FALSE----------------------------------------------- library(VGAM) ## ----nmes5-nbin, cache=TRUE---------------------------------------------- nmes2.nbin <- vglm(cbind(visits, nvisits, ovisits, novisits) ~ ., data = nmes2, family = negbinomial) ## ----nmes5-coef1--------------------------------------------------------- # coefficients for visits coef(nmes2.nbin, matrix = TRUE)[,c(1, 2)] # theta for visits exp(coef(nmes2.nbin, matrix = TRUE)[1, 2]) ## ----nmes5-coef2--------------------------------------------------------- coef(nmes2.nbin, matrix = TRUE)[,c(1, 3, 5, 7)] ## ----nmes5-clist--------------------------------------------------------- clist <- constraints(nmes2.nbin, type = "term") clist$hospital[c(1, 3, 5, 7),] ## ----nmes5-clist2-------------------------------------------------------- clist2 <- clist clist2$hospital <- cbind(rowSums(clist$hospital)) clist2$chronic <- cbind(rowSums(clist$chronic)) clist2$hospital[c(1, 3, 5, 7), 1, drop = FALSE] ## ----nmes5-nbin2, cache=TRUE--------------------------------------------- nmes2.nbin2 <- vglm(cbind(visits, nvisits, ovisits, novisits) ~ ., data = nmes2, constraints = clist2, family = negbinomial(zero = NULL)) ## ----nmes5-coef3--------------------------------------------------------- coef(nmes2.nbin2, matrix = TRUE)[,c(1, 3, 5, 7)] ## ----nmes5-lrtest-------------------------------------------------------- lrtest(nmes2.nbin, nmes2.nbin2) ## ----nmes5-linhyp1------------------------------------------------------- lh <- paste("hospital:", 1 : 3, " = ", "hospital:", 2 : 4, sep="") lh ## ----nmes5-foxkludge, include=FALSE-------------------------------------- if (packageVersion("car") < "2.1.1") { df.residual.vglm <- function(object, ...) object@df.<EMAIL> vcov.vglm <- function(object, ...) vcovvlm(object, ...) coef.vglm <- function(object, ...) coefvlm(object, ...) } ## ----nmes5-linhyp2------------------------------------------------------- car::linearHypothesis(nmes2.nbin, lh) <file_sep>/pages/Rcode/ch09.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch09") #knitrSet("ch09", cache=TRUE) require(vcdExtra, quietly = TRUE, warn.conflicts = FALSE) # should go in Rprofile .locals$ch09 <- NULL .pkgs$ch09 <- NULL ## ----contrasts----------------------------------------------------------- options("contrasts") ## ----loglm1, eval=FALSE-------------------------------------------------- ## loglin(mytable, margin = list(c(1, 2), c(1, 3), c(2, 3))) ## ----loglm2, eval=FALSE-------------------------------------------------- ## loglm(~ (A + B + C)^2, data = mytable) ## ----loglm3, eval=FALSE-------------------------------------------------- ## loglm(Freq ~ (A + B + C)^2, data = mydf) ## ----loglm4, eval=FALSE-------------------------------------------------- ## glm(Freq ~ (A + B + C)^2, data = mydf, family = poisson) ## ----stres-plot0--------------------------------------------------------- berkeley <- as.data.frame(UCBAdmissions) berk.glm1 <- glm(Freq ~ Dept * (Gender + Admit), data = berkeley, family = "poisson") fit <- fitted(berk.glm1) hat <- hatvalues(berk.glm1) stderr <- sqrt(1 - hat) ## ----stres-plot, echo=FALSE, h=6, w=7, out.width='.7\\textwidth', cap='Standard errors of residuals, $\\sqrt{1-h_i}$ decrease with expected frequencies. This plot shows why ordinary Pearson and deviance residuals may be misleading. The symbol size in the plot is proportional to leverage, $h_i$. Labels abbreviate Department, Gender, and Admit, colored by Admit.'---- op <- par(mar = c(5,4,1,1)+.1) plot(fit, stderr, cex = 5 * hat, ylab = "Std. Error of Residual", xlab = "Fitted Frequency", cex.lab = 1.2) labs <- with(berkeley, paste(Dept, substr(Gender, 1, 1), ifelse(Admit == "Admitted", "+", "-"), sep = "")) col <- ifelse(berkeley$Admit == "Admitted", "blue", "red") text(fit, stderr, labs, col = col, cex = 1.2) par(op) ## ----berk-loglm0--------------------------------------------------------- data("UCBAdmissions") library(MASS) berk.loglm0 <- loglm(~ Dept + Gender + Admit, data = UCBAdmissions, param = TRUE, fitted = TRUE) berk.loglm0 ## ----berk-loglm0-1, R.options=list(digits=4)----------------------------- structable(Dept ~ Admit + Gender, fitted(berk.loglm0)) ## ----berk-loglm1--------------------------------------------------------- # conditional independence in UCB admissions data berk.loglm1 <- loglm(~ Dept * (Gender + Admit), data = UCBAdmissions) berk.loglm1 ## ----berk-loglm2--------------------------------------------------------- berk.loglm2 <-loglm(~ (Admit + Dept + Gender)^2, data = UCBAdmissions) berk.loglm2 ## ----berk-loglm-anova---------------------------------------------------- anova(berk.loglm0, berk.loglm1, berk.loglm2, test = "Chisq") ## ------------------------------------------------------------------------ berkeley <- as.data.frame(UCBAdmissions) head(berkeley) ## ----berk-glm1----------------------------------------------------------- berk.glm1 <- glm(Freq ~ Dept * (Gender + Admit), data = berkeley, family = "poisson") ## ----berk-glm2----------------------------------------------------------- berk.glm2 <- glm(Freq ~ (Dept + Gender + Admit)^2, data = berkeley, family = "poisson") ## ----berk-glm-anova------------------------------------------------------ anova(berk.glm1, berk.glm2, test = "Chisq") ## ----berk-glm1-anova----------------------------------------------------- anova(berk.glm1, test = "Chisq") ## ----berk-glm1-mosaic, fig.pos='!htb', h=6, w=8, out.width='.7\\textwidth', cap='Mosaic display for the model [AD][GD], showing standardized residuals for the cell contributions to \\GSQ.', scap='Mosaic display for the model AD GD, showing standardized residuals.'---- library(vcdExtra) mosaic(berk.glm1, shade = TRUE, formula = ~ Dept + Admit + Gender, split = TRUE, residuals_type = "rstandard", main = "Model: [AdmitDept][GenderDept]", labeling = labeling_residuals, abbreviate_labs = c(Gender = TRUE), keep_aspect_ratio = FALSE) ## ----berk-glm3----------------------------------------------------------- berkeley <- within(berkeley, dept1AG <- (Dept == "A") * (Gender == "Female") * (Admit == "Admitted")) head(berkeley) ## ----berk-glm4----------------------------------------------------------- berk.glm3 <- glm(Freq ~ Dept * (Gender + Admit) + dept1AG, data = berkeley, family = "poisson") ## ----berk-glm5----------------------------------------------------------- LRstats(berk.glm3) anova(berk.glm1, berk.glm3, test = "Chisq") ## ----berk-glm6----------------------------------------------------------- coef(berk.glm3)[["dept1AG"]] exp(coef(berk.glm3)[["dept1AG"]]) ## ----berk-glm3-mosaic, fig.pos='!htb', h=6, w=8, out.width='.7\\textwidth', cap='Mosaic display for the model \\code{berk.glm3}, allowing an association of gender and admission in Department A. This model now fits the data well.', scap='Mosaic display for the model berk.glm3', echo=FALSE, fig.pos="H"---- mosaic(berk.glm3, shade = TRUE, formula = ~ Dept + Admit + Gender, split = TRUE, residuals_type = "rstandard", main = "Model: [DeptGender][DeptAdmit] + DeptA*[GA]", labeling = labeling_residuals, abbreviate_labs = c(Gender = TRUE), keep_aspect_ratio = FALSE) ## ----berk-glm3-mosaic-code, fig.pos='!htb', h=6, w=8, out.width='.7\\textwidth', cap='Mosaic display for the model \\code{berk.glm3}, allowing an association of gender and admission in Department A. This model now fits the data well.', scap='Mosaic display for the model berk.glm3', eval=FALSE---- ## mosaic(berk.glm3, shade = TRUE, ## formula = ~ Dept + Admit + Gender, split = TRUE, ## residuals_type = "rstandard", ## main = "Model: [DeptGender][DeptAdmit] + DeptA*[GA]", ## labeling = labeling_residuals, ## abbreviate_labs = c(Gender = TRUE), ## keep_aspect_ratio = FALSE) ## ----berk-logit1, R.options=list(digits=4)------------------------------- (obs <- log(UCBAdmissions[1,,] / UCBAdmissions[2,,])) ## ----berk-logit2--------------------------------------------------------- berk.logit2 <- glm(Admit == "Admitted" ~ Dept + Gender, data = berkeley, weights = Freq, family = "binomial") summary(berk.logit2) ## ----berk-logit3--------------------------------------------------------- berkeley <- within(berkeley, dept1AG <- (Dept == "A") * (Gender == "Female")) berk.logit3 <- glm(Admit == "Admitted" ~ Dept + Gender + dept1AG, data = berkeley, weights = Freq, family = "binomial") ## ----berk-anova, R.options=list(digits=6)-------------------------------- library(car) Anova(berk.logit2) Anova(berk.logit3) ## ----berk-pred2---------------------------------------------------------- pred2 <- cbind(berkeley[,1:3], fit = predict(berk.logit2)) pred2 <- cbind(subset(pred2, Admit == "Admitted"), obs = as.vector(obs)) head(pred2) ## ----berk-logit-plot, eval=FALSE, fig.show='hide'------------------------ ## library(ggplot2) ## ggplot(pred2, aes(x = Dept, y = fit, group = Gender, color = Gender)) + ## geom_line(size = 1.2) + ## geom_point(aes(x = Dept, y = obs, group = Gender, color = Gender), ## size = 4) + ## ylab("Log odds (Admitted)") + theme_bw() + ## theme(legend.position = c(.8, .9), ## legend.title = element_text(size = 14), ## legend.text = element_text(size = 14)) ## ----health1------------------------------------------------------------- Health <- expand.grid(concerns = c("sex", "menstrual", "healthy", "nothing"), age = c("12-15", "16-17"), gender = c("M", "F")) Health$Freq <- c(4, 0, 42, 57, 2, 0, 7, 20, 9, 4, 19, 71, 7, 8, 10, 21) ## ----health2------------------------------------------------------------- health.glm0 <- glm(Freq ~ concerns + age + gender, data = Health, subset = (Freq > 0), family = poisson) health.glm1 <- glm(Freq ~ concerns + age * gender, data = Health, subset = (Freq > 0), family = poisson) ## ----health3------------------------------------------------------------- LRstats(health.glm0, health.glm1) ## ----health-mosaic, h=6, w=8, out.width='.6\\textwidth', cap='Mosaic display for the Health data, model \\code{health.glm1}.', scap='Mosaic display for the Health data, model health.glm1'---- mosaic(health.glm1, ~ concerns + age + gender, residuals_type = "rstandard", rot_labels = 0, just_labels = c(left = "right"), margin = c(left = 5)) ## ----health4------------------------------------------------------------- health.glm2 <- glm(Freq ~ concerns*gender + concerns*age, data = Health, subset = (Freq > 0), family = poisson) LRstats(health.glm2) ## ----health5, R.options=list(width=80), size="footnotesize"-------------- summary(health.glm2) ## ----health-loglin1------------------------------------------------------ health.tab <- xtabs(Freq ~ concerns + age + gender, data = Health) ## ----health-loglm2------------------------------------------------------- nonzeros <- ifelse(health.tab>0, 1, 0) health.loglm0 <- loglm(~ concerns + age + gender, data = health.tab, start = nonzeros) health.loglm1 <- loglm(~ concerns + age * gender, data = health.tab, start = nonzeros) # df is wrong health.loglm2 <- loglm(~ concerns*gender + concerns*age, data = health.tab, start = nonzeros) LRstats(health.loglm0, health.loglm1, health.loglm2) <file_sep>/pages/Rcode/ch01.R ### SECTION ### 1. Introduction ### SECTION ### 1.2. What is categorical data? ### SECTION ### 1.2.1. Case form vs. frequency form ## First lines of Arthritis data data("Arthritis", package = "vcd") head(Arthritis, 5) ## Arthritis data in frequency form as.data.frame(xtabs(~ Treatment + Sex + Improved, data = Arthritis)) ### SECTION ### 1.2.3. Univariate, bivariate, and multivariate data ## Arthritis data for Treatment and Improved as.data.frame(xtabs(~ Treatment + Improved, data = Arthritis)) ### SECTION ### 1.3. Strategies for categorical data analysis ### SECTION ### 1.3.1. Hypothesis testing approaches ## Hair and Eye color data library(vcd) (HairEye <- margin.table(HairEyeColor, c(1, 2))) ## association statistics for Hair and Eye color assocstats(HairEye) ## Figure 1.1.: Graphical displays for the hair color and eye color data. Left: mosaic display; right: correspondence analysis plot. HairEye <- HairEye[,c(1,3,4,2)] mosaic(HairEye, shade = TRUE) library(ca) op <- par(cex=1.4) plot(ca(HairEye), main="Hair Color and Eye Color") title(xlab="Dimension 1 (89.4%)", ylab="Dimension 2 (9.5%)") par(op) ### SECTION ### 1.3.2. Model-building approaches ## Figure 1.2.: Space shuttle O-ring failure, observed and predicted probabilities. data("SpaceShuttle", package="vcd") logit2p <- function(logit) 1/(1 + exp(-logit)) plot(nFailures/6 ~ Temperature, data = SpaceShuttle, xlim = c(30, 81), ylim = c(0,1), main = "NASA Space Shuttle O-Ring Failures", ylab = "Estimated failure probability", xlab = "Temperature (degrees F)", type="n") fm <- glm(cbind(nFailures, 6 - nFailures) ~ Temperature, data = SpaceShuttle, family = binomial) pred <- predict(fm, data.frame(Temperature = 30 : 81), se=TRUE) predicted <- data.frame( Temperature = 30 : 81, prob = logit2p(pred$fit), lower = logit2p(pred$fit - 2*pred$se), upper = logit2p(pred$fit + 2*pred$se) ) with(predicted, { polygon(c(Temperature, rev(Temperature)), c(lower, rev(upper)), col="lightpink", border=NA) lines(Temperature, prob, lwd=3) } ) with(SpaceShuttle, points(Temperature, nFailures/6, col="blue", pch=19, cex=1.3) ) abline(v = 31, lty = 3) text(32, 0, 'Challenger', cex=1.1) ## Figure 1.3.: Donner party data, showing the relationship between age and survival. data("Donner", package="vcdExtra") donner.mod <- glm(survived ~ age, data=Donner, family=binomial) library(ggplot2) if (packageVersion("ggplot2") < "1.1.0") { # old code ggplot(Donner, aes(age, survived)) + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", family = binomial, formula = y ~ x, fill="blue", alpha = 0.3, size=2) } else { # new code ggplot(Donner, aes(age, survived)) + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, fill="blue", alpha = 0.3, size=2) } ## Figure 1.4.: Donner party data, showing other model-based smoothers for the relationship between age and survival. Left: using a natural spline; right: using a non-parametric loess smoother.', fig.pos="!b"---- library(splines) ggplot(Donner, aes(age, survived)) + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", family = binomial, formula = y ~ ns(x, 2), color="darkgreen", fill="darkgreen", alpha = 0.3, size=2) ggplot(Donner, aes(age, survived)) + theme_bw() + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "loess", span=0.9, color="red", fill="red", alpha = 0.2, size=2, na.rm=TRUE) + ylim(0,1) ### SECTION ### 1.4. Graphical methods for categorical data ### SECTION ### 1.4.3. Effect ordering and rendering for data display ## Figure 1.11.: Parallel coordinates plots of the Iris data. Left: Default variable order; right: Variables ordered to make the pattern of correlations more coherent. library(lattice) data("iris", package="datasets") vnames <- gsub("\\.", "\\\n", names(iris)) key = list( columns = 3, title="Species", lines = list(col=c("red", "blue", "green3"), lwd=4), col=c("red", "blue", "green3"), text = list(c("Setosa", "Versicolor", "Virginica"))) # default variable order parallelplot(~iris[1:4], data=iris, groups = Species, varnames = vnames[1:4], key=key, horizontal.axis = FALSE, lwd=4, col=c("red", "blue", "green3")) # effect of order of variables parallelplot(~iris[c(1,3,4,2)], data=iris, groups = Species, varnames = vnames[c(1,3,4,2)], key=key, horizontal.axis = FALSE, lwd=8, col=c(rgb(1,0,0,.2), rgb(0,0,1,.2), rgb(0,205/255,0,.2) )) ### SECTION ### 1.4.6. Data plots, model plots, and data+model plots ## Figure 1.15.: Qualitative color palette for the HSV (left) and HCL (right) spaces. library(colorspace) par(mfrow = c(1,2), mar = c(1,1,1,1), oma = c(0,0,0,0)) pie(rep(1,9), radius = 1, col = rainbow(9), labels = 360 * 0:8/9) pie(rep(1,9), radius = 1, col = rainbow_hcl(9), labels = 360 * 0:8/9) <file_sep>/pages/Rcode/ch08.R ## ----echo=FALSE---------------------------------------------------------- source("Rprofile.R") knitrSet("ch08") .locals$ch08 <- NULL .pkgs$ch08 <- NULL ## ----propodds, child="ch08/propodds.Rnw"--------------------------------- ## ----arth-po0------------------------------------------------------------ data("Arthritis", package = "vcd") head(Arthritis$Improved, 8) ## ----arth-po1------------------------------------------------------------ library(MASS) arth.polr <- polr(Improved ~ Sex + Treatment + Age, data = Arthritis, Hess = TRUE) summary(arth.polr) ## ----arth-po2------------------------------------------------------------ library(car) Anova(arth.polr) ## ----arth-vpo,size="footnotesize"---------------------------------------- library(VGAM) arth.po <- vglm(Improved ~ Sex + Treatment + Age, data = Arthritis, family = cumulative(parallel = TRUE)) arth.po ## ----arth-vnpo,size="footnotesize"--------------------------------------- arth.npo <- vglm(Improved ~ Sex + Treatment + Age, data = Arthritis, family = cumulative(parallel = FALSE)) arth.npo ## ----arth-coef----------------------------------------------------------- coef(arth.po, matrix = TRUE) coef(arth.npo, matrix = TRUE) ## ----arth-lrtest--------------------------------------------------------- VGAM::lrtest(arth.npo, arth.po) ## ----arth-vpo-npo-------------------------------------------------------- tab <- cbind( Deviance = c(deviance(arth.npo), deviance(arth.po)), df = c(df.residual(arth.npo), df.residual(arth.po)) ) tab <- rbind(tab, diff(tab)) rownames(tab) <- c("GenLogit", "PropOdds", "LR test") tab <- cbind(tab, pvalue=1-pchisq(tab[,1], tab[,2])) tab ## ----arth.ppo------------------------------------------------------------ arth.ppo <- vglm(Improved ~ Sex + Treatment + Age, data = Arthritis, family = cumulative(parallel = FALSE ~ Sex)) coef(arth.ppo, matrix = TRUE) ## ----arth-rms1----------------------------------------------------------- library(rms) arth.po2 <- lrm(Improved ~ Sex + Treatment + Age, data = Arthritis) arth.po2 ## ----arth-rmsplot, h=4, w=12, out.width='\\textwidth', cap='Visual assessment of ordinality and the proportional odds assumption for predictors in the Arthritis data. Solid lines connect the stratified means of X given Y. Dashed lines show the estimated expected value of X given Y=j if the proportional odds model holds for X.'---- op <- par(mfrow=c(1,3)) plot.xmean.ordinaly(Improved ~ Sex + Treatment + Age, data=Arthritis, lwd=2, pch=16, subn=FALSE) par(op) ## ----arth-po3------------------------------------------------------------ arth.fitp <- cbind(Arthritis, predict(arth.polr, type = "probs")) head(arth.fitp) ## ----arth-po4------------------------------------------------------------ library(reshape2) plotdat <- melt(arth.fitp, id.vars = c("Sex", "Treatment", "Age", "Improved"), measure.vars = c("None", "Some", "Marked"), variable.name = "Level", value.name = "Probability") ## view first few rows head(plotdat) ## ----arth-polr1, h=8, w=8, out.width='.8\\textwidth', cap='Predicted probabilities for the proportional odds model fit to the Arthritis data.', fig.pos='!htb'---- library(ggplot2) library(directlabels) gg <- ggplot(plotdat, aes(x = Age, y = Probability, colour = Level)) + geom_line(size = 2.5) + theme_bw() + xlim(10, 80) + geom_point(color = "black", size = 1.5) + facet_grid(Sex ~ Treatment, labeller = function(x, y) sprintf("%s = %s", x, y) ) direct.label(gg) ## ----arth-po-eff1, h=5, w=4, out.width='.49\\textwidth', cap='Effect plots for the effect of Age in the proportional odds model for the Arthritis data. Left: responses shown in separate panels. Right: responses shown in stacked format.'---- library(effects) plot(Effect("Age", arth.polr)) plot(Effect("Age", arth.polr), style = "stacked", key.args = list(x = .55, y = .9)) ## ----arth-po-eff2, h=6, w=8, out.width='.9\\textwidth', cap='Effect plot for the effects of Treatment, Sex, and Age in the Arthritis data.'---- plot(Effect(c("Treatment", "Sex", "Age"), arth.polr), style = "stacked", key.arg = list(x = .8, y = .9)) ## ----arth-po-eff3, h=4, w=8, out.width='.9\\textwidth', cap='Latent variable effect plot for the effects of Treatment and Age in the Arthritis data.'---- plot(Effect(c("Treatment", "Age"), arth.polr, latent = TRUE), lwd = 3) ## ----nested, child="ch08/nested.Rnw"------------------------------------- ## ----wlf1---------------------------------------------------------------- library(car) # for data and Anova() data("Womenlf", package = "car") some(Womenlf) ## ----wlf2---------------------------------------------------------------- # create dichotomies Womenlf <- within(Womenlf,{ working <- recode(partic, " 'not.work' = 'no'; else = 'yes' ") fulltime <- recode(partic, " 'fulltime' = 'yes'; 'parttime' = 'no'; 'not.work' = NA")}) some(Womenlf) ## ----wlf3---------------------------------------------------------------- with(Womenlf, table(partic, working)) with(Womenlf, table(partic, fulltime, useNA = "ifany")) ## ----wlf-mod.working----------------------------------------------------- mod.working <- glm(working ~ hincome + children, family = binomial, data = Womenlf) summary(mod.working) ## ----wlf-mod.fulltime---------------------------------------------------- mod.fulltime <- glm(fulltime ~ hincome + children, family = binomial, data = Womenlf) summary(mod.fulltime) ## ----wlf-coef------------------------------------------------------------ cbind(working = coef(mod.working), fulltime = coef(mod.fulltime)) ## ----wlf-lrtest---------------------------------------------------------- LRtest <- function(model) c(LRchisq = model$null.deviance - model$deviance, df = model$df.null - model$df.residual) tab <- rbind(working = LRtest(mod.working), fulltime = LRtest(mod.fulltime)) tab <- rbind(tab, All = colSums(tab)) tab <- cbind(tab, pvalue = 1- pchisq(tab[,1], tab[,2])) tab ## ----wlf-anova, R.options=list(digits=8)--------------------------------- Anova(mod.working) Anova(mod.fulltime) ## ----wlf-fitted1, size='footnotesize'------------------------------------ predictors <- expand.grid(hincome = 1 : 50, children =c('absent', 'present')) fit <- data.frame(predictors, p.working = predict(mod.working, predictors, type = "response"), p.fulltime = predict(mod.fulltime, predictors, type = "response"), l.working = predict(mod.working, predictors, type = "link"), l.fulltime = predict(mod.fulltime, predictors, type = "link") ) print(some(fit, 5), digits = 3) ## ----wlf-fitted2--------------------------------------------------------- fit <- within(fit, { `full-time` <- p.working * p.fulltime `part-time` <- p.working * (1 - p.fulltime) `not working` <- 1 - p.working }) ## ----wlf-reshape--------------------------------------------------------- fit2 <- melt(fit, measure.vars = c("full-time", "part-time", "not working"), variable.name = "Participation", value.name = "Probability") ## ----wlf-fitted-prob, h=4, w=8, out.width='.8\\textwidth', cap="Fitted probabilities from the models for nested dichotomies fit to the data on women's labor force participation."---- gg <- ggplot(fit2, aes(x = hincome, y = Probability, colour= Participation)) + facet_grid(~ children, labeller = function(x, y) sprintf("%s = %s", x, y)) + geom_line(size = 2) + theme_bw() + scale_x_continuous(limits = c(-3, 55)) + scale_y_continuous(limits = c(0, 1)) direct.label(gg, list("top.bumptwice", dl.trans(y = y + 0.2))) ## ----wlf-fitted-logit, h=4, w=8, out.width='.8\\textwidth', cap="Fitted log odds from the models for nested dichotomies fit to the data on women's labor force participation."---- fit3 <- melt(fit, measure.vars = c("l.working", "l.fulltime"), variable.name = "Participation", value.name = "LogOdds") levels(fit3$Participation) <- c("working", "full-time") gg <- ggplot(fit3, aes(x = hincome, y = LogOdds, colour = Participation)) + facet_grid(~ children, labeller = function(x, y) sprintf("%s = %s", x, y)) + geom_line(size = 2) + theme_bw() + scale_x_continuous(limits = c(-3, 50)) + scale_y_continuous(limits = c(-5, 4)) direct.label(gg, list("top.bumptwice", dl.trans(y = y + 0.2))) ## ----genlogit, child="ch08/genlogit.Rnw"--------------------------------- ## ----wlf-glogit1--------------------------------------------------------- levels(Womenlf$partic) ## ----wlf-glogit2--------------------------------------------------------- # choose not working as baseline category Womenlf$partic <- relevel(Womenlf$partic, ref = "not.work") ## ----wlf-glogit3--------------------------------------------------------- library(nnet) wlf.multinom <- multinom(partic ~ hincome + children, data = Womenlf, Hess = TRUE) ## ----wlf-glogit4--------------------------------------------------------- summary(wlf.multinom, Wald = TRUE) ## ----wlf-glogit5--------------------------------------------------------- stats <- summary(wlf.multinom, Wald = TRUE) z <- stats$Wald.ratios p <- 2 * (1 - pnorm(abs(z))) zapsmall(p) ## ----wlf-glogit6--------------------------------------------------------- wlf.multinom2 <- multinom(partic ~ hincome * children, data = Womenlf, Hess = TRUE) Anova(wlf.multinom2) ## ----wlf-glogit7--------------------------------------------------------- predictors <- expand.grid(hincome = 1 : 50, children = c("absent", "present")) fit <- data.frame(predictors, predict(wlf.multinom, predictors, type = "probs") ) ## ----wlf-multi-prob, h=4.5, w=8, out.width='.9\\textwidth', cap="Fitted probabilities from the generalized logit model fit to the data on women's labor force participation."---- fit2 <- melt(fit, measure.vars = c("not.work", "fulltime", "parttime"), variable.name = "Participation", value.name = "Probability") levels(fit2$Participation) <- c("not working", "full-time", "part-time") gg <- ggplot(fit2, aes(x = hincome, y = Probability, colour = Participation)) + facet_grid(~ children, labeller = function(x, y) sprintf("%s = %s", x, y)) + geom_line(size = 2) + theme_bw() + scale_x_continuous(limits = c(-3, 50)) + scale_y_continuous(limits = c(0, 0.9)) direct.label(gg, list("top.bumptwice", dl.trans(y = y + 0.2))) ## ----wlf-ordered--------------------------------------------------------- levels(Womenlf$partic) Womenlf$partic <- ordered(Womenlf$partic, levels=c("not.work", "parttime", "fulltime")) wlf.multinom <- update(wlf.multinom, . ~ .) ## ----wlf-multi-effect, h=5, w=8, out.width='.8\\textwidth', cap="Effect plot for the probabilities of not working and working part time and full time from the generalized logit model fit to the women's labor force data."---- plot(Effect(c("hincome", "children"), wlf.multinom), style = "stacked", key.args = list(x = .05, y = .9))
194caa2da5e2b5d1c0274be048c680358c2a37ff
[ "HTML", "Markdown", "JavaScript", "PHP", "R" ]
20
R
friendly/DDAR
98f345c3741621ade05eb561f4bc8917eaf7c74e
549093f68c0bcc53c1263ef79c347b6ac481ec54
refs/heads/master
<repo_name>hmcts/cnp-module-waf<file_sep>/tests/int/test/integration/default/controls/resource_groups.rb # encoding: utf-8 # copyright: 2017, The Authors # license: All rights reserved require 'rspec/retry' title 'Check Azure Resource Group Configuration' control 'azure-resource-groups' do impact 1.0 title ' Check that the resource group exist' json_obj = json('.kitchen/kitchen-terraform/default-azure/terraform.tfstate') random_name = json_obj['modules'][0]['outputs']['random_name']['value'] + '-waf-int' describe azure_resource_group(name: random_name) do it 'should succeed after a while', retry: 10, retry_wait: 10 do its('location') {should eq 'uksouth'} end end end <file_sep>/templateUpload.sh #!/bin/bash # # Shell script to upload specified files to a storage account # # Force script to return -1 if any std errors set -e connString=$1 source=$2 destination=$3 subscription=$4 command="az storage blob upload-batch --connection-string $connString --source $source --destination $destination" echo "Uploading content" if [ -z "$AZURE_CONFIG_DIR" ]; then echo "AZURE_CONFIG_DIR is not set - running under default AZ context" $command else echo "AZURE_CONFIG_DIR is set - using $subscription" env AZURE_CONFIG_DIR=/opt/jenkins/.azure-$subscription $command fi <file_sep>/README.md # cnp-module-waf A module that lets you create an Application Gatewatway with WAF. ## Usage To use this module you require a cert for the https listener. The cert (`certificate_name`) must be uploaded to a key vault. Once the cert exists in the vault, you will need to use a terraform data resource to read it and pass into the app gateway module for example: ``` locals { backend_name = "${var.product}-${var.component}-${var.env}" backend_hostname = "${local.backend_name}.service.${var.env}.platform.hmcts.net" } data "azurerm_subnet" "app_gateway_subnet" { name = "core-infra-subnet-appGw-${var.env}" virtual_network_name = "core-infra-vnet-${var.env}" resource_group_name = "core-infra-${var.env}" } data "azurerm_key_vault_secret" "cert" { name = "my-public-facing-domain-cert-name-stored-in-vault" vault_uri = "https://my-cert-vault.vault.azure.net/" // This value should be REPLACED with a valid URL } module "waf" { source = "git<EMAIL>:hmcts/cnp-module-waf?ref=v1.0.0" env = "${var.env}" subscription = "${var.subscription}" location = "${var.location}" wafName = "${var.product}" resourcegroupname = "${azurerm_resource_group.shared_resource_group.name}" common_tags = "${var.tags}" gatewayIpConfigurations = [ { name = "internalNetwork" subnetId = "${data.azurerm_subnet.app_gateway_subnet.id}" } ] sslCertificates = [ { name = "public-hostname-cert" // IT COULD BE ANYTHING data = "${data.azurerm_key_vault_secret.cert.value}" password = "" } ] httpListeners = [ { name = "${var.product}-http-listener" FrontendIPConfiguration = "appGatewayFrontendIP" FrontendPort = "frontendPort80" Protocol = "Http" SslCertificate = "" hostName = "${var.public_hostname}" }, { name = "${var.product}-https-listener" FrontendIPConfiguration = "appGatewayFrontendIP" FrontendPort = "frontendPort443" Protocol = "Https" SslCertificate = "public-hostname-cert" // THIS SHOULD MATCH THE NAME SPECIFIED ABOVE IN SSL CERTIFICATES LIST hostName = "${var.public_hostname}" }, ] backendAddressPools = [ { name = "${local.backend_name}" backendAddresses = [ { ipAddress = "${local.backend_hostname}" }, ] }, ] backendHttpSettingsCollection = [ { name = "backend-80-nocookies" port = 80 Protocol = "Http" CookieBasedAffinity = "Disabled" # For more information on using AuthenticationCertificates to enable # e2e encryption with ASE, please see the "Using authentication certificates" # section below, this is needed if your hostname for your app ends in .internal. AuthenticationCertificates = "" probeEnabled = "True" probe = "http-probe" PickHostNameFromBackendAddress = "True" }, { name = "backend-443-nocookies" port = 443 Protocol = "Https" CookieBasedAffinity = "Disabled" # For more information on using AuthenticationCertificates to enable # e2e encryption with ASE, please see the "Using authentication certificates" # section below, this is needed if your hostname for your app ends in .internal AuthenticationCertificates = "" probeEnabled = "True" probe = "https-probe" PickHostNameFromBackendAddress = "True" } ] requestRoutingRules = [ { name = "${var.product}-http" RuleType = "Basic" httpListener = "${var.product}-http-listener" backendAddressPool = "${local.backend_name}" backendHttpSettings = "backend-80-nocookies" }, { name = "${var.product}-https" RuleType = "Basic" httpListener = "${var.product}-https-listener" backendAddressPool = "${local.backend_name}" backendHttpSettings = "backend-443-nocookies" } ] probes = [ { name = "http-probe" protocol = "Http" path = "${var.health_check}" interval = "${var.health_check_interval}" timeout = 30 unhealthyThreshold = "${var.unhealthy_threshold}" pickHostNameFromBackendHttpSettings = "false" backendHttpSettings = "backend-80-nocookies" host = "${local.backend_hostname}" healthyStatusCodes = "200-399" }, { name = "https-probe" protocol = "Https" path = "${var.health_check}" interval = "${var.health_check_interval}" timeout = 30 unhealthyThreshold = "${var.unhealthy_threshold}" pickHostNameFromBackendHttpSettings = "false" backendHttpSettings = "backend-443-nocookies" host = "${local.backend_hostname}" healthyStatusCodes = "200-399" }, ] } ``` ## Using authentication certificates When deploying the application gateway to an environment (App Service Environment) which has a self-signed certificate associated to its internal load balancer (ILB), it will be necessary to whitelist this certificate in order to achieve end-to-end SSL encryption. The example above would have to be modified with the following properties. ``` use_authentication_cert = true // This property has to be set to true backendHttpSettingsCollection = [ { name = "backend-80-nocookies" port = 80 Protocol = "Http" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "" probeEnabled = "True" probe = "http-probe" PickHostNameFromBackendAddress = "True" HostName = "" }, { name = "backend-443-nocookies" port = 443 Protocol = "Https" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "ilbCert" // <<<--- The name of the certificate to use, if ilbCert then it will be automatically found for you. probeEnabled = "True" probe = "https-probe" PickHostNameFromBackendAddress = "True" }, ] ``` ## Using Path Based Routing Rules In Azure Application Gateway, it's possible to apply request routing based on the routes. For example, for diverting requests for a specific path (e.g. /uploads) to another backend pool the following changes need to be done to the configuration above. This configuration diverts those requests made to `/uploads` to another backed (i.e. palo-alto) while the others are sent to the default backend address pool. The `PathBased` routing requires sections identified with `requestRoutingRulesPathBased` and `urlPathMaps` and these sections are optional in case only `Basic` routing is used. It is possible to mix the Basic rule setting and PathBasedRouting as in the following sample. ``` requestRoutingRules = [ { name = "http-www" ruleType = "Basic" httpListener = "${var.product}-http-listener-www" backendAddressPool = "${var.product}-${var.env}-backend-pool" backendHttpSettings = "backend-80-nocookies-www" }, { name = "https-www" ruleType = "Basic" httpListener = "${var.product}-https-listener-www" backendAddressPool = "${var.product}-${var.env}-backend-pool" backendHttpSettings = "backend-443-nocookies-www" ] requestRoutingRulesPathBased = [ { name = "http-gateway" ruleType = "PathBasedRouting" httpListener = "${var.product}-http-listener-gateway" urlPathMap = "http-url-path-map-gateway" }, { name = "https-gateway" ruleType = "PathBasedRouting" httpListener = "${var.product}-https-listener-gateway" urlPathMap = "https-url-path-map-gateway" } ] urlPathMaps = [ { name = "http-url-path-map-gateway" defaultBackendAddressPool = "${var.product}-${var.env}-backend-pool" defaultBackendHttpSettings = "backend-80-nocookies-gateway" pathRules = [ { name = "http-url-path-map-gateway-rule-palo-alto" paths = ["/uploads"] backendAddressPool = "${var.product}-${var.env}-palo-alto" backendHttpSettings = "backend-80-nocookies-gateway" } ] }, { name = "https-url-path-map-gateway" defaultBackendAddressPool = "${var.product}-${var.env}-backend-pool" defaultBackendHttpSettings = "backend-80-nocookies-gateway" pathRules = [ { name = "https-url-path-map-gateway-rule-palo-alto" paths = ["/uploads"] backendAddressPool = "${var.product}-${var.env}-palo-alto" backendHttpSettings = "backend-80-nocookies-gateway" } ] } ] ``` See `ccd-shared-infrastructure` project for a fully working sample of the `PathBasedRouting` ## Configuring the backends The Application Service Environment (ASE) uses the hostname from the request to determine which application will receive the request. For this reason, is necessary that the correct hostname to be forwarded from the Application Gateway (WAF) to the ILB. There are 3 possible configurations that fulfill this requirements. ### Pick hostname from backend address This is the option followed in the main example. The idea behind it lies on using the the FQDN internal domain name of the frontend or service as the backend address, and then use that same FQDN as the hostname for the forwarded request by setting the property `PickHostNameFromBackendAddress` to `True`. Is worth mentioning that with this approach the FE service would not need the public domain name listed in the `Custom Domains` section. ### Force/Override Hostname For this option the backend address could either be the FQDN of the service or the Application Service Environment ILB IP address. The property `PickHostNameFromBackendAddress` would be set to `False` and a new property called "HostName" will need to be added. ``` backendAddressPools = [ { name = "${local.backend_name}" backendAddresses = [ { ipAddress = "${var.ilbIPAddress}" // or it could also be the service hostname, as per above "${local.backend_hostname}" }, ] }, ] backendHttpSettingsCollection = [ { name = "backend-80-nocookies" port = 80 Protocol = "Http" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "" probeEnabled = "True" probe = "http-probe" PickHostNameFromBackendAddress = "False" HostName = "${local.backend_hostname}" // This is where the hostname is being set }, { name = "backend-443-nocookies" port = 443 Protocol = "Https" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "" probeEnabled = "True" probe = "https-probe" PickHostNameFromBackendAddress = "False" HostName = "${local.backend_hostname}" This is where hostname s being set }, ] ``` With this approach the FE service would not need the public domain name listed in the `Custom Domains` section. ### ILB IP In case of choosing the ILB IP address as a backend address and not using the HostName property, it will be required that the frontend service has the public domain name added to the `Custom Domains` list. ``` backendAddressPools = [ { name = "${local.backend_name}" backendAddresses = [ { ipAddress = "${var.ilbIPAddress}" }, ] }, ] backendHttpSettingsCollection = [ { name = "backend-80-nocookies" port = 80 Protocol = "Http" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "" probeEnabled = "True" probe = "http-probe" PickHostNameFromBackendAddress = "False" HostName = "" }, { name = "backend-443-nocookies" port = 443 Protocol = "Https" CookieBasedAffinity = "Disabled" AuthenticationCertificates = "" probeEnabled = "True" probe = "https-probe" PickHostNameFromBackendAddress = "False" HostName = "" }, ] ``` ### Deployment target `deployment_target` parameter, type = String, Required = No, Default value = "", Description = Name of the Deployment Target. If `deployment_target` is empty it works in legacy mode<file_sep>/getCert.sh #!/bin/bash # # Shell script to grab certificates from the vault and provider a base64 encoded version # # Force script to return -1 if any std errors set -e vaultName=$1 certName=$2 fileLocation=$3 subscription=$4 azureConfigDir=/opt/jenkins/.azure-$subscription file=$fileLocation/$certName.out command="az keyvault certificate download --vault-name $vaultName --name $certName --file $file" echo "Grabbing certificate" echo "Using $subscription" echo "" # Check if cert exists and remove if [ -f $file ]; then echo "$file exists, removing" rm $file rm $file.2 else echo "$file not present" fi if [ -d "$azureConfigDir" ]; then echo "Config dir found for subscription $subscription" echo "Grabbing certificate for $certName from $vaultName" echo "" echo "Running command" echo "env AZURE_CONFIG_DIR=$azureConfigDir bash -e $command" result=$(env AZURE_CONFIG_DIR=$azureConfigDir bash -e $command) else echo "Config dir not found - running under current login" echo "Grabbing certificate for $certName from $vaultName" echo "" result=$(bash -e $command) fi if [ -z "$result" ]; then echo "Cert retrieved successfully ..." echo "" cat $file echo "" echo "" echo "Formatting file" echo "" cat $file | tr -d '\n' | sed s/'-----BEGIN CERTIFICATE-----'// | sed s/'-----END CERTIFICATE-----'// >$file.2 cat $file.2 else echo "Error retrieving cert ...." echo "$result" exit fi
e25124a4eb236e3a7d3eaa678a300ab8707a65f4
[ "Markdown", "Ruby", "Shell" ]
4
Ruby
hmcts/cnp-module-waf
e429fe68bd2ab22b8188694a44d4f43e58b4ca34
f08fff1a73cb8b786e09b99d00f6dc7738b5130f
refs/heads/main
<file_sep>package com.capgemini.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class RatingCriteria { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int ratingID; private long min; private long max; private String type; private int score; public int getRatingID() { return ratingID; } public void setRatingID(int ratingID) { this.ratingID = ratingID; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public RatingCriteria() { super(); // TODO Auto-generated constructor stub } public RatingCriteria(int ratingID, long min, long max, String type, int score) { super(); this.ratingID = ratingID; this.min = min; this.max = max; this.type = type; this.score = score; } } <file_sep>package com.capgemini.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Feedback { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int feedbackID; private int orgId; public Feedback(int feedbackID, int orgId, String message, Organisation org) { super(); this.feedbackID = feedbackID; this.orgId = orgId; this.message = message; this.org = org; } public int getOrgId() { return orgId; } public void setOrgId(int orgId) { this.orgId = orgId; } private String message; @ManyToOne @JoinColumn(name = "orgfeedback_fk", referencedColumnName = "orgID") private Organisation org; public int getFeedbackID() { return feedbackID; } public Organisation getOrg() { return org; } public void setOrg(Organisation org) { this.org = org; } public void setFeedbackID(int feedbackID) { this.feedbackID = feedbackID; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Feedback() { } } <file_sep>package com.capgemini.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.capgemini.entities.RatingCriteria; @Repository public interface RatingCriteriaRepo extends JpaRepository<RatingCriteria, Integer> { public RatingCriteria findByType(String type); } <file_sep>package com.capgemini.service; import java.util.List; import com.capgemini.entities.Feedback; public interface FeedbackService { List<Feedback> getFeedbacks(int orgID); Feedback createFeedback(Feedback feedback); } <file_sep>package com.capgemini.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.capgemini.entities.User; import com.capgemini.service.LoginRegister; @RestController @RequestMapping("/api") public class LoginRegisterController { @Autowired private LoginRegister service; @PostMapping("/login") public User loginUser(@RequestBody User user){ String tempEmailId = user.getUserEmail(); String tempPassword = user.getPassword(); User uObj = null; if (tempEmailId != null && tempPassword != null) { uObj = service.fetchUserByEmailIDAndPassword(tempEmailId, tempPassword); } return uObj; } @PostMapping("/registeruser") public User registerUser(@RequestBody User user) throws Exception { String tempEmailId = user.getUserEmail(); if (tempEmailId != null && !"".equals(tempEmailId)) { User obj = service.fetchUserByEmailID(tempEmailId); if (obj != null) { throw new Exception("User with email " + tempEmailId + " is already registered"); } } User uObj = null; uObj = service.registration(user); return uObj; } } <file_sep>package com.capgemini; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Sprint1FinancialratingsystemApplication { public static void main(String[] args) { SpringApplication.run(Sprint1FinancialratingsystemApplication.class, args); } } <file_sep>rootProject.name = 'sprint1-financialratingsystem' <file_sep>package com.capgemini.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.capgemini.entities.Feedback; @Repository public interface FeedbackRepo extends JpaRepository<Feedback, Integer>{ @Query("SELECT f FROM Feedback f WHERE f.orgId=:orgId") List<Feedback> findAllfeedbackByorgID(int orgId); }
63cf4815d5c3fe5b577d6f127e1144725abb0119
[ "Java", "Gradle" ]
8
Java
cgtry/sprint1
6191359373bac38825a7236f071759e9284fe9b7
02615f754181e91cb006ac368fe28541b3a44dd1
refs/heads/master
<file_sep>// // TweetCellTableViewCell.swift // Twitter // // Created by <NAME> on 2/12/20. // Copyright © 2020 Dan. All rights reserved. // import UIKit class TweetCellTableViewCell: UITableViewCell { @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var tweetText: UILabel! @IBOutlet weak var retweetB: UIButton! @IBOutlet weak var favB: UIButton! @IBAction func favorite(_ sender: Any) { let toBeFaved = !favorited if (toBeFaved) { TwitterAPICaller.client?.favorTweet(tweetId: tweetId, success: { self.setFaved(isFaved: true) }, failure: { (Error) in print("Couldn't Favorite!") }) } else { TwitterAPICaller.client?.unFavorTweet(tweetId: tweetId, success: { self.setFaved(isFaved: false) }, failure: { (Error) in print("Couldn't unfavorite!") }) } } @IBAction func retweetA(_ sender: Any) { TwitterAPICaller.client?.retweet(tweetId: tweetId, success: { self.setRetweeted(true) }, failure: { (Error) in print("Error in retweeting \(Error)") }) } var favorited:Bool = false var tweetId: Int = -1 func setFaved(isFaved: Bool) { favorited = isFaved if (favorited) { favB.setImage(UIImage(named:"favor-icon-red"), for: UIControl.State.normal) } else { favB.setImage(UIImage(named:"favor-icon"), for: UIControl.State.normal) } } func setRetweeted(_ isRetweeted: Bool) { if (isRetweeted) { retweetB.setImage(UIImage(named:"retweet-icon-green"), for: UIControl.State.normal) retweetB.isEnabled = false } else { retweetB.setImage(UIImage(named:"retweet-icon"), for: UIControl.State.normal) retweetB.isEnabled = true } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
2aa58b671ed5c78ffd6e36dd24b97214d971967a
[ "Swift" ]
1
Swift
jmorris019/Twitter-Starter
822b52b79b87082e32525854feab37be2d2f9ab7
8c5ee99174aef951576e6bbf280e4249aba1ba92
refs/heads/master
<repo_name>riatoso/apiadvisor<file_sep>/migrations/versions/fa0dc055f43d_.py """empty message Revision ID: fa0dc<PASSWORD> Revises: Create Date: 2020-01-21 12:58:26.131942 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('weather', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('cidade', sa.String(length=80), nullable=False), sa.Column('estado', sa.String(length=2), nullable=False), sa.Column('pais', sa.String(length=80), nullable=False), sa.Column('data', sa.Date(), nullable=False), sa.Column('probabilidade', sa.String(length=80), nullable=False), sa.Column('precipitacao', sa.String(length=80), nullable=False), sa.Column('min', sa.String(length=80), nullable=False), sa.Column('max', sa.String(length=80), nullable=False), sa.Column('code', sa.Integer(), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('weather') # ### end Alembic commands ### <file_sep>/app.py from app import app,manager,db from flask import request, render_template from app import helpers from app.models.tables import Weather from datetime import datetime from sqlalchemy.sql.expression import func @app.route('/') def index(): return render_template('index.html', title='Home',added=False) @app.route('/cidade') def cidade(): cidade_pesquisada = request.args.get('id') if(cidade_pesquisada == ''): return 'Você esqueceu de passar a cidade' response = helpers.weather_access(cidade_pesquisada) for data in response['data']: weather_create = Weather( cidade=response['name'], estado=response['state'], pais=response['country'].strip(), data=datetime.strptime(data['date'], '%Y-%m-%d').date(), probabilidade=data['rain']['probability'], precipitacao=data['rain']['precipitation'], min=data['temperature']['min'], max=data['temperature']['max'], code=cidade_pesquisada ) db.session.add(weather_create) db.session.commit() if('error' in response): return 'Opa, ocorreu um erro ao acessar a api: '+str(response['detail']) return render_template('index.html', title='Cidade',added=True) @app.route('/api/cidade/') @app.route('/api/cidade/<id>') def api_cidade(id=None): if id == None: return { 'error':'No id', 'msg': 'Você esqueceu de passar um ID' } response = helpers.weather_access(id) if('error' in response): return { 'error': str(response['detail']), 'msg': 'Sinto muito, mas você nâo tem acesso' } return response @app.route('/analise') def analise(): inicial = request.args.get('data_inicial') final = request.args.get('data_final') error = None try: datetime.strptime(inicial, '%Y-%m-%d') datetime.strptime(final, '%Y-%m-%d') except: return 'As datas tem que ser no format YYYY-mm-dd' maxima = db.session.query('cidade','max','data',func.max(Weather.max)).filter(Weather.data.between(inicial, final)).order_by(Weather.data.desc()).first() media_precipitacao = db.session.execute('select cidade,avg(precipitacao) as precipitacao from weather group by cidade') print(media_precipitacao) return render_template('analise.html', title='Analise', maxima=maxima, medias=media_precipitacao) if __name__ == "__main__": manager.run() <file_sep>/config.py import os db_path = os.path.join(os.path.dirname(__file__), 'storage.db') db_uri = 'sqlite:///{}'.format(db_path) class General(): DEBUG=True SQLALCHEMY_DATABASE_URI = db_uri SQLALCHEMY_TRACK_MODIFICATIONS = True<file_sep>/Readme.md Implementar um webservice que utilize um serviço de previsão do tempo (http://apiadvisor.climatempo.com.br/doc/index.html#api-Forecast-Forecast15DaysByCity), e persista os dados no banco de dados relacional (SQLite). O backend deve fornecer ainda uma interface para consumo externo (API RESTful). <file_sep>/app/helpers/__init__.py import json import requests from app import app from datetime import datetime def weather_access(id): api_token = '<KEY>' api_url = 'http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/'+id+'/days/15?token='+api_token headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer {0}'.format(api_token)} return json.loads(requests.get(api_url, headers=headers).content) @app.template_filter('date_format') def date_format(date): date_object = datetime.strptime(date, '%Y-%m-%d') return datetime.strftime(date_object,'%d/%m/%Y') @app.template_filter('format_precipitation') def format_precipitation(value): return round(value, 3) <file_sep>/app/models/tables.py from app import db class Weather(db.Model): __tablename__ = "weather" id = db.Column(db.Integer, primary_key=True, autoincrement=True) cidade = db.Column(db.String(80), unique=False, nullable=False) estado = db.Column(db.String(2), unique=False, nullable=False) pais = db.Column(db.String(80), unique=False, nullable=False) data = db.Column(db.Date, unique=False, nullable=False) probabilidade = db.Column(db.String(80), unique=False, nullable=False) precipitacao = db.Column(db.String(80), unique=False, nullable=False) min = db.Column(db.String(80), unique=False, nullable=False) max = db.Column(db.String(80), unique=False, nullable=False) code = db.Column(db.Integer, unique=False, nullable=False) def __init__(self, cidade, estado, pais, data, probabilidade, precipitacao, min, max, code): self.cidade = cidade self.estado = estado self.pais= pais self.data= data self.probabilidade= probabilidade self.precipitacao= precipitacao self.min= min self.max= max self.code= code def __repr__(self): return '<Weather %r>' % self.cidade<file_sep>/readme.txt // Ativar servidor interno source ENV/bin activate // Rodar servidor interno FLASK_ENV=development python3 app.py runserver // Rodar as migrations python3 app.py db init python3 app.py db migrate python3 app.py db upgrade // Urls Gravar dados no banco - http://127.0.0.1:5000/cidade?id=3680 Acesso api externa com retorno em json - http://127.0.0.1:5000/api/cidade/3680 Analise de precipitacao e maior temperatura - http://127.0.0.1:5000/analise?data_inicial=2020-01-21&data_final=2020-01-25 //Banco sqllite storage.db // Cidades consultadas e gravadas no banco Araras Araraquara Ribeirão Preto São Paulo Florianópolis
f9bdb09db9fec3f30fd0dbd5c1726f9b92d8b6ac
[ "Markdown", "Python", "Text" ]
7
Python
riatoso/apiadvisor
231ba9643dced38c09a6e62b1c7c463518c64f18
a49f7fa2dedf98dff572824ae91aeeeed8fda0f9
refs/heads/master
<repo_name>aniketmane/DemoProject<file_sep>/DemoProject/TestDemo/app/src/main/java/com/example/aniket/testdemo/models/ThumbnailImageModel.java package com.example.aniket.testdemo.models; /** * ThumbnailImageModel.java . * @author <NAME> * @version 1.0 */ public class ThumbnailImageModel { private String urlSource; private int height; private int width; // get the image source url public String getUrlSource() { return urlSource; } /** * @param String urlSource * @return void * Set the url to local object */ public void setUrlSource(String urlSource) { this.urlSource = urlSource; } // get the height for image public int getHeight() { return height; } /** * @param int height * @return void * Set the height to local object */ public void setHeight(int height) { this.height = height; } // get the width for image public int getWidth() { return width; } /** * @param int width * @return void * Set the width to local object */ public void setWidth(int width) { this.width = width; } } <file_sep>/DemoProject/TestDemo/app/src/main/java/com/example/aniket/testdemo/util/Constants.java package com.example.aniket.testdemo.util; /** * Constants.java . * @author <NAME> * @version 1.0 */ public class Constants { private static String HOST_NAME="https://en.wikipedia.org/w/api.php?"; private static String ACTION="action"; private static String PROP="prop"; private static String FORMAT="format"; private static String PIPROP="piprop"; private static String PITTHUMBSIZE="pithumbsize"; private static String PILIMIT="pilimit"; private static String GENRATOR="generator"; private static String GPSEARCH="gpssearch"; //create an object of Constants private static Constants instance = new Constants(); //make the constructor private so that this class cannot be //instantiated private Constants(){} //Get the only object available public static Constants getInstance(){ return instance; } /** * @param searchString -Search text Enter in edit text * @return String URL * Get the server URL * */ public String genrateURL(String searchString) { return HOST_NAME+ACTION+"=query&"+PROP+"=pageimages&"+FORMAT+"=json&"+PIPROP+"=thumbnail&"+PITTHUMBSIZE+"=50&"+PILIMIT+"=50&"+GENRATOR+"=prefixsearch&"+GPSEARCH+"="+searchString; } } <file_sep>/DemoProject/TestDemo/app/src/main/java/com/example/aniket/testdemo/app/MainActivity.java package com.example.aniket.testdemo.app; /** * MainActivity.java . * @author <NAME> * @version 1.0 */ import android.app.ProgressDialog; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.example.aniket.testdemo.adapter.CustomListAdapter; import com.example.aniket.testdemo.models.SearchResultModel; import com.example.aniket.testdemo.util.Constants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; public class MainActivity extends AppCompatActivity { private EditText edtSearch; private ProgressDialog pDialog; private ListView listData; private CustomListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getViews(); } //get the actual views private void getViews() { // btnSearch = (Button) findViewById(R.id.btnSearch); edtSearch = (EditText) findViewById(R.id.edtSearch); // btnSearch.setOnClickListener(this); listData = (ListView) findViewById(R.id.lv_Data); edtSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().trim().length()>2) { processRequest(s.toString()); } else { listData.setAdapter(null); if (s.toString().trim().length()==0) Toast.makeText(MainActivity.this, getResources().getString(R.string.empty_warning_message), Toast.LENGTH_SHORT).show(); } } }); } /** * @param searchString -Search text Enter in edit text * @return void * Get the data for requested search text * */ private void processRequest(String searchString) { Log.e("URL", "" + Constants.getInstance().genrateURL(searchString)); JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, Constants.getInstance().genrateURL(searchString), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (pDialog != null) { pDialog.dismiss(); } if (response!=null) { if (response.has("query")) { String responseQuery = response.getJSONObject("query").toString(); ArrayList<SearchResultModel> data = parseData(response); adapter = new CustomListAdapter(MainActivity.this, data); listData.setAdapter(adapter); } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (pDialog != null) { pDialog.dismiss(); } Log.e("Volley", "Error"); } } ); AppController.getInstance().addToRequestQueue(jor); } /** * @param objData -JSON Object * @return ArrayList<SearchResultModel> * Parse the JSON Object returned from API * */ private ArrayList<SearchResultModel> parseData(JSONObject objData) { ArrayList<SearchResultModel> data = null; try { if (objData != null) { data = new ArrayList<SearchResultModel>(); JSONObject objContinue = null; if (objData.has("continue")) { objContinue = objData.getJSONObject("continue"); } JSONObject objQuery = null; if (objData.has("query")) { objQuery = objData.getJSONObject("query"); } int offset = 0; if (objContinue!=null) { if (objContinue.has("query")) { offset = objContinue.getInt("gpsoffset"); } } JSONObject pages = null; if(objQuery!=null) { if (objQuery.has("pages")) { pages = objQuery.getJSONObject("pages"); } } if (pages != null ) { Iterator<String> keys = pages.keys(); while (keys.hasNext()) { SearchResultModel model = new SearchResultModel(); String key = keys.next(); JSONObject innerJObject = pages.getJSONObject(key); if (innerJObject.has("pageid")) { model.setPageId(Long.parseLong(innerJObject.getString("pageid"))); } if (innerJObject.has("title")) { model.setTitle(innerJObject.getString("title")); } if (innerJObject.has("index")) { model.setIndex(Integer.parseInt(innerJObject.getString("index"))); } if (innerJObject.has("thumbnail")) { JSONObject objectThumbnail = innerJObject.getJSONObject("thumbnail"); if (objectThumbnail.has("source")) { model.getImageModel().setUrlSource(objectThumbnail.getString("source")); } if (objectThumbnail.has("width")) { model.getImageModel().setWidth(Integer.parseInt(objectThumbnail.getString("width"))); } if (objectThumbnail.has("height")) { model.getImageModel().setHeight(Integer.parseInt(objectThumbnail.getString("height"))); } } data.add(model); } } } } catch (JSONException e) { e.printStackTrace(); } return data; } }
765aaf4517786d94e0d86e9877d7f06b40675a24
[ "Java" ]
3
Java
aniketmane/DemoProject
efc2aa8814397f1fa053e2f7968ff7c5a62e4755
41d6817723e324bd12cf7efa560ee37b6ddd281c
refs/heads/master
<repo_name>rvillaester/serverless-framework<file_sep>/python/search_students.py import boto3 import json from boto3.dynamodb.conditions import Key, Attr dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('student') def handler(event, context): queryParam = event['queryStringParameters'] print('query param', queryParam) search_by = queryParam['searchBy'] message = 'Success' try: if search_by == 'id': result = table.query( KeyConditionExpression=Key('id').eq(queryParam['id']) ) else: firstname = queryParam.get('firstname') lastname = queryParam.get('lastname') if(firstname and not lastname): expression = Attr('firstname').contains(firstname) if (firstname and lastname): expression = (Attr('firstname').contains(firstname) & Attr('lastname').contains(lastname)) if(lastname and not firstname): expression = Attr('lastname').contains(lastname) result = table.scan( FilterExpression=expression ) items = result['Items'] except BaseException as e: message = str(e) response = { 'statusCode': 200, 'body': json.dumps({ 'message': message, 'items': items }), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } } return response<file_sep>/python/update_student.py import boto3 import json dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('student') def handler(event, context): payload = json.loads(event['body']) print('payload', payload) message = 'Success' try: table.update_item( Key={ 'id': payload['id'] }, UpdateExpression='SET address = :address, email = :email, firstname = :firstname, lastname = :lastname, gender = :gender', ExpressionAttributeValues={ ':address': payload['address'], ':email': payload['email'], ':firstname': payload['firstname'], ':lastname': payload['lastname'], ':gender': payload['gender'] } ) except BaseException as e: message = str(e) response = { 'statusCode': 200, 'body': json.dumps({ 'message': message }), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } } return response<file_sep>/python/put_student.py import boto3 import json dynamo_db = boto3.resource('dynamodb') student_table = dynamo_db.Table('student') key_sequence_table = dynamo_db.Table('key_sequence') def get_sequence(): print('getting sequence') key_sequence = key_sequence_table.get_item( Key={ 'table_name': 'student' } ) return key_sequence['Item']['sequence_no'] def create_student(student_id, payload): print('creating student') student_table.put_item( Item={ 'id': student_id, 'firstname': payload['firstname'], 'lastname': payload['lastname'], 'email': payload['email'], #'birthdate': payload['birthdate'], 'address': payload['address'], 'gender': payload['gender'] } ) def increment_sequence(sequence): print('incrementing sequence') newSequence = sequence + 1 key_sequence_table.update_item( Key={ 'table_name': 'student' }, UpdateExpression='SET sequence_no = :sequence_no', ExpressionAttributeValues={ ':sequence_no': newSequence } ) print('incrementing sequence 123') def handler(event, context): payload = json.loads(event['body']) print('payload', payload) message = 'Success' try: sequence = get_sequence() student_id = 'STD-' + str(sequence) create_student(student_id, payload) increment_sequence(sequence) except BaseException as e: message = str(e) print(message) response = { 'statusCode': 200, 'body': json.dumps({ 'message': message, 'id': student_id }), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } } return response <file_sep>/python/delete_student.py import boto3 import json dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('student') def handler(event, context): payload = json.loads(event['body']) print('payload', payload) message = 'Success' try: table.delete_item( Key={ 'id': payload['id'] } ) except BaseException as e: message = str(e) response = { 'statusCode': 200, 'body': json.dumps({ 'message': message }), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } } return response<file_sep>/python/authenticated_api.py import json def handler(event, context): message = 'Congratulations - this is the lambda function behind a public AUTHENTICATED API' response = { 'statusCode': 200, 'body': json.dumps({ 'message': message }), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } } return response
080a45973858e14c10c91eab49067b673517c2ed
[ "Python" ]
5
Python
rvillaester/serverless-framework
e3a171b2a3c839bc42feb2f0a3e85082ab01106e
e61d51fd5114c1b412d666e9c137bb9c66413b3c
refs/heads/main
<file_sep>package usb import ( "context" "fmt" "log" "os" "github.com/bitrvmpd/goquark/internal/pkg/cfg" fsUtil "github.com/bitrvmpd/goquark/internal/pkg/fs" ) type ID uint8 var ( fileReader *os.File fileWriter *os.File ) const ( BlockSize = 0x1000 GLCI = 0x49434C47 GLCO = 0x4F434C47 header = ` #################################### ###### < < G O Q U A R K > > ###### #################################### goQuark is ready for connections... +-----------------------------------+ | Client: %v | | Version: %v | +-----------------------------------+ ` ) const ( Invalid ID = iota GetDriveCount GetDriveInfo StatPath GetFileCount GetFile GetDirectoryCount GetDirectory StartFile ReadFile WriteFile EndFile Create Delete Rename GetSpecialPathCount GetSpecialPath SelectFile ) type command struct { cmdMap map[ID]func() *buffer } func New(ctx context.Context) (*command, error) { c := command{ buffer: &buffer{ usb: initDevice(ctx), }} // Map cmd ID to respective function c.cmdMap = map[ID]func(){ Invalid: func() { log.Printf("usbUtils.Invalid:") }, GetDriveCount: c.getDriveCount, GetDriveInfo: c.getDriveInfo, StatPath: c.statPath, GetFileCount: c.getFileCount, GetFile: c.getFile, GetDirectoryCount: c.getDirectoryCount, GetDirectory: c.getDirectory, StartFile: c.startFile, ReadFile: c.readFile, WriteFile: c.writeFile, EndFile: c.endFile, Create: c.create, Delete: c.delete, Rename: c.rename, GetSpecialPathCount: c.getSpecialPathCount, GetSpecialPath: c.getSpecialPath, SelectFile: c.selectFile, } return &c, nil } func (c *command) ProcessUSBPackets() { // Loop waiting for device, improve by using recover someway for { // Check if device is connected. b := c.usb.isConnected() // Waits for device to appear // If false, returns. if !<-b { return } //quarkVersion := "0.4.0" //minGoldleafVersion := "0.8.0" // Reads goldleaf description d, err := c.retrieveDesc() if err != nil { log.Fatalf("ERROR: %v", err) } // Reads goldleaf's version number s, err := c.retrieveSerialNumber() if err != nil { log.Fatalf("ERROR: %v", err) } fmt.Printf(header, d, s) // Loop for reading usb for { if err := c.readFromUSB(); err != nil { // When usb is disconnected don't panic. // I need to tell the program to wait for a device again. log.Printf("INFO: Lost connection to device. %v", err) log.Println("Exiting loop...") c.usb.Close() break } // Magic [:4] i, err := c.readInt32() if err != nil { log.Fatalf("ERROR: %v", err) } if i != GLCI { log.Fatalf("ERROR: Invalid magic GLCI, got %v", i) } // CMD [4:] cmd, err := c.readInt32() if err != nil { log.Fatalln(err) } // Invoke requested function c.cmdMap[ID(cmd)]() } } } func (c *command) retrieveDesc() (string, error) { s, err := c.usb.getDescription() if err != nil { return "", err } return s, nil } func (c *command) retrieveSerialNumber() (string, error) { s, err := c.usb.getSerialNumber() if err != nil { return "", err } return s, nil } func (c *command) getDriveCount() { log.Println("GetDriveCount") drives, err := fsUtil.ListDrives() if err != nil { log.Fatalf("ERROR: %v", err) } c.responseStart() c.writeInt32(uint32(len(drives))) c.responseEnd() } func (c *command) getDriveInfo() { log.Println("GetDriveInfo") drives, err := fsUtil.ListDrives() if err != nil { log.Fatalf("ERROR: %v", err) } // Read payload idx, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't retrieve next int32 %v", err) } if int(idx) > len(drives) || int(idx) <= -1 { c.respondFailure(0xDEAD) log.Fatalf("ERROR: Invalid disk index %v", idx) } drive := drives[idx] label, err := fsUtil.GetDriveLabel(drive) if err != nil { log.Fatalf("ERROR: Can't get drive label for %v", drive) } c.responseStart() c.writeString(label) c.writeString(drive) c.writeInt32(0) c.writeInt32(0) c.responseEnd() } func (c *command) getSpecialPath() { log.Println("GetSpecialPath") // Read payload idx, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't retrieve next int32 %v", err) } if int(idx) > int(cfg.Size()) || int(idx) <= -1 { c.respondFailure(0xDEAD) log.Fatalf("ERROR: Invalid path index %v", idx) } folders := cfg.ListFolders() folder := folders[idx] c.responseStart() c.writeString(folder.Alias) c.writeString(fsUtil.NormalizePath(folder.Path)) c.responseEnd() } func (c *command) getSpecialPathCount() { log.Println("GetSpecialPathCount") c.responseStart() c.writeInt32(cfg.Size()) c.responseEnd() } func (c *command) getDirectoryCount() { log.Println("GetDirectoryCount") s, err := c.readString() if err != nil { log.Fatalf("ERROR: Can't send directory count for %v", err) } path := fsUtil.DenormalizePath(s) count, err := fsUtil.GetDirectoriesIn(path) if err != nil { log.Fatalf("ERROR: Can't get directories inside path %v", err) } c.responseStart() c.writeInt32(uint32(len(count))) c.responseEnd() } func (c *command) selectFile() { log.Println("SelectFile") path := fsUtil.NormalizePath("/Users/wuff/Documents/quarkgo") c.responseStart() c.writeString(path) c.responseEnd() } func (c *command) statPath() { log.Println("StatPath") path, err := c.readString() if err != nil { log.Fatalf("ERROR: Can't read string from buffer. %v", err) return } path = fsUtil.DenormalizePath(path) fi, err := os.Stat(path) if err != nil { log.Printf("ERROR: Couldn't get %v stats. %v", path, err) c.respondFailure(0xDEAD) return } ftype := 0 var fsize int64 = 0 if !fi.IsDir() { ftype = 1 fsize = fi.Size() } if fi.IsDir() { ftype = 2 } if ftype == 0 { c.respondFailure(0xDEAD) return } c.responseStart() c.writeInt32(uint32(ftype)) c.writeInt64(uint64(fsize)) c.responseEnd() } func (c *command) getFileCount() { log.Println("GetFileCount") path, err := c.readString() if err != nil { log.Fatalf("ERROR: Can't read string from buffer. %v", err) return } path = fsUtil.DenormalizePath(path) nFiles, err := fsUtil.GetFilesIn(path) if err != nil { log.Fatalf("ERROR: Can't get files in %v. %v", path, err) return } c.responseStart() c.writeInt32(uint32(len(nFiles))) c.responseEnd() } func (c *command) getFile() { log.Println("GetFile") path, err := c.readString() if err != nil { log.Fatalf("ERROR: Can't read string from buffer. %v", err) return } // idx comes after the path idx, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't retrieve next int32 %v", err) } path = fsUtil.DenormalizePath(path) files, err := fsUtil.GetFilesIn(path) if err != nil { log.Fatalf("ERROR: Can't get files in %v. %v", path, err) return } if idx >= len(files) || idx < 0 { c.respondFailure(0xDEAD) return } c.responseStart() c.writeString(files[idx]) c.responseEnd() } func (c *command) getDirectory() { log.Println("GetDirectory") path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) idx, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } dirs, err := fsUtil.GetDirectoriesIn(path) if err != nil { log.Fatalf("ERROR: Couldn't get directories in %v. %v", path, err) } if idx > len(dirs) || idx < 0 { c.respondFailure(0xDEAD) } c.responseStart() c.writeString(dirs[idx]) c.responseEnd() } // TODO: Follow "The happy path is left-aligned" func (c *command) readFile() { log.Println("ReadFile") path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) offset, err := c.readInt64() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } size, err := c.readInt64() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } var file *os.File if fileReader != nil { // Use the already opened fileReader file = fileReader } else { // Or Don't use it for some reason.. file, err = os.Open(path) if err != nil { log.Fatalf("ERROR: Couldn't open %v. %v", path, err) } } _, err = file.Seek(offset, 0) if err != nil { log.Fatalf("ERROR: Couldn't seek %v to offset %v. %v", path, offset, err) } fbuffer := make([]byte, size) bRead, err := file.Read(fbuffer) if err != nil { log.Fatalf("ERROR: Couldn't read %v. %v", path, err) } c.responseStart() c.writeInt64(uint64(bRead)) c.responseEnd() if _, err = c.usb.Write(fbuffer); err != nil { log.Fatalf("ERROR: Couldn't write %v.", err) } } func (c *command) rename() { fType, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) newPath, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } newPath = fsUtil.DenormalizePath(newPath) if fType != 1 && fType != 2 { c.respondFailure(0xDEAD) } err = os.Rename(path, newPath) if err != nil { log.Fatalf("ERROR: Couldn't rename %v to %v. %v", path, newPath, err) } c.respondEmpty() } func (c *command) delete() { fType, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) if fType != 1 && fType != 2 { c.respondFailure(0xDEAD) } err = os.RemoveAll(path) if err != nil { log.Fatalf("ERROR: Couldn't removeAll %v. %v", path, err) } c.respondEmpty() } // TODO: Follow "The happy path is left-aligned" func (c *command) create() { // 1 = file, 2 = dir fType, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) if fType != 1 && fType != 2 { c.respondFailure(0xDEAD) } // 1 = file, 2 = dir if fType == 1 { _, err := os.Create(path) if err != nil { log.Fatalf("ERROR: Couldn't create file %v. %v", path, err) c.respondFailure(0xDEAD) return } } else if fType == 2 { err := os.Mkdir(path, 0755) if err != nil { log.Fatalf("ERROR: Couldn't create file %v. %v", path, err) c.respondFailure(0xDEAD) return } } c.respondEmpty() } // TODO: Follow "The happy path is left-aligned" func (c *command) endFile() { fMode, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } if fMode == 1 { if fileReader != nil { fileReader.Close() fileReader = nil } } else { if fileWriter != nil { fileWriter.Close() fileWriter = nil } } c.respondEmpty() } // TODO: Follow "The happy path is left-aligned" func (c *command) startFile() { path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) fMode, err := c.readInt32() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } if fMode == 1 { if fileReader != nil { fileReader.Close() } // Open Read Only fileReader, err = os.Open(path) if err != nil { log.Fatalf("ERROR: Couldn't open %v. %v", path, err) } } else { if fileWriter != nil { fileWriter.Close() } //Open Read and Write fileWriter, err = os.Create(path) if err != nil { log.Fatalf("ERROR: Couldn't write %v. %v", path, err) } if fMode == 3 { fInfo, err := fileWriter.Stat() if err != nil { log.Fatalf("ERROR: Couldn't get stats for %v. %v", path, err) } _, err = fileWriter.Seek(fInfo.Size(), 0) if err != nil { log.Fatalf("ERROR: Couldn't get stats for %v. %v", path, err) } } } c.respondEmpty() } // TODO: Follow "The happy path is left-aligned" func (c *command) writeFile() { path, err := c.readString() if err != nil { log.Fatalf("ERROR: Couldn't read string from buffer. %v", err) } path = fsUtil.DenormalizePath(path) bLenght, err := c.readInt64() if err != nil { log.Fatalf("ERROR: Couldn't read int32 from buffer. %v", err) } buffer := make([]byte, bLenght) _, err = c.usb.Read(buffer) if err != nil { log.Fatalf("ERROR: Couldn't read directly from buffer. %v", err) } if fileWriter != nil { _, err := fileWriter.Write(buffer) if err != nil { log.Fatalf("ERROR: Couldn't write %v to disk. %v", path, err) c.respondFailure(0xDEAD) return } c.respondEmpty() return } err = os.WriteFile(path, buffer, os.ModeAppend) if err != nil { c.respondFailure(0xDEAD) return } c.respondEmpty() } <file_sep>module github.com/bitrvmpd/goquark go 1.16 require ( github.com/getlantern/systray v1.1.0 github.com/google/gousb v1.1.1 github.com/spf13/cobra v1.1.3 github.com/sqweek/dialog v0.0.0-20200911184034-8a3d98e8211d golang.org/x/text v0.3.5 gopkg.in/yaml.v2 v2.4.0 ) <file_sep># Goquark [WIP] A [Quark](https://github.com/XorTroll/Goldleaf) port in go<file_sep>package ui import ( "context" "fmt" "log" "path" "github.com/bitrvmpd/goquark/internal/pkg/cfg" "github.com/bitrvmpd/goquark/internal/pkg/quark" "github.com/getlantern/systray" "github.com/sqweek/dialog" ) var folders map[int]*systray.MenuItem var ctx context.Context var cancel context.CancelFunc func Build() { ctx = context.Background() ctx, cancel = context.WithCancel(ctx) systray.Run(onReady, onExit) } func onReady() { folders = make(map[int]*systray.MenuItem, cfg.Size()) started := false //systray.SetIcon(icon.Data) systray.SetTitle("goQuark") systray.SetTooltip("") mStart := systray.AddMenuItem("Start", "Starts communication") mStatus := systray.AddMenuItem("Client Stopped", "Show client status") mStatus.Disable() systray.AddSeparator() // Sets the icon of a menu item. Only available on Mac and Windows. systray.AddSeparator() mPath := systray.AddMenuItem("Add Folder...", "Exposes a new folder to Goldleaf") //Reads folders, add tickers to disable them or deleting mPaths := systray.AddMenuItem("Remove Folder", "Click to remove an exposed folder") // Reads configuration, sets routes for i, folder := range cfg.ListFolders() { folders[i] = mPaths.AddSubMenuItem(folder.Alias, folder.Path) } systray.AddSeparator() mQuit := systray.AddMenuItem("Quit", "Quit the whole app") //Listen for submenu items for c, f := range folders { go func(fIndex int, mi *systray.MenuItem) { for { select { case <-ctx.Done(): fmt.Printf("Closing submenu threads: %v\n", fIndex) return case <-mi.ClickedCh: cfg.RemoveFolder(fIndex) // systray doesn't have a way to remove an item. Hiding is ok for now. mi.Hide() } } }(c, f) } // Set button actions for { select { case <-mQuit.ClickedCh: systray.Quit() case <-mStart.ClickedCh: if started { // Stops the client cancel() started = false mStart.SetTitle("Start") mStatus.SetTitle("Client Stopped") mPaths.Enable() continue } ctx = context.Background() ctx, cancel = context.WithCancel(ctx) go quark.Listen(ctx) started = true mStart.SetTitle("Stop") mStatus.SetTitle("Ready for connection") mPaths.Disable() case <-mPath.ClickedCh: f, err := dialog.Directory().Browse() if err != nil { log.Printf("INFO: %v", err) } // Don't add a folder if the user didn't selected it. if f == "" { continue } mPaths.AddSubMenuItem(path.Base(f), f) cfg.AddFolder(path.Base(f), f) } } } func onExit() { if cancel == nil { log.Println("ERROR: Couldn't call cancel") return } cancel() } <file_sep>package usb import ( "bytes" "encoding/binary" "log" "golang.org/x/text/encoding/unicode" ) type buffer struct { in_buff bytes.Buffer out_buff bytes.Buffer usb *USBInterface } func (c *buffer) responseStart() { // Empty our out buffer c.out_buff.Reset() //Fast convertion to uint32 d := make([]byte, 4) binary.LittleEndian.PutUint32(d, GLCO) //Append to our magic and 0 delimiter c.out_buff.Write(d) //Fast convertion to uint32 d = make([]byte, 4) binary.LittleEndian.PutUint32(d, 0) //Append to our magic and 0 delimiter c.out_buff.Write(d) } func (c *buffer) responseEnd() { // Fill with 0 up to 4096 bytes d := make([]byte, BlockSize-c.out_buff.Len()) c.out_buff.Write(d) // Write the buffer _, err := c.usb.Write(c.out_buff.Bytes()) if err != nil { log.Fatalf("ERROR: %v", err) } } func (c *buffer) respondFailure(r uint32) { // Empty our out buffer c.out_buff.Reset() //Fast convertion to uint32 d := make([]byte, 4) binary.LittleEndian.PutUint32(d, GLCO) c.out_buff.Write(d) // Append error b := make([]byte, 4) binary.LittleEndian.PutUint32(b, r) c.out_buff.Write(b) c.responseEnd() } func (c *buffer) respondEmpty() { c.responseStart() c.responseEnd() } func (c *buffer) readInt32() (int, error) { d := make([]byte, 4) _, err := c.in_buff.Read(d) if err != nil { log.Fatalf("ERROR: Couldn't read from buffer!. %v", err) } i := binary.LittleEndian.Uint32(d) return int(i), nil } func (c *buffer) readInt64() (int64, error) { d := make([]byte, 8) _, err := c.in_buff.Read(d) if err != nil { log.Fatalf("ERROR: Couldn't read from buffer!. %v", err) } i := binary.LittleEndian.Uint64(d) return int64(i), nil } func (c *buffer) readFromUSB() error { c.in_buff.Reset() b := make([]byte, BlockSize) _, err := c.usb.Read(b) if err != nil { return err } c.in_buff.Write(b) return nil } func (c *buffer) writeInt32(n uint32) { b := make([]byte, 4) binary.LittleEndian.PutUint32(b, n) c.out_buff.Write(b) } func (c *buffer) writeInt64(n uint64) { b := make([]byte, 8) binary.LittleEndian.PutUint64(b, n) c.out_buff.Write(b) } func (c *buffer) readString() (string, error) { //Pop the size size, err := c.readInt32() if err != nil { return "", err } o := make([]byte, size) enc := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder() _, _, err = enc.Transform(o, c.in_buff.Next(size*2), false) if err != nil { return "", err } // Convert num of bytes reported by enc.Transform s := string(o) return s, nil } func (c *buffer) writeString(v string) { o := make([]byte, BlockSize) // Prepare encoder enc := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() nDst, _, err := enc.Transform(o, []byte(v), false) //Write len of chars. c.writeInt32(uint32(len(v))) if err != nil { log.Fatalf("ERROR: Can't write string: %v", err) } c.out_buff.Write(o[:nDst]) } <file_sep>package cmd import ( "fmt" "os" "os/signal" "syscall" "github.com/bitrvmpd/goquark/internal/pkg/ui" "github.com/getlantern/systray" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "goquark", Short: "A golang implementation of Quark", Long: `GoQuark is Goldleaf's USB client`, Run: func(cmd *cobra.Command, args []string) { ui.Build() }, } func Execute() { // Exit when user press CTRL+C channel := make(chan os.Signal, 1) signal.Notify(channel, os.Interrupt, syscall.SIGTERM) go func() { for range channel { systray.Quit() return } }() if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } <file_sep>package cfg import ( "log" "os" "path/filepath" "gopkg.in/yaml.v2" ) const ConfigPath = "goquark.yaml" type cfgRoot struct { Nodes []cfgNode `yaml:"nodes"` } type cfgNode struct { Alias string `yaml:"alias"` Path string `yaml:"path"` index int } var cfg cfgRoot = cfgRoot{} func init() { loadConfig() } func loadConfig() { userDir, err := os.UserHomeDir() if err != nil { log.Printf("ERROR: %v", err) } // Open or Create if not found. f, err := os.OpenFile(filepath.Join(userDir, ConfigPath), os.O_RDWR|os.O_CREATE, 0666) if err != nil { log.Printf("ERROR: %v", err) } defer f.Close() decoder := yaml.NewDecoder(f) err = decoder.Decode(&cfg) if err != nil { log.Printf("ERROR: %v", err) } //Fill current index for i := 0; i < len(cfg.Nodes); i++ { cfg.Nodes[i].index = i } } func writeConfig() { userDir, err := os.UserHomeDir() if err != nil { log.Printf("ERROR: %v", err) } // Delete the file, to prevent weird bugs. os.Remove(filepath.Join(userDir, ConfigPath)) // Open or Create if not found. f, err := os.OpenFile(filepath.Join(userDir, ConfigPath), os.O_RDWR|os.O_CREATE, 0666) if err != nil { log.Printf("ERROR: %v", err) } defer f.Close() encoder := yaml.NewEncoder(f) err = encoder.Encode(cfg) if err != nil { log.Printf("ERROR: %v", err) } } func Size() uint32 { return uint32(len(cfg.Nodes)) } func AddFolder(name string, path string) { cfg.Nodes = append(cfg.Nodes, cfgNode{name, path, len(cfg.Nodes)}) writeConfig() } func RemoveFolder(idx int) { // Not as efficient, but it works. cfg.Nodes = append(cfg.Nodes[:idx], cfg.Nodes[idx+1:]...) // Update index for i := 0; i < len(cfg.Nodes); i++ { cfg.Nodes[i].index = i } writeConfig() } func ListFolders() []cfgNode { return cfg.Nodes } <file_sep>package quark import ( "context" "log" "github.com/bitrvmpd/goquark/internal/pkg/usb" ) func Listen(ctx context.Context) { c, err := usb.New(ctx) if err != nil { log.Fatalf("ERROR: Couldn't initialize command interface: %v", err) } // Start listening for USB Packets go c.ProcessUSBPackets() // Wait for exit <-ctx.Done() } <file_sep>package fs import ( "io/ioutil" "os" "runtime" "strings" ) var ( osName string ) const homeDrive = "Home" func init() { if runtime.GOOS == "darwin" { osName = "darwin" } else if runtime.GOOS == "windows" { osName = "windows" } else if runtime.GOOS == "linux" { osName = "linux" } } // TODO: Fill this for windows func ListDrives() ([]string, error) { if osName == "windows" { // TODO: Create list drive detection in windows return nil, nil } return []string{homeDrive}, nil } // TODO: Fill this for windows func GetDriveLabel(drive string) (string, error) { if osName == "windows" { return "", nil } return "Home root", nil } // Returns all files inside the specified directory func GetFilesIn(path string) ([]string, error) { files := []string{} f, err := ioutil.ReadDir(path) if err != nil { return nil, err } for _, file := range f { if file.IsDir() { continue } files = append(files, file.Name()) } return files, nil } // Returns all directories inside the specified path func GetDirectoriesIn(path string) ([]string, error) { dirs := []string{} f, err := ioutil.ReadDir(path) if err != nil { return nil, err } for _, file := range f { if !file.IsDir() { continue } dirs = append(dirs, file.Name()) } return dirs, nil } func NormalizePath(path string) string { path = strings.ReplaceAll(path, "\\\\", "/") path = strings.ReplaceAll(path, "//", "/") if osName != "windows" { return homeDrive + ":" + path } return path } func DenormalizePath(path string) string { if osName != "windows" { if strings.HasPrefix(path, homeDrive+":") { return strings.ReplaceAll(path, homeDrive+":", "") } } return strings.ReplaceAll(path, "/", "\\\\") } // Deletes specified path and all its contents func DeletePath(path string) error { err := os.RemoveAll(path) if err != nil { return err } return nil } <file_sep>package cmd import ( "context" "github.com/bitrvmpd/goquark/internal/pkg/quark" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(runCmd) } var runCmd = &cobra.Command{ Use: "run", Short: "Starts Goldleaf client in command line", Long: `Starts listening for Goldleaf connection and serves the specified folders. If no folders are specified it serves the current one`, Run: func(cmd *cobra.Command, args []string) { ctx := context.Background() //ctx, cancel := context.WithCancel(ctx) quark.Listen(ctx) }, } <file_sep>package usb import ( "context" "fmt" "log" "time" "github.com/google/gousb" ) const ( VendorID = 0x057E ProductID = 0x3000 WriteEndpoint = 0x1 ReadEndpoint = 0x81 ) type USBInterface struct { ctx context.Context gCtx *gousb.Context gDev *gousb.Device } func initDevice(ctx context.Context) *USBInterface { return &USBInterface{ ctx: ctx, } } func (u *USBInterface) Close() { u.gDev.Close() u.gCtx.Close() log.Println("Closing gDev and gCtx") } // Waits for a device to be connected that matches VID: 0x057E PID: 0x3000 // Stores context and device for reuse. func (u *USBInterface) isConnected() chan bool { // Set ticker to search for the required device ticker := time.NewTicker(500 * time.Millisecond) c := make(chan bool) go func() { fmt.Println("Waiting for USB device to appear...") // Initialize a new Context. gctx := gousb.NewContext() for range ticker.C { select { case <-u.ctx.Done(): gctx.Close() c <- false return case <-ticker.C: // Open any device with a given VID/PID using a convenience function. // If none is found, it returns nil and nil error dev, _ := gctx.OpenDeviceWithVIDPID(VendorID, ProductID) if dev != nil { // Device found, exit loop. don't close it! u.gCtx = gctx u.gDev = dev c <- true return } } } }() return c } func (u *USBInterface) getDescription() (string, error) { s, err := u.gDev.Product() if err != nil { return "", err } return s, nil } func (u *USBInterface) getSerialNumber() (string, error) { s, err := u.gDev.SerialNumber() if err != nil { return "", err } return s, nil } func (u *USBInterface) Read(p []byte) (int, error) { //Test donde channel for each request. chDone := make(chan interface{}) // Claim the default interface using a convenience function. // The default interface is always #0 alt #0 in the currently active // config. intf, done, err := u.gDev.DefaultInterface() if err != nil { log.Fatalf("%s.DefaultInterface(): %v", u.gDev, err) } defer done() // Open an IN endpoint. ep, err := intf.InEndpoint(ReadEndpoint) if err != nil { log.Fatalf("%s.OutEndpoint(%v): %v", intf, WriteEndpoint, err) } // Set transfer as bulk //ep.Desc.MaxPacketSize = BlockSize ep.Desc.TransferType = gousb.TransferTypeBulk ep.Desc.IsoSyncType = gousb.IsoSyncTypeSync ep.Desc.PollInterval = 0 * time.Millisecond // Just before reading, prepare a way to cancel this request go func() { for { select { case <-u.ctx.Done(): done() u.Close() return case <-chDone: // Successful read, close this goroutine return } } }() // Read data from the USB device. numBytes, err := ep.Read(p) if err != nil { return 0, err } if numBytes != len(p) { log.Fatalf("%s.Read([%v]): only %d bytes read, returned error is %v", ep, numBytes, numBytes, err) } // Notify that we are done! chDone <- struct{}{} return numBytes, nil } func (u *USBInterface) Write(p []byte) (int, error) { //Test donde channel for each request. chDone := make(chan interface{}) // Claim the default interface using a convenience function. // The default interface is always #0 alt #0 in the currently active // config. intf, done, err := u.gDev.DefaultInterface() if err != nil { log.Fatalf("%s.DefaultInterface(): %v", u.gDev, err) } defer done() // Open an OUT endpoint. ep, err := intf.OutEndpoint(WriteEndpoint) if err != nil { log.Fatalf("%s.OutEndpoint(%v): %v", intf, WriteEndpoint, err) } // Set transfer as bulk //ep.Desc.MaxPacketSize = BlockSize ep.Desc.TransferType = gousb.TransferTypeBulk ep.Desc.IsoSyncType = gousb.IsoSyncTypeSync ep.Desc.PollInterval = 0 * time.Millisecond // Just before writting, prepare a way to cancel this request go func() { for { select { case <-u.ctx.Done(): done() u.Close() return case <-chDone: // Successful read, close this goroutine return } } }() // Write data to the USB device. numBytes, err := ep.Write(p) if numBytes != len(p) { log.Fatalf("%s.Write([%v]): only %d bytes written, returned error is %v", ep, numBytes, numBytes, err) } // Notify that we are done! chDone <- struct{}{} return numBytes, nil }
56514cb70445772b784922ebefcbdc3fec7e7d33
[ "Markdown", "Go Module", "Go" ]
11
Go
Lrs121/goquark
389fed4a9b3078d7c949260397eda83f37428243
4b5a5f3439facf5e3c9543b343ca9693bd85c1e5
refs/heads/master
<file_sep># Простое тестовое задание Просто выводим список скомпилированный из двух json-файлов. Обычная страничка html, всё сохраняем (кроме json - они грузятся по адресам). Пока не могу понять как вывести список постранично - вызов функции происходит при открытии страницы, а не при нажатии. [![forthebadge](https://forthebadge.com/images/badges/powered-by-electricity.svg)](https://forthebadge.com) <file_sep>const postsAddress = 'https://jsonplaceholder.typicode.com/posts'; const usersAddress = 'https://jsonplaceholder.typicode.com/users'; const httpGet = (address) => { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", address, false); xmlHttp.send(null); return xmlHttp.responseText; } const createData = (postsAddress, usersAddress) => { postsData = JSON.parse(httpGet(postsAddress)); usersData = JSON.parse(httpGet(usersAddress)); const someData = postsData.reduce((acc, elem) => { const { userId, id, title } = elem; const ourUser = usersData.filter(user => { return user.id === userId; }); let someNote = { id: id, author: ourUser[0].name, title: title, }; acc.push(someNote); return acc; }, []); return someData; } const getNumberOfChunks = (data) => { return numberOfChunk = (Math.ceil(data.length/30)); } const drawTable = (data, page = 1, size = 30) => { const numberOfChunks = getNumberOfChunks(createData(postsAddress, usersAddress)); const firstRecord = page * size - 30; const lastRecord = page * size; let html = ''; html += '<tr>'; for( let j in data[0] ) { html += '<th>' + j + '</th>'; } html += '</tr>'; for( let i = firstRecord; i < lastRecord; i++) { html += '<tr>'; for( let j in data[i] ) { html += '<td>' + data[i][j] + '</td>'; } } document.getElementById('container').innerHTML = '<table>' + html + '</table>'; for (i = 1; i <= numberOfChunk; i++) { let btn = document.createElement("button"); let t = document.createTextNode(`${i}`); btn.appendChild(t); btn.id = `chunk${i}`; //btn.onclick = doFunction; document.body.appendChild(btn) } for (i = 1; i <= numberOfChunk; i++) { //document.getElementById(`chunk${i}`).addEventListener("click", drawTable(data, numberOfChunk)); //document.getElementById(`chunk${i}`).addEventListener("click", alert(`chunk${i}`)); //document.getElementById(`chunk${i}`).addEventListener("click", doFunction); } //document.getElementById("chunk1").onclick = drawTable(data, i); } doFunction = (cry = 'aaa') => { alert(cry); } const fullData = createData(postsAddress, usersAddress); const numberOfChunks = getNumberOfChunks(createData(postsAddress, usersAddress)); drawTable(fullData, 4); //document.getElementById("chunk1").addEventListener("click", doFunction());
8e45d4dba66b6c2711a4da51515f43ae54ff3a00
[ "Markdown", "JavaScript" ]
2
Markdown
echonok/test
f9df3523e8a19dd001cdf2202f00f7640313a8e3
de447606317c6ff3b5fb3d716952aa31da539269
refs/heads/main
<file_sep>// Passwordless integration const apiKey = "demobackend:public:c203e65b581443778ea4823b3ef0d6af"; const backendUrl = "https://demo-backend.passwordless.dev"; const p = new Passwordless.Client({ apiKey }); async function register(alias) { const myToken = await fetch(backendUrl + "/create-token?alias=" + alias).then((r) => r.text()); await p.register(myToken); console.log("Register succeded"); } async function signin(alias) { const token = await p.signinWithAlias(alias); const user = await fetch(backendUrl + "/verify-signin?token=" + token).then((r) => r.json()); console.log("User details", user); return user; } // Print Status messages to UI. function uistatus(text) { const statusel = document.getElementById("status"); const currentText = statusel.innerText; var newLine = "[" + new Date().toLocaleTimeString() + "]: " + text + "\n"; statusel.innerText = newLine + currentText; } uistatus("Welcome! Please register or sign in"); // Bind methods to UI buttons/events: // register document .getElementById("passwordless-register") .addEventListener("click", async (e) => { e.preventDefault(); const alias = document.getElementById("alias").value; await register(alias); uistatus("Succeded with register"); }); // sign in document .getElementById("passwordless-signin") .addEventListener("click", async (e) => { e.preventDefault(); uistatus("Starting authentication..."); const alias = document.getElementById("alias").value; const user = await signin(alias) uistatus("User details: " + JSON.stringify(user, null, 2)); });<file_sep># Part1: Adding fingerprint authentication to your webapp using javascript In this blogpost we will add Fingerprint and FaceID authentiate using javascript and the [passwordless API](https://passwordless.dev). You can checkout all the code on the passwordless-part1 repo. ## Create and serve index.html You might have an existing web app that you can use, but we will create a small boilerplate app. The important thing is that you can access it using either `https` or `http://localhost:xx`. (`file://` won't work because of security limitations) Create a folder and open your favorite editor (Mine is VS Code) ```bash mkdir passwordless-app cd passwordless-app code . ``` Create a `index.html` file with the following boilerplat. The important part is the input field and the buttons. ```html <!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.0" /> <title>Passwordless Minimal</title> <style> body { font-family: sans-serif; } </style> </head> <body> <h2>Passwordless Minimal demo</h2> <p>To run this example you don't have to do anything other than supply a unique alias.</p> <input type="text" id="alias" placeholder="Unique Alias (Username, email)" /> <button id="passwordless-register">Register</button> <button id="passwordless-signin">Login</button> <pre id="status"></pre> <script src="https://cdn.passwordless.dev/dist/0.2.0/passwordless.iife.js" crossorigin="anonymous"></script> <script src="auth.js"></script> </body> </html> ``` Make sure that you include the script tags that reference the `passwordless.iife.js`-library and the `auth.js` file. Serve the file using `npx http-server` and checkout the result at `http://localhost:8080`. ## Let's create auth.js Add a new file called `auth.js`. In this file we will add our authentication code. Start by adding the apiKey and two methods, `register` and `sign in`. (Yes, you should use the `demobackend` API key for now.) ```js // Passwordless integration const apiKey = "demobackend:public:c203e65b581443778ea4823b3ef0d6af"; const backendUrl = "https://demo-backend.passwordless.dev"; const p = new Passwordless.Client({ apiKey }); async function register(alias) { const myToken = await fetch(backendUrl + "/create-token?alias=" + alias).then((r) => r.text()); await p.register(myToken); console.log("Register succeded"); } async function signin(alias) { const token = await p.signinWithAlias(alias); const user = await fetch(backendUrl + "/verify-signin?token=" + token).then((r) => r.json()); console.log("User details", user); return user; } ``` So far so good, but we need to connect our buttons to the methods we created. In `auth.js`, add the following: ```js // Bind methods to UI buttons/events: // register document .getElementById("passwordless-register") .addEventListener("click", async (e) => { e.preventDefault(); const alias = document.getElementById("alias").value; await register(alias); status("Succeded with register"); }); // sign in document .getElementById("passwordless-signin") .addEventListener("click", async (e) => { e.preventDefault(); const alias = document.getElementById("alias").value; const user = await signin(alias) status("User details: " + JSON.stringify(user, null, 2)); }); // Print Status messages to UI. const statusel = document.getElementById("status"); function status(text) { const currentText = statusel.innerText; var newLine = "[" + new Date().toLocaleTimeString() + "]: " + text + "\n"; statusel.innerText = newLine + currentText; } status("Welcome! Please register or sign in"); ``` ## Testing it Refresh `http://localhost:8080` again. Enter a unique nickname and try clicking the register button. ## Adding your own backend In the next part we will look how to connect this UI your own backend using Node.js. It's about as easy as this was.
906cb2389f14dd040a7b18cbf7cac8c57c3d7552
[ "JavaScript", "Markdown" ]
2
JavaScript
abergs/passwordless-blog
439691432a8bf3bb1e99ec5f4bb1b093544f20a5
df12e3b47615a7020ab217445f7afd60714493d5
refs/heads/main
<file_sep>const normalPerson={ firstName: 'Rahim', lastName:'Uddin', salary:15000, getFullName: function(){ console.log(this.firstName, this.lastName); }, chargeBill: function(amount, tips, tax){ this.salary=this.salary- amount- tips- tax; return this.salary; } } // console.log(normalPerson.firstName); // normalPerson.chargeBill(150); // console.log(normalPerson.salary); const heroPerson={ firstName: 'Hero', lastName:'Balam', salary:25000, } //normalPerson.chargeBill(); // const heroChargeBill= normalPerson.chargeBill.bind(heroPerson); // heroChargeBill (1000) // heroChargeBill (1000) // console.log(heroPerson.salary) // normalPerson.chargeBill.call(normalPerson,1000,1000,2000); // console.log(normalPerson.salary); // normalPerson.chargeBill.call(heroPerson,1000,1000,2000); // console.log(heroPerson.salary); normalPerson.chargeBill.apply(heroPerson, [3000, 300, 30]); console.log(heroPerson.salary);<file_sep>var name="kuddus" function add(num1,num2) { var result= num1+num2; console.log('result inside',result); return result; } var sum= add(10,15) class Person{ constructor(firstName, lastName, salary){ this.firstName= firstName; this.lastName= lastName; this.salary= salary; } } const heroPerson= new Person("hero", "Balam", 2000); console.log(heroPerson) const friendlyPerson= new Person("hero", "kalam", 1000); console.log(friendlyPerson)<file_sep>import logo from './logo.svg'; import './App.css'; import { useEffect, useState } from 'react'; function App() { let [actor,setActor] =useState([]) useEffect(()=>{ fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(data => setActor(data)) } ,[]) const nayoks=[{nam:'Shuvo' ,age:66},{nam:'Bappi', age:6}] return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> { actor.map(nayok=><Nayok name={nayok.name} Key={actor.id} age={nayok.age}></Nayok>) } </header> </div> ); } function MovieCounter(){ let [count,setCount] =useState(0) console.log(count, setCount) const handleClick=()=> setCount(count+1) return ( <div> <button onClick={handleClick}> Click here</button> <h5>Number of Movie : {count}</h5> </div> ) } function Nayok(props){ console.log(props) const nayokStyle={ backgroundColor: "grey", borderRadius:'5px', color:'blue', border: '2px solid green', padding: '20px' } return ( <div style={nayokStyle}> <h1> <NAME> {props.name} </h1> <h1> Amr age {props.age} </h1> </div> ) } export default App; <file_sep>import React from 'react'; const Cart = (props) => { const cart=props.cart; const totalPopulation=cart.reduce((sum,country)=> sum+country.population,0) return ( <div> <h1>This is {props.cart.length}</h1> <h1>total population {totalPopulation}</h1> </div> ); }; export default Cart;<file_sep>function doSomething(){ console.log(33330); }; console.log(12000); setTimeout(()=> {console.log("waiting"),1000}); console.log(2000); setInterval(function doSomething(){ console.log(33330); }, 1000); <file_sep>import React from 'react'; const Country = (props) => { const {name,population, region,flag} = props.country; const countryStyle={textAlign: 'center' ,border: '1px solid red',margin:'10px',padding:'10px'} const handleAddCountry=props.handleAddCountry; return ( <div style={countryStyle}> <h4>{name}</h4> <h4>{population}</h4> <h4>{region}</h4> <img style={{height:'50px'}} src={flag} alt=""/> <br/> <button onClick={()=> handleAddCountry(props.country)}> Add Country</button> </div> ); }; export default Country;
bc9d6f50b3cb7603e5f17547be49d25a0a26828f
[ "JavaScript" ]
6
JavaScript
rahadarmannabid/shopping-cart
7474dfb952eada8649d920c2978b81b4c4c704aa
71bc2e7e713e67fb57e5a276a98f03fa93f519b1
refs/heads/main
<repo_name>kennethfan/JAVA-000<file_sep>/Week_01/src/main/java/classloader/MyClassLoader.java package classloader; import java.io.*; public class MyClassLoader extends AbstractMyClassLoader { private static final int base = 255; @Override protected InputStream getClassInputStream(String name) throws ClassNotFoundException { String path = getClass().getResource("/").getPath() + name + ".xlass"; File file = new File(path); try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new ClassNotFoundException("can not find class file path: " + path); } } @Override protected byte[] getBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int length; while ((length = inputStream.read(bytes)) != -1) { for (int i = 0; i < length; i++) { /** * 解码 */ bytes[i] = (byte) (base - bytes[i] & 0xFF); } byteArrayOutputStream.write(bytes, 0, length); } return byteArrayOutputStream.toByteArray(); } }
2d0751871174255de2672887a2ef6d2099ebdb4e
[ "Java" ]
1
Java
kennethfan/JAVA-000
2e5249404780e4fa73c2c571fbf167f079c13047
9f8f0fd986ba29559b25ebd0a166a7b358389520
refs/heads/master
<file_sep># Comparison of Newton's Method in Optimisation and Gradient Descent I experiment with and benchmark NM vs. GD for multivariate linear regression, on the Iris flower dataset. Newton's Method converges within 2 steps and performs favourably to GD. However, it requires computation of the Hessian, as well as depends heavily on the weight initialisation. (Vanilla) Gradient Descent: ![](./utils/eq2.PNG) Newton's Method: ![](./utils/eq3.PNG) <file_sep>""" PROBLEMS: - No alpha for NM, bad alpha for GD: SOLVED - NaN values for GD: SOLVED - Hardcoded starting theta for NM & GD: !!!!! - Timing: Need per epoch & Need hundred iters """ from sklearn import datasets import numpy as np import numpy.linalg as lnp from time import time import matplotlib.pyplot as plt #np.random.seed(1) #data, valid = datasets.load_boston(), False data, valid = datasets.load_iris(), True X = data["data"] Y = data["target"] m = Y.shape[0] def MSE(dist): global m return lnp.norm(dist**2, 1)/(2*m) # for the bias: X = np.insert(X, 0, 1, axis=1) if valid: margin = 0.0233 #global minima at 3 sig fig for MSE on this distribution & overflow else: margin = 11 #preliminary #random init: sample to make better #np.random.seed(1) #theta = np.ndarray((X.shape[1])) theta = np.full((X.shape[1]), 5) y_hat = np.matmul(X, theta) dist = Y-y_hat X_T = X.T cost = MSE(dist) #no need transpose because np doesn't differentiate between column & row vectors def nm(theta, y_hat, X_T, dist, cost, lr): start = time() global X, Y, margin, m, indices cost_log = [] epoch = 0 hessian = np.matmul(X_T, X) inv_hessian = lnp.inv(hessian) while cost > margin: #cost_log.append(cost) #commented for timing #print("Epoch #" + str(epoch) + ":", cost) cost_log.append(cost) epoch += 1 grad = np.matmul(X_T, dist/-m) theta = theta-lr*np.matmul(inv_hessian, grad) y_hat = np.matmul(X, theta) dist = Y-y_hat X_T = X.T cost = MSE(dist) cost_log.append(cost) end = time() print("\n" + "Finished NM in " + str(epoch+1), "epochs with error " + str(cost_log[-1]) + "\n") print("Optimal theta:", theta) print("\n\n" + "y_hat, y") for i in indices: print(y_hat[i], Y[i]) return end-start, cost_log def gd(theta, y_hat, X_T, dist, cost, lr): start = time() global X, Y, margin, m, indices cost_log = [] epoch = 0 while cost > margin: cost_log.append(cost) #cost_log.append(cost) #commented for timing epoch += 1 grad = np.matmul(X_T, dist)/-m theta = theta-lr*grad y_hat = np.matmul(X, theta) dist = Y-y_hat X_T = X.T cost = MSE(dist) cost_log.append(cost) end = time() print("\n" + "Finished GD in " + str(epoch+1), "epochs with error " + str(cost_log[-1]) + "\n") print("Optimal theta:", theta) print("\n\n" + "y_hat, y") for i in indices: print(y_hat[i], Y[i]) return end-start, cost_log indices = [np.random.randint(0,m) for i in range(10)] #randomly sample 10 pairs for testing #print(theta) GD_time, gd_log = gd(theta, y_hat, X_T, dist, cost, 0.032) # max 3 dp. cuz overflow print("\n\n" + "#"*10 + "\n\n") NM_time, nm_log = nm(theta, y_hat, X_T, dist, cost, 150) print("\n\n\n" + "GD time", GD_time, "| NM time", NM_time) plt.plot(gd_log, label="GD") plt.plot(nm_log, label="NM") plt.xlabel("Epochs") plt.ylabel("MSE Cost") plt.title("Newton's Method vs. Gradient Descent") plt.show() #can save too if GD_time > NM_time: print("NM is faster") #if runtime is to fast, can't always tell cuz of sig fig else: print("GD is faster") """ SANITY CHECK: #foo1, foo2, foo3, foo4, foo5, foo6, foo7 = theta, y_hat, cost, Y, m, X, margin #insert before GD assert(theta.all() == foo1.all()) assert(y_hat.all() == foo2.all()) assert(cost == foo3) assert(Y.all() == foo4.all()) assert(m == foo5) assert(X.all() == foo6.all()) assert(margin == foo7) """
57990d30e64025beaf86afe9243abb2dc81b8f09
[ "Markdown", "Python" ]
2
Markdown
pyto314/Newtons-Method-vs-Gradient-Descent-on-Iris-Dataset
075d5b58687be326ded8a1418231895cd01bb34d
4431e5bc67ad0ad020cc8ec784eb03997116972f
refs/heads/master
<repo_name>FXIhub/exfelsync<file_sep>/dealer.py import time, sys dealer = lambda *args: Dealer(*args).start() class Dealer(object): def __init__(self, socket, buf): self._socket = socket # TODO: Create a ZMQ service that can deal out data to a client self._buf = buf def start(self): print("Starting reading...") while(True): print("Reader", len(self._buf)) #for k in self._buf.keys(): # del self._buf[k] sys.stdout.flush() time.sleep(1) <file_sep>/combiner.py from multiprocessing import Process, Manager from listener import slowdata_listener from listener import agipd_listener from dealer import dealer def main(): # Initialize data managers buffer_agipd_03 = Manager().dict() buffer_agipd_04 = Manager().dict() buffer_agipd_15 = Manager().dict() buffer_slowdata = Manager().dict() buffers = [buffer_agipd_03, buffer_agipd_04, buffer_agipd_15, buffer_slowdata] # List of processes processes = [] processes.append(Process(target=dealer, args=('tcp://127.0.0.1:5100', buffer_agipd_03))) processes.append(Process(target=agipd_listener, args=('tcp://127.0.0.1:4600', buffer_agipd_03, 10))) processes.append(Process(target=agipd_listener, args=('tcp://127.0.0.1:4601', buffer_agipd_04, 10))) processes.append(Process(target=agipd_listener, args=('tcp://127.0.0.1:4602', buffer_agipd_15, 10))) processes.append(Process(target=slowdata_listener, args=('tcp://127.0.0.1:4602', buffer_slowdata, 10))) # Start all processes for p in processes: p.start() # Stop all processes for p in processes: p.join() assert not p.is_alive() assert p.exitcode == 0 if __name__ == '__main__': main() <file_sep>/listener.py import numpy as np import msgpack import msgpack_numpy import zmq msgpack_numpy.patch() class Listener(object): """Simple listener.""" def __init__(self, socket, buf, lifetime = 60): self._socket = socket self._zmq_context = zmq.Context() self._zmq_request = self._zmq_context.socket(zmq.REQ) self._zmq_request.connect(self._socket) self._buf = buf self._running = False self._lifetime = lifetime def get_data(self): """Receive data packets over the network""" self._zmq_request.send(b'next') return msgpack.loads(self._zmq_request.recv()) def write_data(self, data): """Write data into the buffer""" print('Wrote %d bytes' % (len(data))) def _drop_old_data(self, current_time): """Remove expired data from the buffer""" for k in self._buf.keys(): timelimit = current_time - self._lifetime if (k < timelimit): del self._buf[k] def start(self): print("Starting...") self._running = True while(self._running): self.write_data(self.get_data()) def stop(self): self._running = False agipd_listener = lambda *args: AGIPDListener(*args).start() class AGIPDListener(Listener): def __init__(self, *args, **kwargs): Listener.__init__(self, *args, **kwargs) def get_pulse_data(self, obj, pos): img = np.rollaxis(obj['image.data'][:,:,:,pos], 2) img = np.ascontiguousarray(img.reshape((img.shape[0], 1, img.shape[1], img.shape[2]))) return img def get_pulse_time(self, obj, pos): timestamp = obj['metadata']['timestamp'] return timestamp['sec'] + timestamp['frac'] * 1e-18 + pos * 1e-2 def write_data(self,data): train = data['SPB_DET_AGIPD1M-1/DET/3CH0:xtdf'] for p in range(2,64-2,2): pulse_data = self.get_pulse_data(train, p) pulse_time = self.get_pulse_time(train, p) self._buf[pulse_time] = pulse_data self._drop_old_data(pulse_time) slowdata_listener = lambda *args: SlowDataListener(*args).start() class SlowDataListener(Listener): def __init__(self, *args, **kwargs): Listener.__init__(self, *args, **kwargs) def write_data(self,data): print(data) # Testing def main(): listener = Listener('tcp://localhost:4500', {}) try: listener.start() except KeyboardInterrupt: listener.stop() print("Exiting...") if __name__ == '__main__': main()
4d232bf7b6d0c602f9e14814130e9fe2a74f8ac0
[ "Python" ]
3
Python
FXIhub/exfelsync
8292da38b846cb79afafa4f38cd108734ff8c5df
240777d568e14f774318b9857c99d8e73238bb84
refs/heads/main
<repo_name>andreabassi78/PSF_3D_generator<file_sep>/Defocus/PSF3D_generator_with_defocus.py # -*- coding: utf-8 -*- """ Created on Fri Oct 16 11:00:29 2020 Creates a 3D PSF starting from an abberrated pupil (with Zernike Polynomials) @author: <NAME> """ import numpy as np from zernike_polynomials import nm_polynomial from numpy.fft import ifft2, ifftshift, fftshift, fftfreq import matplotlib.pyplot as plt um = 1.0 mm = 1000*um Npixels = 256 # Pixels in x,y assert Npixels%2 == 0 # Npixels must be even n = 1.33 # refractive index wavelength = 0.520*um NA = 0.3 dr = 0.1629073 * um # spatial sampling in xy dz = 0.1629073* um N = 0 # Zernike radial order M = 0 # Zernike azimutal frequency weight = 0.0 # weight of the Zernike abberration weight=1 means a wavefront error of lambda SaveData = False # %% Start calculation k = n/wavelength # wavenumber k_cut_off = NA/wavelength # cut off frequency in the coherent case DeltaXY = wavelength/2/NA # Diffraction limited transverse resolution DeltaZ = wavelength/n/(1-np.sqrt(1-NA**2/n**2)) # Diffraction limited axial resolution # DeltaZ = 2*n*wavelength/NA**2 # Fresnel approximation # z positions to be used: the range is z_extent_ratio times the depth of field z_extent_ratio = 4 Nz = int(z_extent_ratio*DeltaZ/dz) # Nz=Npixels-1 # Nz can be chosen to have any value zs = dz * (np.arange(Nz) - Nz // 2) # generate the k-space kx_lin = fftshift(fftfreq(Npixels, dr)) ky_lin = fftshift(fftfreq(Npixels, dr)) # kx_lin = dk * (np.arange(Npixels) - Npixels // 2) # ky_lin = dk * (np.arange(Npixels) - Npixels // 2) dk = kx_lin[1]-kx_lin[0] kx, ky = np.meshgrid(kx_lin,ky_lin) # #generate the real space (unused) x = y = dr * (np.arange(Npixels) - Npixels // 2) #x = y = fftshift(fftfreq(Npixels, dk)) # k-space in radial coordinates k_rho = np.sqrt(kx**2 + ky**2) k_theta = np.arctan2(ky,kx) # create a Zernike Polynomial to insert abberrations phase = np.pi* nm_polynomial(N, M, k_rho/k_cut_off, k_theta, normalized = False) ATF0 = np.exp (1.j * weight * phase) # Amplitude Transfer Function kz = np.sqrt(k**2-k_rho**2) # evanescent_idx = (k_rho >= k) # indexes of the evanescent waves (kz is NaN for these indexes) # evanescent_idx = np.isnan(kz) cut_idx = (k_rho >= k_cut_off) # indexes of the evanescent waves (kz is NaN for these indexes) ATF0[cut_idx] = 0 PSF3D = np.zeros(((Nz,Npixels-1,Npixels-1))) intensities = np.zeros(Nz) # a constant value of intensities for every z, is an indicator that the simulation is correct. for idx,z in enumerate(zs): angular_spectrum_propagator = np.exp(1.j*2*np.pi*kz*z) ATF = ATF0 * angular_spectrum_propagator mask_idx = (k_rho > k_cut_off) ATF[mask_idx] = 0 # Creates a circular mask ASF = ifftshift(ifft2(ATF)) #* k**2/f**2 # Amplitude Spread Function ASF = ASF[1:,1:] PSF = np.abs(ASF)**2 # Point Spread Function PSF3D[idx,:,:] = PSF intensities[idx] = np.sum(PSF) print('The numerical aperture of the system is:', NA) print('The transverse resolution is:', DeltaXY ,'um') print('The axial resolution is:', DeltaZ ,'um') print('The axial resolution is:', 2*n*wavelength/NA**2 ,'um, with Fresnel approximation') print('The pixel size is:', dr ,'um') print('The voxel depth is:', dz ,'um') # %% figure 1 fig1, ax = plt.subplots(1, 2, figsize=(9, 5), tight_layout=False) fig1.suptitle(f'Zernike coefficient ({N},{M}):{weight}, z={z:.2f}$\mu$m') im0=ax[0].imshow(np.angle(ATF), cmap='gray', extent = [np.amin(kx),np.amax(kx),np.amin(ky),np.amax(ky)], origin = 'lower' ) ax[0].set_xlabel('kx (1/$\mu$m)') ax[0].set_ylabel('ky (1/$\mu$m)') ax[0].set_title('Pupil (phase)') fig1.colorbar(im0,ax = ax[0]) im1=ax[1].imshow(PSF, cmap='gray', extent = [np.amin(x)+dr,np.amax(x),np.amin(y)+dr,np.amax(y)], origin = 'lower' ) ax[1].set_xlabel('x ($\mu$m)') ax[1].set_ylabel('y ($\mu$m)') ax[1].set_title('PSF') # %% figure 2 plane_y = round(Npixels/2) plane_z = round(Nz/2) fig2, axs = plt.subplots(1, 2, figsize=(9, 5), tight_layout=False) axs[0].set_title('|PSF(x,y,0)|') axs[0].set(xlabel = 'x ($\mu$m)') axs[0].set(ylabel = 'y ($\mu$m)') axs[0].imshow(PSF3D[plane_z,:,:], extent = [np.amin(x)+dr,np.amax(x),np.amin(y)+dr,np.amax(y)]) axs[1].set_title('|PSF(x,0,z)|') axs[1].set(xlabel = 'x ($\mu$m)') axs[1].set(ylabel = 'z ($\mu$m)') axs[1].imshow(PSF3D[:,plane_y,:], extent = [np.amin(x)+dr,np.amax(x),np.amin(zs),np.amax(zs)]) if SaveData: if N !=0 or M != 0: note = f'aberratted_n{N}_m{M}_w{weight:.2f}' else: note = None basename = 'psf' filename = '_'.join(filter(None,[basename,f'NA{NA}',f'n{n}',note])) from skimage.external import tifffile as tif psf16 = ( PSF3D * (2**16-1) / np.amax(PSF3D) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, Nz, 1, Npixels-1, Npixels-1, 1 # dimensions in TZCYXS order tif.imsave(filename+'.tif', psf16, imagej=True, resolution = (1.0/dr, 1.0/dr), metadata={'spacing': dz, 'unit': 'um'})<file_sep>/Defocus/PSFgenerator_class/SIM_pupil.py # -*- coding: utf-8 -*- """ Created on Sun Oct 11 10:20:28 2020 @author: <NAME> """ import numpy as np from scipy.special import binom import matplotlib.pyplot as plt import matplotlib.cm as cm def gaussian_kernel(X,Y, Wx, Wy, X0=0, Y0=0): """ creates a 3D gaussian kernel numpy array with size Ly,Lx waist along x, y traslated from origin by X0,Y0 """ kern = 1.0 * np.exp( - ((X-X0)**2)/Wx**2 - ((Y-Y0)**2)/Wy**2 ) return kern def multiple_gaussians(x, y, waistx, waisty, rhos, thetas, normalized = True): #disc = np.zeros((x.shape[0],x.shape[1]), dtype='complex128') disc = np.zeros_like(x) for rho,theta in zip(rhos,thetas): disc += gaussian_kernel(x, y, waistx, waisty, rho*np.cos(theta), rho*np.sin(theta)) r = np.sqrt(x**2+y**2) disc = disc * (r <= 1.) if normalized: disc = disc / np.sum(disc) return disc if __name__ == "__main__": Npixels = 512 # number of pixels R = 1 # extent of the xy space x = y = np.linspace(-R, +R, Npixels) X, Y = np.meshgrid(x,y) rho = np.sqrt(X**2 + Y**2) theta = np.arctan2(Y,X) n = 5 # Zernike radial order m = 1 # Zernike azimutal frequency Z = multiple_gaussians(X,Y, 0.1, 0.2, [0.5,1,0.5], [0, 2*np.pi/3, 4*np.pi/3], normalized = True) fig1 = plt.figure(figsize=(9, 9)) plt.title(f'Zernike polynomial of order ({n},{m})') plt.imshow(np.abs(Z), interpolation='none', cmap=cm.gray, origin='lower', extent = [-R,R,-R,R] ) plt.colorbar() <file_sep>/Defocus/PSFgenerator_class/vectors.py # -*- coding: utf-8 -*- """ Created on Wed Mar 3 22:53:42 2021 @author: <NAME> """ import numpy as np def extend_to_Vector(method): """Class decorator to extend base method to the Vector objects""" def wrapper(*args): first = args[0] second = args[1] if isinstance(second, Vector): function = getattr(first.v, method.__name__) result = function(second.v) else: function = getattr(first.v, method.__name__) result = function(second) return Vector.from_array(result) return wrapper class Vector(): ''' Class for handling 3D vectors in which each element of the vector is a 2D numpy.array. It is an overstructure of numpy but keeps higher level code more readable. ''' def __init__(self,x,y,z): ''' x, y and z are 2D numpy.array''' self.v = np.array([z,y,x]) def __repr__(self): return f'{self.__class__.__name__}(\n{self.v})' @property def shape(self): return self.v.shape @property def x(self): return self.v[2,:,:] @property def y(self): return self.v[1,:,:] @property def z(self): return self.v[0,:,:] @property def mag(self): return np.linalg.norm(self.v, axis =0) @property def norm(self): v = self.v return self.from_array(v/np.linalg.norm(v, axis =0)) @staticmethod def from_array(array): return Vector(array[0,:,:],array[1,:,:],array[2,:,:]) def to_array(self): return self.v def to_size_like(self, other): '''Take a single element Vector and transform it to a 2D Vector of the same size of other ''' vec = self.v o = np.ones_like(other.v[0]) # self.v = np.array([vec[0]*o, vec[1]*o, vec[2]*o]) return Vector(vec[0]*o, vec[1]*o, vec[2]*o) def zeros_like(self): i = self.v.shape[1] j = self.v.shape[2] xyz = np.zeros([i,j]) return Vector(xyz,xyz,xyz) def ones_like(self): i = self.v.shape[1] j = self.v.shape[2] xyz = np.ones([i,j]) return Vector(xyz,xyz,xyz) def __neg__(self): return self.from_array(-self.v) @extend_to_Vector def __add__(self, other): pass @extend_to_Vector def __sub__(self,other): pass @extend_to_Vector def __mul__(self,other): pass @extend_to_Vector def __truediv__(self,other): pass @extend_to_Vector def __divmod__(self,other): pass def cross(self,other): c = np.cross(self.v, other.v, axis=0) return self.from_array(c) def dot(self,other): return np.sum(self.v*other.v,axis=0) if __name__ == '__main__': a = np.random.randint(0,9,[2,2]) v = Vector(a,a,a) # w = Vector.from_array(np.random.randint(0,9,[3,2,2])) w = Vector.from_array(3*np.ones([3,2,2])) r = 3*np.ones([2,2]) r[1,1] = 0 print(v.shape)<file_sep>/Defocus/PSFgenerator_class/old/SIM_generator.py # -*- coding: utf-8 -*- """ Created on Tue Feb 23 17:02:23 2021 Creates a 3D PSF aberrated by the presence of an inclined slab @author: <NAME> """ import numpy as np from numpy.fft import ifft2, ifftshift, fftshift, fftfreq import matplotlib.pyplot as plt from SIM_pupil import multiple_gaussians um = 1.0 mm = 1000 * um deg = np.pi/180 Npixels = 128# Pixels in x,y assert Npixels % 2 == 0 # Npixels must be even n0 = 1.33 # refractive index of the medium n1 = 1.338 # refractive index of the slab thickness = 170 * um # slab thickness wavelength = 0.518 * um alpha = 45 * deg # angle of the slab relative to the y axis NA = 0.5 SaveData = False # %% generate the spatial frequencies to propagate DeltaXY = wavelength/2/NA # Diffraction limited transverse resolution DeltaZ = wavelength/n0/(1-np.sqrt(1-NA**2/n0**2)) # Diffraction limited axial resolution dr = DeltaXY/2 # spatial sampling in xy, chosen to be a fraction of the resolution ratio = 2 dz = ratio * dr # spatial sampling in z k = n0/wavelength # wavenumber k_cut_off = NA/wavelength # cut off frequency in the coherent case # z positions to be used: the range is z_extent_ratio times the depth of field Nz= Npixels-1 # Nz can be chosen to have any value zs = dz * (np.arange(Nz) - Nz // 2) # generate the k-space kx_lin = fftshift(fftfreq(Npixels, dr)) ky_lin = fftshift(fftfreq(Npixels, dr)) # kx_lin = dk * (np.arange(Npixels) - Npixels // 2) # ky_lin = dk * (np.arange(Npixels) - Npixels // 2) dk = kx_lin[1]-kx_lin[0] kx, ky = np.meshgrid(kx_lin,ky_lin) # #generate the real space (used only for visulaization) x = y = dr * (np.arange(Npixels) - Npixels // 2) #x = y = fftshift(fftfreq(Npixels, dk)) # k-space in radial coordinates with np.errstate(invalid='ignore'): k_rho = np.sqrt(kx**2 + ky**2) k_theta = np.arctan2(ky,kx) kz = np.sqrt(k**2-k_rho**2) # %% calculate the effect of the slab k1 = n1/n0 * k # note that in the slab k_rho remains the same, in agreement with Snell's law with np.errstate(invalid='ignore'): theta0 = np.arcsin(ky/k) theta1 = np.arcsin(n0/n1 * np.sin(theta0 + alpha)) - alpha ky1 = k1 * np.sin (theta1) k_rho1 = np.sqrt( kx**2 + ky1**2 ) kz1 = np.sqrt( k1**2 - k_rho1**2 ) # additional phase due to propagation in the slab phase = 2*np.pi * (kz1 - kz) * thickness / np.cos(alpha) # Fresnel approximation # phase = -np.pi*(k_rho1**2/2/k1-k_rho**2/2/k) * thickness / np.cos(alpha) # %% calculate the displacement of the focus calculated by ray-tracing maxtheta0 = np.arcsin(NA/n0) maxtheta1 = np.arcsin(NA/n1) # diplacement along z (it is the displacement at alpha==0) displacementZ = thickness * (1-np.tan(maxtheta1)/np.tan(maxtheta0)) # calculate the displacement of a paraxial ray from the optical axis # (this is correctly calculated as a fucntion of alpha) alpha1 = np.arcsin(n0/n1*np.sin(alpha)) displacementY = - thickness/ np.cos(alpha1)*np.sin(alpha-alpha1) # correct for defocus, to recenter the PSF in z==0 and y==0 (the new ray-tracing focus point) phase += 2*np.pi * kz * displacementZ phase += 2*np.pi * ky * displacementY # %% generate the pupil and the transfer functions """ source_rho = [0.9, 0.9, 0.9] source_theta = [0, 2*np.pi/3, 4*np.pi/3] eff_waist = 0.01 print(f'{eff_waist =}') ATF0 = multiple_gaussians(kx/k_cut_off, ky/k_cut_off, eff_waist, eff_waist*10, source_rho, source_theta) ATF0 *= np.exp( 1.j*phase) # Amplitude Transfer Function (pupil) cut_idx = (k_rho >= k_cut_off) # indexes of the evanescent waves (kz is NaN for these indexes) # evanescent_idx = np.isnan(kz) ATF0[cut_idx] = 0 # exclude k above the PSF3D = np.zeros(((Nz,Npixels-1,Npixels-1))) for idx,z in enumerate(zs): angular_spectrum_propagator = np.exp(1.j*2*np.pi*kz*z) ATF = ATF0 * angular_spectrum_propagator mask_idx = (k_rho > k_cut_off) ATF[mask_idx] = 0 # Creates a circular mask ASF = ifftshift(ifft2(ATF)) #* k**2/f**2 # Amplitude Spread Function ASF = ASF[1:,1:] PSF = np.abs(ASF)**2 # Point Spread Function PSF3D[idx,:,:] = PSF print('The numerical aperture of the system is:', NA) print('The transverse resolution is:', DeltaXY ,'um') print('The axial resolution is:', DeltaZ ,'um') print('The pixel size is:', dr ,'um') print('The voxel depth is:', dz ,'um') print(f'The displacement z from the focus is: {displacementZ} um') print(f'The displacement y from the optical axis is: {displacementY} um') # %% figure 1 fig1, ax = plt.subplots(1, 2, figsize=(9, 5), tight_layout=False) fig1.suptitle(f'NA = {NA}, slab thickness = {thickness} $\mu$m, n0 = {n0}, n1 = {n1}') im0=ax[0].imshow(np.abs(ATF0), cmap='gray', extent = [np.amin(kx),np.amax(kx),np.amin(ky),np.amax(ky)], origin = 'lower' ) ax[0].set_xlabel('kx (1/$\mu$m)') ax[0].set_ylabel('ky (1/$\mu$m)') ax[0].set_title('Pupil (real part)') fig1.colorbar(im0,ax = ax[0]) im1=ax[1].imshow(PSF, cmap='gray', extent = [np.amin(x)+dr,np.amax(x),np.amin(y)+dr,np.amax(y)], origin = 'lower' ) ax[1].set_xlabel('x ($\mu$m)') ax[1].set_ylabel('y ($\mu$m)') ax[1].set_title(f'PSF at z={z:.2f}$\mu$m') # %% figure 2 idx_x = idx_y = (Npixels//2) idx_z = (Nz//2) fig2, axs = plt.subplots() fig2.suptitle('Max intensity projection') planez = PSF3D[idx_z,:,:] axs.set_title('|PSF(x,y)|') axs.set(xlabel = 'x ($\mu$m)') axs.set(ylabel = 'y ($\mu$m)') axs.imshow(planez, extent = [np.amin(x)+dr,np.amax(x),np.amin(y)+dr,np.amax(y)], cmap='hot' ) fig3, axs = plt.subplots(1, 2, figsize=(9, 5), tight_layout=False) fig3.suptitle('Max intensity projections') planey = PSF3D[:,idx_y,:] axs[0].set_title('|PSF(x,z)|') axs[0].set(xlabel = 'x ($\mu$m)') axs[0].set(ylabel = 'z ($\mu$m)') axs[0].imshow(planey, extent = [np.amin(x)+dr,np.amax(x),np.amin(zs),np.amax(zs)], cmap='hot' ) #axs[0].set_aspect(1/ratio) planex = PSF3D[:,:,idx_x] axs[1].set_title('|PSF(y,z)|') axs[1].set(xlabel = 'y ($\mu$m)') #axs[1].set(ylabel = 'z ($\mu$m)') axs[1].imshow(planex, extent = [np.amin(x)+dr,np.amax(x),np.amin(zs),np.amax(zs)], cmap='hot' ) #axs[1].set_aspect(1/ratio) if SaveData: basename = 'psf' filename = '_'.join(filter(None,[basename,f'NA_{NA}', f'size_{thickness}', f'alpha_{alpha:.2f}', f'n0_{n0}',f'n1_{n1}',f'lambda_{wavelength}'])) from skimage.external import tifffile as tif psf16 = ( PSF3D * (2**16-1) / np.amax(PSF3D) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, Nz, 1, Npixels-1, Npixels-1, 1 # dimensions in TZCYXS order tif.imsave(filename+'.tif', psf16, imagej=True, resolution = (1.0/dr, 1.0/dr), metadata={'spacing': dz, 'unit': 'um'})<file_sep>/Ewald/PSF3D_generator_with_Ewald_pixelsize.py # -*- coding: utf-8 -*- """ Created on Fri Oct 16 09:13:15 2020 Creates a 3D PSF starting from the Edward sphere @author: <NAME> """ import numpy as np from numpy.fft import fftn, ifftn, fftshift, ifftshift, fftfreq import matplotlib.pyplot as plt from AmplitudeTransferFunction_3D import amplitude_transfer_function um = 1.0 # base unit is um mm = 1000 * um N = 128 # the number of voxel in N**3 assert N%2 == 0 # N must be even n = 1.33 # refractive index NA = 1.1 # numerical aperture wavelength = 0.520 * um dr = 0.1 * um # spatial sampling in xyz SaveData = 'False' Detection_Mode = 'standard' # choose between 'standard' and '4pi' Microscope_Type = 'widefield' # choose between: 'widefield', 'gaussian', 'bessel', 'SIM', 'STED', 'aberrated' waist = 1.5 * um if Microscope_Type == 'gaussian': effectiveNA = wavelength/np.pi/waist else: effectiveNA = NA # %% Start calculation K = n/wavelength # wavenumber k_cut_off = NA/wavelength # cut off frequency in the coherent case DeltaXY = wavelength/2/NA # Diffraction limited transverse resolution DeltaZ = wavelength/n/(1-np.sqrt(1-NA**2/n**2)) # Diffraction limited axial resolution # DeltaZ = 2*n*wavelength/NA**2 # Fresnel approximation # generate the k-space kx_lin = kylin = kzlin = fftshift(fftfreq(N, dr)) Kmin=min(kx_lin) Kmax=max(kx_lin) if K > Kmax: raise ValueError('k-frequencies not allowed, try reducing the voxel size dr') dk = kx_lin[1]-kx_lin[0] #%% generate the Amplitude Transfer Function (also called Coherent Transfer Function) H = amplitude_transfer_function(N, Kmin, Kmax, n) H.create_ewald_sphere(K) H.set_numerical_aperture(NA, Detection_Mode) H.set_microscope_type(NA, Microscope_Type, effectiveNA/NA) # calculate the Spread and Transfer Function ATF = H.values # 3D Amplitude Transfer Function ASF = ifftshift(ifftn(fftshift(ATF))) # 3D Amplitude Spread Function ASF = ASF[1:,1:,1:] PSF = np.abs(ASF)**2 # 3D Point Spread Function PSF = PSF / np.sum(PSF) # Normalize the PSF on its eneregy OTF = fftshift(fftn(ifftshift(PSF))) # 3D Optical Transfer Function # show figures plane=round(N/2) epsilon = 1e-9 # to avoid calculating log 0 later ATF_show = np.rot90( ( np.abs(ATF[plane,:,:]) ) ) ASF_show = np.rot90( ( np.abs(ASF[plane,:,:]) ) ) PSF_show = np.rot90( ( np.abs(PSF[plane,:,:]) ) ) OTF_show = np.rot90( ( np.abs(OTF[plane,:,:]) ) ) # set font size plt.rcParams['font.size'] = 12 #create figure 1 and subfigures fig1, axs = plt.subplots(2,2,figsize=(9,9)) fig1.suptitle(Detection_Mode + ' ' + Microscope_Type + ' microscope') # recover the extent of the axes x,y,z rmin = H.rmin+H.dr rmax = H.rmax # create subplot: axs[0,0].set_title("|ASF(x,0,z)|") axs[0,0].set(ylabel = 'z ($\mu$m)') axs[0,0].imshow(ASF_show, extent=[rmin,rmax,rmin,rmax]) # create subplot: axs[0,1].set_title("|ATF($k_x$,0,$k_z$)|") axs[0,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[0,1].imshow(ATF_show, extent=[Kmin,Kmax,Kmin,Kmax]) # create subplot: axs[1,0].set_title('|PSF(x,0,z)|') axs[1,0].set(xlabel = 'x ($\mu$m)') axs[1,0].set(ylabel = 'z ($\mu$m)') axs[1,0].imshow(PSF_show, extent=[rmin,rmax,rmin,rmax]) # create subplot: axs[1,1].set_title('log|OTF($k_x$,0,$k_z$)|') axs[1,1].set(xlabel = '$k_x$ (1/$\mu$m)') axs[1,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[1,1].imshow(OTF_show, extent=[Kmin,Kmax,Kmin,Kmax]) # finally, render the figures plt.show() print('The numerical aperture of the system is:', effectiveNA) print('The transverse resolution is:', wavelength/2/effectiveNA ,'um') if Detection_Mode == 'standard': print('The axial resolution is:', wavelength/n/(1-np.sqrt(1-effectiveNA**2/n**2)) ,'um') print('The axial resolution is:', 2*n*wavelength/effectiveNA**2 ,'um, with Fresnel approximation') if SaveData: voxel_size = H.dr print('The voxel size is:',voxel_size,'um') from skimage.external import tifffile as tif psf16 = np.transpose(PSF,(2,0,1)) psf16 = ( psf16 * (2**16-1) / np.amax(psf16) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, N-1, 1, N-1, N-1, 1 # dimensions in TZCYXS order sampling = voxel_size tif.imsave(f'Ewald_NA{effectiveNA}_n{n}.tif', psf16, imagej=True, resolution = (1.0/sampling, 1.0/sampling), metadata={'spacing': sampling, 'unit': 'um'})<file_sep>/Defocus/PSFgenerator_class/_psf_generator.py # -*- coding: utf-8 -*- """ Created on Tue Feb 23 17:02:23 2021 Generate 3D PSF with different pupils and various abberrations between the object and the lens. @author: <NAME> """ import numpy as np from numpy.fft import ifft2, ifftshift, fftshift, fftfreq import matplotlib.pyplot as plt from zernike_polynomials import nm_polynomial from SIM_pupil import multiple_gaussians from psf_generator import PSF_generator from vectors import Vector class vectorial_generator(PSF_generator): def add_slab_vectorial(self, n1, thickness, alpha): """ Calculates the effect of the slab, using vectorial theory, considering s and p polarizations. n1: refractive index of the slab thickness: thickness alpha: angle from the xy plane, conventionally from the y axis """ n0 = self.n k= self.k k1 = n1/n0 * k kx=self.kx ky=self.ky kz=self.kz # k vector vk = Vector(kx,ky,kz) uk = vk.norm ux = Vector(1,0,0).to_size_like(vk) uy = Vector(0,1,0).to_size_like(vk) uz = Vector(0,0,1).to_size_like(vk) # normal to the surface u = Vector(0, np.sin(alpha), np.cos(alpha)).to_size_like(vk) us = (uk.cross(u)).norm up = us.cross(uk) E0 = ux # assume initial polarization along x E = uk.cross(-uz.cross(E0)) E= E/E.mag Es = E.dot(us) Ep = E.dot(up) print(E) # incidence angle, relative to the slab surface #phi0 = np.arccos(uk.cross(u).mag()) phi0 = np.arcsin(np.abs(uk.dot(u))) #Snell's law: phi1 = np.arcsin(n0/n1 * np.sin(phi0)) beta = phi0-phi1 #uk1 = uk * np.cos(beta) - up * np.sin(beta) with np.errstate(invalid='ignore'): theta0 = np.arcsin(ky/k) theta1 = np.arcsin(n0/n1 * np.sin(theta0 + alpha)) - alpha ky1 = k1 * np.sin (theta1) k_rho1 = np.sqrt( kx**2 + ky1**2 ) kz1 = np.sqrt( k1**2 - k_rho1**2 ) # additional phase due to propagation in the slab phase = (kz1-kz) * 2*np.pi * thickness / np.cos(alpha) # Fresnel law of refraction Ts01 = 2 * n0 * np.cos(theta0) / (n0* np.cos(theta0) + n1 * np.cos(theta1)) Tp01 = 2 * n0 * np.cos(theta0) / (n0* np.cos(theta1) + n1 * np.cos(theta0)) Ts10 = 2 * n1 * np.cos(theta1) / (n1* np.cos(theta1) + n0 * np.cos(theta0)) Tp10 = 2 * n1 * np.cos(theta1) / (n1* np.cos(theta0) + n0 * np.cos(theta1)) transmittance = (Es*Ts01*Ts10 + Ep*Tp01*Tp10 ) # assuming equal s and p polarization components #bprint(transmittance) self.amplitude *= transmittance self.phase += phase self.thickness = thickness self.alpha = alpha self.n1 = n1 self.correct_slab_defocus() if __name__ == '__main__': um = 1.0 mm = 1000 * um deg = np.pi/180 NA = 0.1 wavelength = 0.518 * um n0 = 1.33 # refractive index of the medium n1 = 1.4 # refractive index of the slab thickness = 170 * um # slab thickness alpha = 0 * deg # angle of the slab relative to the y axis SaveData = False Nxy = 8 Nz = 1 aspect_ratio = 2 # ratio between z and xy sampling gen = vectorial_generator(NA, n0, wavelength, Nxy, Nz, over_sampling=1, aspect_ratio=aspect_ratio) # gen.add_Ndimensional_SIM_pupil() # gen.add_lattice_pupil(cutin = 0.84, cutout = 1, # waistx = 0.015,waist_ratio = 20,source_num = 4) # gen.add_lightsheet_pupil() gen.add_slab_vectorial(n1, thickness, alpha) # gen.add_slab_vectorial(n1, thickness, alpha) # gen.add_Zernike_aberration(3, 3, weight=1) gen.generate_pupil() gen.generate_3D_PSF() # Show results #gen.print_values() gen.show_pupil() gen.show_PSF_projections(aspect_ratio=1, mode='MIP') if SaveData: gen.save_data() <file_sep>/Ewald/old/PSF_3D_generator.py ''' Created on 28 jul 2019 @author: <NAME>, Politecnico di Milano Lecture on 3D Optical Transfer Functions and Ewald Sphere. Optical Microscopy Course (Biophotonics) ''' import numpy as np from numpy.fft import fftn, ifftn, fftshift, ifftshift import matplotlib.pyplot as plt import time from AmplitudeTransferFunction_3D import amplitude_transfer_function from xlrd.formula import num2strg N = 64 # sampling number um = 1. # base unit is um n = 1 # refractive index NA = 0.14 # numerical aperture wavelength = 0.520 * um print('The numerical aperture of the system is:', NA) print('The transverse resolution is:', wavelength/2/NA ,'um') print('The axial resolution is:', wavelength/n/(1-np.sqrt(1-NA**2/n**2)) ,'um') print('The axial resolution is:', 2*n*wavelength/NA**2 ,'um, with Fresnel approximation') K = n / wavelength Kextent = 1.01*K # extent of the k-space Detection_Mode = 'standard' #choose between 'standard' and '4pi' Microscope_Type = 'widefield' # choose between: 'widefield', 'gaussian', 'bessel', 'SIM', 'STED', 'aberrated' SaveData = True # Generate the Amplitude Transfer Function (or Coherent Transfer Function) t0=time.time() # this is to calculate the execution time H = amplitude_transfer_function(N, Kextent, n) voxel_size = H.dr extent = H.xyz_extent print('The voxel size is', voxel_size,'um') H.create_ewald_sphere(K) H.set_numerical_aperture(NA, Detection_Mode) pupil, psf_xy0 = H.set_microscope_type(NA, Microscope_Type) ATF = H.values # 3D Amplitude Transfer Function ASF = ifftshift(ifftn(fftshift(ATF))) * N**3 # # 3D Amplitude Spread Function (normalized for the total volume) PSF = np.abs(ASF)**2 # 3D Point Spread Function OTF = fftshift(fftn(ifftshift(PSF))) # 3D Optical Transfer Function print('Elapsed time for calculation: ' + num2strg( time.time()-t0) + 's' ) ############################ ##### Show figures plane=round(N/2) epsilon = 1e-9 # to avoid calculating log 0 later ATF_show = np.rot90( ( np.abs(ATF[plane,:,:]) ) ) ASF_show = np.rot90( ( np.abs(ASF[plane,:,:]) ) ) PSF_show = np.rot90( ( np.abs(PSF[plane,:,:]) ) ) OTF_show = np.rot90( 10*np.log10 ( np.abs(OTF[plane,:,:]) + epsilon ) ) # set font size plt.rcParams['font.size'] = 12 #create figure 1 and subfigures fig1, axs = plt.subplots( 2, 2, figsize= (9,9) ) fig1.suptitle(Detection_Mode + ' ' + Microscope_Type + ' microscope') # Recover extent of axes x,y,z (it is the inverse of the k sampling xyz_extent = 1/(2*dK)) Rmax=H.xyz_extent zoom_factor = 1 #Kextent / K # create subplot: axs[0,0].set_title("|ASF(x,0,z)|") axs[0,0].set(ylabel = 'z ($\mu$m)') axs[0,0].imshow(ASF_show, vmin = ASF_show.min(), vmax = ASF_show.max(), extent=[-Rmax,Rmax,-Rmax,Rmax]) axs[0,0].xaxis.zoom(zoom_factor) axs[0,0].yaxis.zoom(zoom_factor) # create subplot: axs[0,1].set_title("|ATF($k_x$,0,$k_z$)|") axs[0,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[0,1].imshow(ATF_show , extent=[-Kextent,Kextent,-Kextent,Kextent]) # create subplot: axs[1,0].set_title('|PSF(x,0,z)|') axs[1,0].set(xlabel = 'x ($\mu$m)') axs[1,0].set(ylabel = 'z ($\mu$m)') axs[1,0].imshow(PSF_show, vmin = PSF_show.min(), vmax = PSF_show.max(), extent=[-Rmax,Rmax,-Rmax,Rmax]) axs[1,0].xaxis.zoom(zoom_factor) axs[1,0].yaxis.zoom(zoom_factor) # create subplot: axs[1,1].set_title('log|OTF($k_x$,0,$k_z$)|') axs[1,1].set(xlabel = '$k_x$ (1/$\mu$m)') axs[1,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[1,1].imshow(OTF_show, extent=[-Kextent,Kextent,-Kextent,Kextent]) # finally, render the figures plt.show() ############################ ##### Save Psf to .tif file if SaveData: from skimage.external import tifffile as tif psf16 = np.transpose(PSF,(2,0,1)) psf16 = ( psf16 * (2**16-1) / np.amax(psf16) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, N, 1, N, N, 1 # dimensions in TZCYXS order sampling = voxel_size tif.imsave(f'psf_{NA}.tif', psf16, imagej=True, resolution = (1.0/sampling, 1.0/sampling), metadata={'spacing': sampling, 'unit': 'um'})<file_sep>/Ewald/PSF3D_generator_with_Ewald.py # -*- coding: utf-8 -*- """ Created on Fri Oct 16 09:13:15 2020 Creates a 3D PSF starting from the Edward sphere @author: <NAME> """ import numpy as np from numpy.fft import fftn, ifftn, fftshift, ifftshift import matplotlib.pyplot as plt from AmplitudeTransferFunction_3D import amplitude_transfer_function um = 1.0 # base unit is um mm = 1000 * um N = 128 # the number of voxel in N**3 assert N%2 == 0 # N must be even n = 1.33 # refractive index NA = 1.1 # numerical aperture wavelength = 0.520 * um K = n / wavelength SaveData = 'False' Detection_Mode = 'standard' # choose between 'standard' and '4pi' Microscope_Type = 'widefield' # choose between: 'widefield', 'gaussian', 'bessel', 'SIM', 'STED', 'aberrated' if Microscope_Type == 'gaussian': waist = 1.5 * um effectiveNA = wavelength/np.pi/waist print ('effective NA:', effectiveNA) else: effectiveNA = NA Kextent = 2*K # extent of the k-space #%% generate the Amplitude Transfer Function (also called Coherent Transfer Function) H = amplitude_transfer_function(N, -Kextent, Kextent, n) H.create_ewald_sphere(K) H.set_numerical_aperture(NA, Detection_Mode) H.set_microscope_type(NA, Microscope_Type, effectiveNA/NA) # calculate the Spread and Transfer Function ATF = H.values # 3D Amplitude Transfer Function ASF = ifftshift(ifftn(fftshift(ATF))) # 3D Amplitude Spread Function ASF = ASF[1:,1:,1:] PSF = np.abs(ASF)**2 # 3D Point Spread Function PSF = PSF / np.sum(PSF) # Normalize the PSF on its eneregy OTF = fftshift(fftn(ifftshift(PSF))) # 3D Optical Transfer Function # show figures plane=round(N/2) epsilon = 1e-9 # to avoid calculating log 0 later ATF_show = np.rot90( ( np.abs(ATF[plane,:,:]) ) ) ASF_show = np.rot90( ( np.abs(ASF[plane,:,:]) ) ) PSF_show = np.rot90( ( np.abs(PSF[plane,:,:]) ) ) #OTF_show = np.rot90( 10*np.log10 ( np.abs(OTF[plane,:,:]) + epsilon ) ) OTF_show = np.rot90( ( np.abs(OTF[plane,:,:]) ) ) # set font size plt.rcParams['font.size'] = 12 #create figure 1 and subfigures fig1, axs = plt.subplots(2,2,figsize=(9,9)) fig1.suptitle(Detection_Mode + ' ' + Microscope_Type + ' microscope') # recover the extent of the axes x,y,z rmin = H.rmin+H.dr rmax = H.rmax # create subplot: axs[0,0].set_title("|ASF(x,0,z)|") axs[0,0].set(ylabel = 'z ($\mu$m)') axs[0,0].imshow(ASF_show, extent=[rmin,rmax,rmin,rmax]) # create subplot: axs[0,1].set_title("|ATF($k_x$,0,$k_z$)|") axs[0,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[0,1].imshow(ATF_show, extent=[-Kextent,Kextent,-Kextent,Kextent]) # create subplot: axs[1,0].set_title('|PSF(x,0,z)|') axs[1,0].set(xlabel = 'x ($\mu$m)') axs[1,0].set(ylabel = 'z ($\mu$m)') axs[1,0].imshow(PSF_show, extent=[rmin,rmax,rmin,rmax]) # create subplot: axs[1,1].set_title('log|OTF($k_x$,0,$k_z$)|') axs[1,1].set(xlabel = '$k_x$ (1/$\mu$m)') axs[1,1].set(ylabel = '$k_z$ (1/$\mu$m)') axs[1,1].imshow(OTF_show, extent=[-Kextent,Kextent,-Kextent,Kextent]) # # zoom in: # for i in (0,1): # for j in (0,1): # if j == 1: # zoom_factor = Kextent/K/2 # else: # zoom_factor = Kextent/K # axs[i,j].xaxis.zoom(zoom_factor) # axs[i,j].yaxis.zoom(zoom_factor) # finally, render the figures plt.show() print('The numerical aperture of the system is:', effectiveNA) print('The transverse resolution is:', wavelength/2/effectiveNA ,'um') if Detection_Mode == 'standard': print('The axial resolution is:', wavelength/n/(1-np.sqrt(1-effectiveNA**2/n**2)) ,'um') print('The axial resolution is:', 2*n*wavelength/effectiveNA**2 ,'um, with Fresnel approximation') if SaveData: voxel_size = H.dr print('The voxel size is:',voxel_size,'um') from skimage.external import tifffile as tif psf16 = np.transpose(PSF,(2,0,1)) psf16 = ( psf16 * (2**16-1) / np.amax(psf16) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, N-1, 1, N-1, N-1, 1 # dimensions in TZCYXS order sampling = voxel_size tif.imsave(f'Ewald0_NA{NA}_n{n}.tif', psf16, imagej=True, resolution = (1.0/sampling, 1.0/sampling), metadata={'spacing': sampling, 'unit': 'um'})<file_sep>/Defocus/PSFgenerator_class/psf_generator.py # -*- coding: utf-8 -*- """ Created on Tue Feb 23 17:02:23 2021 @author: <NAME> """ import numpy as np from numpy.fft import ifft2, ifftshift, fftshift, fftfreq import matplotlib.pyplot as plt from zernike_polynomials import nm_polynomial from SIM_pupil import multiple_gaussians class PSF_generator(): ''' Class to generate 3D Point Spread Functions with different pupils and various abberrations between the object and the lens. ''' def __init__(self, NA, n, wavelength, Nxy, Nz, over_sampling=4, aspect_ratio=1): ''' NA: numerical aperture n: refractive index wavelength Nxy: number of pixels in kx-ky (pixels in x-y is Nxy-1) Nz: number of pixels in kz (and in z) over_sampling: ratio between the Abbe resolution and spatial sampling aspect_ratio: ratio between z and xy sampling ''' assert Nxy % 2 == 0, "XY number of pixels must be even" self.NA = NA # Numerical aperture self.n = n # refraction index at the object self.wavelength = wavelength self.Nxy = Nxy self.Nz = Nz DeltaXY = wavelength/2/NA # Diffraction limited transverse resolution self.dr = DeltaXY/over_sampling # spatial sampling in xy, chosen to be a fraction (over_sampling) of the resolution self.aspect_ratio = aspect_ratio self.dz = aspect_ratio * self.dr # spatial sampling in z # generate the real space (xy is used only for visulaization) # x = y = fftshift(fftfreq(Npixels, dk)) self.x = self.y = self.dr * (np.arange(Nxy) - Nxy // 2) self.z = self.dz * (np.arange(self.Nz) - self.Nz // 2) self.k = n/wavelength # wavenumber self.k_cut_off = NA/wavelength # cut off frequency in the coherent case self.generate_kspace() def generate_kspace(self): """ Generates the k-space used to define the transfer functions """ kx_lin = fftshift(fftfreq(self.Nxy, self.dr)) ky_lin = fftshift(fftfreq(self.Nxy, self.dr)) # kx_lin = dk * (np.arange(Nxy) - Nxy // 2) # ky_lin = dk * (np.arange(Nxy) - Nxy // 2) self.dk = kx_lin[1]-kx_lin[0] kx, ky = np.meshgrid(kx_lin,ky_lin) # k-space in radial coordinates with np.errstate(invalid='ignore'): self.k_rho = np.sqrt(kx**2 + ky**2) self.k_theta = np.arctan2(ky,kx) self.kz = np.sqrt(self.k**2-self.k_rho**2) self.kx = kx self.ky = ky self.phase = np.zeros_like(self.kz) self.amplitude = np.ones_like(self.kz) self.ATF0 = np.zeros_like(self.kz) self.PSF3D = np.zeros(((self.Nz,self.Nxy-1,self.Nxy-1))) def add_slab_scalar(self, n1, thickness, alpha): """ Calculates the effect of the slab, using scalar theory, without considering s and p polarizations. n1: refractive index of the slab thickness: thickness alpha: angle from the xy plane, conventionally from the y axis """ n0 = self.n k= self.k k1 = n1/n0 * k ky=self.ky kx=self.kx kz=self.kz # note that, at alpha=0, k_rho remains the same in the slab, in agreement with Snell's law with np.errstate(invalid='ignore'): theta0 = np.arcsin(ky/k) theta1 = np.arcsin(n0/n1 * np.sin(theta0 + alpha)) - alpha ky1 = k1 * np.sin (theta1) k_rho1 = np.sqrt( kx**2 + ky1**2 ) kz1 = np.sqrt( k1**2 - k_rho1**2 ) # additional phase due to propagation in the slab phase = 2*np.pi * (kz1-kz) * thickness / np.cos(alpha) # Fresnel law of refraction (not used and not important al low NA) # Ts01 = 2 * n0 * np.cos(theta0) / (n0* np.cos(theta0) + n1 * np.cos(theta1)) # Tp01 = 2 * n0 * np.cos(theta0) / (n0* np.cos(theta1) + n1 * np.cos(theta0)) # Ts10 = 2 * n1 * np.cos(theta1) / (n1* np.cos(theta1) + n0 * np.cos(theta0)) # Tp10 = 2 * n1 * np.cos(theta1) / (n1* np.cos(theta0) + n0 * np.cos(theta1)) # transmittance = (Ts01*Ts10 + Tp01*Tp10 ) / 2 # assuming equal s and p polarization components # self.amplitude *= transmittance self.phase += phase self.thickness = thickness self.alpha = alpha self.n1 = n1 self.correct_slab_defocus() def correct_slab_defocus(self): """ Calculates the displacement of the focus along z and y as it was calculated by ray-tracing and changes the phase accordingly. Correcting for defocus does not change the PSF shape but recenters it around the origin """ n0 = self.n NA= self.NA if hasattr(self, 'thickness'): thickness = self.thickness n1 = self.n1 alpha = self.alpha else: raise Exception('Slab parameters not specified') maxtheta0 = np.arcsin(NA/n0) maxtheta1 = np.arcsin(NA/n1) # diplacement along z (it is calculated at alpha==0) self.displacementZ = thickness * (1-np.tan(maxtheta1)/np.tan(maxtheta0)) # calculate the displacement of a paraxial ray from the optical axis # (this is correctly calculated as a fucntion of alpha) alpha1 = np.arcsin(n0/n1*np.sin(alpha)) self.displacementY = - thickness/ np.cos(alpha1)*np.sin(alpha-alpha1) # correct for defocus, to recenter the PSF in z==0 and y==0 (the new ray-tracing focus point) self.phase += 2*np.pi * self.kz * self.displacementZ self.phase += 2*np.pi * self.ky * self.displacementY # remove piston phase = self.phase phase = phase[np.isfinite(phase)] self.phase= (self.phase - np.min(phase)) def add_Zernike_aberration(self, N, M, weight): self.phase += weight*nm_polynomial(N, M, self.k_rho/self.k_cut_off, self.k_theta, normalized = True ) def generate_pupil(self): """ generate the pupil and the transfer functions """ ATF0 = self.amplitude * np.exp( 1.j*self.phase) #ATF0 = np.exp( 1.j*phase) # Amplitude Transfer Function (pupil) cut_idx = (self.k_rho >= self.k_cut_off) # indexes of the evanescent waves (kz is NaN for these indexes) ATF0[cut_idx] = 0 # exclude k above the cut off frequency self.ATF0 = ATF0 def add_Ndimensional_SIM_pupil(self, kr = 0.7, waist = 0.01, source_num = 3 ): ''' Generates the pupil for mutlidimensional SIM microscopy (typically 2,3 or 4 sources are used) kr: spatial frequency (radial component) of the sources, relative to the cutoff frequency self.k_cut_off waist: of the gaussian source, relative to the cutoff frequency self.k_cut_off ''' NumSources = 3 source_theta = 2*np.pi/source_num * np.arange(source_num) source_kr = [kr] * NumSources self.amplitude *= multiple_gaussians(self.kx/self.k_cut_off, self.ky/self.k_cut_off, waist, waist, source_kr, source_theta) def add_lightsheet_pupil(self, waistx = 0.015, waist_ratio = 20, ): ''' Generates the pupil for light sheet illumination waistx: of the gaussian source along. waist_ratio: ratio between the waist along y and the one along x If waist_x<<1 waist_ratio>>1, a light sheet is formed in the plane xz ''' waisty = waistx * waist_ratio beam= multiple_gaussians(self.kx/self.k_cut_off, self.ky/self.k_cut_off, waistx, waisty, [0.0], [0.0]) self.amplitude *=beam def add_lattice_pupil(self, cutin = 0.84, cutout = 1, waistx = 0.015, waist_ratio = 20, source_num = 3 ): ''' Generates the pupil for lattice light sheet microscopy All parameters are relative to the cutoff frequency self.k_cut_off cutin: minimum radial spatial frequency of the annular ring cutout: maximum radial spatial frequency of the annular ring waistx: of the gaussian source along x waist_ratio: ratio between the waist along y and the one along x source_num: order of the lattice ''' source_rho = [(cutout+cutin)/2] * source_num # repeat list source_num times source_theta = 2*np.pi/source_num * np.arange(source_num) waisty = waistx * waist_ratio beams= multiple_gaussians(self.kx/self.k_cut_off, self.ky/self.k_cut_off, waistx, waisty, source_rho, source_theta) cut_idx = (self.k_rho <= self.k_cut_off*cutin) | (self.k_rho >= self.k_cut_off*cutout) mask = np.ones_like(self.k_rho) mask[cut_idx] = 0 # exclude k above the cut off frequency self.amplitude *=beams*mask def generate_3D_PSF(self): ATF0 = self.ATF0 for idx,zi in enumerate(self.z): angular_spectrum_propagator = np.exp(1.j*2*np.pi*self.kz*zi) ATF = ATF0 * angular_spectrum_propagator evanescent_idx = (self.k_rho > self.k) ATF[evanescent_idx] = 0 ASF = ifftshift(ifft2(ATF)) #* k**2/f**2 # Amplitude Spread Function ASF = ASF[1:,1:] PSF = np.abs(ASF)**2 # Point Spread Function self.PSF3D[idx,:,:] = PSF def _calculateRMS(self): '''calculates the RMS wavefron error For Zernike abberrations it is the weight of the rms == 1 indicates 1-wavelength wavefront error ''' cut_idx = self.k_rho >= self.k_cut_off area = self.ATF0.size - np.sum(cut_idx) phase = self.phase # /(2*np.pi) #m = np.zeros_like(phase) phase[cut_idx] = 0 phase = phase[np.isfinite(phase)] rms = np.sqrt(np.sum(phase**2)/area) return(rms) def print_values(self): DeltaXY = self.wavelength/2/self.NA # Diffraction limited transverse resolution DeltaZ = self.wavelength/self.n/(1-np.sqrt(1-self.NA**2/self.n**2)) # Diffraction limited axial resolution print(f'The numerical aperture of the system is: {self.NA}') print(f'The transverse resolution is: {DeltaXY:.03f} um') print(f'The axial resolution is: {DeltaZ:.03f} um') print(f'The pixel size is: {self.dr:.03f} um') print(f'The voxel depth is: {self.dz:.03f} um') if hasattr(self, 'displacementZ'): print(f'The displacement z from the focus is: {self.displacementZ} um') if hasattr(self, 'displacementY'): print(f'The displacement y from the optical axis is: {self.displacementY} um') if hasattr(self, 'calculateRMS'): print(f'The RMS wavefront error is {self.calculateRMS()}') def show_pupil(self): """ Shows the Amplitude Transfer Function (pupil) in amplitude and phase """ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=False) sup_title = f'NA = {self.NA}, n = {self.n}' if hasattr(self,'thickness'): sup_title += f', slab thickness = {self.thickness} $\mu$m, n1 = {self.n1}, alpha = {self.alpha:.02f}' fig.suptitle(sup_title) for idx in range(2): if idx==0: data = np.abs(self.ATF0) title = 'Pupil (amplitude)' elif idx ==1: data = np.angle(self.ATF0) title = 'Pupil (phase)' im0=ax[idx].imshow(data, cmap='pink', extent = [np.amin(self.kx),np.amax(self.kx),np.amin(self.ky),np.amax(self.ky)], origin = 'lower' ) ax[idx].set_xlabel('kx (1/$\mu$m)') ax[idx].set_ylabel('ky (1/$\mu$m)') ax[idx].set_title(title) fig.colorbar(im0,ax = ax[idx]) def show_PSF_projections(self, aspect_ratio, mode ='MIP'): """ Shows the 3D PSF in 3 orthogonal views Aspect ratio: between the z axis and the other axes scale mode: 'MIP' or 'plane': MAximum intensity projection or plane incercepting the origin """ fig, axs = plt.subplots(1, 3, figsize=(12,6), tight_layout=False) sup_title = f'NA = {self.NA}, n = {self.n}' if hasattr(self,'thickness'): sup_title += f', slab thickness = {self.thickness} $\mu$m, n1 = {self.n1}, alpha = {self.alpha:.02f}' fig.suptitle(sup_title) label_list = ( ('x','y'),('x','z'),('y','z') ) for idx, labels in enumerate(label_list): if mode =='MIP': # create maximum intensity projection MIP = np.amax(self.PSF3D,axis=idx) im_to_show = MIP elif mode =='plane': PSF = self.PSF3D Nz,Ny,Nx = PSF.shape Nlist = [Nz,Ny,Nx] im_to_show = PSF.take(indices=Nlist[idx]//2 , axis=idx) else: raise(ValueError, 'Please specify PSF showing mode' ) values0 = getattr(self, labels[0]) values1 = getattr(self, labels[1]) delta0 = self.dr delta1 = self.dr if idx==0 else 0 extent = [np.amin(values0)+delta0, np.amax(values0), np.amin(values1)+delta1, np.amax(values1)] if idx == 0: vmin = np.amin(im_to_show) vmax = np.amax(im_to_show) axs[idx].imshow(im_to_show, cmap='twilight', extent = extent, origin = 'lower', vmin=vmin, vmax=vmax ) axs[idx].set_xlabel(f'{labels[0]} ($\mu$m)') axs[idx].set_ylabel(f'{labels[1]} ($\mu$m)') axs[idx].set_title(f'|PSF({labels[0]},{labels[1]})|') if labels[1] == 'z': axs[idx].set_aspect(1/aspect_ratio) def save_data(self): basename = 'psf' filename = '_'.join([basename, f'NA_{self.NA}', f'n_{self.n}']) if hasattr(self, 'thickness'): filename = '_'.join([filename, f'size_{self.thickness}', f'alpha_{self.alpha:.2f}', f'n1_{self.n1}']) from skimage.external import tifffile as tif psf16 = ( self.PSF3D * (2**16-1) / np.amax(self.PSF3D) ).astype('uint16') #normalize and convert to 16 bit psf16.shape = 1, self.Nz, 1, self.Nxy-1, self.Nxy-1, 1 # dimensions in TZCYXS order tif.imsave(filename+'.tif', psf16, imagej=True, resolution = (1.0/self.dr, 1.0/self.dr), metadata={'spacing': self.dz, 'unit': 'um'}) if __name__ == '__main__': um = 1.0 mm = 1000 * um deg = np.pi/180 NA = 0.3 wavelength = 0.518 * um n0 = 1.33 # refractive index of the medium n1 = 1.5 # refractive index of the slab thickness = 170 * um # slab thickness alpha = 45 * deg # angle of the slab relative to the y axis SaveData = False Nxy = 256 Nz = 256 aspect_ratio = 2 # ratio between z and xy sampling gen = PSF_generator(NA, n0, wavelength, Nxy, Nz, over_sampling = 4, aspect_ratio=aspect_ratio) # gen.add_Ndimensional_SIM_pupil() # gen.add_lattice_pupil() # gen.add_lightsheet_pupil() gen.add_slab_scalar(n1, thickness, alpha) # gen.add_slab_vectorial(n1, thickness, alpha) # gen.add_Zernike_aberration(5, 1, weight=0.5) gen.generate_pupil() gen.generate_3D_PSF() # Show results gen.print_values() gen.show_pupil() gen.show_PSF_projections(aspect_ratio=1, mode='MIP') if SaveData: gen.save_data()
f27dcb6e6103c2c3e321587f19909b81cc66b8a2
[ "Python" ]
9
Python
andreabassi78/PSF_3D_generator
4a586e75f7f7957b664e3a60a43adfda19fb634a
71bc1adb0fec171fc53004ce148a48aef54d9fe0
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Sun Nov 18 10:09:15 2018 @author: shrey """ import nltk from nltk.classify import NaiveBayesClassifier from nltk.classify.util import accuracy #Building Model def format_sentence(sent): return({word: True for word in nltk.word_tokenize(sent)}) Positive = [] with open(r"C:/Users/shrey/Desktop/pos_tweets.txt") as f: for i in f: Positive.append([format_sentence(i), 'Positive']) Negative = [] with open(r"C:/Users/shrey/Desktop/neg_tweets.txt",encoding="utf8") as f: for i in f: Negative.append([format_sentence(i), 'Negative']) training = Positive[:int((0.8)*len(Positive))] + Negative[:int((0.8)*len(Negative))] test = Positive[int((0.8)*len(Positive)):] + Negative[int((0.8)*len(Negative)):] #Checking Accuracy classifier = NaiveBayesClassifier.train(training) print('***************************************************************************') print(accuracy(classifier, test)) #Tweets Classification example1 = "The hard truth about the United States is that the money other countries spend on health and infrastructure, we spend on war." print(classifier.classify(format_sentence(example1))) example2 = "Elephant family save drowning calf by pushing it to shallow end of the pool. Wonderful." print(classifier.classify(format_sentence(example2))) example3 = "<NAME> has conceded defeat after a recount in the close fought Florida gubernatorial election." print(classifier.classify(format_sentence(example3))) example4 = "As of 12pm, AQI remains red. Those with health issues should avoid outdoor activities. AQI may fluctuate." print(classifier.classify(format_sentence(example4))) example5 = "Abrams Still Bitter After Election Loss; Refuses To Call Kemp Legitimate Winner" print(classifier.classify(format_sentence(example5))) example6 = "#NSFfunded researchers at the @UW uncover an almost 6,000-year record of the West Antarctic Ice Sheet’s motion." print(classifier.classify(format_sentence(example6))) example7 = "Incredible to be with our GREAT HEROES today in California. We will always be with you!" print(classifier.classify(format_sentence(example7))) example8 = "It was my great honor to host a celebration of Diwali, the Hindu Festival of Lights, in the Roosevelt Room at the @WhiteHouse this afternoon. Very, very special people!" print(classifier.classify(format_sentence(example8))) example9 = "<NAME>'s sharp attacks on China are fueling fears of a Cold War that could divide Asia." print(classifier.classify(format_sentence(example9))) example10 = "House Democrats are vowing an all-out fight to salvage the Consumer Financial Protection Bureau." print(classifier.classify(format_sentence(example10)))<file_sep># NLP - Setiment Analysis Trained the data using pos_tweets.txt and neg_tweets.txt Selected 10 random tweets from Twitter Classified the tweets as 'pos' or 'neg’ using Naive Bayes Classifier and checked for accuracy
6dae5c241e6056c9314aac2a57640117c1ad5752
[ "Markdown", "Python" ]
2
Python
ssingh68/Sentiment-Analysis
e70282350b16a20cb5be5c53d12a67c680ed9739
3900054038807be9c0e68fc5b54e7b13cbb197f9
refs/heads/master
<file_sep>'use strict'; /** * Enable the following blocks to test raspberry pi camera availability to chrome in kiosk mode. ( i have concerns about piZeroW being able to handle all of this ) **/ // const constraints = window.constraints = { // audio: false, // video: true // }; // function handleSuccess(stream) { // const video = document.querySelector('video'); // const videoTracks = stream.getVideoTracks(); // console.log('Got stream with constraints:', constraints); // console.log(`Using video device: ${videoTracks[0].label}`); // window.stream = stream; // make variable available to browser console // video.srcObject = stream; // } // function handleError(error) { // if (error.name === 'ConstraintNotSatisfiedError') { // const v = constraints.video; // errorMsg(`The resolution ${v.width.exact}x${v.height.exact} px is not supported by your device.`); // } else if (error.name === 'PermissionDeniedError') { // errorMsg('Permissions have not been granted to use your camera and ' + // 'microphone, you need to allow the page access to your devices in ' + // 'order for the demo to work.'); // } // errorMsg(`getUserMedia error: ${error.name}`, error); // } // function errorMsg(msg, error) { // const errorElement = document.querySelector('#errorMsg'); // errorElement.innerHTML += `<p>${msg}</p>`; // if (typeof error !== 'undefined') { // console.error(error); // } // } // async function initialize() { // try { // const stream = await navigator.mediaDevices.getUserMedia(constraints); // handleSuccess(stream); // } catch (e) { // handleError(e); // } // } // initialize(); var hoursContainer = document.querySelector('.hours') var minutesContainer = document.querySelector('.minutes') var secondsContainer = document.querySelector('.seconds') var tickElements = Array.from(document.querySelectorAll('.tick')) var last = new Date(0) last.setUTCHours(-1) var tickState = true function updateTime() { var now = new Date let militaryTime = last.getHours().toString(); var ampm = militaryTime >= 12 ? 'pm' : 'am'; var lastHours = last.getHours().toString(); var nowHours = now.getHours().toString(); //var humanHours = (nowHours % 12 || 12).toString(); if (lastHours !== nowHours) { updateContainer(hoursContainer, nowHours) } var lastMinutes = last.getMinutes().toString() var nowMinutes = now.getMinutes().toString() if (lastMinutes !== nowMinutes) { updateContainer(minutesContainer, nowMinutes) } var lastSeconds = last.getSeconds().toString() var nowSeconds = now.getSeconds().toString() if (lastSeconds !== nowSeconds) { //tick() updateContainer(secondsContainer, nowSeconds) } last = now } function tick() { tickElements.forEach(t => t.classList.toggle('tick-hidden')) } function updateContainer(container, newTime) { var time = newTime.split('') if (time.length === 1) { time.unshift('0') } var first = container.firstElementChild if (first.lastElementChild.textContent !== time[0]) { updateNumber(first, time[0]) } var last = container.lastElementChild if (last.lastElementChild.textContent !== time[1]) { updateNumber(last, time[1]) } } function updateNumber(element, number) { //element.lastElementChild.textContent = number var second = element.lastElementChild.cloneNode(true) second.textContent = number element.appendChild(second) element.classList.add('move') setTimeout(function () { element.classList.remove('move') }, 990) setTimeout(function () { element.removeChild(element.firstElementChild) }, 990) } setInterval(updateTime, 100) /* ---- Background Image SlideShow Prototype */ var IMAGE_DISPLAY_DURATION = 60000; var IMAGE_FADE_DURATION = 3000; function revealNextImage() { var img_url = `https://source.unsplash.com/collection/10591049/1600x900&random=${Math.floor(Math.random() * IMAGE_DISPLAY_DURATION)}` $('#background_image').css({ 'background-image': `url(${img_url})` }).fadeIn(IMAGE_FADE_DURATION).promise().done(() => { setTimeout(fadeCurrentImage, IMAGE_DISPLAY_DURATION) }); } function fadeCurrentImage() { $('#background_image').fadeOut(IMAGE_FADE_DURATION).promise().done(() => { revealNextImage(); }); } revealNextImage();<file_sep># smrt - Yet another raspberry pi "smart-mirror". ### TLDR What is this? At the moment all I'm doing is configuring a RaspberryPi Zero W to run X and display a webkit view which pulls up this repo's public page located here: [preview](https://www.nicholaswagner.dev/smrt/) ### Why would you do this? A little while back one of my development LCDs died. After a little fiddling I discovered that it was only PARTIALLY broken. The display still works fine for CEA devices (think consumer television applications), but does not work with DMT standard devices. (think computer screens) As a nerd with a raspberry pi I knew what must be done, and this project was born. ### // TODO - [x] figure out how to run X on boot and display webkit view - [x] create proof of concept slideshow which pulls interesting imgages - [ ] build widget which pulls iCal/Google Cal agenda - [ ] build Date/Time widget - [ ] build Weather widget - [ ] design smart mirror frame/mount for dispay - [ ] design raspberry pi zero w + camera case which works with smart mirror design #### CEA / DMT What's that? CEA: Electronic Industries Alliance (EIA-861B) refers to a CEA/EIA standard which consists of display timing and formats supported by Digital Televisions DMT: Display Monitor Timings (DMT) are a list of VESA standard pre-defined timings which are commonly used within the Computer industry.
027f513ee8477ab0238e6587e0d57b53a66f30b8
[ "JavaScript", "Markdown" ]
2
JavaScript
nicholaswagner/smrt
24c6d0e869efdc7b96815b3e2efd23d5cb2ccedc
53eb964dee18616ca93f1bd33bc75101d1dea58c
refs/heads/master
<file_sep>// // CSHExpandableTableViewCell.swift // CoffeeShop // // Created by <NAME> on 10/22/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation class CSHExpandableTableViewCell: UITableViewCell { var isExpanded: Bool = false var isVisible: Bool = false }<file_sep>// // ShopsListDataController.swift // CoffeeShop // // Created by <NAME> on 2/20/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import MapKit import RxCocoa import RxSwift extension MKPointAnnotation { convenience init(venue: CSHVenue) { self.init() title = venue.name subtitle = "\(venue.location?.address ?? "") @\(venue.location?.distance ?? 0)m" if let lat = venue.location?.lat, let lng = venue.location?.lng { coordinate = CLLocationCoordinate2DMake(lat, lng) } } } @objc (ShopsListDataController) class ShopsListDataController: NSObject, UITableViewDataSource { fileprivate var venues = [CSHVenue]() fileprivate var images = [String: Data]() var annotations: [MKPointAnnotation]? { return venues.map { MKPointAnnotation(venue: $0) } } func venue(at indexPath: IndexPath) -> CSHVenue? { guard venues.count > indexPath.row else { return nil } return venues[indexPath.row] } func addVenue(_ venue: CSHVenue, completion: ((Int) -> Void)?) { if self.venues.contains(venue) { return } venues.append(venue) images[venue.identifier] = nil venues = venues.sorted{ $0.location?.distance ?? 0 < $1.location?.distance ?? 0 } if let index = venues.index(where: {$0.identifier == venue.identifier}) { completion?(index) } } func imageForVenue(_ venue: CSHVenue, completion: ((_ index: Int) -> Void)?) { guard images[venue.identifier] == nil, let photo = venue.photo else { return } DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { [weak self] in guard let url = URL(string: photo), let imageData = try? Data(contentsOf: url) else { return } self?.images[venue.identifier] = imageData DispatchQueue.main.sync(execute: { [weak self] in guard let index = self?.venues.index(where: { $0.identifier == venue.identifier }) else { return } completion?(index) }) }) } func venueImage(at indexPath: IndexPath) -> UIImage? { guard let venue = venue(at: indexPath) else { return nil } return UIImage(data: images[venue.identifier] ?? Data()) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return venues.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: CSHVenueTableViewCell.reusableIdentifier(), for: indexPath) as? CSHVenueTableViewCell else { return UITableViewCell() } cell.model = CSHVenueCellViewModel(venue: venues[indexPath.row], image: venueImage(at: indexPath)) return cell } } <file_sep>// // VenuesManager.swift // CoffeeShop // // Created by <NAME> on 4/20/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import CoreLocation import RxCocoa import RxSwift extension Array where Element: Hashable { var unique: [Element] { return Array(Set(self)) } } // 1. get all venues of a certain type // 2. check for duplicates with the main pool of venues // 3. get all tips for non duplicate venues // 4. check for venues whose tips contain keywords like "free wifi" etc // 5. call "didFindWirelessVenue" for wifi tagged venues // 6. get the venues public photos webpath class CSHVenuesManager: NSObject { fileprivate struct Constants { static let standardLookupRadius = "2500" static let defaultWifiEnabledVenueNames = ["starbucks", "caffe nero", "pizza express", "harris + hoole"] } fileprivate let location: CLLocation! fileprivate let disposeBag = DisposeBag() override init() { self.location = CLLocation() super.init() } init(location: CLLocation) { self.location = location super.init() } var startLookingForVenues: Observable<Void> { return Observable.create { observer in observer.on(.next()) observer.on(.completed) return Disposables.create() } } func lookForVenuesWithWIFI() -> Observable<[CSHVenue]> { let defaultWirelessVenues = CSHFoursquareClient.sharedInstance.venues(at: location, queries: Constants.defaultWifiEnabledVenueNames, radius: Constants.standardLookupRadius) let coffeeWirelessVenues = CSHFoursquareClient.sharedInstance.coffeeVenues(at: location, radius: Constants.standardLookupRadius) let foodWirelessVenues = CSHFoursquareClient.sharedInstance.foodVenues(at: location, radius: Constants.standardLookupRadius) let venues = Observable.combineLatest(coffeeWirelessVenues, foodWirelessVenues, resultSelector: {$0 + $1}) return venues .observeOn(MainScheduler.instance) .flatMapLatest { venues -> Observable<[CSHVenue: [CSHVenueTip]]> in return Observable .from(venues.removeDuplicates().map{ CSHFoursquareClient.sharedInstance.venueTips(for: $0) }) .merge() .filter { (tip: [CSHVenue : [CSHVenueTip]]) -> Bool in tip.values.first?.index(where: { $0.isWIFI() }) != nil } } .flatMapLatest { venueTips -> Observable<[CSHVenue]> in let venues = venueTips.flatMap({ (tip: (key: CSHVenue, value: [CSHVenueTip])) -> CSHVenue in return tip.key }) return Observable.combineLatest(defaultWirelessVenues, Observable.from(venues), resultSelector: {$0 + $1}) } } func lookForPhotos(of venues: [CSHVenue]) -> Observable<[CSHVenue]> { let result = venues.flatMap ({ CSHFoursquareClient.sharedInstance.venuePhotos(for: $0).flatMap { photo -> Observable<CSHVenue> in guard let identifier = photo.keys.first, let url = photo.values.first else { return Observable.empty() } venues.updateVenue(identifier, withPhotoURL: url) if let venue = venues.venue(for: identifier) { return Observable.just(venue) } return Observable.empty() } }) return Observable.from(result).merge().toArray() } } <file_sep>// // CSHFoursquareClient.swift // CoffeeShop // // Created by <NAME> on 4/24/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import MapKit import Alamofire import AlamofireObjectMapper import RxCocoa import RxSwift private struct CSHFoursquareRequest { let location: CLLocation? let radius: String? let queryParameter: String? let queryType: String let version: String let sortByDistance: String let limit: String let identifier: String? let isForPhotos: Bool init(location: CLLocation, radius: String, queryParameter: String, queryType: String = "query", version: String = "20150420", sortByDistance: String = "1", limit: String = "100") { self.location = location self.radius = radius self.queryParameter = queryParameter self.queryType = queryType self.version = version self.sortByDistance = sortByDistance self.limit = limit self.identifier = nil self.isForPhotos = false } init(identifier: String, forPhotos: Bool = false, version: String = "20150420", sortByDistance: String = "1", limit: String = "100", queryType: String = "query") { self.identifier = identifier self.location = nil self.radius = nil self.queryParameter = nil self.queryType = queryType self.version = version self.sortByDistance = sortByDistance self.limit = limit self.isForPhotos = forPhotos } fileprivate var venueResources: [String: String] { return ["client_id": CSHConfiguration.sharedInstance.foursquareClientID, "client_secret": CSHConfiguration.sharedInstance.foursquareClientSecret, "v": version, "sort": "recent"] } fileprivate var venues: [String: String] { guard let location = location else { return [:] } let latitudeLongitude = String(format: "%.8f,%.8f", location.coordinate.latitude, location.coordinate.longitude) return ["ll": latitudeLongitude, "client_id": CSHConfiguration.sharedInstance.foursquareClientID, "client_secret": CSHConfiguration.sharedInstance.foursquareClientSecret, queryType: queryParameter ?? "", "v": version, "radius": radius ?? "2000", "sortByDistance": sortByDistance, "limit": limit] } func asString() -> String { let sink: [URLQueryItem] = location.map { _ in venues.map{ URLQueryItem(name: $0.0, value: $0.1) } } ?? venueResources.map{ URLQueryItem(name: $0.0, value: $0.1) } var components = URLComponents() components.queryItems = sink components.scheme = CSHConfiguration.sharedInstance.foursquareProtocol components.host = CSHConfiguration.sharedInstance.foursquareHost components.path = location.map { _ in CSHConfiguration.sharedInstance.foursquarePath } ?? "/v2/venues/\(identifier ?? "")/\(isForPhotos ? "photos": "tips")" return components.string ?? "" } } private enum CSHVenueResourceType { case tip(String) case photo(String) var request: String? { switch self { case .tip(let identifier): return CSHFoursquareRequest(identifier: identifier).asString() case .photo(let identifier): return CSHFoursquareRequest(identifier: identifier, forPhotos: true).asString() } } } typealias CSHVenuesCompletionBlock = ([CSHVenue]?, Error?) -> Void final class CSHFoursquareClient { static let sharedInstance = CSHFoursquareClient() internal required init() {} fileprivate func venues(at location: CLLocation, query: String, queryType: String, radius: String) -> Observable<[CSHVenue]> { return Observable.create { observer in let request = CSHFoursquareRequest(location: location, radius: radius, queryParameter: query) let path = request.asString() let requestRef = Alamofire.request(path).responseObject{ (response: DataResponse<CSHFoursquareResponse>) in if let value = response.result.value, let items = value.response?.items { observer.on(.next(items.flatMap{ $0.venue })) observer.on(.completed) } else if let error = response.result.error { observer.onError(error) } } return Disposables.create(with: { requestRef.cancel() }) } } func coffeeVenues(at location: CLLocation, radius: String) -> Observable<[CSHVenue]> { return venues(at: location, query: "coffee", queryType: "section", radius: radius) } func foodVenues(at location: CLLocation, radius: String) -> Observable<[CSHVenue]> { return venues(at: location, query: "food", queryType: "section", radius: radius) } fileprivate let disposeBag = DisposeBag() func venues(at location: CLLocation, queries: [String], radius: String) -> Observable<[CSHVenue]> { return Observable .from(queries.map { self.venues(at: location, query: $0, queryType: "query", radius: radius) }) .merge() .reduce([CSHVenue](), accumulator: { var sink = $0 sink.append(contentsOf: $1) return sink }) } typealias CSHFoursquareVenueTipsCompletion = (([String: [CSHVenueTip]]?, Error?) -> Void) typealias CSHFoursquareVenueTipResponse = CSHFoursquareVenueResourceResponse<CSHFoursquareVenueTipResponseObject> func venueTips(for venue: CSHVenue) -> Observable<[CSHVenue: [CSHVenueTip]]> { guard let resourceRequest = CSHVenueResourceType.tip(venue.identifier).request else { return Observable.just([:]) } return Observable.create{ observer in let requestRef = Alamofire.request(resourceRequest).responseObject{ (response: DataResponse<CSHFoursquareVenueTipResponse>) in if let value = response.result.value, let items = value.response?.tips?.items { observer.on(.next([venue: items])) observer.on(.completed) } else if let error = response.result.error { observer.onError(error) } } return Disposables.create(with: { requestRef.cancel() }) } } typealias CSHFoursquareVenuePhotosCompletion = (([String: [CSHVenuePhoto]]?, Error?) -> Void) typealias CSHFoursquareVenuePhotoResponse = CSHFoursquareVenueResourceResponse<CSHFoursquareVenuePhotoResponseObject> func venuePhotos(for venue: CSHVenue) -> Observable<[String: String]> { guard let request = CSHVenueResourceType.photo(venue.identifier).request else { return Observable.just([:]) } return Observable.create{ observer in let requestRef = Alamofire.request(request).responseObject{ (response: DataResponse<CSHFoursquareVenueResourceResponse<CSHFoursquareVenuePhotoResponseObject>>) in if let value = response.result.value, let items = value.response?.photo?.items { if let photo = items.index (where: { $0.source?.name.range(of: "iOS") != nil }).map ({ items[$0] }) { observer.on(.next([venue.identifier: photo.url])) } observer.on(.completed) } else if let error = response.result.error { observer.onError(error) } } return Disposables.create(with: { requestRef.cancel() }) } } } <file_sep>// // CSHConfiguration.swift // CoffeeShop // // Created by <NAME> on 8/6/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation struct CSHConfiguration { static let sharedInstance = CSHConfiguration() fileprivate var keys: [String:Any] = [:] fileprivate var foursquareAPIKey: [String:String]? { get { return self.keys["FoursquareAPI"] as? [String:String] } } fileprivate init() { if let keysPath = Bundle.main.path(forResource: "configuration", ofType: "plist") { keys = (NSDictionary(contentsOfFile: keysPath) as? [String: AnyObject])! } } var foursquareClientID: String { return foursquareAPIKey?["ClientID"] ?? "" } var foursquareClientSecret: String { return foursquareAPIKey?["ClientSecret"] ?? "" } var foursquareProtocol: String { return foursquareAPIKey?["Protocol"] ?? "" } var foursquareHost: String { return foursquareAPIKey?["Host"] ?? "" } var foursquarePath: String { return foursquareAPIKey?["Path"] ?? "" } } <file_sep>// // TipResponse.swift // CoffeeShop // // Created by <NAME> on 4/19/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import ObjectMapper struct CSHTipResponse: Mappable { var id: String! var createdAt: CUnsignedLong? var text: String! init?(map: Map) { } mutating func mapping(map: Map) { id <- map["id"] createdAt <- map["createdAt"] text <- map["text"] } } <file_sep>// // ShopsListViewController.swift // CoffeeShop // // Created by <NAME> on 4/24/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import MapKit import RxCocoa import RxSwift class ShopsListViewController: UIViewController, UITableViewDelegate { fileprivate struct Constants { static let ExpandedTableViewCellSize:CGFloat = 300 static let NormalTableViewCellSize:CGFloat = 110 static let TableViewInsets = UIEdgeInsetsMake(50, 0, 0, 0) static let PushSegueIdentifier = "PushSegue" } fileprivate var locationManager: CSLocationManager! fileprivate var location: CLLocation? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchingMessageLabel: UILabel! @IBOutlet weak var pulsatingButton: CSPulsatingButton! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var topBarView: UIView! @IBOutlet weak var progressBar: M13ProgressViewSegmentedBar! @IBOutlet weak var yPosProgressBarConstraint: NSLayoutConstraint! @IBOutlet fileprivate weak var tableViewAnimation: CSTableViewAnimation! @IBOutlet fileprivate weak var dataController: ShopsListDataController! var tableViewController: UITableViewController! var refreshControl: UIRefreshControl = UIRefreshControl() fileprivate var selectedCellIndexPath: IndexPath? fileprivate var previouslySelectedCellIndexPath: IndexPath? fileprivate var venuesManager: CSHVenuesManager! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() locationManager = CSLocationManager() tableView.contentInset = Constants.TableViewInsets progressBar.configure() // Do any additional setup after loading the view. refreshControl.setup(in: tableView, viewController: self, selector: #selector(self.setupLocationObserver)) setupLocationObserver() setupTableViewObserver() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let shopsMapViewController = segue.destination as? ShopsMapViewController, segue.identifier == Constants.PushSegueIdentifier else { return } shopsMapViewController.annotations = dataController.annotations shopsMapViewController.location = location } fileprivate func setupTableViewObserver() { tableView.rx.itemSelected .subscribe(onNext: { [unowned self] indexPath in self.selectedCellIndexPath = indexPath self.tableView.reloadRows(at: [indexPath], with: .none) self.previouslySelectedCellIndexPath = self.selectedCellIndexPath != self.previouslySelectedCellIndexPath ? self.selectedCellIndexPath : nil }) .addDisposableTo(disposeBag) } @objc private func setupLocationObserver() { locationManager.locationDidUpdate .flatMapLatest({ [unowned self] location -> Observable<[CSHVenue]> in guard let location = location else { return Observable.just([]) } self.location = location self.startLookingForVenues() self.venuesManager = CSHVenuesManager(location: location) return self.venuesManager.lookForVenuesWithWIFI() }) .flatMap({ venues -> Observable<[CSHVenue]> in venues.forEach { self.didFindWirelessVenue($0) } return self.venuesManager.lookForPhotos(of: venues) }) .subscribe(onNext: { venues in venues.forEach { self.didFindPhotoForWirelessVenue($0) } }, onCompleted: { [unowned self] _ in self.finishLookingForVenues() }) .addDisposableTo(disposeBag) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let selected = selectedCellIndexPath, selected == indexPath, previouslySelectedCellIndexPath != selectedCellIndexPath { return Constants.ExpandedTableViewCellSize } return Constants.NormalTableViewCellSize } } //MARK: - VenuesManager delegates extension ShopsListViewController { fileprivate func startLookingForVenues() { UIApplication.shared.isNetworkActivityIndicatorVisible = true pulsatingButton.liftAnimation(view: view) } fileprivate func finishLookingForVenues() { UIApplication.shared.isNetworkActivityIndicatorVisible = false let date = Date().stringWithDateFormat("MMM d, h:mm a") let title = "Last update: \(date)" let attrsDictionary = [NSForegroundColorAttributeName: UIColor.white] let attributedTitle = NSAttributedString(string: title, attributes: attrsDictionary) progressBar.isHidden = true pulsatingButton.dropAnimation(view: view) { $0?.animate() } tableView.reloadData() refreshControl.attributedTitle = attributedTitle; refreshControl.endRefreshing() } func didFailToFindVenueWithError(_ error: NSError!) { print("ERROR: \(error)") } func didFindPhotoForWirelessVenue(_ venue: CSHVenue) { dataController.imageForVenue(venue) { index in self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.fade) } } func didFindWirelessVenue(_ venue: CSHVenue?) { guard let venue = venue else { return } dataController.addVenue(venue) { index in self.searchingMessageLabel.isHidden = true self.progressBar.animateInView(self.view, completion: nil) self.tableView.insertRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.fade) } } } //MARK: - CSPulsatingButtonDelegate extension ShopsListViewController: CSPulsatingButtonDelegate { func didPressPulsatingButton(_ sender: UIButton!) { } } <file_sep>// // ShopsMapViewController.swift // CoffeeShop // // Created by <NAME> on 4/24/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import MapKit class ShopsMapViewController: UIViewController {//, MKMapViewDelegate { @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var pulsatingButton: UIButton! @IBOutlet weak var mapView: MKMapView! var annotations: [MKPointAnnotation]? var location: CLLocation? fileprivate let MetersPerMile = 1609.344 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. guard let coordinates = self.location?.coordinate, let annotations = self.annotations, let viewRegion = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: coordinates.latitude, longitude: coordinates.longitude), 4*MetersPerMile, 4*MetersPerMile) as MKCoordinateRegion? else { return } // 3 mapView.setRegion(viewRegion, animated: true) mapView.addAnnotations(annotations) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func actionButtonTapped(_ sender: UIButton) { self.navigationController?.popViewController(animated: true) } } <file_sep>// // CSHVenueCellViewModel.swift // CoffeeShop // // Created by <NAME> on 10/18/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation struct CSHVenueCellViewModel { fileprivate (set) var name: String fileprivate (set) var rating: String fileprivate (set) var ratingColor: UIColor fileprivate (set) var price: String fileprivate (set) var openingHours: String fileprivate (set) var previewImage: UIImage fileprivate (set) var distance: String fileprivate (set) var street: String fileprivate (set) var cityPostCode: String init(venue: CSHVenue, image: UIImage?) { self.name = venue.name if let rating = venue.rating { self.rating = String(format: "%.1f", rating) } else { self.rating = "" } self.ratingColor = UIColor(hexString: venue.ratingColor ?? "") ?? UIColor.gray self.price = [String](repeating: venue.price?.currency ?? "€", count: venue.price?.tier ?? 1).reduce("", +) if let status = venue.hours?.status { self.openingHours = status } else { self.openingHours = venue.hours?.isOpen ?? false ? "Open" : "" } self.previewImage = image ?? UIImage() self.distance = "\(venue.location?.distance ?? 0) m" self.street = venue.location?.address ?? "" self.cityPostCode = venue.address } } <file_sep>// // CSGroupItems.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSGroupItems: Mappable { var venue: CSHVenue? var tips: [String]? var referralId: String? var reasons: [String: AnyObject]? init?(map: Map) { } mutating func mapping(map: Map) { venue <- map["venue"] tips <- map["tips"] referralId <- map["referralId"] reasons <- map["reasons"] } } <file_sep>// // VenueAnnotation.swift // CoffeeShop // // Created by <NAME> on 5/3/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import Foundation import MapKit import AddressBook struct CSHVenueAnnotation { let title: String let subtitle: String let coordinate: CLLocationCoordinate2D init(name: String, address: String, coordinate: CLLocationCoordinate2D) { self.title = name self.subtitle = address self.coordinate = coordinate } } <file_sep>// // UIRefreshControl+CSAdditions.swift // CoffeeShop // // Created by <NAME> on 3/17/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation extension UIRefreshControl { func setup(in parentTableView: UITableView, viewController: UIViewController, selector: Selector) { self.backgroundColor = UIColor.clear self.tintColor = UIColor.white self.addTarget(viewController, action: selector, for: UIControlEvents.valueChanged) parentTableView.insertSubview(self, at: 0) } } <file_sep>// // CSVenueTip.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHVenueTip: Mappable { var identifier: String? var createdAt: UInt? var text: String? var photourl: String? init?(map: Map) { } mutating func mapping(map: Map) { identifier <- map["id"] createdAt <- map["createdAt"] text <- map["text"] photourl <- map["photourl"] } func isWIFI() -> Bool { guard let venueTip = self.text else { return false } let containsWifi = venueTip.range(of: "wifi") != nil let hasWifi = venueTip.range(of: "no wifi") == nil && venueTip.range(of: "no free wifi") == nil && venueTip.range(of: "no wi-fi") == nil && venueTip.range(of: "no free wi-fi") == nil return containsWifi && hasWifi } } struct CSHFoursquareVenueResourceResponse<T>: Mappable where T:Mappable { var meta: CSHFoursquareResponseMeta? var response: T? init?(map: Map){ } mutating func mapping(map: Map) { meta <- map["meta"] response <- map["response"] } } struct CSHFoursquareVenueTipResponseObject: Mappable { var tips: CSHFoursquareVenueResourceData<CSHVenueTip>? init?(map: Map){ } mutating func mapping(map: Map) { tips <- map["tips"] } } struct CSHFoursquareVenueTipData: Mappable { var count: Int? var items: [CSHVenueTip]? init?(map: Map){ } mutating func mapping(map: Map) { count <- map["count"] items <- map["items"] } } struct CSHFoursquareVenueResourceData<T>: Mappable where T:Mappable { var count: Int? var items: [T]? init?(map: Map){ } mutating func mapping(map: Map) { count <- map["count"] items <- map["items"] } } struct CSHFoursquareVenuePhotoResponseObject: Mappable { var photo: CSHFoursquareVenueResourceData<CSHVenuePhoto>? init?(map: Map){ } mutating func mapping(map: Map) { photo <- map["photos"] } } <file_sep>// // CSLocation.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHLocation: Mappable { var address: String? var city: String? var country: String? var cc: String? var postalCode: String? var state: String? var distance: Int? var lat: Double? var lng: Double? init?(map: Map) { } mutating func mapping(map: Map) { address <- map["address"] city <- map["city"] country <- map["country"] cc <- map["cc"] postalCode <- map["postalCode"] state <- map["state"] distance <- map["distance"] lat <- map["lat"] lng <- map["lng"] } } <file_sep>// // CSHVenuePhoto.swift // CoffeeShop // // Created by <NAME> on 8/29/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHVenuePhotoSource: Mappable { var name: String! var url: String! init?(map: Map){ } mutating func mapping(map: Map) { name <- map["name"] url <- map["url"] } } struct CSHVenuePhoto: Mappable { var identifier: String! var createdAt: Int? var width: Int? var height: Int? var prefix: String? var suffix: String? var visibility: String? var source: CSHVenuePhotoSource? var url: String { get { guard let prefix = self.prefix, let width = self.width, let height = self.height, let suffix = self.suffix else { return "" } return "\(prefix)\(width)x\(height)\(suffix)" } } init?(map: Map){ } mutating func mapping(map: Map) { identifier <- map["id"] createdAt <- map["createdAt"] width <- map["width"] height <- map["height"] prefix <- map["prefix"] suffix <- map["suffix"] source <- map["source"] } } <file_sep>// // LocationManager.swift // CoffeeShop // // Created by <NAME> on 4/20/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import CoreLocation import RxCocoa import RxSwift class CSLocationManager: NSObject { typealias CompletionBlock_t = (_ location: CLLocation?, _ error: NSError?) -> Void fileprivate let locationManager: CLLocationManager = CLLocationManager() fileprivate var completion:CompletionBlock_t? var locationDidUpdate: Observable<CLLocation?> { return Observable.create { observer in self.start { location, error in if let error = error, error.code > 0 { observer.on(.error(error)) return } observer.on(.next(location)) observer.on(.completed) } return Disposables.create() } } fileprivate func start(_ completion: CompletionBlock_t?) { locationManager.delegate = self self.completion = completion if locationManager.responds(to: #selector(CLLocationManager.requestWhenInUseAuthorization)) { locationManager.requestWhenInUseAuthorization() } else { locationManager.startUpdatingLocation() } } fileprivate func stop() { locationManager.stopUpdatingLocation() } override init() { super.init() if CLLocationManager.locationServicesEnabled() { self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation self.locationManager.distanceFilter = 100.0; } } } extension CSLocationManager: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { locationManager.stopUpdatingLocation() guard let location = locations.last else { return } completion?(location, nil) } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { locationManager.startUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationManager.stopUpdatingLocation() completion?(nil, error as NSError?) } } <file_sep>platform :ios, '9.0' target 'CoffeeShop' do pod 'SVProgressHUD' pod 'GHUnit' pod 'AlamofireObjectMapper', '~> 4.0' use_frameworks! end <file_sep>// // Stats.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHStats: Mappable { var checkins: Int? var tips: Int? var users: Int? init?(map: Map) { } mutating func mapping(map: Map) { checkins <- map["checkinsCount"] tips <- map["tipCount"] users <- map["usersCount"] } } <file_sep>// // Array+Additions.swift // CoffeeShop // // Created by <NAME> on 8/29/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation extension Array where Element:CSHVenue { func removeDuplicates() -> Array { var seen: [String:Bool] = [:] return self.filter{ seen.updateValue(false, forKey: $0.identifier) ?? true } } func updateVenue(_ identifier: String, withPhotoURL photoURL: String) { guard let venue = self.venue(for: identifier) else { return } venue.photo = photoURL } func venue(for identifier: String) -> CSHVenue? { return self.index { $0.identifier == identifier }.map{ self[$0] } } func contains(_ venue: CSHVenue?) -> Bool { if let venue = venue { return self.venue(for: venue.identifier) != nil } return false } } <file_sep>// // CSGroup.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHGroup: Mappable { var type: String! var name: String? var items: [AnyObject]? init?(map: Map) { } mutating func mapping(map: Map) { type <- map["type"] name <- map["name"] items <- map["items"] } } <file_sep>// // CircleTransitionAnimator.swift // CoffeeShop // // Created by <NAME> on 5/2/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class CircleTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning, CAAnimationDelegate { weak var transitionContext: UIViewControllerContextTransitioning? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let containerView = transitionContext.containerView let fromShopsListViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? ShopsListViewController let fromShopsMapViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? ShopsMapViewController let button = (nil == fromShopsListViewController) ? fromShopsMapViewController?.actionButton : fromShopsListViewController?.actionButton let toShopsMapViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? ShopsMapViewController let toShopsListViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? ShopsListViewController var toViewController: UIViewController! = nil if let tvc = toShopsMapViewController { toViewController = tvc containerView.addSubview(toViewController.view) } else { if let tvc = toShopsListViewController { containerView.addSubview(tvc.view) toViewController = toShopsListViewController } } //4 let circleMaskPathInitial = UIBezierPath(ovalIn: button!.frame) let extremePoint = CGPoint(x: button!.center.x - 0, y: button!.center.y - toViewController.view.bounds.height) let radius = sqrt((extremePoint.x*extremePoint.x) + (extremePoint.y*extremePoint.y)) let circleMaskPathFinal = UIBezierPath(ovalIn: button!.frame.insetBy(dx: -radius, dy: -radius)) //5 let maskLayer = CAShapeLayer() maskLayer.path = circleMaskPathFinal.cgPath toViewController.view.layer.mask = maskLayer //6 let maskLayerAnimation = CABasicAnimation(keyPath: "path") maskLayerAnimation.fromValue = circleMaskPathInitial.cgPath maskLayerAnimation.toValue = circleMaskPathFinal.cgPath maskLayerAnimation.duration = self.transitionDuration(using: transitionContext) maskLayerAnimation.delegate = self maskLayer.add(maskLayerAnimation, forKey: "path") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled) transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from)?.view.layer.mask = nil } } <file_sep>// // CSPulsatingButton.swift // CoffeeShop // // Created by <NAME> on 2/23/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit typealias AnimationCompletionBlock = () -> () private class AnimationCompletionBlockHolder : NSObject { var block : AnimationCompletionBlock! = nil } @IBDesignable class CSPulsatingAnimationButtonItem: UIButton { @IBInspectable var cornerRadius: CGFloat = 22.0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var scaleAnimationToValue: CGFloat = 1.0 @IBInspectable var animationRepeatCount: Float = 20.0 @IBInspectable var completionAnimationKey: String = "" @IBInspectable var fadeAnimationFromValue: Float = 0.5 fileprivate var scaleAnimation: CABasicAnimation! fileprivate var fadeAnimation: CABasicAnimation! fileprivate class CSFadeAnimation: CABasicAnimation { convenience init(fromValue: Any? = 0.5, duration: CFTimeInterval = 1.3, repeatCount: Float = 20.0, delegate: UIView?) { self.init() self.init(keyPath: "opacity") self.fromValue = fromValue self.toValue = NSNumber(value: 0.0 as Float) self.duration = duration self.repeatCount = repeatCount } } fileprivate class CSScaleAnimation: CABasicAnimation { convenience init(toValue: AnyObject?, duration: CFTimeInterval = 1.3, repeatCount: Float = 20.0) { self.init() self.init(keyPath: "transform.scale") self.fromValue = NSNumber(value: 0.2 as Float) self.toValue = toValue self.duration = duration self.repeatCount = repeatCount self.autoreverses = false } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configureForAnimation() { let holder = AnimationCompletionBlockHolder() let completion = { self.isHidden = true } holder.block = completion scaleAnimation = CSScaleAnimation(toValue: scaleAnimationToValue as AnyObject?, repeatCount: animationRepeatCount) fadeAnimation = CSFadeAnimation(repeatCount: animationRepeatCount, delegate: self.superview) fadeAnimation.setValue(holder, forKey: completionAnimationKey) self.layer.setValue(NSNumber(value: 0.2 as Float), forKeyPath: "transform.scale") self.layer.add(fadeAnimation, forKey: "opacity") self.layer.add(scaleAnimation, forKey: nil) self.isHidden = false } func animateWithBlocks() { self.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) UIView.animate(withDuration: 1.3, delay: 0, options: [.repeat], animations: { () -> Void in UIView.setAnimationRepeatCount(self.animationRepeatCount) self.isHidden = false self.alpha = 0.0 self.transform = CGAffineTransform(scaleX: self.scaleAnimationToValue, y: self.scaleAnimationToValue) }, completion: { (finished) -> Void in if finished { self.isHidden = true } }) } } @IBDesignable class CSPulsatingButton: UIView { @IBOutlet fileprivate weak var contentView: UIView? fileprivate var smallButtonScaleAnimation: CABasicAnimation! fileprivate var smallButtonFadeAnimation: CABasicAnimation! fileprivate var mediumButtonScaleAnimation: CABasicAnimation! fileprivate var mediumButtonFadeAnimation: CABasicAnimation! fileprivate var largeButtonScaleAnimation: CABasicAnimation! fileprivate var largeButtonFadeAnimation: CABasicAnimation! @IBOutlet fileprivate weak var largeButton: CSPulsatingAnimationButtonItem! @IBOutlet fileprivate weak var mediumButton: CSPulsatingAnimationButtonItem! @IBOutlet fileprivate weak var smallButton: CSPulsatingAnimationButtonItem! @IBOutlet fileprivate weak var pulsatingButton: UIButton! @IBOutlet fileprivate var animationButtonItems: [CSPulsatingAnimationButtonItem]! @IBInspectable fileprivate var xibName: String? @IBInspectable internal var color: UIColor? weak var delegate: CSPulsatingButtonDelegate? override func awakeFromNib() { loadFromXib() setup() } func loadFromXib() -> UIView? { guard let dotIndex = NSStringFromClass(type(of: self)).range(of: ".") else { return nil } let stringFromClass = NSStringFromClass(type(of: self)) let index = stringFromClass.index(dotIndex.lowerBound, offsetBy:stringFromClass[dotIndex].characters.count) let className = stringFromClass.substring(from: index) guard let xib = Bundle.main.loadNibNamed(className, owner: self, options: nil), let views = xib as? [UIView], views.count > 0 else { return nil } guard let view = xib[0] as? UIView else { return nil } self.addSubview(view) return views[0] } fileprivate func setup() { largeButton.isHidden = true mediumButton.isHidden = true smallButton.isHidden = true pulsatingButton.backgroundColor = color ?? UIColor.clear animationButtonItems.forEach{ $0.backgroundColor = color ?? UIColor.clear } pulsatingButton.addTarget(self, action: #selector(didPressPulsatingButton), for: .touchUpInside) } func animate() { (self.animationButtonItems as NSArray).value(forKey: "configureForAnimation") } internal func animationDidStop(_ animation: CAAnimation, finished flag: Bool) { let completion = animationButtonItems.flatMap { animation.value(forKey: $0.completionAnimationKey) as? AnimationCompletionBlockHolder } guard completion.count > 0 else { return } completion[0].block() } @objc fileprivate func didPressPulsatingButton() { self.delegate?.didPressPulsatingButton(self.pulsatingButton) } } // MARK: Animate the control extension CSPulsatingButton { func dropAnimation(view: UIView) { animate(view: view, constantValue: 0.0, completion: nil) } typealias CSPulsatingButtonCompletion = ((CSPulsatingButton?) -> Void) func dropAnimation(view: UIView, completion: CSPulsatingButtonCompletion?) { animate(view: view, constantValue: 0.0, completion: completion) } func liftAnimation(view: UIView) { animate(view: view, constantValue: -100.0, completion: nil) } func liftAnimation(view: UIView, completion: CSPulsatingButtonCompletion?) { animate(view: view, constantValue: -100.0, completion: completion) } fileprivate func animate(view: UIView, constantValue: CGFloat, completion: CSPulsatingButtonCompletion?) { guard let superview = self.superview else { return } for constraint in superview.constraints { if constraint.firstItem as? NSObject == self && constraint.firstAttribute == .top { constraint.constant = constantValue break } } UIView.animate( withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10.0, options: .curveEaseIn, animations: { view.layoutIfNeeded() }, completion: { [weak self] (complete) in completion?(self) return }) } } protocol CSPulsatingButtonDelegate: NSObjectProtocol { func didPressPulsatingButton(_ sender: UIButton!) } <file_sep>// // MasterDataController.swift // CoffeeShop // // Created by <NAME> on 4/20/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class MasterDataController: NSObject { fileprivate func configureRestKit() { let baseURL = URL(string: "https://api.foursquare.com/v2") // let client = AFHTTPClient(baseURL: baseURL) // // // initialize RestKit // let objectManager = RKObjectManager(HTTPClient: client) // // var venueMapping = RKObjectMapping.mappingForClass(Venue) // venueMapping.addAttributeMappingsFromDictionary(["name": "name", // "id" : "identifier"]) // // var locationMapping = RKObjectMapping.mappingForClass(Location) // RKObjectMapping *locationMapping = [RKObjectMapping mappingForClass:[Location class]]; // [locationMapping addAttributeMappingsFromDictionary:@{ @"address" : @"address", // @"city" : @"city", // @"country" : @"country", // @"crossStreet" : @"crossStreet", // @"postalCode" : @"postalCode", // @"state" : @"state", // @"distance" : @"distance", // @"lat" : @"lat", // @"lng" : @"lng"}]; // // [venueMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"location" toKeyPath:@"location" withMapping:locationMapping]]; // // RKObjectMapping *tipsMapping = [RKObjectMapping mappingForClass:[TipR class]]; // [tipsMapping addAttributeMappingsFromDictionary:@{ @"id": @"identifier", // @"createdAt": @"createdAt", // @"text": @"text"}]; // // RKObjectMapping *statsMapping = [RKObjectMapping mappingForClass:[Stats class]]; // [statsMapping addAttributeMappingsFromDictionary:@{ @"checkinsCount" : @"checkins", // @"tipsCount" : @"tips", // @"usersCount" : @"users"}]; // // [venueMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"stats" toKeyPath:@"stats" withMapping:statsMapping]]; // RKObjectMapping *groupsMapping = [RKObjectMapping mappingForClass:[Group class]]; // [groupsMapping addAttributeMappingsFromDictionary:@{@"name" : @"name", // @"type" : @"type"}]; // // RKObjectMapping *groupItemsMapping = [RKObjectMapping mappingForClass:[GroupItems class]]; // [groupItemsMapping addAttributeMappingsFromDictionary:@{ @"referralId" : @"referralId", // @"reasons": @"reasons"}]; // // [groupItemsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"tips" toKeyPath:@"tips" withMapping:tipsMapping]]; // [groupItemsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"venue" toKeyPath:@"venue" withMapping:venueMapping]]; // [groupsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"items" toKeyPath:@"items" withMapping:groupItemsMapping]]; // RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:groupsMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"response.groups" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; // // [objectManager addResponseDescriptor:responseDescriptor]; } fileprivate func f() { } } <file_sep>// // M13ProgressViewSegmentedBar+CSAdditions.swift // CoffeeShop // // Created by <NAME> on 3/17/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation extension M13ProgressViewSegmentedBar { func configure() { self.progressDirection = M13ProgressViewSegmentedBarProgressDirectionLeftToRight self.indeterminate = true self.segmentShape = M13ProgressViewSegmentedBarSegmentShapeCircle self.primaryColor = UIColor.white self.secondaryColor = UIColor.gray } func animateInView(_ view: UIView, completion: (() -> Void)?) { guard let superview = self.superview else { return } for constraint in superview.constraints { guard constraint.secondItem as? NSObject == self && constraint.firstAttribute == .centerY else { continue } superview.removeConstraint(constraint) let newConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1, constant: 35) newConstraint.isActive = true break } UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 3.0, options: .curveEaseIn, animations: { view.layoutIfNeeded() }, completion: { (complete: Bool) in completion?() }) } } <file_sep>// // WCPulsatingButton.swift // CoffeeShop // // Created by <NAME> on 4/25/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit extension UIButton { func addPulseEffect() { } }<file_sep>// // CSVenue.swift // CoffeeShop // // Created by <NAME> on 4/11/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import ObjectMapper struct CSHHours: Mappable { var status: String? var isOpen: Bool? init?(map: Map){ } mutating func mapping(map: Map) { status <- map["status"] isOpen <- map["isOpen"] } } struct CSHPrice: Mappable { var message: String? var currency: String! var tier: Int? init?(map: Map){ } mutating func mapping(map: Map) { message <- map["message"] currency <- map["currency"] tier <- map["tier"] } } struct CSHFoursquareResponse: Mappable { var meta: CSHFoursquareResponseMeta? var response: CSHFoursquareResponseObject? init?(map: Map){ } mutating func mapping(map: Map) { meta <- map["meta"] response <- map["response"] } } struct CSHFoursquareResponseMeta: Mappable { var code: Int? var requestId: String? init?(map: Map){ } mutating func mapping(map: Map) { code <- map["code"] requestId <- map["requestId"] } } struct CSHFoursquareResponseObject: Mappable { var query: String? var totalResults: Int? var items: [CSHFoursquareResponseObjectGroupItem]? init?(map: Map){ } mutating func mapping(map: Map) { query <- map["query"] totalResults <- map["totalResults"] items <- map["groups.0.items"] } } struct CSHFoursquareResponseObjectGroupItem: Mappable { var venue: CSHVenue? var referralId: String? init?(map: Map){ } mutating func mapping(map: Map) { venue <- map["venue"] referralId <- map["referralId"] } } class CSHVenue: Mappable { var identifier: String! var name: String! var location: CSHLocation? var stats: CSHStats? var rating: Float? var ratingColor: String? var hours: CSHHours? var price: CSHPrice? var photo: String? var address: String { guard let location = self.location, let city = location.city, let postalCode = location.postalCode else { return "" } var result = "" if city.isEmpty == false { result = (result as NSString).appending(city) } if postalCode.isEmpty == false { if result.isEmpty == false && result.characters.last != "," { result = (result as NSString).appending(", ") } result = (result as NSString).appending(postalCode) } var sink:[String] = [] if city.isEmpty == false { sink.append(city) } if postalCode.isEmpty == false { sink.append(postalCode) } if sink.count > 1 { return sink.joined(separator: ", ") } if sink.count > 0 { return sink[0] } return "" } required init?(map: Map){ } func mapping(map: Map) { identifier <- map["id"] name <- map["name"] location <- map["location"] stats <- map["stats"] rating <- map["rating"] ratingColor <- map["ratingColor"] hours <- map["hours"] price <- map["price"] } } extension CSHVenue: Hashable { /// The hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { return identifier.characters.flatMap{Int(String($0))}.reduce(0, +) } public static func ==(_ lhs: CSHVenue, _ rhs: CSHVenue) -> Bool { return lhs.identifier == rhs.identifier } } <file_sep>// // VenueCell.swift // CoffeeShop // // Created by <NAME> on 2/20/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit @objc (CSHVenueTableViewCell) final class CSHVenueTableViewCell: UITableViewCell { @IBOutlet fileprivate weak var nameLabel: UILabel! @IBOutlet fileprivate weak var distanceLabel: UILabel! @IBOutlet fileprivate weak var streetAddress: UILabel! @IBOutlet fileprivate weak var cityPostCodeAddress: UILabel! @IBOutlet fileprivate weak var priceLabel: UILabel! @IBOutlet fileprivate weak var ratingLabel: UILabel! @IBOutlet fileprivate weak var previewImage: UIImageView! @IBOutlet fileprivate weak var openingHoursLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } var model: CSHVenueCellViewModel? { didSet { configure(model: model) } } func configure(model: CSHVenueCellViewModel?) { guard let cellViewModel = model else { return } self.nameLabel.text = cellViewModel.name self.ratingLabel.text = "" self.ratingLabel.text = cellViewModel.rating self.ratingLabel.backgroundColor = cellViewModel.ratingColor self.priceLabel.text = cellViewModel.price self.openingHoursLabel.text = cellViewModel.openingHours self.previewImage.image = cellViewModel.previewImage self.distanceLabel.text = cellViewModel.distance self.streetAddress.text = cellViewModel.street self.cityPostCodeAddress.text = cellViewModel.cityPostCode self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale } class func reusableIdentifier() -> String { return NSStringFromClass(self) } } <file_sep>// // CSTableAnimation.swift // CoffeeShop // // Created by <NAME> on 2/19/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit @IBDesignable class CSTableViewAnimation: NSObject { fileprivate enum Constants { static let DefaultDuration = 1.5 static let DefaultDelay = 0.05 } @IBOutlet weak var owner: UITableView! @IBInspectable var duration: TimeInterval @IBInspectable var delay: TimeInterval @IBInspectable var dampingRatio: CGFloat @IBInspectable var velocity: CGFloat override required init() { self.duration = Constants.DefaultDuration self.delay = Constants.DefaultDelay self.dampingRatio = 0.0 self.velocity = 0.0 } fileprivate func hideCell(_ cell: UITableViewCell) { cell.transform = CGAffineTransform(translationX: 0, y: owner.bounds.size.height); cell.alpha = 0; } fileprivate func showCell(_ cell: UITableViewCell) { guard let row = owner.indexPath(for: cell)?.row else { return } UIView.animate(withDuration: Constants.DefaultDuration, delay: Constants.DefaultDelay * Double(row), usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: [], animations: { cell.transform = CGAffineTransform(translationX: 0, y: 0); cell.alpha = 1.0 }, completion: nil) } func play() { self.owner.reloadData() _ = owner.visibleCells.map { hideCell($0) } _ = owner.visibleCells.map { showCell($0) } } }
1ff577250b5a6e4799f5033fe9adf4f78f9ee65f
[ "Swift", "Ruby" ]
28
Swift
eigams/Woffee
db105a5e078716bc8f2974f52e843664807a7b64
b4afa554922b7a5402b84a2809da4fa5dd50beb7
refs/heads/main
<repo_name>rowemac/class-022221-JSProject-Frontend<file_sep>/index.js // BASELINE BUILD - RECOMMENDED START UP document.addEventListener("click", (event)=>{ console.log("💻🔬👀:: You Just Clicked on == ", event.target) } ) //// 'Listen To TheDOM🌌🧘🌠👁✨' // Initially showTheForm === false let showTheForm = false; const API_DATABASE_URL = "http://localhost:3000/toys" // console.log("Hey! This is our Toy Database URL ->", API_DATABASE_URL) document.addEventListener("DOMContentLoaded", function(){ console.log("WE, ARE,, LIVE🙆🏾‍♂️✨") const actorFormContainer = document.querySelector(".container"); // Hide & Seek With The Form ;) const buttonToShowUsTheForm = document.querySelector("#new-actor-btn"); buttonToShowUsTheForm.addEventListener("click", () => { // Hide & Seek With The Form ;) showTheForm = !showTheForm; // Working as a Toggle // Initially showTheForm === false if (showTheForm) { actorFormContainer.style.display = "block"; } else { actorFormContainer.style.display = "none"; } }); // *** LAGGING ON FIRST CLICK // *** MOVE THIS DOWN *** const renderToy =(toyObj)=> { // Creating a Display in a Card for each Toy // Create the Outer Wrapping/Containing Element //// - In this case a <div> const cardDiv = document.createElement("div") // Assigning any classes etc to it //// - In this case: class="card" cardDiv.classList.add("card") cardDiv.setAttribute("data-id", toyObj.id) cardDiv.id = toyObj.id // use innerHTML to create the inner elements cardDiv.innerHTML = ` <h2 id="lesseeee" data-id="${toyObj.id}">${toyObj.name}</h2> <img src=${toyObj.image} class="toy-avatar" /> 🙌<p> ${toyObj.likes} Cheers </p>🙌 <button data-id="${toyObj.id}" class="like-btn">✨🙌👏CHEER!👏🙌✨</button> <button data-id="${toyObj.id}" class="edit-btn"> 🎭EDIT THIS ACTOR🎩 </button> <button data-id="${toyObj.id}" class="delete-btn"> DELETE🚁💫🚂? </button> ` // *** SHOW HOW TO ADJUST SIZING *** // // *** SHOW THIS WITH CREATE ELEMENT *** // // SSSlap it on the DOM (toy-collection) // cardDiv.innerText = `<p> Tsam </p>` // console.log(cardDiv) // cardDiv.innerHTML = `<p> HSAM </p>` // console.log(cardDiv) const collectionDiv = document.querySelector("#toy-collection") collectionDiv.append(cardDiv) } const renderAllToys =(toyArray)=> { toyArray.forEach(toyObj => { renderToy(toyObj) } ) //// Using a (ForOfLoop) // for(let toyObj of toyArray){ // renderToy(toyObj) // } } //===== BASIC GET FETCH PROCESS ======== fetch(API_DATABASE_URL).then(response => response.json()) .then(fetchedArray => { console.log(fetchedArray); renderAllToys(fetchedArray) // fetchedArray.forEach(arrayObj => console.log(arrayObj) ) }) //// !! //// (fetchedArray => { //// .then(console.log) // // console.log(">>>>>>>>>>>", fetchedArray) // WE DON'T HAVE ACCESS OUTSIDE OF FETCH :( // fetch(API_DATABASE_URL).then(response => response.json()) // .then(console.log) // // .then(whatWeFetched => {console.log(whatWeFetched)} ) // What We Are Going to Decide to Do With The Data // fetch(API_DATABASE_URL).then(response => response.json()) // .then(fetchedArray => { // fetchedArray.forEach(arrayObj => console.log(arrayObj) ) // }) //// !! //// (fetchedArray => { // // //then(console.log) // //===== BASIC GET FETCH PROCESS ======== //===== POST FETCH PROCESS ======== // Connecting 'JS-Puppet-Strings' to The New Toy Form const newToyForm = document.querySelector(".add-toy-form") newToyForm.addEventListener("submit", event =>{ event.preventDefault(); // console.log("**********", event.target) //// THIS IS NOT CODE THAT WILD MAKE THE POST HAPPEN //// This Console.loging The Main Event of Focus: >>>> "submit" <<<< // Getting User Form Input Data 📋🖋🤪 const name = event.target.name.value const image = event.target.image.value const submit = event.target.submit console.log("SHOW ME SUBMIT - IN THE FORM: ", submit) //// This will ONLY show up upon hitting The "SUBMIT" Button fetch(API_DATABASE_URL, { method: "POST", headers: { "Content-Type": "application/json"}, body: JSON.stringify({ "name": name, "image": image, "likes": 222 /* WHAT WE ARE POSTING */ }) }) .then(response => response.json()) .then(theThingWePostedButFromTheServer => renderToy(theThingWePostedButFromTheServer) ) //.then(theThingWePosted => console.log("Hey! This is what we posted 📋🤓👍: ", theThingWePosted)) // event.target.reset() // *** SHOWING CLEARING VALUES WITH AN EMPTY STRING *** // // *** SHOWING PAGE AUTO SCROLLING AFTER POST *** // }) //// addEventListener("submit", event =>{ // newToyForm.addEventListener("submit", event =>{ console.log(event) }) // newToyForm.addEventListener("submit", event =>{ console.log(event.target) }) // *** 3rd .then() - Getting all Attributes + try/catch *** // //======== DELETE + EDIT FETCH (Based on Buttons) ======== const cardsCollection = document.querySelector("#toy-collection") // console.log(cardsCollection) //// *** // *** ?? *** ASK *** Why Not Submit cardsCollection.addEventListener("click", event =>{ event.preventDefault(); // console.log(event.target) //// // if(event.target.matches(".delete-btn")){ console.log(event.target) } // if(event.target.matches(".delete-btn")){ console.log(event.target.dataset.id) } if(event.target.matches(".delete-btn")){ // *** (===) MAKE A VIDEO!! console.log(event.target) const id = event.target.dataset.id const geThatOuttaHeeyah = document.getElementById(id) fetch(`${API_DATABASE_URL}/${id}`, { method: "DELETE", headers: { "Content-Type": "application/json" } }) .then(response => response.json()) .then( // event.target.closest(".card").remove() geThatOuttaHeeyah.remove() ) // fetch(`${API_DATABASE_URL}/${id}`, { // method: "DELETE", // headers: { "Content-Type": "application/json" } // }) // .then(response => response.json()) // .then(theThingWeJustDeleted => console.log("You Just Deleted ->", theThingWeJustDeleted)) } if (event.target.matches(".like-btn") ) { // || event.target.matches("img") // const pTagWithLikes = event.target.parent // // closest(".card").querySelector("p") const pTagWithLikes = event.target.closest(".card").querySelector("p") // const pTagWithLikes = document.getElementById(id) *** // const pTagWithLikes = event.target.previousElementSibling const likeCount = parseInt(pTagWithLikes.textContent) // *** parsInt *** // parsInt is like (.to_i) in (Ruby) 🙌 const newLikes = likeCount + 1 const id = event.target.dataset.id // Make a PATCH/EDIT to > /toys/:id const bodyObj = { likes: newLikes } // Sending the Number of Likes fetch(`${API_DATABASE_URL}/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(bodyObj), }) .then(r => r.json()) .then(updatedToy => { console.log(updatedToy) // pessimistic approach: pTagWithLikes.textContent = `${updatedToy.likes} Cheers` }) // Update the number of likes on the DOM // Optimistic approach: // pTagWithLikes.textContent = `${newLikes} Likes` } if (event.target.matches("h2")) { // *** can also show it with a class name *** // // let h2Clicked = false ? == "yes" : "no" // let nameH2 = event.target == const nameH2 = event.target console.log(nameH2) console.log(nameH2.innerText) // const nameH2prevState = event.target // // Hold a Copy of the "Previous State"😏🗃 // **** // console.log(nameH2.innerText) // //nameEditForm = document.createElement() const formForNameH2 = document.createElement("form") formForNameH2.innerHTML = ` Changing Name: <form class="name-change-form"> <h4>Name:</h4> <input type="text" name="name" value="" placeholder={nameH2.innerText} class="input-text" /> <br /> <input type="submit" name="submit" value="Update Actor Name!!!!" class="submit" /> </form> ` console.log(formForNameH2) const samsCard = document.getElementById(nameH2.dataset.id) // const samsCard = document.getElementById(1) console.log(">>>>>>>>", samsCard) // nameH2.document.querySelector // *** EDIT A STATIC FORM *** //// PUT AN EVENT LISTENER ON THE WHOLE FORM !!!! // // // const pTagWithLikes = document.getElementById(id) *** // // // const pTagWithLikes = event.target.previousElementSibling // // const likeCount = parseInt(pTagWithLikes.textContent) // *** parsInt *** // // // parsInt is like (.to_i) in (Ruby) 🙌 // // const newLikes = likeCount + 1 // // // Make a PATCH/EDIT to > /toys/:id let updatedName = event.target.name.value const bodyObj = { name: updatedName } // Sending the New Name const id = event.target.dataset.id fetch(`${API_DATABASE_URL}/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(bodyObj), }) .then(r => r.json()) .then(updatedToy => { console.log(updatedToy) // pessimistic approach: // pTagWithLikes.textContent = `${updatedToy.likes} Cheers` }) // Update the number of likes on the DOM // Optimistic approach: // pTagWithLikes.textContent = `${newLikes} Likes` } //else if(event.target.matches("form")){ console.log("OKAY WE'RE DONE! 😅") } // else if(event.target.matches("form")){ console.log("OKAY WE'RE DONE! 😅") // // nameH2 = nameH2prevState // } //// *** Show Ternary *** //// }) //// !! //// cardsCollection.addEventListener("click", event =>{ event.preventDefault(); }) //// !! //// document.addEventListener("DOMContentLoaded", function(){ // document.addEventListener("DOMContentLoaded", function(){ console.log("WE, ARE,, LIVE🙆🏾‍♂️✨") })<file_sep>/js/actor.js console.log("WE GOT OUR ACTORS IN THE HOUSE?? 🎤👀") // (3) // * * * * CLASS SYNTAX * * * * class Actor{ static all = [] //// state😏🗃 of our Actors -- On the Frontend //// similar to (@@all) constructor(name, imageURL){ this.name = name, this.image = imageURL, Actor.all.push(this) // Actor.all[] << this ~ @actor } // constructor(name, imageURL, knownForSaying){ // this.name = name, // this.image = imageURL, // this.catchPhrase = knownForSaying // Actor.all.push(this) // // Actor.all[] << this ~ @actor // } // DON'T need the Function Syntax for // sayCatchPhrase(){ // console.log(`${this.catchPhrase}`) // } //sayCatchPhrase(){ console.log(`${this.catchPhrase}`) } // this.catchPhrase = function(){ console.log(`${knownForSaying}`) } } const sam = new Actor("Sam", "https://ca.slack-edge.com/T02MD9XTF-U018W9H54N6-6bb69b64ec24-512") const jass = new Actor("Jass", "Jass") // const sam = new Actor("Sam", "https://ca.slack-edge.com/T02MD9XTF-U018W9H54N6-6bb69b64ec24-512", // "WE, ARE,, LIVE!") // const jass = new Actor("Jass", "Jass", // "-hehe-") // const * = new Actor("", "", // "") //// How We Would Make More Actors // *** MAKE US ALL DO SOMETHING *** // -------------------------------- // MONTHS //// [ J , F , M , A ] // // (2) // //// !!💫 (@@all) // // Constructor -- HoverOver😉✨ // Actor.all = [] //// vv !! vv // function Actor(name, imageURL, knownForSaying){ // this.name = name, // this.image = imageURL, // Actor.prototype.catchPhrase = function(){ console.log(`${knownForSaying}`) } // // this.catchPhrase = function(){ console.log(`${knownForSaying}`) } // Actor.all.push(this) // } // const sam = new Actor("Sam", "https://ca.slack-edge.com/T02MD9XTF-U018W9H54N6-6bb69b64ec24-512", // "WE, ARE,, LIVE!") // const jass = new Actor("Jass", "Jass", // "-hehe-") // // crew = [] // // crew.push(sam) // // Actor.all = [] // ^^^^ // // Actor.all.push(this) // // -------------------------------- // // Factory Function // // (1) // function actorMaker(name, imageURL, knownForSaying){ // return{ // name: name, // image: imageURL, // catchPhrase: function(){ console.log(`${knownForSaying}`) } // } // } // const sam = actorMaker("Sam", "https://ca.slack-edge.com/T02MD9XTF-U018W9H54N6-6bb69b64ec24-512", // "WE, ARE,, LIVE!") // const jass = actorMaker("Jass", "Jass", // "-hehe-") // // sam.catchPhrase !! // crew = [] // crew.push(sam) // crew.push(jass) // // --------------------------------
383e46b940c39fe268773d60a2b5ff9ec24efcc2
[ "JavaScript" ]
2
JavaScript
rowemac/class-022221-JSProject-Frontend
08d041b958f2bc924b9f2f3efab95941236503b2
4ecff46708aa8295d67501fc908a35f1728edf62
refs/heads/main
<file_sep>from .cka import CKA __version__ = "0.2"<file_sep>import torch from torchvision.datasets import CIFAR10 from torch.utils.data import DataLoader import torchvision.transforms as transforms import numpy as np import random from torch_cka import CKA from timm.models import vit_base_patch32_224, resnetv2_50x1_bitm def seed_worker(worker_id): worker_seed = torch.initial_seed() % 2**32 np.random.seed(worker_seed) random.seed(worker_seed) g = torch.Generator() g.manual_seed(0) np.random.seed(0) random.seed(0) model1 = resnetv2_50x1_bitm(pretrained=True) model2 = vit_base_patch32_224(pretrained=True) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) batch_size = 256 dataset = CIFAR10(root='../data/', train=False, download=True, transform=transform) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, worker_init_fn=seed_worker, generator=g,) cka = CKA(model1, model2, device='cuda') cka.compare(dataloader) cka.plot_results(save_path="../assets/resnet-vit_compare.png")<file_sep>import os import torch import torch.utils.model_zoo as model_zoo # from torchvision.models import resnet18, resnet34, resnet50, densenet121 from torchvision.datasets import CIFAR10, Flickr8k, STL10, SBDataset from torch.utils.data import DataLoader, Dataset import torchvision.transforms as transforms import torch.nn as nn from functools import partial import pprint from typing import List from warnings import warn from tqdm.notebook import tqdm import matplotlib.pyplot as plt import numpy as np import random from mpl_toolkits import axes_grid1 from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.models import swin_small_patch4_window7_224, resnetv2_50x1_bitm, resnet34, resnetv2_101x1_bitm import pandas as pd from PIL import Image from collections import OrderedDict def seed_worker(worker_id): worker_seed = torch.initial_seed() % 2**32 np.random.seed(worker_seed) random.seed(worker_seed) g = torch.Generator() g.manual_seed(0) np.random.seed(0) random.seed(0) class MLP(nn.Module): def __init__(self, input_dims, n_hiddens, n_class): super(MLP, self).__init__() assert isinstance(input_dims, int), 'Please provide int for input_dims' self.input_dims = input_dims current_dims = input_dims layers = OrderedDict() if isinstance(n_hiddens, int): n_hiddens = [n_hiddens] else: n_hiddens = list(n_hiddens) for i, n_hidden in enumerate(n_hiddens): layers['fc{}'.format(i+1)] = nn.Linear(current_dims, n_hidden) layers['relu{}'.format(i+1)] = nn.ReLU() layers['drop{}'.format(i+1)] = nn.Dropout(0.2) current_dims = n_hidden layers['out'] = nn.Linear(current_dims, n_class) self.model= nn.Sequential(layers) print(self.model) def forward(self, input): input = input.view(input.size(0), -1) assert input.size(1) == self.input_dims return self.model.forward(input) def mnist(input_dims=784, n_hiddens=[256, 256], n_class=10, pretrained=None): model_urls = { 'mnist': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/mnist-b07bb66b.pth' } model = MLP(input_dims, n_hiddens, n_class) if pretrained is not None: m = model_zoo.load_url(model_urls['mnist']) state_dict = m.state_dict() if isinstance(m, nn.Module) else m assert isinstance(state_dict, (dict, OrderedDict)), type(state_dict) model.load_state_dict(state_dict) return model <file_sep>import torch import torch.nn as nn from torch.utils.data import DataLoader from tqdm import tqdm from functools import partial from warnings import warn from typing import List, Dict import matplotlib.pyplot as plt from .utils import add_colorbar class CKA: def __init__(self, model1: nn.Module, model2: nn.Module, model1_name: str = None, model2_name: str = None, model1_layers: List[str] = None, model2_layers: List[str] = None, device: str ='cpu'): """ :param model1: (nn.Module) Neural Network 1 :param model2: (nn.Module) Neural Network 2 :param model1_name: (str) Name of model 1 :param model2_name: (str) Name of model 2 :param model1_layers: (List) List of layers to extract features from :param model2_layers: (List) List of layers to extract features from :param device: Device to run the model """ self.model1 = model1 self.model2 = model2 self.device = device self.model1_info = {} self.model2_info = {} if model1_name is None: self.model1_info['Name'] = model1.__repr__().split('(')[0] else: self.model1_info['Name'] = model1_name if model2_name is None: self.model2_info['Name'] = model2.__repr__().split('(')[0] else: self.model2_info['Name'] = model2_name if self.model1_info['Name'] == self.model2_info['Name']: warn(f"Both model have identical names - {self.model2_info['Name']}. " \ "It may cause confusion when interpreting the results. " \ "Consider giving unique names to the models :)") self.model1_info['Layers'] = [] self.model2_info['Layers'] = [] self.model1_features = {} self.model2_features = {} if len(list(model1.modules())) > 150 and model1_layers is None: warn("Model 1 seems to have a lot of layers. " \ "Consider giving a list of layers whose features you are concerned with " \ "through the 'model1_layers' parameter. Your CPU/GPU will thank you :)") self.model1_layers = model1_layers if len(list(model2.modules())) > 150 and model2_layers is None: warn("Model 2 seems to have a lot of layers. " \ "Consider giving a list of layers whose features you are concerned with " \ "through the 'model2_layers' parameter. Your CPU/GPU will thank you :)") self.model2_layers = model2_layers self._insert_hooks() self.model1 = self.model1.to(self.device) self.model2 = self.model2.to(self.device) self.model1.eval() self.model2.eval() def _log_layer(self, model: str, name: str, layer: nn.Module, inp: torch.Tensor, out: torch.Tensor): if model == "model1": self.model1_features[name] = out elif model == "model2": self.model2_features[name] = out else: raise RuntimeError("Unknown model name for _log_layer.") def _insert_hooks(self): # Model 1 for name, layer in self.model1.named_modules(): if self.model1_layers is not None: if name in self.model1_layers: self.model1_info['Layers'] += [name] layer.register_forward_hook(partial(self._log_layer, "model1", name)) else: self.model1_info['Layers'] += [name] layer.register_forward_hook(partial(self._log_layer, "model1", name)) # Model 2 for name, layer in self.model2.named_modules(): if self.model2_layers is not None: if name in self.model2_layers: self.model2_info['Layers'] += [name] layer.register_forward_hook(partial(self._log_layer, "model2", name)) else: self.model2_info['Layers'] += [name] layer.register_forward_hook(partial(self._log_layer, "model2", name)) def _HSIC(self, K, L): """ Computes the unbiased estimate of HSIC metric. Reference: https://arxiv.org/pdf/2010.15327.pdf Eq (3) """ N = K.shape[0] ones = torch.ones(N, 1).to(self.device) result = torch.trace(K @ L) result += ((ones.t() @ K @ ones @ ones.t() @ L @ ones) / ((N - 1) * (N - 2))).item() result -= ((ones.t() @ K @ L @ ones) * 2 / (N - 2)).item() return (1 / (N * (N - 3)) * result).item() def compare(self, dataloader1: DataLoader, dataloader2: DataLoader = None) -> None: """ Computes the feature similarity between the models on the given datasets. :param dataloader1: (DataLoader) :param dataloader2: (DataLoader) If given, model 2 will run on this dataset. (default = None) """ if dataloader2 is None: warn("Dataloader for Model 2 is not given. Using the same dataloader for both models.") dataloader2 = dataloader1 self.model1_info['Dataset'] = dataloader1.dataset.__repr__().split('\n')[0] self.model2_info['Dataset'] = dataloader2.dataset.__repr__().split('\n')[0] N = len(self.model1_layers) if self.model1_layers is not None else len(list(self.model1.modules())) M = len(self.model2_layers) if self.model2_layers is not None else len(list(self.model2.modules())) self.hsic_matrix = torch.zeros(N, M, 3) num_batches = min(len(dataloader1), len(dataloader1)) for (x1, *_), (x2, *_) in tqdm(zip(dataloader1, dataloader2), desc="| Comparing features |", total=num_batches): self.model1_features = {} self.model2_features = {} _ = self.model1(x1.to(self.device)) _ = self.model2(x2.to(self.device)) for i, (name1, feat1) in enumerate(self.model1_features.items()): X = feat1.flatten(1) K = X @ X.t() K.fill_diagonal_(0.0) self.hsic_matrix[i, :, 0] += self._HSIC(K, K) / num_batches for j, (name2, feat2) in enumerate(self.model2_features.items()): Y = feat2.flatten(1) L = Y @ Y.t() L.fill_diagonal_(0) assert K.shape == L.shape, f"Feature shape mistach! {K.shape}, {L.shape}" self.hsic_matrix[i, j, 1] += self._HSIC(K, L) / num_batches self.hsic_matrix[i, j, 2] += self._HSIC(L, L) / num_batches self.hsic_matrix = self.hsic_matrix[:, :, 1] / (self.hsic_matrix[:, :, 0].sqrt() * self.hsic_matrix[:, :, 2].sqrt()) assert not torch.isnan(self.hsic_matrix).any(), "HSIC computation resulted in NANs" def export(self) -> Dict: """ Exports the CKA data along with the respective model layer names. :return: """ return { "model1_name": self.model1_info['Name'], "model2_name": self.model2_info['Name'], "CKA": self.hsic_matrix, "model1_layers": self.model1_info['Layers'], "model2_layers": self.model2_info['Layers'], "dataset1_name": self.model1_info['Dataset'], "dataset2_name": self.model2_info['Dataset'], } def plot_results(self, save_path: str = None, title: str = None): fig, ax = plt.subplots() im = ax.imshow(self.hsic_matrix, origin='lower', cmap='magma') ax.set_xlabel(f"Layers {self.model2_info['Name']}", fontsize=15) ax.set_ylabel(f"Layers {self.model1_info['Name']}", fontsize=15) if title is not None: ax.set_title(f"{title}", fontsize=18) else: ax.set_title(f"{self.model1_info['Name']} vs {self.model2_info['Name']}", fontsize=18) add_colorbar(im) plt.tight_layout() if save_path is not None: plt.savefig(save_path, dpi=300) plt.show()<file_sep>from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt def add_colorbar(im, aspect=10, pad_fraction=0.5, **kwargs): """Add a vertical color bar to an image plot.""" divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() cax = divider.append_axes("right", size=width, pad=pad) plt.sca(current_ax) return im.axes.figure.colorbar(im, cax=cax, **kwargs)<file_sep>import torch from torchvision.models import resnet18, resnet34, resnet50, wide_resnet50_2 from torchvision.datasets import CIFAR10 from torch.utils.data import DataLoader import torchvision.transforms as transforms import numpy as np import random from torch_cka import CKA def seed_worker(worker_id): worker_seed = torch.initial_seed() % 2**32 np.random.seed(worker_seed) random.seed(worker_seed) g = torch.Generator() g.manual_seed(0) np.random.seed(0) random.seed(0) model1 = resnet18(pretrained=True) model2 = resnet34(pretrained=True) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) batch_size = 256 dataset = CIFAR10(root='../data/', train=False, download=True, transform=transform) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, worker_init_fn=seed_worker, generator=g,) # cka = CKA(model1, model2, # model1_name="ResNet18", model2_name="ResNet34", # device='cuda') # # cka.compare(dataloader) # # cka.plot_results(save_path="../assets/resnet_compare.png") #=============================================================== model1 = resnet50(pretrained=True) model2 = wide_resnet50_2(pretrained=True) cka = CKA(model1, model2, model1_name="ResNet50", model2_name="WideResNet50", device='cuda') cka.compare(dataloader) cka.plot_results(save_path="../assets/resnet-resnet_compare.png")<file_sep># PyTorch Model Compare A tiny package to compare two neural networks in PyTorch. There are many ways to compare two neural networks, but one robust and scalable way is using the **Centered Kernel Alignment** (CKA) metric, where the features of the networks are compared. ### Centered Kernel Alignment Centered Kernel Alignment (CKA) is a representation similarity metric that is widely used for understanding the representations learned by neural networks. Specifically, CKA takes two feature maps / representations ***X*** and ***Y*** as input and computes their normalized similarity (in terms of the Hilbert-Schmidt Independence Criterion (HSIC)) as <img src="assets/cka.png" alt="CKA original version" width="60%" style="display: block; margin-left: auto; margin-right: auto;"> Where ***K*** and ***L*** are similarity matrices of ***X*** and ***Y*** respectively. However, the above formula is not scalable against deep architectures and large datasets. Therefore, a minibatch version can be constructed that uses an unbiased estimator of the HSIC as ![alt text](assets/cka_mb.png "CKA minibatch version") ![alt text](assets/cka_hsic.png "CKA HSIC calculation") The above form of CKA is from the 2021 ICLR paper by [<NAME>., <NAME>, <NAME>](https://arxiv.org/abs/2010.15327). ## Getting Started ### Installation ``` pip install torch_cka ``` ### Usage ```python from torch_cka import CKA model1 = resnet18(pretrained=True) # Or any neural network of your choice model2 = resnet34(pretrained=True) dataloader = DataLoader(your_dataset, batch_size=batch_size, # according to your device memory shuffle=False) # Don't forget to seed your dataloader cka = CKA(model1, model2, model1_name="ResNet18", # good idea to provide names to avoid confusion model2_name="ResNet34", model1_layers=layer_names_resnet18, # List of layers to extract features from model2_layers=layer_names_resnet34, # extracts all layer features by default device='cuda') cka.compare(dataloader) # secondary dataloader is optional results = cka.export() # returns a dict that contains model names, layer names # and the CKA matrix ``` ## Examples `torch_cka` can be used with any pytorch model (subclass of `nn.Module`) and can be used with pretrained models available from popular sources like torchHub, timm, huggingface etc. Some examples of where this package can come in handy are illustrated below. ### Comparing the effect of Depth A simple experiment is to analyse the features learned by two architectures of the same family - ResNets but of different depths. Taking two ResNets - ResNet18 and ResNet34 - pre-trained on the Imagenet dataset, we can analyse how they produce their features on, say CIFAR10 for simplicity. This comparison is shown as a heatmap below. ![alt text](assets/resnet_compare.png "Comparing ResNet18 and ResNet34") We see high degree of similarity between the two models in lower layers as they both learn similar representations from the data. However at higher layers, the similarity reduces as the deeper model (ResNet34) learn higher order features which the is elusive to the shallower model (ResNet18). Yet, they do indeed have certain similarity in their last fc layer which acts as the feature classifier. ### Comparing Two Similar Architectures Another way of using CKA is in ablation studies. We can go further than those ablation studies that only focus on resultant performance and employ CKA to study the internal representations. Case in point - ResNet50 and WideResNet50 (k=2). WideResNet50 has the same architecture as ResNet50 except having wider residual bottleneck layers (by a factor of 2 in this case). ![alt text](assets/resnet-wideresnet_compare.png "Comparing ResNet50 and WideResNet50") We clearly notice that the learned features are indeed different after the first few layers. The width has a more pronounced effect in deeper layers as compared to the earlier layers as both networks seem to learn similar features in the initial layers. As a bonus, here is a comparison between ViT and the latest SOTA model [Swin Transformer](https://arxiv.org/abs/2103.14030) pretrained on ImageNet22k. ![alt text](assets/Swin-ViT-comparison.png "Comparing Swin Transformer and ViT") ### Comparing quite different architectures CNNs have been analysed a lot over the past decade since AlexNet. We somewhat know what sort of features they learn across their layers (through visualizations) and we have put them to good use. One interesting approach is to compare these understandable features with newer models that don't permit easy visualizations (like recent vision transformer architectures) and study them. This has indeed been a hot research topic (see [Raghu et.al 2021](https://arxiv.org/abs/2108.08810)). ![alt text](assets/Vit_ResNet34_comparison.png "Comparing ResNet34 and ViT-Base") ### Comparing Datasets Yet another application is to compare two datasets - preferably two versions of the data. This is especially useful in production where data drift is a known issue. If you have an updated version of a dataset, you can study how your model will perform on it by comparing the representations of the datasets. This can be more telling about actual performance than simply comparing the datasets directly. This can also be quite useful in studying the performance of a model on downstream tasks and fine-tuning. For instance, if the CKA score is high for some features on different datasets, then those can be frozen during fine-tuning. As an example, the following figure compares the features of a pretrained Resnet50 on the Imagenet test data and the VOC dataset. Clearly, the pretrained features have little correlation with the VOC dataset. Therefore, we have to resort to fine-tuning to get at least satisfactory results. ![alt text](assets/VOC-comparison.png "Comparing Imagenet and VOC datasets") ## Tips - If your model is large (lots of layers or large feature maps), try to extract from select layers. This is to avoid out of memory issues. - If you still want to compare the entire feature map, you can run it multiple times with few layers at each iteration and export your data using `cka.export()`. The exported data can then be concatenated to produce the full CKA matrix. - Give proper model names to avoid confusion when interpreting the results. The code automatically extracts the model name for you by default, but it is good practice to label the models according to your use case. - When providing your dataloader(s) to the `compare()` function, it is important that they are [seeded properly](https://pytorch.org/docs/stable/data.html#data-loading-randomness) for reproducibility. - When comparing datasets, be sure to set `drop_last=True` when building the dataloader. This resolves shape mismatch issues - especially in differently sized datasets. ## Citation If you use this repo in your project or research, please cite as - ``` @software{subramanian2021torch_cka, author={<NAME>}, title={torch_cka}, url={https://github.com/AntixK/PyTorch-Model-Compare}, year={2021} } ``` <file_sep>torch torchvision tqdm matplotlib numpy
a1c3cb699351d059a8337539fff50edd344ef5d0
[ "Markdown", "Python", "Text" ]
8
Python
franciszchen/PyTorch-Model-Compare
b4da691f56bdea305ddec807087be12e6291c86e
533557eb5ddc7f3137d14c9ca6a15b19ef23c018
refs/heads/master
<file_sep>import copy from attack_template import AttackTemplate class TemplateGenerator: def __init__(self, correlator, db): self.template_dict = dict() self.correlator = correlator self.db= db def generate(self): # TCP SYN Flooding attack_info = { "name": "TCP SYN Flooding", "consequense": "Denial of Service", "severity": 3, } tcp_syn_flood = AttackTemplate( attack_info, self.correlator, self.db ) tcp_syn_flood.addNode( node_id=0, node_name="address scan", children=[1], alerts=[ [0.4, {"NEW_ORIG": []}], [0.6, {"NEW_RESP": []}], ], pi=0.02, ) tcp_syn_flood.addNode( node_id=1, node_name="tcp syn flooding", parents=[0], q_list=[0.1], alerts=[ [0.7, {"PACKET_AB_TOO_MANY": [], "PACKET_BA_TOO_MANY": []}], [0.2, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], [0.1, {"MEAN_BYTES_AB_TOO_SMALL": [], "MEAN_BYTES_BA_TOO_SMALL": []}], ], ) # TCP SYN Flooding (with rule) attack_info = { "name": "TCP SYN Flooding", "consequense": "Denial of Service", "severity": 3, } tcp_syn_flood_rule = AttackTemplate( attack_info, self.correlator, self.db ) tcp_syn_flood_rule.addNode( node_id=0, node_name="address scan", children=[1], alerts=[ [0.4, {"NEW_ORIG": []}], [0.6, {"NEW_RESP": []}], ], pi=0.02, ) tcp_syn_flood_rule.addNode( node_id=1, node_name="tcp syn flooding", parents=[0], q_list=[0.1], alerts=[ [0.7, {"PACKET_AB_TOO_MANY": [[["flow.tcp_flag_most", 2]]], "PACKET_BA_TOO_MANY": [[["flow.tcp_flag_most", 2]]]}], [0.2, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], [0.1, {"MEAN_BYTES_AB_TOO_SMALL": [], "MEAN_BYTES_BA_TOO_SMALL": []}], ], ) # Data Integrity Attack attack_info = { "name": "Data Integrity Attack", "consequense": "Tampering of Measurement Data", "severity": 2, } data_integrity = AttackTemplate( attack_info, self.correlator, self.db ) data_integrity.addNode( node_id=0, node_name="man in the middle", children=[2], alerts=[ [1, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], ], pi=0.05, ) data_integrity.addNode( node_id=1, node_name="compromised node", children=[2], alerts=[], pi=0.03, ) data_integrity.addNode( node_id=2, node_name="data integrity attack", node_type="OR", parents=[0, 1], q_list=[0.3, 0.05], alerts=[ [1, {"BINARY_FAULT": [], "ANALOG_TOO_LARGE": [], "ANALOG_TOO_SMALL": []}], ], ) # Voltage Tampering Attack attack_info = { "name": "Voltage Tampering Attack", "consequense": "Tampering of Voltage Measurement Data", "severity": 2, } voltage_tampering = AttackTemplate( attack_info, self.correlator, self.db ) voltage_tampering.addNode( node_id=0, node_name="man in the middle", children=[2], alerts=[ [1, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], ], pi=0.05, ) voltage_tampering.addNode( node_id=1, node_name="compromised node", children=[2], alerts=[], pi=0.03, ) voltage_tampering.addNode( node_id=2, node_name="voltage tampering attack", node_type="OR", parents=[0, 1], q_list=[0.3, 0.05], alerts=[ [1, {"ANALOG_TOO_LARGE": [[["measurement_type", "Voltage"]]], "ANALOG_TOO_SMALL": [[["measurement_type", "Voltage"]]]}], ], ) # Command Injection attack_info = { "name": "Command Injection", "consequense": "", "severity": 3, } command_injection = AttackTemplate( attack_info, self.correlator, self.db ) command_injection.addNode( node_id=0, node_name="man in the middle", children=[3], alerts=[ [1, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], ], pi=0.05, ) command_injection.addNode( node_id=1, node_name="address scan", children=[2], alerts=[ [0.4, {"NEW_ORIG": []}], [0.6, {"NEW_RESP": []}], ], pi=0.02, ) command_injection.addNode( node_id=2, node_name="service scan", parents=[1], q_list=[0.3], children=[3], alerts=[ [1, {"NEW_SERVICE": []}], ], ) command_injection.addNode( node_id=3, node_name="command injection", node_type="OR", parents=[0, 2], q_list=[0.3, 0.5], alerts=[ [1, {"NEW_OPERATION": []}], ], ) # COLD_RESTART Command Injection attack_info = { "name": "COLD_RESTART Command Injection", "consequense": "", "severity": 3, } coldrestart_command_injection = AttackTemplate( attack_info, self.correlator, self.db ) coldrestart_command_injection.addNode( node_id=0, node_name="man in the middle", children=[3], alerts=[ [1, {"PACKET_IAT": [], "OPERATION_TOO_LATE": []}], ], pi=0.05, ) coldrestart_command_injection.addNode( node_id=1, node_name="address scan", children=[2], alerts=[ [0.4, {"NEW_ORIG": []}], [0.6, {"NEW_RESP": []}], ], pi=0.02, ) coldrestart_command_injection.addNode( node_id=2, node_name="service scan", parents=[1], q_list=[0.3], children=[3], alerts=[ [1, {"NEW_SERVICE": []}], ], ) coldrestart_command_injection.addNode( node_id=3, node_name="COLD_RESTART command injection", node_type="OR", parents=[0, 2], q_list=[0.3, 0.5], alerts=[ [1, {"NEW_OPERATION": [[["operation.fc", 13]]]}], ], ) #self.template_dict["TCP SYN Flooding"] = tcp_syn_flood #self.template_dict["Command Injection"] = command_injection #self.template_dict["Data Integrity Attack"] = data_integrity self.template_dict["TCP SYN Flooding (with rule)"] = tcp_syn_flood_rule self.template_dict["Voltage Tampering Attack"] = voltage_tampering self.template_dict["COLD_RESTART Command Injection"] = coldrestart_command_injection def getTemplates(self): rst = dict() for attack_name, template in self.template_dict.iteritems(): rst[attack_name] = [template.copy()] return rst <file_sep># aius AIUS Repository (EDMAND/CAPTAR combination) This folder contains codes for the framework named Aius. It's a framework for anomaly detection and attack reasoning in SCADA systems. The three folders contain different files: code: This folder stores all the code files (Bro and Python scripts) for the framework. Each file will be described in more details later in this ReadMe. csv: This folder stores '.csv' files that contain simulated measurement data in ITI testbed. They are used to generate baseline traffic and anomaly data for evaluation puporse. trace: This folder stores several trace files for traffic in SCADA systems for test purpose. To run the framework, run the 'run.sh' file. Two running mode can be selected using the following two different commands: "./run.sh real": This runs the framework based on traffic stored in a specified trace file. The trace file can be specified in the run.sh. "./run.sh": This runs the framework based on traffic generated by our traffic generator. A brief description of each file in the 'code' folder is given as follows: 'end_point.bro': Bro script that serves as the end point for communication with the Python part. 'flow_level.bro': Data extractor module file for the transport level traffic. 'protocol_level.bro': Data extractor module file for the protocol level traffic. 'protocol_level_modbus.bro': Sub-module file responsible for the Modbus protocol level extraction. 'protocol_level_dnp3.bro': Sub-module file responsible for the DNP3 protocol level extraction. 'data_level.bro': Data extractor module for the content level traffic. 'data_level_modbus.bro': Sub-module file responsible for the Modbus content level extraction. 'data_level_dnp3.bro': Sub-module file responsible for the DNP3 content level extraction. 'edmand.py': Main file for the anomaly detection sub-framework named EDMAND. 'parse_packet.py': File for the transport level parser. 'packet.py': File to store the input data structure for packet level anomlay detection. 'parse_operation.py': File for the protocol level parser. 'operation.py': File to store the input data structure for protocol level anomaly detection. 'parse_data_value.py': File for the content level parser. 'data_value.py': File to store the input data structure for content level anomaly detection. 'analyze_packet.py': File for the packet processor. 'analyze_flow.py': File for the flow processor. 'flow.py': File to store the input data structure for flow level anomaly detection. 'anomaly.py': File to store the anomaly data. 'den_stream.py': File for the clustering anomaly detection mechanism. 'inc_mean_std.py': File for the Mean-STD anomaly detection mechanism. 'manage_anomaly.py': File for the alert manager. 'generate_traffic': File for the synthetic traffic generator. 'analyze_alert': Main file for the attack reasoning sub-framework named CAPTAR. 'anomaly_analyzer.py': File for the causal reasoning engine. 'correlate_alert.py': File for the alert correlator. 'attack_step.py': File to store the attack step node in the causal polytree. 'attack_template.py': File to store the attack tempalte (causal polytree). 'generate_template': File to create the attack templates. <file_sep>import datetime class Flow: def __init__(self, start=None, end=None, orig=None, resp=None, protocol_type=None, service=None, tcp_flag_most=None, count_pkt_ab=0, count_pkt_ba=0, mean_bytes_ab=None, std_bytes_ab=None, mean_bytes_ba=None, std_bytes_ba=None, mean_iat_ab=None, std_iat_ab=None, mean_iat_ba=None, std_iat_ba=None, ): self.start = start self.end = end self.orig = orig self.resp = resp self.protocol_type = protocol_type self.service = service self.tcp_flag_most = tcp_flag_most self.count_pkt_ab = count_pkt_ab self.count_pkt_ba = count_pkt_ba self.mean_bytes_ab = mean_bytes_ab self.std_bytes_ab = std_bytes_ab self.mean_bytes_ba = mean_bytes_ba self.std_bytes_ba = std_bytes_ba self.mean_iat_ab = mean_iat_ab self.std_iat_ab = std_iat_ab self.mean_iat_ba = mean_iat_ba self.std_iat_ba = std_iat_ba def getDict(self): rst = {"start": self.start, "end": self.end, "orig": self.orig, "resp": self.resp, "protocol_type": self.protocol_type, "serivce": self.service, "tcp_flag_most": self.tcp_flag_most, "count_pkt_ab": self.count_pkt_ab, "count_pkt_ba": self.count_pkt_ba, "mean_bytes_ab": self.mean_bytes_ab, "std_bytes_ab": self.std_bytes_ab, "mean_bytes_ba": self.mean_bytes_ba, "std_bytes_ba": self.std_bytes_ba, "mean_iat_ab": self.mean_iat_ab, "std_iat_ab": self.mean_iat_ab, "mean_iat_ba": self.mean_iat_ba, "std_iat_ba": self.std_iat_ba} return rst def __str__(self): return ''' start = {0} end = {1} orig = {2} resp = {3} protocol_type = {4} service = {5} tcp_flag_most = {6} count_pkt_ab = {7} count_pkt_ba = {8} mean_bytes_ab = {9} std_bytes_ab = {10} mean_bytes_ba = {11} std_bytes_ba = {12} mean_iat_ab = {13} std_iat_ab = {14} mean_iat_ba = {15} std_iat_ba = {16} '''.format( datetime.datetime.fromtimestamp(self.start), datetime.datetime.fromtimestamp(self.end), self.orig, self.resp, self.protocol_type, self.service, self.tcp_flag_most, self.count_pkt_ab, self.count_pkt_ba, self.mean_bytes_ab, self.std_bytes_ab, self.mean_bytes_ba, self.std_bytes_ba, self.mean_iat_ab, self.std_iat_ab, self.mean_iat_ba, self.std_iat_ba, ) <file_sep>import gevent import pickle import socket import sys import threading import timeit import numpy from gevent import select from gevent.queue import Queue, Empty from pprint import pprint from analyze_alert import AlertAnalyzer meta_alert_queue = Queue() EDMAND_NUM = 1 TIMEOUT = 120 def alert_receiver(n): bind_ip = "127.0.0.1" bind_port = 9998 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print("Listening on {}:{}".format(bind_ip, bind_port)) def handle_client_connection(client_socket, address): print("Accepted connection from {}:{}".format(address[0], address[1])) data = client_socket.recv(655350) while len(data) > 0: meta_alert = pickle.loads(data) meta_alert_queue.put_nowait(meta_alert) client_socket.send("ACK") data = client_socket.recv(655350) gevent.sleep(0) print("Connection from {}:{} closed".format(address[0], address[1])) count = EDMAND_NUM while count > 0: client_sock, address = server.accept() client_handler = threading.Thread( target = handle_client_connection, args = (client_sock, address,) ) client_handler.start() count -= 1 gevent.sleep(0.01) def alert_analyzer(n): countdown = TIMEOUT/0.01 aa = AlertAnalyzer() reasoning_time = [] count = 0 while countdown > 0: try: while True: meta_alert = meta_alert_queue.get_nowait() start = timeit.default_timer() aa.analyze(meta_alert) reasoning_time.append(timeit.default_timer() - start) countdown = TIMEOUT/0.01 gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) aa.print_alerts() aa.print_candidates() print("Alert analyzer {} quit!".format(n)) if len(reasoning_time) > 0: reasoning_array = numpy.array([reasoning_time]) print("Alert analyzer time: " + str(numpy.mean(reasoning_array, axis=1))) print("Alert analyzer num: " + str(len(reasoning_time))) print("Alert analyzer std: " + str(numpy.std(reasoning_array, axis=1))) def main(): gevent.joinall([ gevent.spawn(alert_receiver, 1), gevent.spawn(alert_analyzer, 1), ]) if __name__ == '__main__': main() <file_sep>import numpy as np import math UPDATE_TH = 0.95 def sigmoid(x): return 2 * (1 / (1 + math.exp(-x)) - 0.5) def anomaly_score(x, mean, std): return (1 - std**2/(x-mean)**2)**2 class IncMeanSTD(): def __init__(self, norm): self.norm = norm self.total = 0 self.mean = None self.std = None self.S = None self.last = None def detect(self, x): if self.total >= 2 and abs(x-self.mean) > self.std: if x > self.mean: rst = 1 else: rst = -1 confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.mean, self.std) else: rst = 0 confi = 1 return (rst, confi, self.mean, self.std) def update(self, x, always_update=False): rst, confi, mean, std = self.detect(x) if always_update or rst == 0 or confi < UPDATE_TH: self.total += 1 if self.total == 1: self.last = x self.mean = self.last self.S = 0 else: new_mean = self.mean+(x-self.mean)/self.total self.S += (x-self.mean)*(x-new_mean) self.std = math.sqrt(self.S/(self.total-1)) self.mean = new_mean return (rst, confi, self.mean, self.std) def check(self, x): rst = 0 confi = 1 if self.total >= 2 and x-self.mean > self.std: rst = 1 confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.mean, self.std) return (rst, confi, self.mean, self.std) def getTotal(self): return self.total def getMean(self): return self.mean def getSTD(self): return self.std def __str__(self): return "mean: {0}, std: {1}, count: {2}".format(self.mean, self.std, self.total) class ExpMeanSTD(): def __init__(self, norm, alpha, delta=0): self.norm = norm self.total = 0 self.alpha = alpha self.delta = delta self.mean = None self.variance = None self.max = None self.min = None def detect(self, x): if self.total >= 2 and abs(x-self.mean) > max(self.delta, self.getSTD()): if x > self.mean: rst = 1 else: rst = -1 confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.mean, self.getSTD()) else: rst = 0 confi = 1 return (rst, confi, self.mean, self.getSTD()) def update(self, x, always_update=False): if x == None: return (0, 1, self.mean, self.getSTD()) rst, confi, mean, std = self.detect(x) if always_update or rst == 0 or confi < UPDATE_TH: self.total += 1 if self.total == 1: self.mean = x self.variance = 0 self.max = x self.min = x else: diff = x - self.mean incr = self.alpha * diff self.mean = self.mean + incr self.variance = (1 - self.alpha) * (self.variance + diff * incr) self.max = max(self.max, x) self.min = min(self.min, x) return (rst, confi, self.mean, self.getSTD()) def check(self, x): rst = 0 confi = 1 if self.total >= 2 and x-self.mean > self.getSTD(): rst = 1 confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.mean, self.getSTD()) return (rst, confi, self.mean, self.getSTD()) def getTotal(self): return self.total def getMean(self): return self.mean def getSTD(self): if self.variance == None: return None return math.sqrt(abs(self.variance)) def getMax(self): return self.max def getMin(self): return self.min def __str__(self): return "mean: {0}, std: {1}, count: {2}".format(self.mean, self.getSTD(), self.total) class IncAdaptMeanSTD(): def __init__(self, norm, adapt_num): self.norm = norm self.adapt_num = adapt_num self.total = 0 self.current_total = 0 self.pre_mean = None self.pre_std = None self.mean = None self.std = None self.S = None self.last = None def detect(self, x): if x != None and self.total >= 2 and abs(x-self.getMean()) > self.getSTD(): if x > self.getMean(): rst = 1 else: rst = -1 num = min(self.adapt_num, self.total) confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.getMean(), self.getSTD()) else: rst = 0 confi = 1 return (rst, confi, self.getMean(), self.getSTD()) def update(self, x, always_update=False): rst, confi, mean, std = self.detect(x) if x != None and (always_update or rst == 0 or confi < UPDATE_TH): self.total += 1 self.current_total += 1 if self.current_total == 1: self.last = x self.mean = self.last self.S = 0 else: new_mean = self.mean+(x-self.mean)/self.total self.S += (x-self.mean)*(x-new_mean) self.std = math.sqrt(self.S/(self.total-1)) self.mean = new_mean if self.current_total == self.adapt_num: self.pre_mean = self.mean self.pre_std = self.std self.current_total = 0 return (rst, confi, self.getMean(), self.getSTD()) def check(self, x): rst = 0 confi = 1 if self.total >= 2 and x-self.getMean() > self.getSTD(): rst = 1 confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.getMean(), self.getSTD()) return (rst, confi, self.getMean(), self.getSTD()) def getTotal(self): return self.total def getMean(self): if self.pre_mean == None: return self.mean else: return self.pre_mean def getSTD(self): if self.pre_std == None: return self.std else: return self.pre_std def __str__(self): return "mean: {0}, std: {1}, count: {2}".format(self.getMean(), self.getSTD(), self.getTotal()) class PeriodicExpMeanSTD(): def __init__(self, norm, period_len, slot_len): self.period_len = period_len self.slot_len = slot_len self.slot_num = period_len/slot_len self.slots = [ ExpMeanSTD(norm, 0.02) for i in range(self.slot_num)] def getIndex(self, ts): ts = int(round(ts)) return (ts % self.period_len) / self.slot_len def detect(self, x, ts): return self.slots[self.getIndex(ts)].detect(x) def update(self, x, ts, always_update=False): return self.slots[self.getIndex(ts)].update(x, always_update) def getTotal(self, ts): return self.slots[self.getIndex(ts)].getTotal() def getMean(self, ts): return self.slots[self.getIndex(ts)].getMean() def getSTD(self, ts): return self.slots[self.getIndex(ts)].getSTD() def getMaxDiff(self): maxDiff = 0 for i in range(self.slot_num): slot_max = self.slots[i].getMax() slot_min = self.slots[i].getMin() if slot_max == None or slot_min == None: return None diff = self.slots[i].getMax() - self.slots[i].getMin() #print(str(i) + ": " + str(diff)) maxDiff = max(maxDiff, diff) return maxDiff def getMaxSTDRatio(self): maxSTDRatio = 0 for i in range(self.slot_num): std = self.slots[i].getSTD() mean = self.slots[i].getMean() if std == None: return None if mean == 0: return None maxSTDRatio = max(maxSTDRatio, std/mean) return maxSTDRatio def __str__(self): rst = "" for i in range(self.slot_num): rst += "index: {0}, {1}\n".format(i, str(self.slots[i])) return rst class Unknown(): def __init__(self, norm): self.norm = norm self.total = 0 self.mean = None self.max= None self.min = None def detect(self, x): rst = 0 confi = 1 diff = None if self.total > 0: if x > self.getMax(): rst = 1 diff = abs(self.getMax()-self.getMean()) confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.getMean(), diff) if x < self.getMin(): rst = -1 diff = abs(self.getMin()-self.getMean()) confi = sigmoid(self.total/self.norm) * anomaly_score(x, self.getMean(), diff) return (rst, confi, self.mean, diff) def update(self, x, always_update=False): rst, confi, mean, diff = self.detect(x) if always_update or rst == 0 or confi < UPDATE_TH: self.total += 1 if self.total == 1: self.mean = x self.max = x self.min = x else: self.mean = self.getMean()+(x-self.getMean())/self.total self.max = max(self.getMax(), x) self.min = min(self.getMin(), x) return (rst, confi, self.mean, diff) def getTotal(self): return self.total def getMean(self): return self.mean def getMax(self): return self.max def getMin(self): return self.min def __str__(self): return "mean: {0}, max: {1}, min: {2}, count: {3}".format(self.getMean(), self.getMax(), self.getMin(), self.getTotal()) class Analog(): freq_ratio_th = 0.005 volt_ratio_th = 0.05 periodic_per = 0.5 periodic_ratio_th = 0.2 pi = np.array([0.25, 0.25, 0.25, 0.25]) believe_th = 0.7 # isAround60 CPT1 = np.array([[0.99, 0.01], [0.01, 0.99], [0.01, 0.99], [0.01, 0.99]]) # STDRatio [low, medium, high] CPT2 = np.array([[0.98, 0.01, 0.01], [0.4, 0.55, 0.05], [0.01, 0.19, 0.8], [0.1, 0.1, 0.8]]) # isPeriodic CPT3 = np.array([[0.01, 0.69, 0.3], [0.01, 0.69, 0.3], [0.6, 0.1, 0.3], [0.1, 0.6, 0.3]]) def __init__(self, norm, period_len, slot_len): self.norm = norm self.total = 0 self.type = "Unidentified" self.type_confi = 1 self.inc_mean_std = IncMeanSTD(norm) self.exp_mean_std = ExpMeanSTD(norm, 0.02) self.periodic_exp_mean_std = PeriodicExpMeanSTD(norm, period_len, slot_len) self.unknown = Unknown(norm) def detect(self, x, ts): if self.type == "Frequency" or self.type == "Voltage": return self.exp_mean_std.detect(x) elif self.type == "Current/Power": return self.periodic_exp_mean_std.detect(x, ts) else: return self.unknown.detect(x) def update(self, x, ts, always_update=False): if self.type == "Frequency" or self.type == "Voltage" or self.type == "Unidentified": rst1, confi1, mean1, diff1 = self.exp_mean_std.update(x, always_update) if self.type == "Current/Power" or self.type == "Unidentified": rst2, confi2, mean2, diff2 = self.periodic_exp_mean_std.update(x, ts, always_update) if self.type == "Unidentified": self.inc_mean_std.update(x, always_update) rst3, confi3, mean3, diff3 = self.unknown.update(x, always_update) self.total += 1 if self.type == "Unidentified" and self.total > 180 and self.total % 30 == 0: self.identify() if self.type == "Frequency" or self.type == "Voltage": return (rst1, confi1, mean1, diff1) elif self.type == "Current/Power": return (rst2, confi2, mean2, diff2) else: return (rst3, confi3, mean3, diff3) def getTotal(self): return self.total def getMean(self): if self.inc_mean_std != None: return self.inc_mean_std.getMean() else: return None def getSTD(self): if self.inc_mean_std != None: return self.inc_mean_std.getSTD() else: return None def getMax(self): if self.unknown != None: return self.unknown.getMax() else: return None def getMin(self): if self.unknown != None: return self.unknown.getMin() else: return None def getDiff(self): if self.unknown != None: return self.getMax() - self.getMin() else: return None def getType(self): return self.type def getTypeConfi(self): return self.type_confi # 0 = True, 1 = False, 2 = Unknown def isAround60(self): if self.getMean() > 59 and self.getMean() < 61: return np.array([1, 0]) else: return np.array([0, 1]) def STDRatio(self, threshold1, threshold2): std = self.getSTD() mean = self.getMean() if mean == 0: if std == 0: return np.array([1, 0, 0]) else: return np.array([0, 0, 1]) ratio = std / abs(mean) if ratio < threshold1: return np.array([1, 0, 0]) elif ratio < threshold2: return np.array([0, 1, 0]) else: return np.array([0, 0, 1]) def isPeriodic(self, percentage, threshold): maxDiff = self.periodic_exp_mean_std.getMaxDiff() maxSTDRatio = self.periodic_exp_mean_std.getMaxSTDRatio() #print(maxDiff) #print(self.getDiff()) #print(maxSTDRatio) if maxDiff == None or maxSTDRatio == None: return np.array([0, 0, 1]) elif maxDiff < self.getDiff() * percentage and maxSTDRatio < threshold: return np.array([1, 0, 0]) else: return np.array([0, 1, 0]) def identify(self): # isAround60 lambda1 = np.dot(self.CPT1, self.isAround60()) lambda_total = lambda1 #print("isAround60: " + str(self.isAround60())) # STDRatio lambda2 = np.dot(self.CPT2, self.STDRatio(self.freq_ratio_th, self.volt_ratio_th)) lambda_total = np.multiply(lambda_total, lambda2) #print("STDRatio: " + str(self.STDRatio(self.freq_ratio_th, self.volt_ratio_th))) # isPeriodic lambda3 = np.dot(self.CPT3, self.isPeriodic(self.periodic_per, self.periodic_ratio_th)) lambda_total = np.multiply(lambda_total, lambda3) #print("isPeriodic: " + str(self.isPeriodic(self.periodic_per, self.periodic_ratio_th))) believe = np.multiply(self.pi, lambda_total) believe = believe/believe.sum(0) if believe[0] > self.believe_th: self.type = "Frequency" self.type_confi = believe[0] self.inc_mean_std = None self.periodic_inc_mean_std = None self.unknown = None elif believe[1] > self.believe_th: self.type = "Voltage" self.type_confi = believe[1] self.inc_mean_std = None self.periodic_inc_mean_std = None self.unknown = None elif believe[2] > self.believe_th: self.type = "Current/Power" self.type_confi = believe[2] self.inc_mean_std = None self.unknown = None def __str__(self): return "count: {0}\ninc_mean_std:\n{1}periodic_inc_mean_std:\n{2}unknown:\n{3}".format(self.getTotal(), str(self.inc_mean_std), str(self.periodic_inc_mean_std), str(self.unknown)) <file_sep>import copy import timeit import numpy from pprint import pprint from attack_step import AttackStep class AttackTemplate: def __init__(self, attack_info=None, correlator=None, db=None, ): self.attack_info = attack_info self.node_list = [] # key: anomaly_desp value: dict(node_id, match_rule) self.alert_match_dict = dict() # key: alert_id value: node_id self.matched_alerts = dict() self.correlator = correlator self.db = db self.cor_time = [] self.update_time = [] def addNode(self, node_id=None, node_name=None, node_type="OR", parents=None, q_list=None, children=None, alerts=None, pi=None, ): parents_pi = None if parents is not None: parents_pi = [] for parent in parents: parents_pi.append(self.node_list[parent].getPiChild(node_id)) for alert_unit in alerts: for desp in alert_unit[1]: if desp not in self.alert_match_dict: self.alert_match_dict[desp] = {node_id: alert_unit[1][desp]} else: self.alert_match_dict[desp][node_id] = alert_unit[1][desp] attack_step = AttackStep(node_id, node_name, node_type, parents, q_list, children, alerts, pi, parents_pi) self.node_list.append(attack_step) def findCorrelation(self, alert, node_id): start = timeit.default_timer() rst = 0 meta_alerts = self.db.meta_alert node = self.node_list[node_id] # Correlate own alerts node_alerts = node.getMatchedAlerts() for node_alert_id in node_alerts: dest_alert = meta_alerts.find_one({"_id": node_alert_id}) cor_rst = self.correlator.correlate(dest_alert, alert) rst = max(rst, cor_rst) # Correlate alerts of parents if node.hasParents(): parents = node.getParents() for parent in parents: parent_node = self.node_list[parent] parent_node_alerts = parent_node.getMatchedAlerts() for parent_node_alert_id in parent_node_alerts: dest_alert = meta_alerts.find_one({"_id": parent_node_alert_id}) cor_rst = self.correlator.correlate(dest_alert, alert) if self.correlator.timeOrder(alert, dest_alert) < 0: return -1 rst = max(rst, cor_rst) # Correlate alerts of children if node.hasChildren(): children = node.getChildren() for child in children: child_node = self.node_list[child] child_node_alerts = child_node.getMatchedAlerts() for child_node_alert_id in child_node_alerts: dest_alert = meta_alerts.find_one({"_id": child_node_alert_id}) cor_rst = self.correlator.correlate(dest_alert, alert) if self.correlator.timeOrder(alert, dest_alert) > 0: return -1 rst = max(rst, cor_rst) self.cor_time.append(timeit.default_timer() - start) return rst def updateTreeFromChild(self, node_id, src_child_id, child_la): node = self.node_list[node_id] node.setLaChild(src_child_id, child_la) node.calLa() node.calBEL() for child_id in node.getChildren(): if child_id != src_child_id: self.updateTreeFromParent(child_id, node_id, node.getPiChild(child_id)) if node.hasParents(): for parent_id in node.getParents(): self.updateTreeFromChild(parent_id, node_id, node.getLaParent(parent_id)) def updateTreeFromParent(self, node_id, src_parent_id, parent_pi): node = self.node_list[node_id] node.setPiParent(src_parent_id, parent_pi) node.calPi() node.calBEL() if node.hasChildren(): for child_id in node.getChildren(): self.updateTreeFromParent(child_id, node_id, node.getPiChild(child_id)) for parent_id in node.getParents(): if parent_id != src_parent_id: self.updateTreeFromChild(parent_id, node_id, node.getLaParent(parent_id)) def updateTreeFromNode(self, alert, node_id): start = timeit.default_timer() self.matched_alerts[alert["_id"]] = node_id node = self.node_list[node_id] node.updateAlert(alert) node.calLa() node.calBEL() if node.hasChildren(): for child_id in node.getChildren(): self.updateTreeFromParent(child_id, node_id, node.getPiChild(child_id)) if node.hasParents(): for parent_id in node.getParents(): self.updateTreeFromChild(parent_id, node_id, node.getLaParent(parent_id)) self.update_time.append(timeit.default_timer() - start) def matchAlert(self, alert): candidates = [self] correlated_node = None max_cor = 0 potential_nodes = [] if alert["desp"] in self.alert_match_dict: for node_id in self.alert_match_dict[alert["desp"]]: if self.checkMatchRule(alert, self.alert_match_dict[alert["desp"]][node_id]): cor_rst = self.findCorrelation(alert, node_id) if cor_rst > 0: if cor_rst > max_cor: correlated_node = node_id elif cor_rst == 0: potential_nodes.append(node_id) #print("correlated_node: " + str(correlated_node)) #print("potential_nodes: " + str(potential_nodes)) if correlated_node is not None: self.updateTreeFromNode(alert, correlated_node) else: for node_id in potential_nodes: candidate = self.copy() candidate.updateTreeFromNode(alert, node_id) candidates.append(candidate) return candidates def checkMatchRule(self, alert, match_rule): if len(match_rule) == 0: return True for conjunction in match_rule: conjunction_val = True for literal in conjunction: index_str = literal[0] value = literal[1] index_list = index_str.split(".") cur = alert find_value = True for i in range(len(index_list)): index = index_list[i] if index not in cur: find_val = False break else: cur = cur[index] if find_value == False or cur != value: conjunction_val = False break if conjunction_val == True: return True return False def updateAlert(self, alert): if alert["_id"] in self.matched_alerts: node_id = self.matched_alerts[alert["_id"]] if alert["confi"] != self.node_list[node_id].getAlertConfiInNode(alert): self.updateTreeFromNode(alert, node_id) def getAvgBEL(self): total_bel = 0 for node in self.node_list: total_bel += node.getBEL() return total_bel / len(self.node_list) def getMaxLeafBEL(self): max_bel = 0 for node in self.node_list: if not node.hasChildren(): max_bel = max(node.getBEL(), max_bel) return max_bel def getRankScore(self): return self.getMaxLeafBEL() + 0.0000001 * len(self.matched_alerts) def getLastUpdateTime(self): meta_alerts = self.db.meta_alert rst = None for alert_id in self.matched_alerts: alert = meta_alerts.find_one({"_id": alert_id}) if rst is None: rst = alert["ts"][1] else: rst = max(rst, alert["ts"][1]) return rst def isTemplate(self): return not self.matched_alerts def getNode(self, node_id): return self.node_list[node_id] def copy(self): rst = AttackTemplate( self.attack_info, self.correlator, self.db, ) rst.node_list = copy.deepcopy(self.node_list) rst.alert_match_dict = copy.deepcopy(self.alert_match_dict) rst.matched_alerts = copy.deepcopy(self.matched_alerts) rst.cor_time = copy.deepcopy(self.cor_time) rst.update_time = copy.deepcopy(self.update_time) return rst def __str__(self): rst = "\nattack info: {\n" for key in self.attack_info: rst += " {}: {}\n".format(key, self.attack_info[key]) rst += "}}\nMax_Leaf_BEL: {}\nnode list: [\n".format(self.getMaxLeafBEL()) for node in self.node_list: rst += str(node) rst += "]\n" if len(self.cor_time) > 0: cor_array = numpy.array([self.cor_time]) rst += "cor_avg_time: {}\n".format(numpy.mean(cor_array, axis=1)) rst += "cor_std: {}\n".format(numpy.std(cor_array, axis=1)) rst += "cor_num: {}\n".format(len(self.cor_time)) if len(self.update_time) > 0: update_array = numpy.array([self.update_time]) rst += "update_avg_time: {}\n".format(numpy.mean(update_array, axis=1)) rst += "update_std: {}\n".format(numpy.std(update_array, axis=1)) rst += "update_num: {}\n".format(len(self.update_time)) return rst <file_sep>from data_value import DataValue import datetime def parse_data_value(args): data_info = args[0] data_value = DataValue() # Timestamp data_value.ts = (data_info[0] - datetime.datetime(1970, 1, 1)).total_seconds() #print(data_value.ts) # Connection data_value.holder_ip = str(data_info[1][0][2]) # Control Protocol data_value.protocol = str(data_info[2]) # uid data_value.uid = str(data_info[3]) # Data type data_value.data_type = str(data_info[4]) # Target index data_value.index = data_info[5].value # Data value data_value.value = data_info[6] # Is event data_value.is_event = data_info[7] #print(data_value) return data_value <file_sep>from packet import Packet from flow import Flow from anomaly import PacketAnomaly from den_stream import DenStream1D from inc_mean_std import IncMeanSTD, ExpMeanSTD import datetime import numpy as np import math TIME_NORM = 60.0 * 10 COUNT_NORM = 100.0 COUNT_EACH_NORM = 100.0 CONFI_TH = 0.9 PERIOD = 60*10 def sigmoid(x): return 2 * (1 / (1 + math.exp(-x)) - 0.5) def generate_flow(start, end, orig, resp, protocol, service, service_stats, flow_queue): tcp_flag_most = -1 tcp_flag_max = 0 for tcp_flag in service_stats.tcp_flag_count: if service_stats.tcp_flag_count[tcp_flag] > tcp_flag_max: tcp_flag_most = tcp_flag tcp_flag_max = service_stats.tcp_flag_count[tcp_flag] flow = Flow( start, end, orig, resp, protocol, service, tcp_flag_most, service_stats.bytes_flow_ab.getTotal(), service_stats.bytes_flow_ba.getTotal(), service_stats.bytes_flow_ab.getMean(), service_stats.bytes_flow_ab.getSTD(), service_stats.bytes_flow_ba.getMean(), service_stats.bytes_flow_ba.getSTD(), service_stats.iat_flow_ab.getMean(), service_stats.iat_flow_ab.getSTD(), service_stats.iat_flow_ba.getMean(), service_stats.iat_flow_ba.getSTD() ) flow_queue.put_nowait(flow) def generate_anomaly(ts, desp, confi, index, anomaly_queue, packet=None, current=None, normal_mean=None, normal_std=None): if confi >= CONFI_TH: anomaly = PacketAnomaly(ts, desp, confi, index, packet, current, normal_mean, normal_std) anomaly_queue.put_nowait(anomaly) class IPPairStats(): def __init__(self): self.protocol_dict = dict() self.total = 0 class ProtocolStats(): def __init__(self): self.service_dict = dict() self.total = 0 class ServiceStats(): def __init__(self, index, anomaly_queue): self.index = index self.anomaly_queue = anomaly_queue self.total_ab = 0 self.total_ba = 0 self.tcp_flag_count = dict() self.last_seen_ab = None self.iat_ab = DenStream1D(0.5) #self.iat_ab = ExpMeanSTD(COUNT_EACH_NORM, 0.02) self.iat_flow_ab = IncMeanSTD(COUNT_EACH_NORM) self.last_seen_ba = None self.iat_ba = DenStream1D(0.5) #self.iat_ba = ExpMeanSTD(COUNT_EACH_NORM, 0.02) self.iat_flow_ba = IncMeanSTD(COUNT_EACH_NORM) self.bytes_ab = DenStream1D(1) #self.bytes_ab = ExpMeanSTD(COUNT_EACH_NORM, 0.02) self.bytes_flow_ab = IncMeanSTD(COUNT_EACH_NORM) self.bytes_ba = DenStream1D(1) #self.bytes_ba = ExpMeanSTD(COUNT_EACH_NORM, 0.02) self.bytes_flow_ba = IncMeanSTD(COUNT_EACH_NORM) def clearFlow(self): self.tcp_flag_count = dict() self.iat_flow_ab = IncMeanSTD(COUNT_EACH_NORM) self.iat_flow_ba = IncMeanSTD(COUNT_EACH_NORM) self.bytes_flow_ab = IncMeanSTD(COUNT_EACH_NORM) self.bytes_flow_ba = IncMeanSTD(COUNT_EACH_NORM) def update(self, packet, ip_pair): if packet.tcp_flag not in self.tcp_flag_count: self.tcp_flag_count[packet.tcp_flag] = 1 else: self.tcp_flag_count[packet.tcp_flag] += 1 if packet.sender == ip_pair.split(";")[0]: if self.last_seen_ab != None: iat = packet.ts - self.last_seen_ab rst, ano_score, p_c_list, p_r_list = self.iat_ab.merge(iat, packet.ts) #rst, ano_score, p_c_list, p_r_list = self.iat_ab.update(iat) self.iat_flow_ab.update(iat) #print("iat_ab: " + str(iat)) #print(self.iat_ab) if not rst: desp = "PACKET_IAT" confi = sigmoid(self.total_ab/COUNT_EACH_NORM) * ano_score generate_anomaly(packet.ts, desp, confi, self.index, self.anomaly_queue, packet, iat, p_c_list, p_r_list) self.last_seen_ab = packet.ts packet_len = packet.packet_len rst, ano_score, p_c_list, p_r_list = self.bytes_ab.merge(packet_len, packet.ts) #rst, ano_score, p_c_list, p_r_list = self.bytes_ab.update(packet_len) self.bytes_flow_ab.update(packet_len) #print("bytes_ab: " + str(packet_len)) #print(self.bytes_ab) if not rst: desp = "PACKET_BYTES" confi = sigmoid(self.total_ab/COUNT_EACH_NORM) * ano_score generate_anomaly(packet.ts, desp, confi, self.index, self.anomaly_queue, packet, packet_len, p_c_list, p_r_list) self.total_ab += 1 else: if self.last_seen_ba != None: iat = packet.ts - self.last_seen_ba rst, ano_score, p_c_list, p_r_list = self.iat_ba.merge(iat, packet.ts) #rst, ano_score, p_c_list, p_r_list = self.iat_ba.update(iat) self.iat_flow_ba.update(iat) #print("iat_ba: " + str(iat)) #print(self.iat_ba) if not rst: desp = "PACKET_IAT" confi = sigmoid(self.total_ba/COUNT_EACH_NORM) * ano_score generate_anomaly(packet.ts, desp, confi, self.index, self.anomaly_queue, packet, iat, p_c_list, p_r_list) self.last_seen_ba = packet.ts packet_len = packet.packet_len rst, ano_score, p_c_list, p_r_list = self.bytes_ba.merge(packet_len, packet.ts) #rst, ano_score, p_c_list, p_r_list = self.bytes_ba.update(packet_len) self.bytes_flow_ba.update(packet_len) #print("bytes_ba: " + str(packet_len)) #print(self.bytes_ba) if not rst: desp = "PACKET_BYTES" confi = sigmoid(self.total_ba/COUNT_EACH_NORM) * ano_score generate_anomaly(packet.ts, desp, confi, self.index, self.anomaly_queue, packet, packet_len, p_c_list, p_r_list) self.total_ba += 1 class PacketAnalyzer(): def __init__(self, anomaly_queue, flow_queue): self.orig_dict = dict() self.resp_dict = dict() self.protocol_dict = dict() self.service_dict = dict() self.ip_pair_dict = dict() self.total = 0 self.start_time = None self.anomaly_queue = anomaly_queue self.flow_queue = flow_queue self.last_aggregate = -1 def analyze(self, packet): if self.last_aggregate == -1: self.last_aggregate = packet.ts self.start_time = packet.ts while packet.ts > self.last_aggregate + PERIOD: self.aggregate() self.last_aggregate += PERIOD orig = packet.conn[0] resp = packet.conn[2] protocol = packet.protocol_type service_list = packet.service ip_pair = orig + ";" + resp inverse_ip_pair = resp + ";" + orig cur_ip_pair = ip_pair index = ip_pair + ";" + protocol + ";" + str(service_list) confi = sigmoid(self.total/COUNT_NORM) * sigmoid(abs(packet.ts-self.start_time)/TIME_NORM) if orig not in self.orig_dict: self.orig_dict[orig] = 0 if self.orig_dict[orig] < COUNT_NORM: generate_anomaly(packet.ts, "NEW_ORIG", confi, index, self.anomaly_queue, packet) if resp not in self.resp_dict: self.resp_dict[resp] = 0 if self.resp_dict[resp] < COUNT_NORM: generate_anomaly(packet.ts, "NEW_RESP", confi, index, self.anomaly_queue, packet) if protocol not in self.protocol_dict: self.protocol_dict[protocol] = 0 if self.protocol_dict[protocol] < COUNT_NORM: generate_anomaly(packet.ts, "NEW_PROTOCOL", confi, index, self.anomaly_queue, packet) for service in service_list: if service not in self.service_dict: self.service_dict[service] = 0 if self.service_dict[service] < COUNT_NORM: generate_anomaly(packet.ts, "NEW_SERVICE", confi, index, self.anomaly_queue, packet) self.service_dict[service] += 1 self.orig_dict[orig] += 1 self.resp_dict[resp] += 1 self.protocol_dict[protocol] += 1 self.total += 1 if ip_pair not in self.ip_pair_dict and inverse_ip_pair not in self.ip_pair_dict: self.ip_pair_dict[ip_pair] = IPPairStats() if ip_pair not in self.ip_pair_dict: ip_pair_stats = self.ip_pair_dict[inverse_ip_pair] index = inverse_ip_pair + ";" + protocol + ";" + str(service_list) cur_ip_pair = inverse_ip_pair else: ip_pair_stats = self.ip_pair_dict[ip_pair] confi = sigmoid(ip_pair_stats.total/COUNT_NORM) if protocol not in ip_pair_stats.protocol_dict: ip_pair_stats.protocol_dict[protocol] = ProtocolStats() protocol_stats = ip_pair_stats.protocol_dict[protocol] if protocol_stats.total < COUNT_NORM: generate_anomaly(packet.ts, "NEW_PROTOCOL", confi, index, self.anomaly_queue, packet) ip_pair_stats.total += 1 confi = sigmoid(protocol_stats.total/COUNT_NORM) for service in service_list: if service not in protocol_stats.service_dict: protocol_stats.service_dict[service] = ServiceStats(index, self.anomaly_queue) service_stats = protocol_stats.service_dict[service] if service_stats.total_ab + service_stats.total_ba < COUNT_NORM: generate_anomaly(packet.ts, "NEW_SERVICE", confi, index, self.anomaly_queue, packet) service_stats.update(packet, cur_ip_pair) protocol_stats.total += 1 def aggregate(self): for ip_pair in self.ip_pair_dict: ip_pair_stats = self.ip_pair_dict[ip_pair] ip_pair_list = ip_pair.split(";") orig = ip_pair_list[0] resp = ip_pair_list[1] for protocol in ip_pair_stats.protocol_dict: protocol_stats = ip_pair_stats.protocol_dict[protocol] for service in protocol_stats.service_dict: service_stats = protocol_stats.service_dict[service] generate_flow(self.last_aggregate, self.last_aggregate+PERIOD, orig, resp, protocol, service, service_stats, self.flow_queue) service_stats.clearFlow() <file_sep>from data_value import DataValue from collections import deque from anomaly import MeasurementAnomaly from inc_mean_std import Analog import numpy as np import math COUNT_EACH_NORM = 100.0 CONFI_TH = 0.6 PERIOD_LEN = 60 * 60 * 24 SLOT_LEN = 60 * 20 def getVariability(x): if x == 0 or x == 1: return 0 return -x*math.log(x, 2) - (1-x)*math.log(1-x, 2) def sigmoid(x): return 2 / (1 + math.exp(-x)) - 1 def generate_anomaly(ts, desp, confi, index, anomaly_queue, measurement=None, measurement_type=None, type_confi=0, current=None, mean=None, std=None): if confi >= CONFI_TH: anomaly = MeasurementAnomaly(ts, desp, confi, index, measurement, measurement_type, type_confi, current, mean, std) anomaly_queue.put_nowait(anomaly) class BinaryValue: def __init__(self, key, data_value, anomaly_queue): self.index = key self.count_total = 0 self.count_true = 0 self.normal_status = None self.anomaly_queue = anomaly_queue def detect(self, data_value): value = data_value.value confi = 0 if self.normal_status != None and self.normal_status * value < 0: ratio = self.count_true*1.0/self.count_total confi = sigmoid(self.count_total/COUNT_EACH_NORM) * (1-getVariability(ratio)) desp = "BINARY_FAULT" generate_anomaly(data_value.ts, desp, confi, self.index, self.anomaly_queue, data_value, "Binaray", 1, value, self.normal_status, max(ratio, 1-ratio)) if not data_value.is_event and confi < 0.95: self.count_total += 1 if value > 0: self.count_true += 1 ratio = self.count_true*1.0/self.count_total if ratio >= 0.5: self.normal_status = 1 else: self.normal_status = -1 class AnalogValue: def __init__(self, key, data_value, anomaly_queue): self.index = key self.analog_model = Analog(COUNT_EACH_NORM, PERIOD_LEN, SLOT_LEN) self.anomaly_queue = anomaly_queue def detect(self, data_value): #print(data_value.index) #print(self.analog_model.getType()) value = data_value.value ts = data_value.ts if not data_value.is_event: rst, confi, mean, diff = self.analog_model.update(value, ts) else: rst, confi, mean, diff = self.analog_model.detect(value, ts) if rst != 0: if rst == 1: desp = "ANALOG_TOO_LARGE" else: desp = "ANALOG_TOO_SMALL" generate_anomaly(ts, desp, confi, self.index, self.anomaly_queue, data_value, self.analog_model.getType(), self.analog_model.getTypeConfi(), value, mean, diff) class DataValueModel: def __init__(self, key, data_value, anomaly_queue): self.type = "Unknown" self.data = None if data_value.protocol == "MODBUS": if data_value.data_type == "Coil": self.type = "Modbus_Coil" self.data = BinaryValue(key, data_value, anomaly_queue) elif data_value.data_type == "HoldingRegister": self.type = "Modbus_HoldingRegister" elif data_value.data_type == "InputRegister": self.type = "Modbus_InputRegister" elif data_value.data_type == "DiscreteInput": self.type = "Modbus_DiscreteInput" else: self.type = "Modbus_Other" elif data_value.protocol == "DNP3_TCP": if data_value.data_type == "Analog": self.type = "DNP3_Analog" self.data = AnalogValue(key, data_value, anomaly_queue) elif data_value.data_type == "Binary": self.type = "DNP3_Binary" self.data = BinaryValue(key, data_value, anomaly_queue) elif data_value.data_type == "Counter": self.type = "DNP3_Counter" else: self.type = "DNP3_Other" def update(self, data_value): if self.type == "DNP3_Binary" or self.type == "DNP3_Analog": self.data.detect(data_value) #else: # print(3, self.type) class DataAnalyzer(): def __init__(self, anomaly_queue): self.data_dict = dict() self.anomaly_queue = anomaly_queue def analyze(self, data_value): #print(data_value) key = data_value.holder_ip + ";" + data_value.protocol + ";" + data_value.uid + ";" + data_value.data_type + ";" + str(data_value.index) #print(key) if key not in self.data_dict: self.data_dict[key] = DataValueModel(key, data_value, self.anomaly_queue); self.data_dict[key].update(data_value) <file_sep>import datetime class Packet: def __init__(self, ts=None, sender=None, receiver=None, protocol_type=None, tcp_flag=-1, service=None, packet_len=None, conn=None ): self.ts = ts self.sender = sender self.receiver = receiver self.protocol_type=protocol_type self.tcp_flag = tcp_flag self.service = service self.packet_len = packet_len self.conn = conn def getDict(self): rst = {"ts": self.ts, "sender": self.sender, "receiver": self.receiver, "protocol_type": self.protocol_type, "tcp_flag": self.tcp_flag, "service": self.service, "packet_len": self.packet_len, "conn": self.conn} return rst def __str__(self): return ''' ts = {0} sender = {1} receiver = {2} protocol_type = {3} tcp_flag = {4} service = {5} packet_len = {6} conn = {7} '''.format( datetime.datetime.fromtimestamp(self.ts), self.sender, self.receiver, self.protocol_type, self.tcp_flag, self.service, self.packet_len, self.conn ) <file_sep>import datetime class Operation: def __init__(self, ts=None, orig_ip=None, resp_ip=None, service=None, uid=None, fc=None, fn=None, is_orig=False ): self.ts = ts self.orig_ip = orig_ip self.resp_ip = resp_ip self.service = service self.uid = uid self.fc = fc self.fn = fn self.is_orig = is_orig def getDict(self): rst = {"ts": self.ts, "orig_ip": self.orig_ip, "resp_ip": self.resp_ip, "service": self.service, "uid": self.uid, "fc": self.fc, "fn": self.fn, "is_orig": self.is_orig} return rst def __str__(self): return ''' ts = {0} orig_ip = {1} resp_ip = {2} service = {3} uid = {4} fc = {5} fn = {6} is_orig = {7} '''.format( datetime.datetime.fromtimestamp(self.ts), self.orig_ip, self.resp_ip, self.service, self.uid, self.fc, self.fn, self.is_orig ) <file_sep>import datetime class Anomaly: def __init__(self, ts=None, desp=None, confi=0, anomaly_type=None, index=None, current=None, mean=None, dev=None ): self.ts = ts self.desp = desp self.confi = confi self.anomaly_type = anomaly_type self.index = index self.current = current self.mean = mean self.dev = dev def getTS(self): return self.ts def getDesp(self): return self.desp def getConfi(self): return self.confi def getAnomalyType(self): return self.anomaly_type def getIndex(self): return self.index def getCurrent(self): return self.current def getMean(self): return self.mean def getDict(self): rst = {"ts": self.ts, "desp": self.desp, "confi": self.confi, "anomaly_type": self.anomaly_type, "index": self.index, "current": self.current, "mean": self.mean, "dev": self.dev} return rst def getDev(self): return self.dev def __str__(self): return ''' ts = {0} desp = {1} confi = {2} anomaly_type = {3} index = {4} current = {5} mean = {6} dev = {7} '''.format( datetime.datetime.fromtimestamp(self.ts), self.desp, self.confi, self.anomaly_type, self.index, self.current, self.mean, self.dev ) class PacketAnomaly(Anomaly): def __init__(self, ts=None, desp=None, confi=0, index=None, packet=None, current=None, normal_mean=None, normal_diff=None ): Anomaly.__init__(self, ts, desp, confi, "packet", index, current, normal_mean, normal_diff) self.packet = packet def getPacket(self): return self.packet def matchIndex(self, index): index_own = self.index.split(";") index_dest = index.split(";") for i in range(2): if index_own[i] == index_dest[i]: return True return False def aggregateIndex(self, index): index_own = self.index.split(";") index_dest = index.split(";") for i in range(4): if index_own[i] != index_dest[i]: index_dest[i] = "-" return ';'.join(index_dest) def getDict(self): rst = Anomaly.getDict(self) type_specific = {"packet": self.packet.getDict()} rst.update(type_specific) return rst def __str__(self): return Anomaly.__str__(self)[:-1] + ''' packet = {0}'''.format(" ".join(str(self.packet).splitlines(True))) class FlowAnomaly(Anomaly): def __init__(self, ts=None, desp=None, confi=0, index=None, flow=None, current=None, mean=None, std=None ): Anomaly.__init__(self, ts, desp, confi, "flow", index, current, mean, std) self.flow = flow def getFlow(self): return self.flow def getDict(self): rst = Anomaly.getDict(self) type_specific = {"flow": self.flow.getDict()} rst.update(type_specific) return rst def __str__(self): return Anomaly.__str__(self)[:-1] + ''' flow = {0}'''.format(" ".join(str(self.flow).splitlines(True))) class OperationAnomaly(Anomaly): def __init__(self, ts=None, desp=None, confi=0, index=None, operation=None, iat=None, mean=None, std=None ): Anomaly.__init__(self, ts, desp, confi, "operation", index, iat, mean, std) self.operation = operation def getOperation(self): return self.operation def getDict(self): rst = Anomaly.getDict(self) if self.operation != None: type_specific = {"operation": self.operation.getDict()} rst.update(type_specific) return rst def __str__(self): return Anomaly.__str__(self)[:-1] + ''' operation = {0}'''.format(" ".join(str(self.operation).splitlines(True))) class MeasurementAnomaly(Anomaly): def __init__(self, ts=None, desp=None, confi=0, index=None, measurement=None, measurement_type=None, type_confi=0, current=None, mean=None, std=None ): Anomaly.__init__(self, ts, desp, confi, "measurement", index, current, mean, std) self.measurement = measurement self.measurement_type = measurement_type self.type_confi = type_confi def getMeasurement(self): return self.measurement def getMeasurementType(self): return self.measurement_type def getTypeConfi(self): return self.type_confi def getDict(self): rst = Anomaly.getDict(self) type_specific = {"measurement_type": self.measurement_type, "type_confi": self.type_confi, "measurement": self.measurement.getDict()} rst.update(type_specific) return rst def __str__(self): return Anomaly.__str__(self)[:-1] + ''' measurement_type = {0} type_confi = {1}'''.format(self.measurement_type, self.type_confi) + ''' measurement = {0}'''.format(" ".join(str(self.measurement).splitlines(True))) <file_sep>#!/usr/bin/env python from __future__ import unicode_literals import sys sys.path.append('/usr/local/bro/lib/broctl') import broker import gevent import pickle import socket import timeit import numpy from gevent import select from gevent.queue import Queue, Empty from pprint import pprint from parse_packet import parse_packet from parse_operation import parse_operation from parse_data_value import parse_data_value from packet import Packet from flow import Flow from operation import Operation from data_value import DataValue from analyze_packet import PacketAnalyzer from analyze_flow import FlowAnalyzer from analyze_operation import OperationAnalyzer from analyze_data import DataAnalyzer from manage_anomaly import AnomalyManager from generate_traffic import TrafficGenerator raw_packet_queue = Queue() raw_operation_queue = Queue() raw_data_value_queue = Queue() packet_queue = Queue() operation_queue = Queue() data_value_queue = Queue() flow_queue = Queue() anomaly_queue = Queue() meta_alert_queue = Queue() TIMEOUT = 120 COUNT_INIT = TIMEOUT / 0.01 def listener(): ep = broker.Endpoint() sub = ep.make_subscriber("edmand") ep.listen("127.0.0.1", 9999) total_time = 0 count = 0 while True: (t, msg)= sub.get() start = timeit.default_timer() t = str(t) ev = broker.bro.Event(msg) if t == "edmand/packet_get": raw_packet_queue.put_nowait(ev.args()) if t == "edmand/protocol_get": raw_operation_queue.put_nowait(ev.args()) if t == "edmand/data_get": raw_data_value_queue.put_nowait(ev.args()) if t == "edmand/bro_done": ep.shutdown() #print("Listener quit!") if count != 0: print("Listener time: " + str(total_time/count)) return; #print("got message") total_time += timeit.default_timer() - start count += 1 gevent.sleep(0) def packet_parser(n): countdown = COUNT_INIT total_time = 0 count = 0 while countdown > 0: try: while True: #print(count) raw_packet = raw_packet_queue.get_nowait() start = timeit.default_timer() packet = parse_packet(raw_packet) packet_queue.put_nowait(packet) total_time += timeit.default_timer() - start count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Packet parser %s quit!' % (n)) if count != 0: print("Packet parser time: " + str(total_time/count)) def operation_parser(n): countdown = COUNT_INIT total_time = 0 count = 0 while countdown > 0: try: while True: #print(count) raw_operation = raw_operation_queue.get_nowait() start = timeit.default_timer() operation = parse_operation(raw_operation) operation_queue.put_nowait(operation) total_time += timeit.default_timer() - start count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Operation parser %s quit!' % (n)) if count != 0: print("Operation parser time: " + str(total_time/count)) def data_value_parser(n): countdown = COUNT_INIT total_time = 0 count = 0 while countdown > 0: try: while True: #print(count) raw_data_value = raw_data_value_queue.get_nowait() start = timeit.default_timer() data_value = parse_data_value(raw_data_value) data_value_queue.put_nowait(data_value) total_time += timeit.default_timer() - start count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Data value parser %s quit!' % (n)) if count != 0: print("Content parser time: " + str(total_time/count)) def traffic_generator(n): generator = TrafficGenerator(packet_queue, operation_queue, data_value_queue) generator.generate() print('Traffic generator %s quit!' % (n)) def packet_analyzer(n): countdown = COUNT_INIT anl = PacketAnalyzer(anomaly_queue, flow_queue) packet_time = [] count = 0 while countdown > 0: try: while True: packet = packet_queue.get_nowait() #print(packet) start = timeit.default_timer() anl.analyze(packet) packet_time.append(timeit.default_timer() - start) count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Packet analyzer %s quit!' % (n)) if count != 0: packet_array = numpy.array([packet_time]) print("Packet analyzer time: " + str(numpy.mean(packet_array, axis=1))) print("Packet analyzer num: " + str(len(packet_time))) print("Packet analyzer std: " + str(numpy.std(packet_array, axis=1))) def flow_analyzer(n): countdown = COUNT_INIT anl = FlowAnalyzer(anomaly_queue) flow_time = [] count = 0 while countdown > 0: try: while True: flow = flow_queue.get_nowait() #print(flow) start = timeit.default_timer() anl.analyze(flow) flow_time.append(timeit.default_timer() - start) count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Flow analyzer %s quit!' % (n)) if count != 0: flow_array = numpy.array([flow_time]) print("Flow analyzer time: " + str(numpy.mean(flow_array, axis=1))) print("Flow analyzer num: " + str(len(flow_time))) print("Flow analyzer std: " + str(numpy.std(flow_array, axis=1))) def operation_analyzer(n): countdown = COUNT_INIT anl = OperationAnalyzer(anomaly_queue) operation_time = [] count = 0 while countdown > 0: try: while True: operation = operation_queue.get_nowait() #print(operation) start = timeit.default_timer() anl.analyze(operation) operation_time.append(timeit.default_timer() - start) count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Operation analyzer %s quit!' % (n)) if count != 0: operation_array = numpy.array([operation_time]) print("Operation analyzer time: " + str(numpy.mean(operation_array, axis=1))) print("Operation analyzer num: " + str(len(operation_time))) print("Operation analyzer std: " + str(numpy.std(operation_array, axis=1))) def data_value_analyzer(n): countdown = COUNT_INIT anl = DataAnalyzer(anomaly_queue) content_time = [] count = 0 while countdown > 0: try: while True: data_value = data_value_queue.get_nowait() #print(data_value) start = timeit.default_timer() anl.analyze(data_value) content_time.append(timeit.default_timer() - start) count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #print('Data value analyzer %s quit!' % (n)) if count != 0: content_array = numpy.array([content_time]) print("Content analyzer time: " + str(numpy.mean(content_array, axis=1))) print("Content analyzer num: " + str(len(content_time))) print("Content analyzer std: " + str(numpy.std(content_array, axis=1))) def anomaly_manager(n): countdown = COUNT_INIT mng = AnomalyManager(meta_alert_queue) manager_time = [] count = 0 while countdown > 0: try: while True: anomaly = anomaly_queue.get_nowait() start = timeit.default_timer() mng.manage(anomaly) manager_time.append(timeit.default_timer() - start) count += 1 countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) #mng.print_alerts() mng.stop() #print('Anomaly Manager %s quit!' % (n)) if count != 0: manager_array = numpy.array([manager_time]) print("Anomaly Manager time: " + str(numpy.mean(manager_array, axis=1))) print("Anomaly Manager num: " + str(len(manager_time))) print("Anomaly Manager std: " + str(numpy.std(manager_array, axis=1))) def alert_sender(n): countdown = COUNT_INIT client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(("127.0.0.1", 9998)) while countdown > 0: try: while True: meta_alert = meta_alert_queue.get_nowait() #pprint(meta_alert) data = pickle.dumps(meta_alert) client.send(data) ack = client.recv(512) assert(ack == "ACK") countdown = COUNT_INIT gevent.sleep(0) except Empty: countdown -= 1 gevent.sleep(0.01) print('Alert sender %s quit!' % (n)) client.close() def main(): if sys.argv[1] == "real": print("Real Traffic") gevent.joinall([ gevent.spawn(listener), gevent.spawn(packet_parser, 1), gevent.spawn(operation_parser, 1), gevent.spawn(data_value_parser, 1), gevent.spawn(packet_analyzer, 1), gevent.spawn(flow_analyzer, 1), gevent.spawn(operation_analyzer, 1), gevent.spawn(data_value_analyzer, 1), gevent.spawn(anomaly_manager, 1), gevent.spawn(alert_sender, 1), ]) else: print("Simulated Traffic") gevent.joinall([ gevent.spawn(traffic_generator, 1), gevent.spawn(packet_analyzer, 1), gevent.spawn(flow_analyzer, 1), gevent.spawn(operation_analyzer, 1), gevent.spawn(data_value_analyzer, 1), gevent.spawn(anomaly_manager, 1), gevent.spawn(alert_sender, 1), ]) if __name__ == '__main__': main() <file_sep>import numpy as np import math P_MISSING_ALERT = 0.1 class AttackStep: def __init__(self, node_id=None, node_name=None, node_type="OR", parents=None, q_list=None, children=None, alerts=None, pi=None, parents_pi=None, ): self.node_id = node_id self.node_name = node_name self.bel = np.array([0.5, 0.5]) self.pi = None self.la = None self.q_list = None self.c_list = None self.alerts = [] self.node_index = node_id self.node_type = node_type self.parents = parents self.children = children if len(alerts) > 0: w_total = 0 for alert_unit in alerts: w_total += float(alert_unit[0]) unit_dict = dict() for desp in alert_unit[1]: unit_dict[desp] = dict() self.alerts.append([float(alert_unit[0]), unit_dict]) assert(abs(w_total-1.0) < 0.0001) self.children_la = [] if children is not None: for child in children: self.children_la.append(np.array([1, 1])) if parents is None: self.pi = np.array([1.0-float(pi), float(pi)]) else: self.parents_pi = parents_pi self.q_list = q_list self.c_list = [1.0 - q for q in q_list] self.calPi() self.calLa() self.calBEL() def calBEL(self): bel = np.multiply(self.pi, self.la) self.bel = bel / bel.sum(0) def calLa(self): la = np.array([0.5, 0.5]) for child_la in self.children_la: la = np.multiply(la, child_la) if len(self.alerts) > 0: total_confi = 0 for alert_unit in self.alerts: max_confi = P_MISSING_ALERT for desp in alert_unit[1]: id_dict = alert_unit[1][desp] if bool(id_dict): cur = np.array([0.5, 0.5]) for confi in id_dict.itervalues(): cur = np.multiply(cur, np.array([1-confi, confi])) cur = cur / cur.sum(0) max_confi = max(max_confi, cur[1]) total_confi += alert_unit[0] * max_confi la = np.multiply(la, np.array([1.0-total_confi, total_confi])) self.la = la / la.sum(0) def calPi(self): if self.parents is not None: pi_total = 1 if self.node_type == "OR": for i in range(len(self.parents)): pi_total *= (1.0 - self.c_list[i]*self.parents_pi[i]) self.pi = np.array([pi_total, 1.0- pi_total]) else: for i in range(len(self.parents)): pi_total *= (1.0 - self.c_list[i]*(1.0-self.parents_pi[i])) self.pi = np.array([1.0 - pi_total, pi_total]) def hasParents(self): return self.parents is not None def getParents(self): return self.parents def hasChildren(self): return self.children is not None def getChildren(self): return self.children def getBEL(self): return self.bel[1] def setLaChild(self, node_id, child_la): assert(node_id in self.children) i = self.children.index(node_id) self.children_la[i] = child_la def setPiParent(self, node_id, parent_pi): assert(node_id in self.parents) i = self.parents.index(node_id) self.parents_pi[i] = parent_pi def getPiChild(self, node_id): assert(node_id in self.children) i = self.children.index(node_id) pi_child = np.divide(self.bel, self.children_la[i]) pi_child = pi_child / pi_child.sum(0) return pi_child[1] def getLaParent(self, node_id): assert(node_id in self.parents) i = self.parents.index(node_id) if self.node_type == "OR": pi_i = self.pi[0] / (1.0-self.c_list[i]*self.parents_pi[i]) la_parent_1 = self.la[0]*self.q_list[i]*pi_i + self.la[1]*(1.0-self.q_list[i]*pi_i) la_parent_0 = self.la[0]*pi_i + self.la[1]*(1.0-pi_i) else: pi_i = self.pi[1] / (1.0-self.c_list[i]*(1-self.parents_pi[i])) la_parent_1 = self.la[0]*(1.0-pi_i) + self.la[1]*pi_i la_parent_0 = self.la[0]*(1.0-self.q_list[i]*pi_i) + self.la[1]*self.q_list[i]*pi_i return np.array([la_parent_0, la_parent_1]) def getAlertConfiInNode(self, alert): for alert_unit in self.alerts: if alert["desp"] in alert_unit[1]: if alert["_id"] in alert_unit[1][alert["desp"]]: return alert_unit[1][alert["desp"]][alert["_id"]] return None def getMatchedAlerts(self): rst = [] for alert_unit in self.alerts: for id_dict in alert_unit[1].itervalues(): for alert_id in id_dict: rst.append(alert_id) return rst def updateAlert(self, alert): for alert_unit in self.alerts: if alert["desp"] in alert_unit[1]: alert_unit[1][alert["desp"]][alert["_id"]] = alert["confi"] def __str__(self): if len(self.alerts) == 0: return " node: {} name: {} BEL: {}\n".format(self.node_id, self.node_name, self.bel[1]) else: title = " node: {} name: {} BEL: {} alerts:".format(self.node_id, self.node_name, self.bel[1]) matched_alerts = "" for alert_unit in self.alerts: for anomaly_desp in alert_unit[1]: dest_id = None max_confi = 0 count = 0 for alert_id, confi in alert_unit[1][anomaly_desp].iteritems(): count += 1 if confi > max_confi: dest_id = alert_id max_confi = confi if dest_id is not None: matched_alerts += ''' desp: {} alert_num: {} example_alert_id: {} confi: {}'''.format(anomaly_desp, count, alert_id, alert_unit[1][anomaly_desp][alert_id] ) if matched_alerts == "": return title + " no matched alerts\n" else: return title + matched_alerts + "\n" <file_sep>import datetime import numpy as np import threading import time import math from anomaly import Anomaly from pymongo import MongoClient from pprint import pprint class AnomalyManager(): max_time_gap = 2*60 priority_th = 0.5 confi_th1 = 0.95 confi_th2 = 0.98 count_th1 = 2 count_th2 = 10 small_period = 1 large_period = 2 confi_high_th = 0.95 confi_low_th = 0.85 th_period = 1 th_exp_para = 0.05 # Alert Severity Table AST = {"PACKET_IAT": 0, "PACKET_BYTES": 0, "NEW_ORIG": 2, "NEW_RESP": 2, "NEW_PROTOCOL": 2, "NEW_SERVICE": 2, "PACKET_AB_TOO_MANY": 2, "PACKET_AB_TOO_FEW": 1, "PACKET_BA_TOO_MANY": 2, "PACKET_BA_TOO_FEW": 1, "MEAN_BYTES_AB_TOO_LARGE": 1, "MEAN_BYTES_AB_TOO_SMALL": 0, "STD_BYTES_AB_TOO_LARGE": 0, "MEAN_BYTES_BA_TOO_LARGE": 1, "MEAN_BYTES_BA_TOO_SMALL": 0, "STD_BYTES_BA_TOO_LARGE": 0, "MEAN_IAT_AB_TOO_LARGE": 1, "MEAN_IAT_AB_TOO_SMALL": 1, "STD_IAT_AB_TOO_LARGE": 0, "MEAN_IAT_BA_TOO_LARGE": 1, "MEAN_IAT_BA_TOO_SMALL": 1, "STD_IAT_BA_TOO_LARGE": 0, "OPERATION_TOO_LATE": 1, "OPERATION_TOO_EARLY": 1, "OPERATION_MISSING": 2, "INVALID_FUNCTION_CODE": 2, "RESPONSE_FROM_ORIG": 2, "REQUEST_FROM_RESP": 2, "NEW_OPERATION": 2, "BINARY_FAULT": 2, "ANALOG_TOO_LARGE": 1, "ANALOG_TOO_SMALL": 1} # Critical Node List CNL = ["172.16.31.10"] pi = np.array([0.6, 0.4]) # Alert Type Sevrity CPT1 = np.array([[0.6, 0.3, 0.1], [0.2, 0.35, 0.45]]) # Confidence Score CPT2 = np.array([[0.6, 0.3, 0.1], [0.15, 0.35, 0.5]]) # Alert Count CPT3 = np.array([[0.25, 0.3, 0.45], [0.45, 0.3, 0.25]]) # Critical Node CPT4 = np.array([[0.2, 0.8], [0.55, 0.45]]) # Critical Operation CPT5 = np.array([[0.1, 0.5, 0.4], [0.25, 0.15, 0.5]]) def __init__(self, meta_alert_queue): self.meta_alert_queue = meta_alert_queue self.client = MongoClient() self.client.drop_database("alert_database") self.alert_db = self.client.alert_database self.fast_timer = threading.Timer(self.small_period, self.sendHighPriorityAlert) self.fast_timer.start() self.slow_timer = threading.Timer(self.large_period, self.sendLowPriorityAlert) self.slow_timer.start() self.do_run = True self.current_confi_th = self.confi_high_th self.update_amount = (self.confi_high_th - self.confi_low_th) / 300 self.th_timer = threading.Timer(self.th_period, self.updateThreshold) self.th_timer.start() def stop(self): self.do_run = False def sendHighPriorityAlert(self): #print("High") if self.do_run: send_list = self.alert_db.high_priority.find() for alert_to_send in send_list: self.meta_alert_queue.put_nowait(alert_to_send) self.alert_db.high_priority.remove({}) self.fast_timer = threading.Timer(self.small_period, self.sendHighPriorityAlert) self.fast_timer.start() def sendLowPriorityAlert(self): #print("Low") if self.do_run: send_list = self.alert_db.low_priority.find() for alert_to_send in send_list: self.meta_alert_queue.put_nowait(alert_to_send) self.alert_db.low_priority.remove({}) self.slow_timer = threading.Timer(self.large_period, self.sendLowPriorityAlert) self.slow_timer.start() def updateThreshold(self): if self.do_run: self.current_confi_th = min(self.confi_high_th, self.current_confi_th + self.update_amount) #print("Current Confidence Threshold: " + str(self.current_confi_th)) self.th_timer = threading.Timer(self.th_period, self.updateThreshold) self.th_timer.start() def insertAlert(self, anomaly): #print(anomaly) alerts = self.alert_db.alert alert_id = alerts.insert_one(anomaly.getDict()).inserted_id #alert = alerts.find_one({"_id": alert_id}) #print(type(alert)) def createMetaAlert(self, anomaly): meta_alert = anomaly.getDict() meta_alert["ts"] = [meta_alert["ts"], meta_alert["ts"]] meta_alert["count"] = 1 priority_score = self.calculatePriority(meta_alert) return meta_alert def updateMetaAlert(self, anomaly, meta_alert): if meta_alert["desp"] == "NEW_ORIG" or meta_alert["desp"] == "NEW_RESP": meta_alert["index"] = anomaly.aggregateIndex(meta_alert["index"]) if anomaly.getTS() > meta_alert["ts"][1]: meta_alert["current"] = anomaly.getCurrent() meta_alert["mean"] = anomaly.getMean() meta_alert["dev"] = anomaly.getDev() if anomaly.getAnomalyType() == "packet": meta_alert["packet"] = anomaly.getPacket().getDict() elif anomaly.getAnomalyType() == "flow": meta_alert["flow"] = anomaly.getFlow().getDict() elif anomaly.getAnomalyType() == "operation": meta_alert["operation"] = anomaly.getOperation().getDict() elif anomaly.getAnomalyType() == "measurement": meta_alert["measurement"] = anomaly.getMeasurement().getDict() meta_alert["ts"][0] = min(meta_alert["ts"][0], anomaly.getTS()) meta_alert["ts"][1] = max(meta_alert["ts"][1], anomaly.getTS()) meta_alert["confi"] = max(meta_alert["confi"], anomaly.getConfi()) meta_alert["count"] += 1 return meta_alert def aggregate(self, anomaly): self.insertAlert(anomaly) meta_alerts = self.alert_db.meta_alert dest_meta_alert = None desp = anomaly.getDesp() if desp == "NEW_ORIG" or desp == "NEW_RESP": candidates = meta_alerts.find({"desp": desp}) for candidate in candidates: if anomaly.matchIndex(candidate["index"]) and ( anomaly.getTS() > candidate["ts"][0] - self.max_time_gap or anomaly.getTS() < candidate["ts"][1] + self.max_time_gap): dest_meta_alert = candidate break else: candidates = meta_alerts.find({"desp": anomaly.getDesp(), "index": anomaly.getIndex()}) for candidate in candidates: if (anomaly.getTS() > candidate["ts"][0] - self.max_time_gap or anomaly.getTS() < candidate["ts"][1] + self.max_time_gap): dest_meta_alert = candidate break if dest_meta_alert == None: new_meta_alert = self.createMetaAlert(anomaly) else: new_meta_alert = self.updateMetaAlert(anomaly, dest_meta_alert) return new_meta_alert def alertTypeSeverity(self, meta_alert): if self.AST[meta_alert["desp"]] == 0: return np.array([1, 0, 0]) elif self.AST[meta_alert["desp"]] == 1: return np.array([0, 1, 0]) else: return np.array([0, 0, 1]) def confidenceScore(self, meta_alert): if meta_alert["confi"] < self.confi_th1: return np.array([1, 0, 0]) elif meta_alert["confi"] < self.confi_th2: return np.array([0, 1, 0]) else: return np.array([0, 0, 1]) def alertCount(self, meta_alert): if meta_alert["count"] < self.count_th1: return np.array([1, 0, 0]) elif meta_alert["count"] < self.count_th2: return np.array([0, 1, 0]) else: return np.array([0, 0, 1]) def isCriticalNode(self, meta_alert): yes = np.array([1, 0]) no = np.array([0, 1]) if (meta_alert["anomaly_type"] == "packet" and (meta_alert["packet"]["sender"] in self.CNL or meta_alert["packet"]["receiver"] in self.CNL)): return yes if (meta_alert["anomaly_type"] == "flow" and (meta_alert["flow"]["orig"] in self.CNL or meta_alert["flow"]["resp"] in self.CNL)): return yes if (meta_alert["anomaly_type"] == "operation" and (meta_alert["operation"]["orig_ip"] in self.CNL or meta_alert["operation"]["resp_ip"] in self.CNL)): return yes if (meta_alert["anomaly_type"] == "measurement" and meta_alert["measurement"]["holder_ip"] in self.CNL): return yes return no def isCriticalOperation(self, meta_alert): yes = np.array([1, 0, 0]) no = np.array([0, 1, 0]) unknown = np.array([0, 0, 1]) if (meta_alert["anomaly_type"] == "packet" or meta_alert["anomaly_type"] == "flow" or meta_alert["anomaly_type"] == "measurement" or meta_alert["operation"] is None): return unknown else: if meta_alert["operation"]["service"] == "DNP3": fc = meta_alert["operation"]["fc"] if (fc >= 2 and fc <= 6 or fc >= 13 and fc <= 14 or fc >= 16 and fc <= 21 or fc >= 24 and fc <= 31): return yes else: return no else: return unknown def calculatePriority(self, meta_alert): # Alert Type Severity lambda1 = np.dot(self.CPT1, self.alertTypeSeverity(meta_alert)) lambda_total = lambda1 # Confidence Score lambda2 = np.dot(self.CPT2, self.confidenceScore(meta_alert)) lambda_total = np.multiply(lambda_total, lambda2) # Alert Count lambda3 = np.dot(self.CPT3, self.alertCount(meta_alert)) lambda_total = np.multiply(lambda_total, lambda3) # Critical Node lambda4 = np.dot(self.CPT4, self.isCriticalNode(meta_alert)) lambda_total = np.multiply(lambda_total, lambda4) # Cirital Operation lambda5 = np.dot(self.CPT5, self.isCriticalOperation(meta_alert)) lambda_total = np.multiply(lambda_total, lambda5) believe = np.multiply(self.pi, lambda_total) believe = believe / believe.sum(0) #pprint(meta_alert) #print(believe[1]) #print("") return believe[1] def scheduleAlert(self, meta_alert): meta_alerts = self.alert_db.meta_alert priority_score = self.calculatePriority(meta_alert) if "_id" in meta_alert.keys(): pre_priority_score = meta_alert["priority_score"] meta_alert["priority_score"] = priority_score meta_alerts.replace_one({"_id": meta_alert["_id"]}, meta_alert) if priority_score > self.priority_th: if pre_priority_score <= self.priority_th: self.meta_alert_queue.put_nowait(meta_alert) else: self.alert_db.high_priority.replace_one({"_id": meta_alert["_id"]}, meta_alert, True) else: self.alert_db.low_priority.replace_one({"_id": meta_alert["_id"]}, meta_alert, True) else: meta_alert["priority_score"] = priority_score new_id = meta_alerts.insert_one(meta_alert).inserted_id meta_alert["_id"] = new_id if priority_score > self.priority_th: self.meta_alert_queue.put_nowait(meta_alert) else: self.alert_db.low_priority.insert_one(meta_alert) #pprint(meta_alert) #print("") def manage(self, anomaly): if anomaly.getConfi() > self.current_confi_th: self.current_confi_th = self.confi_low_th + ( (self.current_confi_th - self.confi_low_th) * math.exp(-self.th_exp_para) ) meta_alert = self.aggregate(anomaly) self.scheduleAlert(meta_alert) def print_alerts(self): alerts = self.alert_db.alert meta_alerts = self.alert_db.meta_alert print("Alert Number: " + str(alerts.count())) print("Meta-Alert Number: " + str(meta_alerts.count())) #for meta_alert in meta_alerts.find(): # print("") # pprint(meta_alert) <file_sep>from operation import Operation from anomaly import OperationAnomaly from inc_mean_std import ExpMeanSTD import numpy as np import math TIME_NORM = 60.0 * 5 COUNT_NORM = 500.0 COUNT_EACH_NORM = 500.0 PERIODIC_CHECK_TIME = 10*60 CONFI_TH = 0.6 def sigmoid(x): return 2 * (1 / (1 + math.exp(-x)) - 0.5) def generate_anomaly(ts, desp, confi, index, anomaly_queue, operation=None, iat=None, mean=None, std=None, power=1): if confi**power >= CONFI_TH: anomaly = OperationAnomaly(ts, desp, confi**power, index, operation, iat, mean, std) anomaly_queue.put_nowait(anomaly) class FunctionStats: def __init__(self, index, operation, anomaly_queue): self.index = index self.anomaly_queue = anomaly_queue self.last_seen = operation.ts self.iat = ExpMeanSTD(COUNT_EACH_NORM, 0.02) def update(self, operation): iat = operation.ts - self.last_seen #print(iat) #print(self.iat) rst, confi, mean, std = self.iat.update(iat) if rst != 0: if rst == 1: desp = "OPERATION_TOO_LATE" else: desp = "OPERATION_TOO_EARLY" generate_anomaly(operation.ts, desp, confi, self.index, self.anomaly_queue, operation, iat, mean, std, power=2) self.last_seen = operation.ts def check(self, ts): iat = ts-self.last_seen rst, confi, mean, std = self.iat.check(iat) if rst == 1: desp = "OPERATION_MISSING" generate_anomaly(ts, desp, confi, self.index, self.anomaly_queue, iat=iat, mean=mean, std=std) class OperationModel: def __init__(self, index, operation, anomaly_queue): self.index = index self.fc_dict = dict() self.anomaly_queue = anomaly_queue self.first_seen = operation.ts self.total_seen = 0 def update(self, operation): index = self.index + ";" + str(operation.fc) if operation.service == "DNP3_TCP": if operation.fc < 0 or operation.fc > 255: generate_anomaly(operation.ts, "INVALID_FUNCTION_CODE", 1, index, self.anomaly_queue, operation) return if operation.fc == 129 or operation.fc == 130: if operation.is_orig: generate_anomaly(operation.ts, "RESPONSE_FROM_ORIG", 1, index, self.anomaly_queue, operation) return else: if not operation.is_orig: generate_anomaly(operation.ts, "REQUEST_FROM_RESP", 1, index, self.anomaly_queue, operation) return elif operation.service == "Modbus": if operation.fc < 1 or operation.fc > 127: generate_anomaly(operation.ts, "INVALID_FUNCTION_CODE", 1, index, self.anomaly_queue, operation) return if operation.fc not in self.fc_dict: #print("sigmoid: " + str(sigmoid(self.total_seen/COUNT_NORM))) confi = sigmoid(self.total_seen/COUNT_NORM) * sigmoid((operation.ts-self.first_seen)/TIME_NORM) generate_anomaly(operation.ts, "NEW_OPERATION", confi, index, self.anomaly_queue, operation) self.fc_dict[operation.fc] = FunctionStats(index, operation, self.anomaly_queue) else: self.fc_dict[operation.fc].update(operation) self.total_seen += 1 def check(self, ts): for fc in self.fc_dict: self.fc_dict[fc].check(ts) class OperationAnalyzer(): def __init__(self, anomaly_queue): self.last_check = None self.operation_dict = dict() self.anomaly_queue = anomaly_queue def analyze(self, operation): #print(operation) key = operation.orig_ip + ";" + operation.resp_ip + ";" + operation.service + ";" + operation.uid #print(key) if key not in self.operation_dict: self.operation_dict[key] = OperationModel(key, operation, self.anomaly_queue); self.operation_dict[key].update(operation) if self.last_check == None: self.last_check = operation.ts elif operation.ts > self.last_check + PERIODIC_CHECK_TIME: self.check(operation.ts) self.last_check += PERIODIC_CHECK_TIME def check(self, ts): for key in self.operation_dict: self.operation_dict[key].check(ts) <file_sep>from operation import Operation import datetime def parse_operation(args): protocol_info = args[0] operation = Operation() # Timestamp operation.ts = (protocol_info[0] - datetime.datetime(1970, 1, 1)).total_seconds() # Connection operation.orig_ip = str(protocol_info[1][0][0]) operation.resp_ip = str(protocol_info[1][0][2]) # Control Protocol (service) operation.service = str(protocol_info[2]) # uid operation.uid = str(protocol_info[3]) # Function code operation.fc = protocol_info[4].value # Function name operation.fn = str(protocol_info[5]) # Is from teh originator side operation.is_orig = protocol_info[6] #print(operation) return operation <file_sep>from packet import Packet import datetime def parse_conn(conn, packet): # Connection tuple conn_tuple = conn[0] orig_h = str(conn_tuple[0]) orig_p = str(conn_tuple[1]) resp_h = str(conn_tuple[2]) resp_p = str(conn_tuple[3]) packet.conn = (orig_h, orig_p, resp_h, resp_p) #print(packet.conn) # Service packet.service = list(map(str, conn[5])) #print(packet.service) # conn_id conn_id = str(conn[7]) #print(conn_id) def parse_hdr(hdr, packet): # IPv4 if hdr[0] is not None: #print("ip4") packet.packet_len = hdr[0][2].value packet.sender = str(hdr[0][6]) packet.receiver = str(hdr[0][7]) #print("packet_len: {}, src: {}, dst: {}".format(packet.packet_len, packet.sender, packet.receiver)) # IPv6 elif hdr[1] is not None: #print("ip6") packet.packet_len = hdr[0][2].value packet.sender = str(hdr[0][5]) packet.receiver = str(hdr[0][6]) #print("packet_len: {}, src: {}, dst: {}".format(packet.packet_len, packet.sender, packet.receiver)) # TCP if hdr[2] is not None: packet.protocol_type = "TCP" #print(packet.protocol_type) packet.tcp_flag = hdr[2][6].value #print("tcp_flag: {}".format(packet.tcp_flag)) # UDP elif hdr[3] is not None: packet.protocol_type = "UDP" #print(packet.protocol_type) # ICMP elif hdr[4] is not None: packet.protocol_type = "ICMP" #print(packet.protocol_type) def parse_packet(args): packet_info = args[0] packet = Packet() # Timestamp packet.ts = (packet_info[0] - datetime.datetime(1970, 1, 1)).total_seconds() #print(packet.ts) # Connection parse_conn(packet_info[1], packet) # Packet header parse_hdr(packet_info[2], packet) #print(packet) return packet <file_sep>import numpy as np import random import math import csv from packet import Packet from flow import Flow from operation import Operation from data_value import DataValue from Queue import PriorityQueue as PQueue CC_NUM = 1 STATION_NUM = 10 class PacketGenerator(): def __init__(self, sender, receiver, protocol_type, service, packet_len, conn, tcp_flag=0, ): self.sender = sender self.receiver = receiver self.protocol_type = protocol_type self.service = service self.packet_len = packet_len self.conn = conn self.tcp_flag = tcp_flag def generate_one(self, ts): packet = Packet(ts, self.sender, self.receiver, self.protocol_type, self.tcp_flag, self.service, self.packet_len, self.conn) return packet class OperationGenerator(): def __init__(self, orig_ip, resp_ip, service, uid, fc, fn, is_orig ): self.orig_ip = orig_ip self.resp_ip = resp_ip self.service = service self.uid = uid self.fc = fc self.fn = fn self.is_orig = is_orig def generate_one(self, ts): operation = Operation(ts, self.orig_ip, self.resp_ip, self.service, self.uid, self.fc, self.fn, self.is_orig) return operation class MeasurementGenerator(): def __init__(self, holder_ip, protocol, uid, data_type, index, interval=None, mean=None, analog_type=None, diff=None, amp=None, period=None): self.holder_ip = holder_ip self.protocol = protocol self.uid = uid self.data_type = data_type self.index = index self.interval = interval self.mean = mean self.analog_type = analog_type self.diff = diff self.amp = amp self.period = period def generate_one(self, idx, ts): if self.data_type == "Binary": value = self.mean elif self.data_type == "Analog": if self.analog_type == "Frequency" or self.analog_type == "Voltage": value = np.random.normal(self.mean, self.diff) elif self.analog_type == "Current/Power": value = (self.mean + self.amp * math.sin(idx*self.interval%self.period/self.interval*2*math.pi) + np.random.normal(0, self.diff)) else: value = random.uniform(self.mean-self.diff, self.mean+self.diff) else: value = 0 measurement = DataValue(ts, self.holder_ip, self.protocol, self.uid, self.data_type, self.index, value, False) return measurement class MeasurementReader(): def __init__(self, holder_ip, protocol, uid, data_type, index, csv_rows, col_name): self.holder_ip = holder_ip self.protocol = protocol self.uid = uid self.data_type = data_type self.index = index self.col_name = col_name self.csv_rows = csv_rows def generate_one(self, idx, row_idx, ts): row = self.csv_rows[row_idx] value = float(row[self.col_name]) measurement = DataValue(ts, self.holder_ip, self.protocol, self.uid, self.data_type, self.index, value, False) return measurement class CommunicationPair(): def __init__(self, priority_queue, cc_ip, ss_ip, uid, csv_steady, anomalies=[], csv_over_voltage=None, csv_under_voltage=None, csv_over_current=None, ): self.pq = priority_queue self.g_dict = {} self.ts = None self.anomalies = sorted( anomalies, key=lambda a: self.getIndex(a["start_day"], a["start_index"]), ) ss_port = "20000tcp" cc_port = str(random.randint(44000, 47000)) + "tcp" conn = (cc_ip, cc_port, ss_ip, ss_port) self.g_dict["p_read"] = PacketGenerator( cc_ip, ss_ip, "TCP", ["DNP3_TCP"], 79, conn, ) self.g_dict["o_read"] = OperationGenerator( cc_ip, ss_ip, "DNP3_TCP", uid, 1, "READ", True, ) self.g_dict["p_resp"] = PacketGenerator( ss_ip, cc_ip, "TCP", ["DNP3_TCP"], 98, conn, ) self.g_dict["o_resp"] = OperationGenerator( cc_ip, ss_ip, "DNP3_TCP", uid, 129, "RESPONSE", False, ) self.g_dict["p_conf"] = PacketGenerator( cc_ip, ss_ip, "TCP", ["DNP3_TCP"], 67, conn, ) self.g_dict["o_conf"] = OperationGenerator( cc_ip, ss_ip, "DNP3_TCP", uid, 0, "CONFIRM", True, ) self.g_dict["p_ack"] = PacketGenerator( ss_ip, cc_ip, "TCP", ["DNP3_TCP"], 52, conn, ) self.g_dict["m_f"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 1, csv_steady, "MVf1", ) self.g_dict["m_v"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 2, csv_steady, "MVVa2", ) self.g_dict["m_i"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 3, csv_steady, "MVIa1", ) self.g_dict["m_p"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 4, csv_steady, "MVPa1", ) self.g_dict["m_b"] = MeasurementGenerator( ss_ip, "DNP3_TCP", uid, "Binary", 5, 20, 1, ) if csv_over_voltage is not None: self.g_dict["m_v_o"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 2, csv_over_voltage, "MVVa2", ) if csv_under_voltage is not None: self.g_dict["m_v_u"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 2, csv_under_voltage, "MVVa2", ) if csv_over_current is not None: self.g_dict["m_i_o"] = MeasurementReader( ss_ip, "DNP3_TCP", uid, "Analog", 3, csv_over_current, "MVIa1", ) def getIndex(self, day, i): return day*3*60*24 + i def addAnomalies(self, anomalies): self.anomalies += anomalies self.anomalies = sorted( self.anomalies, key=lambda a: self.getIndex(a["start_day"], a["start_index"]), ) def getAnomaly(self, anomaly_name, day, i): k = 0 while k < len(self.anomalies): anomaly = self.anomalies[k] if self.getIndex(anomaly["end_day"], anomaly["end_index"]) < self.getIndex(day, i): self.anomalies.remove(anomaly) elif self.getIndex(anomaly["start_day"], anomaly["start_index"]) > self.getIndex(day, i): return None elif anomaly["name"] == anomaly_name: return anomaly else: k += 1 return None def generate_read(self, day, i): self.ts = self.getIndex(day, i)*20 + 0.2 + np.random.normal(0, 0.02) # Delay Command anomaly = self.getAnomaly("Delay Command", day, i) if anomaly is not None: self.ts += anomaly["value"] p_read = self.g_dict["p_read"].generate_one(self.ts) # Change Command Size anomaly = self.getAnomaly("Change Command Size", day, i) if anomaly is not None: p_read.packet_len = anomaly["value"] self.pq.put((self.ts, 'p', p_read)) o_read = self.g_dict["o_read"].generate_one(self.ts) # Tamper Command anomaly = self.getAnomaly("Tamper Command", day, i) if anomaly is not None: o_read.fc = anomaly["fc"] o_read.fn = anomaly["fn"] self.pq.put((self.ts, 'o', o_read)) def generate_ack1(self): self.ts = self.ts + 0.002 + np.random.normal(0, 0.0005) p_ack1 = self.g_dict["p_ack"].generate_one(self.ts) self.pq.put((self.ts, 'p', p_ack1)) def generate_resp(self, day, i): row_idx = i*24000/(3*60*24) self.ts = self.ts + 0.01 + np.random.normal(0, 0.003) # Delay Response anomaly = self.getAnomaly("Delay Response", day, i) if anomaly is not None: self.ts += anomaly["value"] p_resp = self.g_dict["p_resp"].generate_one(self.ts) self.pq.put((self.ts, 'p', p_resp)) o_resp = self.g_dict["o_resp"].generate_one(self.ts) self.pq.put((self.ts, 'o', o_resp)) m_f = self.g_dict["m_f"].generate_one(day*3*60*24+i, row_idx, self.ts) # Tamper Frequncy anomaly = self.getAnomaly("Tamper Frequency", day, i) if anomaly is not None: m_f.value = anomaly["value"] self.pq.put((self.ts, 'd', m_f)) m_v = self.g_dict["m_v"].generate_one(day*3*60*24+i, row_idx, self.ts) # Over Voltage anomaly = self.getAnomaly("Over Voltage", day, i) if anomaly is not None: m_v = self.g_dict["m_v_o"].generate_one(day*3*60*24+i, row_idx, self.ts) # Under Voltage anomaly = self.getAnomaly("Under Voltage", day, i) if anomaly is not None: m_v = self.g_dict["m_v_u"].generate_one(day*3*60*24+i, row_idx, self.ts) self.pq.put((self.ts, 'd', m_v)) # Tamper Frequncy anomaly = self.getAnomaly("Tamper Voltage", day, i) if anomaly is not None: m_v.value = anomaly["value"] self.pq.put((self.ts, 'd', m_v)) m_i = self.g_dict["m_i"].generate_one(day*3*60*24+i, row_idx, self.ts) # Over Current anomaly = self.getAnomaly("Over Current", day, i) if anomaly is not None: m_i = self.g_dict["m_i_o"].generate_one(day*3*60*24+i, row_idx, self.ts) self.pq.put((self.ts, 'd', m_i)) m_p = self.g_dict["m_p"].generate_one(day*3*60*24+i, row_idx, self.ts) # Tamper Power anomaly = self.getAnomaly("Tamper Power", day, i) if anomaly is not None: m_p.value = anomaly["value"] self.pq.put((self.ts, 'd', m_p)) m_b = self.g_dict["m_b"].generate_one(day*3*60*24+i, self.ts) # Tamper Binary anomaly = self.getAnomaly("Tamper Binary", day, i) if anomaly is not None: m_b.value = anomaly["value"] self.pq.put((self.ts, 'd', m_b)) def generate_conf(self): self.ts = self.ts + 0.2*2 + np.random.normal(0, 0.05) p_conf = self.g_dict["p_conf"].generate_one(self.ts) self.pq.put((self.ts, 'p', p_conf)) o_conf = self.g_dict["o_conf"].generate_one(self.ts) self.pq.put((self.ts, 'o', o_conf)) def generate_ack2(self): self.ts = self.ts + 0.002 + np.random.normal(0, 0.0005) p_ack2 = self.g_dict["p_ack"].generate_one(self.ts) self.pq.put((self.ts, 'p', p_ack2)) class TrafficGenerator(): def __init__(self, packet_queue, operation_queue, data_value_queue): self.packet_queue = packet_queue self.operation_queue = operation_queue self.data_value_queue = data_value_queue self.num_day = 14 self.pq = PQueue() self.anomalies = [] # Read Analog Measurement Files self.csv_steady = None with open("../csv/S1_Steady_State.csv") as csvfile: reader = csv.DictReader(csvfile) self.csv_steady = [row for row in reader] self.csv_over_voltage = None with open("../csv/S4_Overvoltage_Tripping.csv") as csvfile: reader = csv.DictReader(csvfile) self.csv_over_voltage = [row for row in reader] self.csv_under_voltage = None with open("../csv/S7_Undervoltage_Tripping.csv") as csvfile: reader = csv.DictReader(csvfile) self.csv_under_voltage = [row for row in reader] self.csv_over_current = None with open("../csv/S3_Overcurrent_Instant_Fault6.csv") as csvfile: reader = csv.DictReader(csvfile) self.csv_over_current = [row for row in reader] # Calculate Substation per Control Center self.ss_num = [] count = 0 ss_per_cc = int(math.ceil(float(STATION_NUM)/CC_NUM)) for i in range(CC_NUM): if i == CC_NUM-1: self.ss_num.append(STATION_NUM - count) else: self.ss_num.append(ss_per_cc) count += ss_per_cc # Create Generators self.cc_list = [] uid = "85:80" for i in range(CC_NUM): cc_ip = "100.0." + str(i) + ".1" ss_list = [] for j in range(self.ss_num[i]): ss_ip = "100.0." + str(i) + "." + str(j+2) anomalies = [] comm_pair = CommunicationPair( self.pq, cc_ip, ss_ip, uid, self.csv_steady, anomalies, self.csv_over_voltage, self.csv_under_voltage, self.csv_over_current, ) ss_list.append(comm_pair) self.cc_list.append(ss_list) # Inject Anomalies self.injectTCPSYNFlooding() self.injectDataIntegrityAttack() self.injectCommandInjection() def injectTCPSYNFlooding(self): day = 9 address_scan = { "name": "Address Scan", "start_day": day, "start_index": 500, "end_day": day, "end_index": 500, "attacker_ip": "172.16.17.32", "subnet": "100.0.0.", } tcp_syn_flooding = { "name": "TCP SYN Flooding", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1600, "interval": 0.2, "target_ip": "172.16.58.3", } delay_command = { "name": "Delay Command", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1600, "value": 5, } self.anomalies += [address_scan, tcp_syn_flooding] for j in range(self.ss_num[0]): self.cc_list[0][j].addAnomalies([delay_command]) def injectDataIntegrityAttack(self): day = 11 delay_response = { "name": "Delay Response", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1100, "value": 1, } tamper_frequency = { "name": "Tamper Frequency", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1100, "value": 61, } over_voltage = { "name": "Over Voltage", "start_day": day, "start_index": 0, "end_day": day, "end_index": 3*60*24-1, } under_voltage = { "name": "Under Voltage", "start_day": day, "start_index": 0, "end_day": day, "end_index": 3*60*24-1, } tamper_voltage = { "name": "Tamper Voltage", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1100, "value": 10, } over_current = { "name": "Over Current", "start_day": day, "start_index": 0, "end_day": day, "end_index": 3*60*24-1, } tamper_power = { "name": "Tamper Power", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1100, "value": 10, } tamper_binary = { "name": "Tamper Binary", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1100, "value": -1.0, } self.cc_list[0][1].addAnomalies([delay_response, tamper_voltage]) #self.cc_list[0][1].addAnomalies([delay_response, tamper_frequency, tamper_binary]) #self.cc_list[0][1].addAnomalies([tamper_frequency, tamper_binary]) def injectCommandInjection(self): day = 13 address_scan = { "name": "Address Scan", "start_day": day, "start_index": 500, "end_day": day, "end_index": 500, "attacker_ip": "192.168.3.11", "subnet": "100.0.0.", } service_scan = { "name": "Service Scan", "start_day": day, "start_index": 700, "end_day": day, "end_index": 700, "attacker_ip": "192.168.3.11", "subnet": "100.0.0.", } tamper_command = { "name": "Tamper Command", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1000, "fc": 13, "fn": "COLD_RESTART", } delay_command = { "name": "Delay Command", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1000, "value": 1, } change_command_size = { "name": "Change Command Size", "start_day": day, "start_index": 1000, "end_day": day, "end_index": 1000, "value": 70, } #self.cc_list[0][2].addAnomalies([delay_command, change_command_size, tamper_command]) self.cc_list[0][2].addAnomalies([change_command_size, tamper_command]) self.anomalies += [address_scan, service_scan] def getIndex(self, day, i): return day*3*60*24 + i def getAnomaly(self, anomaly_name): rst = [] for anomaly in self.anomalies: if anomaly["name"] == anomaly_name: rst.append(anomaly) return rst def prepare(self): for day in range(self.num_day): for i in range(3*60*24): for ss_list in self.cc_list: for comm_pair in ss_list: comm_pair.generate_read(day, i) for ss_list in self.cc_list: for comm_pair in ss_list: comm_pair.generate_ack1() for ss_list in self.cc_list: for comm_pair in ss_list: comm_pair.generate_resp(day, i) for ss_list in self.cc_list: for comm_pair in ss_list: comm_pair.generate_conf() for ss_list in self.cc_list: for comm_pair in ss_list: comm_pair.generate_ack2() # Address Scan address_scans = self.getAnomaly("Address Scan") for anomaly in address_scans: ts = self.getIndex(anomaly["start_day"], anomaly["start_index"])*20 dst_port = "20000tcp" src_port = str(random.randint(44000, 47000)) + "tcp" subnet = anomaly["subnet"] cc_index = int(subnet.split(".")[2]) for j in range(1, 256): src_ip = anomaly["attacker_ip"] dst_ip = subnet + str(j) conn = (src_ip, src_port, dst_ip, dst_port) scan_gen = PacketGenerator( src_ip, dst_ip, "TCP", [], 48, conn, ) p_scan = scan_gen.generate_one(ts) self.pq.put((ts, 'p', p_scan)) if j < self.ss_num[cc_index] + 1: ts = ts + 0.2 + np.random.normal(0, 0.02) ack_gen = PacketGenerator( dst_ip, src_ip, "TCP", [], 52, conn, ) p_ack = ack_gen.generate_one(ts) self.pq.put((ts, 'p', p_ack)) # TCP SYN Flooding tcp_syn_floods = self.getAnomaly("TCP SYN Flooding") for anomaly in tcp_syn_floods: start_time = self.getIndex(anomaly["start_day"], anomaly["start_index"])*20 end_time = self.getIndex(anomaly["end_day"], anomaly["end_index"])*20 dst_port = "20000tcp" src_port = str(random.randint(44000, 47000)) + "tcp" dst_ip = anomaly["target_ip"] target_ip_list = dst_ip.split(".") cc_index = int(target_ip_list[2]) for j in range(self.ss_num[cc_index]+1): src_ip = "100.0.0." + str(j+1) if src_ip != dst_ip: conn = (src_ip, src_port, dst_ip, dst_port) syn_gen = PacketGenerator( src_ip, dst_ip, "TCP", ["DNP3_TCP"], 48, conn, 2, ) ts = start_time while ts <= end_time: p_syn = syn_gen.generate_one(ts) self.pq.put((ts, 'p', p_syn)) ts += anomaly["interval"] # Service Scan service_scans = self.getAnomaly("Service Scan") for anomaly in service_scans: ts = self.getIndex(anomaly["start_day"], anomaly["start_index"])*20 src_port = str(random.randint(44000, 47000)) + "tcp" subnet = anomaly["subnet"] cc_index = int(subnet.split(".")[2]) for j in range(self.ss_num[cc_index]+1): src_ip = anomaly["attacker_ip"] dst_ip = subnet + str(j) dst_port = "502tcp" conn = (src_ip, src_port, dst_ip, dst_port) scan_gen = PacketGenerator( src_ip, dst_ip, "TCP", ["MODEBUS"], 48, conn, ) p_scan = scan_gen.generate_one(ts) self.pq.put((ts, 'p', p_scan)) dst_port = "102tcp" conn = (src_ip, src_port, dst_ip, dst_port) scan_gen = PacketGenerator( src_ip, dst_ip, "TCP", ["IEC61850"], 48, conn, ) p_scan = scan_gen.generate_one(ts) self.pq.put((ts, 'p', p_scan)) dst_port = "20000tcp" conn = (src_ip, src_port, dst_ip, dst_port) scan_modbus_gen = PacketGenerator( src_ip, dst_ip, "TCP", ["DNP3_TCP"], 48, conn, ) p_scan = scan_gen.generate_one(ts) self.pq.put((ts, 'p', p_scan)) ts = ts + 0.2 + np.random.normal(0, 0.02) ack_gen = PacketGenerator( dst_ip, src_ip, "TCP", ["DNP3_TCP"], 52, conn, ) p_ack = ack_gen.generate_one(ts) self.pq.put((ts, 'p', p_ack)) def generate(self): self.prepare() while not self.pq.empty(): cur = self.pq.get() if cur[1] == 'p': self.packet_queue.put_nowait(cur[2]) elif cur[1] == 'o': self.operation_queue.put_nowait(cur[2]) else: self.data_value_queue.put_nowait(cur[2]) <file_sep>cd code if [[($# -eq 1) && ($1 = "real")]] then python edmand.py real & python anomaly_analyzer.py & bro -Cr ../trace/dnp3_test.pcap end_point.bro & wait else python edmand.py simulate & python anomaly_analyzer.py & wait fi <file_sep>import datetime class DataValue: def __init__(self, ts=None, holder_ip=None, protocol=None, uid=None, data_type=None, index=None, value=None, is_event=False ): self.ts = ts self.holder_ip = holder_ip self.protocol = protocol self.uid = uid self.data_type = data_type self.index = index self.value = value self.is_event = is_event def getDict(self): rst = {"ts": self.ts, "holder_ip": self.holder_ip, "service": self.protocol, "uid": self.uid, "data_type": self.data_type, "index": self.index, "value": self.value, "is_event": self.is_event} return rst def __str__(self): return ''' ts = {0} holder_ip = {1} protocol = {2} uid = {3} data_type = {4} index = {5} value = {6} is_event = {7} '''.format( datetime.datetime.fromtimestamp(self.ts), self.holder_ip, self.protocol, self.uid, self.data_type, self.index, self.value, self.is_event ) <file_sep>import numpy as np import math #LAMBDA = 0.002 LAMBDA = 0.005 MU = 20.0 BETA = 0.2 T_p = seconds=math.ceil(math.log(BETA*MU/(BETA*MU-1), 2)/LAMBDA) def fading(t): return 2**(-LAMBDA * t) class DenStream1D(): def __init__(self, epsilon): self.P_list = [] self.O_list = [] self.last_update = None self.epsilon = epsilon #print("T_p: " + str(T_p)) class OMicroCluster(): def __init__(self, epsilon, p, ts): self.epsilon = epsilon self.CF1 = p self.CF2 = p**2 self.w = 1 self.t0 = ts self.last_update = ts def __str__(self): return "o_c: {0}, o_w: {1}, o_r: {2}".format(self.getCenter(), self.w, self.getRadius()) def getCenter(self): return self.CF1 / self.w def getRadius(self): return math.sqrt(abs(self.CF2/self.w-(self.CF1/self.w)**2)) def merge(self, p, ts): if ts > self.last_update: fade = fading(ts-self.last_update) self.CF1 = fade * self.CF1 self.CF2 = fade * self.CF2 self.w = fade * self.w self.last_update = ts new_CF1 = self.CF1 + p new_CF2 = self.CF2 + p**2 new_w = self.w + 1 r = math.sqrt(abs(new_CF2/new_w-(new_CF1/new_w)**2)) if r <= self.epsilon: self.CF1 = new_CF1 self.CF2 = new_CF2 self.w = new_w return True else: return False def update(self, ts): xi = (2**(-LAMBDA*(ts-self.t0+T_p))-1)/(2**(-LAMBDA*T_p)-1) #print("Xi: " + str(xi)) if ts > self.last_update: fade = fading(ts-self.last_update) self.CF1 = fade * self.CF1 self.CF2 = fade * self.CF2 self.w = fade * self.w self.last_update = ts if self.w < xi: return False else: return True class PMicroCluster(): def __init__(self, o_micro_cluster): self.epsilon = o_micro_cluster.epsilon self.CF1 = o_micro_cluster.CF1 self.CF2 = o_micro_cluster.CF2 self.w = o_micro_cluster.w self.last_update = o_micro_cluster.last_update def __str__(self): return "p_c: {0}, p_w: {1}, p_r: {2}".format(self.getCenter(), self.w, self.getRadius()) def getCenter(self): return self.CF1 / self.w def getRadius(self): return math.sqrt(abs(self.CF2/self.w-(self.CF1/self.w)**2)) def merge(self, p, ts): if ts > self.last_update: fade = fading(ts-self.last_update) self.CF1 = fade * self.CF1 self.CF2 = fade * self.CF2 self.w = fade * self.w self.last_update = ts new_CF1 = self.CF1 + p new_CF2 = self.CF2 + p**2 new_w = self.w + 1 r = math.sqrt(abs(new_CF2/new_w-(new_CF1/new_w)**2)) if r <= self.epsilon: self.CF1 = new_CF1 self.CF2 = new_CF2 self.w = new_w return True else: return False def update(self, ts): if ts > self.last_update: fade = fading(ts-self.last_update) self.CF1 = fade * self.CF1 self.CF2 = fade * self.CF2 self.w = fade * self.w self.last_update = ts if self.w < BETA * MU: return False else: return True def distance(self, p, c): return abs(p - c) def merge(self, p, ts): p = float(p) #print(p) rst = True nearest_p = None dis_p = None ano_score = 0 p_c_list = [] p_r_list = [] for p_micro_cluster in self.P_list: c = p_micro_cluster.getCenter() r = p_micro_cluster.getRadius() p_c_list.append(c) p_r_list.append(r) dis_cur = self.distance(p, c) if nearest_p == None or dis_cur < dis_p: nearest_p = p_micro_cluster dis_p = dis_cur if nearest_p == None or not nearest_p.merge(p, ts): nearest_o = None dis_o = None for o_micro_cluster in self.O_list: dis_cur = self.distance(p, o_micro_cluster.getCenter()) if nearest_o == None or dis_cur < dis_o: nearest_o = o_micro_cluster dis_o = dis_cur if nearest_o != None and nearest_o.merge(p, ts): if nearest_o.w > BETA * MU: self.O_list.remove(nearest_o) self.P_list.append(DenStream1D.PMicroCluster(nearest_o)) else: rst = False ano_score = 1 - (nearest_o.w-1)/(BETA*MU-1) else: self.O_list.append(DenStream1D.OMicroCluster(self.epsilon, p, ts)) rst = False ano_score = 1 if self.last_update == None: self.last_update = ts elif ts > self.last_update + T_p: self.update(ts) self.last_update = ts return (rst, ano_score, p_c_list, p_r_list) def update(self, ts): for p_micro_cluster in self.P_list: if not p_micro_cluster.update(ts): self.P_list.remove(p_micro_cluster) for o_micro_cluster in self.O_list: if not o_micro_cluster.update(ts): self.O_list.remove(o_micro_cluster) def __str__(self): if self.P_list: rst = "\nP_list:\n" for i in range(len(self.P_list)): rst += "index: " + str(i) + ", " + str(self.P_list[i]) + "\n" else: rst = "\nP_list: Empty\n" if self.O_list: rst += "O_list:\n" for i in range(len(self.O_list)): rst += "index: " + str(i) + ", " + str(self.O_list[i]) + "\n" else: rst += "O_list: Empty\n" return rst <file_sep>from flow import Flow from anomaly import FlowAnomaly from inc_mean_std import ExpMeanSTD import numpy as np import math COUNT_EACH_NORM = 500.0 CONFI_TH = 0.666666 def sigmoid(x): return 2 * (1 / (1 + math.exp(-x)) - 0.5) def generate_anomaly(ts, desp, confi, index, anomaly_queue, flow=None, iat=None, mean=None, std=None, power=1): if confi**power >= CONFI_TH: anomaly = FlowAnomaly(ts, desp, confi, index, flow, iat, mean, std) anomaly_queue.put_nowait(anomaly) class FlowModel: def __init__(self, index, anomaly_queue): self.index = index self.anomaly_queue = anomaly_queue self.count_pkt_ab = ExpMeanSTD(COUNT_EACH_NORM, 0.02, 3) self.count_pkt_ba = ExpMeanSTD(COUNT_EACH_NORM, 0.02, 3) self.mean_bytes_ab = ExpMeanSTD(COUNT_EACH_NORM, 0.02) self.mean_bytes_ba = ExpMeanSTD(COUNT_EACH_NORM, 0.02) def update(self, flow): self.update_each(flow, flow.count_pkt_ab, self.count_pkt_ab, "PACKET_AB_TOO_MANY", "PACKET_AB_TOO_FEW") self.update_each(flow, flow.count_pkt_ba, self.count_pkt_ba, "PACKET_BA_TOO_MANY", "PACKET_BA_TOO_FEW") self.update_each(flow, flow.mean_bytes_ab, self.mean_bytes_ab, "MEAN_BYTES_AB_TOO_LARGE", "MEAN_BYTES_AB_TOO_SMALL") self.update_each(flow, flow.mean_bytes_ba, self.mean_bytes_ba, "MEAN_BYTES_BA_TOO_LARGE", "MEAN_BYTES_BA_TOO_SMALL") def update_each(self, flow, current, stats, desp_g=None, desp_l=None): rst, confi, mean, std = stats.update(current, True) if rst != 0: if rst == 1 and desp_g != None: generate_anomaly(flow.end, desp_g, confi, self.index, self.anomaly_queue, flow, current, mean, std, ) if rst == -1 and desp_l != None: generate_anomaly(flow.end, desp_l, confi, self.index, self.anomaly_queue, flow, current, mean, std, ) class FlowAnalyzer(): def __init__(self, anomaly_queue): self.flow_dict = dict() self.anomaly_queue = anomaly_queue def analyze(self, flow): #print(flow) key = flow.orig + ";" + flow.resp + ";" + flow.protocol_type + ";" + flow.service #print(key) if key not in self.flow_dict: self.flow_dict[key] = FlowModel(key, self.anomaly_queue); self.flow_dict[key].update(flow) <file_sep>import numpy as np import math class AlertCorrelator(): cor_th = 0.5 # CPT for Time Difference cor_CPT1 = np.array([[0.3, 0.3, 0.3, 0.1], [0.1, 0.2, 0.2, 0.5]]) # CPT for IP Similarity cor_CPT2 = np.array([[0.7, 0.15, 0.1, 0.05], [0.1, 0.3, 0.3, 0.3]]) # CPT for Same Protocol cor_CPT3 = np.array([[0.8, 0.2], [0.4, 0.6]]) # Dictionary for Anomaly Description Index anomaly_index = { 'PACKET_IAT': 0, 'PACKET_BYTES': 1, 'NEW_ORIG': 2, 'NEW_RESP': 3, 'NEW_PROTOCOL': 4, 'NEW_SERVICE': 5, 'PACKET_AB_TOO_MANY': 6, 'PACKET_AB_TOO_FEW': 7, 'PACKET_BA_TOO_MANY': 8, 'PACKET_BA_TOO_FEW': 9, 'MEAN_BYTES_AB_TOO_LARGE': 10, 'MEAN_BYTES_AB_TOO_SMALL': 11, 'MEAN_BYTES_BA_TOO_LARGE': 12, 'MEAN_BYTES_BA_TOO_SMALL': 13, 'OPERATION_TOO_LATE': 14, 'OPERATION_TOO_EARLY': 15, 'OPERATION_MISSING': 16, 'INVALID_FUNCTION_CODE': 17, 'RESPONSE_FROM_ORIG': 18, 'REQUEST_FROM_RESP': 19, 'NEW_OPERATION': 20, 'BINARY_FAULT': 21, 'ANALOG_TOO_LARGE': 22, 'ANALOG_TOO_SMALL': 23, } def __init__(self, time_accuracy=10, ): self.time_accuracy = time_accuracy self.cor_pi = [] anomaly_num = len(self.anomaly_index) for i in range(anomaly_num): row = [] for j in range(anomaly_num): row.append(np.array([0.2, 0.8])) self.cor_pi.append(row) def timeDifference(self, alert1, alert2): if (alert1['ts'][0] - alert2['ts'][1]) * (alert1['ts'][1] - alert2['ts'][0]) <= 0: return np.array([1, 0, 0, 0]) else: timediff = min(abs(alert1['ts'][0] - alert2['ts'][1]), abs(alert1['ts'][1] - alert2['ts'][0])) if timediff <= 60: return np.array([1, 0, 0, 0]) elif timediff <= 60*60: return np.array([0, 1, 0, 0]) elif timediff <= 60*60*24: return np.array([0, 0, 1, 0]) else: return np.array([0, 0, 0, 1]) def timeOrder(self, alert1, alert2): diff = alert1['ts'][0] - alert2['ts'][0] if abs(diff) <= self.time_accuracy: return 0 elif diff > 0: return 1 else: return -1 def ipSimilarity(self, ip1, ip2): ip1 = ip1.split('.') ip2 = ip2.split('.') assert(len(ip1) == 4) assert(len(ip2) == 4) similarity = 0 for i in range(4): if ip1[i] != ip2[i]: break similarity += 1 return similarity def ipPairSimilarity(self, alert1, alert2): if alert1['anomaly_type'] == 'measurement': ip_pair1 = [alert1['index'].split(';')[0]] else: ip_pair1 = alert1['index'].split(';')[0:2] if alert2['anomaly_type'] == 'measurement': ip_pair2 = [alert2['index'].split(';')[0]] else: ip_pair2 = alert2['index'].split(';')[0:2] max_similarity = 0 for ip1 in ip_pair1: if ip1 == "-": continue for ip2 in ip_pair2: if ip2 == "-": continue max_similarity = max(max_similarity, self.ipSimilarity(ip1, ip2)) if max_similarity == 4: return np.array([1, 0, 0, 0]) elif max_similarity == 3: return np.array([0, 1, 0, 0]) elif max_similarity == 2: return np.array([0, 0, 1, 0]) else: return np.array([0, 0, 0, 1]) def sameProtocol(self, alert1, alert2): if alert1['anomaly_type'] == 'packet': tmp = alert1['index'].split(';')[3].strip('[]').split(',') protocol1 = [proto.strip('\' ') for proto in tmp] elif alert1['anomaly_type'] == 'flow': protocol1 = [alert1['index'].split(';')[3]] elif alert1['anomaly_type'] == 'operation': protocol1 = [alert1['index'].split(';')[2]] else: protocol1 = [alert1['index'].split(';')[1]] if alert2['anomaly_type'] == 'packet': tmp = alert2['index'].split(';')[3].strip('[]').split(',') protocol2 = [proto.strip('\' ') for proto in tmp] elif alert2['anomaly_type'] == 'flow': protocol2 = [alert2['index'].split(';')[3]] elif alert2['anomaly_type'] == 'operation': protocol2 = [alert2['index'].split(';')[2]] else: protocol2 = [alert2['index'].split(';')[1]] for p1 in protocol1: for p2 in protocol2: if p1 != '' and p1 == p2: return np.array([1, 0]) return np.array([0, 1]) def correlate(self, alert1, alert2): # Get Prior Probability index1 = self.anomaly_index[alert1['desp']] index2 = self.anomaly_index[alert2['desp']] prior = self.cor_pi[index1][index2] # Time Difference lambda1 = np.dot(self.cor_CPT1, self.timeDifference(alert1, alert2)) lambda_total = lambda1 #print(self.timeDifference(alert1, alert2)) # IP Similarity lambda2 = np.dot(self.cor_CPT2, self.ipPairSimilarity(alert1, alert2)) lambda_total = np.multiply(lambda_total, lambda2) #print(self.ipPairSimilarity(alert1, alert2)) # Same Protocol lambda3 = np.dot(self.cor_CPT3, self.sameProtocol(alert1, alert2)) lambda_total = np.multiply(lambda_total, lambda3) #print(self.sameProtocol(alert1, alert2)) believe = np.multiply(prior, lambda_total) believe = believe / believe.sum(0) #pprint(meta_alert) #print(believe[1]) #print("") if believe[0] >= self.cor_th: return believe[0] else: return -1 <file_sep>import datetime import numpy as np import time import math from pymongo import MongoClient from pprint import pprint from correlate_alert import AlertCorrelator from generate_template import TemplateGenerator BEL_TH = 0 TIME_TH = 60*60*24*10 CANDIDATE_LIMIT = 3 class AlertAnalyzer(): def __init__(self): self.client = MongoClient() self.client.drop_database("meta_alert_database") self.alert_db = self.client.meta_alert_database self.alert_correlator = AlertCorrelator() self.template_generator = TemplateGenerator(self.alert_correlator, self.alert_db) self.template_generator.generate() self.candidate_dict = self.template_generator.getTemplates() def analyze(self, meta_alert): #print("") #pprint(meta_alert) #print("") update_time = meta_alert["ts"][1] meta_alerts = self.alert_db.meta_alert replace_rst = meta_alerts.replace_one({"_id": meta_alert["_id"]}, meta_alert, upsert=True) if replace_rst.matched_count > 0: for candidates in self.candidate_dict.itervalues(): for candidate in candidates: candidate.updateAlert(meta_alert) else: for attack_name, candidates in self.candidate_dict.iteritems(): new_candidates = [] for candidate in candidates: if candidate.isTemplate() or update_time - candidate.getLastUpdateTime() < TIME_TH: new_candidates += candidate.matchAlert(meta_alert) if len(new_candidates) > CANDIDATE_LIMIT: new_candidates.sort(key=lambda x: x.getRankScore()) index = 0 while index < len(new_candidates) and len(new_candidates) > CANDIDATE_LIMIT: if new_candidates[index].isTemplate(): index += 1 else: new_candidates.remove(new_candidates[index]) self.candidate_dict[attack_name] = new_candidates def print_alerts(self): meta_alerts = self.alert_db.meta_alert print("Meta-Alert Number: " + str(meta_alerts.count())) #for meta_alert in meta_alerts.find(): # print("") # pprint(meta_alert) def print_candidates(self, top_k=100): print_list = [] for candidates in self.candidate_dict.itervalues(): candidates.sort(key=lambda x: x.getRankScore(), reverse=True) if not candidates[0].isTemplate() and candidates[0].getMaxLeafBEL() > BEL_TH: print_list.append(candidates[0]) print_list.sort(key=lambda x: x.getRankScore(), reverse=True) top_k = min(top_k, len(print_list)) for i in range(top_k): print(print_list[i])
4db72897037b08a28203bf0c0367ac3df47f8d4d
[ "Python", "Text", "Shell" ]
25
Python
ITI/aius
e3e6990d06f4732c05a226869fc3eb44a37df4e6
c44f9baac83f3b7adcab90f51082322e91f0b6c8
refs/heads/master
<file_sep>// // main.swift // SimpleCalc // // Created by <NAME> on 10/7/15. // Copyright (c) 2015 <NAME>. All rights reserved. // INFO 498 // import Foundation // Accepts string input from console func input() -> String { let keyboard = NSFileHandle.fileHandleWithStandardInput() let inputData = keyboard.availableData let result = NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String return result.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } // Converts given String to Double and returns result func convertToDouble(incoming:String) -> Double { return (incoming as NSString).doubleValue } // Splits given String by spaces into an Array func splitBySpaces(incoming:String) -> [String] { return incoming.componentsSeparatedByString(" ") } // Returns factorial of given Int func factorial(incoming:Double) -> Double { if incoming < 2 { return 1 } else { return incoming * factorial(incoming - 1) } } println("Welcome to <NAME>'s SimpleCalc! Now ready for input.") // First line entered by user split into an array by spaces var userInput = splitBySpaces(input()) // There are multiple elements in the input, treat as multi-operand operation if (userInput.count > 1) { let op = userInput[userInput.count - 1] switch op { case "count": // Count operation, return array size minus operator descriptor println(userInput.count - 1) case "avg": // Average operation, add all numbers, divide by array size minus operator descriptor let numberCount = userInput.count - 1 var result : Double = 0 var temp : Double = 0 for var index = 0; index < numberCount; index++ { temp = convertToDouble(userInput[index]) result += temp } result = result / Double(numberCount) println(result) case "fact": // Factorial operation, print error if given more than one number, otherwise return factorial if (userInput.count > 2) { println("Factorial operation only accepts one number") } else { println(factorial(convertToDouble(userInput[0]))) } default: // Operation given in incorrect format or unrecognized operator println("Not an accepted operator!") } } else { // Only one element in first input, treat as simple multi-line calculation // Gather variables and convert to double let first = convertToDouble(userInput[0]) // Operator println("Enter desired operation") let op = input() // Second number println("Enter second number") let second = convertToDouble(input()) println("Result:") var r: Double // Print result based on operator switch op { case "+": r = first + second println(r) case "-": r = first - second println(r) case "*": r = first * second println(r) case "/": r = first / second println(r) case "%": r = first % second println(r) default: // Operator not recognized println("Not an accepted operator!") } }
23dd613d962de95e89b0d300dc949d7ebd56f7be
[ "Swift" ]
1
Swift
AlexSchenck/SimpleCalc-iOS
1000e50a919f89a02f9a69ef1b0f2d55ac68b491
32b9642df66e0d9d795593f240e3bb0b46306149
refs/heads/master
<file_sep># robocode-chkv This repository contains the code for Robocode bot created for TechIgnite 2015 by, <NAME>, <NAME>, <NAME>, <NAME><file_sep>package chkv; import robocode.*; import java.awt.Color; /** * Created by HirSlk on 10/9/2015 * API help : http://robocode.sourceforge.net/docs/robocode/robocode/Robot.html */ public class BotMain extends AdvancedRobot { double bFHeight; double bFWidth; public void run() { setAdjustRadarForGunTurn(false); bFHeight = this.getBattleFieldHeight(); bFWidth = this.getBattleFieldWidth(); setColors(Color.red,Color.blue,Color.green); // body,gun,radar while(true) { try { moveRobot(); fireRobot(); surviveRobot(); } catch (Exception e) { System.out.println(e.getMessage()); } } } private void fireRobot () { this.turnGunRight(360); } private void surviveRobot () { //this.ahead(100); } private void moveRobot () { double myX = this.getX(); double myY = this.getY(); double myHeading = this.getHeading(); boolean turnRight = false; boolean turnLeft = false; int safeDistance = 200; if (myHeading < 90) { if ((safeDistance * Math.cos(Math.toRadians(myHeading%90))) > (bFHeight - myY)) { turnRight = true; } if ((safeDistance * Math.sin(Math.toRadians(myHeading%90))) > (bFWidth - myX)) { turnLeft = true; } } else if (90 <= myHeading && myHeading < 180) { if ((safeDistance * Math.sin(Math.toRadians(myHeading % 90))) > (myY)) { turnLeft = true; } if ((safeDistance * Math.cos(Math.toRadians(myHeading % 90))) > (bFWidth - myX)) { turnRight = true; } } else if (180 <= myHeading && myHeading < 270) { if ((safeDistance * Math.cos(Math.toRadians(myHeading%90))) > (myY)) { turnRight = true; } if ((safeDistance * Math.sin(Math.toRadians(myHeading%90))) > (myX)) { turnLeft = true; } } else if (270 <= myHeading) { if ((safeDistance * Math.sin(Math.toRadians(myHeading % 90))) > (bFHeight - myY)) { turnLeft = true; } if ((safeDistance * Math.cos(Math.toRadians(myHeading % 90))) > (myX)) { turnRight = true; } } if ((turnLeft == true) && (turnRight == true)) { this.setTurnRight(180); } else if (turnLeft == true) { this.setTurnLeft(90); } else if (turnRight == true) { this.setTurnRight(90); } this.ahead(100); } /** * onScannedRobot: What to do when you see another robot */ public void onScannedRobot(ScannedRobotEvent e) { // Replace the next line with any behavior you would like fire(2); } /** * onHitByBullet: What to do when you're hit by a bullet */ public void onHitByBullet(HitByBulletEvent e) { // Replace the next line with any behavior you would like //turnRight(30); //moveRobot(); } /** * onHitWall: What to do when you hit a wall */ public void onHitWall(HitWallEvent e) { // Replace the next line with any behavior you would like //back(20); } }
a61300ee1ede11b20ba82f2f67e435200d251a53
[ "Markdown", "Java" ]
2
Markdown
hiranthasankalpa/robocode-chkv
13dcc2697a4a22c3233116cf5a9ec35ae2c3b928
aded859590a902e7e66ea62d9121e143935cf66b
refs/heads/main
<file_sep>// server/index.js const express = require("express"); const PORT = process.env.PORT || 3001; const app = express(); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get("/api", (req, res) => { res.json({ message: "Hello from server!" }); }); app.listen(PORT, () => { console.log(`Server listening on ${PORT}`); });<file_sep>import React from 'react'; import './Chat.css' import {IconButton} from "@material-ui/core"; import {Mic, Send, Phone} from "@material-ui/icons"; const Chat = ({chatName="<NAME>"}) => { return ( <div className="chat-container"> <div className="chat-header"> {chatName} </div> <div className="chat-dialog-field"> <div className="chat-message-field bot-message"> <img className="chat-message-avatar"/> <p className="chat-message-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, corporis! Voluptate voluptatum quos consectetur cumque.</p> </div> <div className="chat-message-field user-message"> <img className="chat-message-avatar"/> <p className="chat-message-text">Lorem ipsum dolor sit amet.</p> </div> </div> <div className="chat-create-message-field"> <input className="chat-message-input" placeholder="Напишите сообщение..."/> <IconButton><Send/></IconButton> <IconButton><Mic/></IconButton> </div> </div> ); }; export default Chat;<file_sep>import '../utils/App.css'; import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css' import NaviBar from '../components/Navibar'; import { BrowserRouter } from 'react-router-dom'; import AppRouter from '../components/AppRouter'; import {AuthProvider} from "../Auth"; function App() { const [data, setData] = React.useState(null); return ( <AuthProvider> <BrowserRouter className="App page"> <NaviBar/> <AppRouter/> </BrowserRouter> </AuthProvider> ); } export default App;<file_sep>import React from 'react' import { Container, Row, Col } from 'react-bootstrap' import MyCard2 from '../MyCard2' import surg from '../../resources/surgeon.jpg' import '../Mycard.css' import '../../utils/App.css' import firebase from './../../firebase' import { StylesProvider } from '@material-ui/core' import ScrollArea from 'react-scrollbar' export default class DoctorsPage extends React.Component { constructor() { super() this.state = {cardInfo: []} } componentDidMount() { const dbRef = firebase.database().ref(); dbRef.child("doctor_types").get().then((doctors) => { this.setState({cardInfo: doctors.val()}); console.log(this.state.cardInfo) }) } componentDidUpdate() { console.log("Updated"); } render() { console.log(this.state.cardInfo) return ( <div className="grid" onLoad={() => console.log("LOADED")}> { this.state.cardInfo.map( (card, index) => <MyCard2 title={card.type} img={card.image_id} desc={card.desc}/>)} </div> ) } }<file_sep>import React from 'react' import '../../utils/App.css' import Chat from "../chatbot/Chat"; import './ChatPage.css' import ChooseDoctorPage from './ChooseDoctorPage' export default function ChatPage() { return ( <div className="chat-page"> <div className="chat"> <Chat /> </div> <div className="recom"> <ChooseDoctorPage/> </div> </div> ) }
b91d0ad915ec831f4589e8aba53149883dffd350
[ "JavaScript" ]
5
JavaScript
AlexeyKozlovsky/IT_Cow_web_app
9da1cea99b52a79320764de14d8d5d61a1a87f39
1aa5012b60c5f5c496d4da91b707864c1e8efca0
refs/heads/master
<repo_name>zhangzh56/yikatong-parent<file_sep>/yikatong-core/src/main/java/com/meatball/vo/ResultMsg.java /** * Project Name:meatball-core * File Name:ResultMsg.java * Package Name:com.meatball.vo * Date:2017年10月17日下午4:18:11 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import springfox.documentation.annotations.ApiIgnore; /** * @Title: ResultMsg.java * @Package com.meatball.vo * @Description: TODO(返回消息) * @author 張翔宇 * @date 2017年10月17日 下午4:18:11 * @version V1.0 */ @ApiModel(value = "ResultMsg", description = "消息返回") @ApiIgnore public class ResultMsg { // 状态码 @ApiModelProperty("状态码") private int code; // 消息内容 @ApiModelProperty("消息内容") private String message; // @ApiModelProperty("权限令牌") private String token; @ApiModelProperty("返回数据") private Object data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ResultMsg(int code) { this.code = code; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public ResultMsg(int code, String message) { this.code = code; this.message = message; } public ResultMsg(int code, String message, String token) { this.code = code; this.message = message; this.token = token; } public ResultMsg(int code, String message, String token, Object data) { this.code = code; this.message = message; this.token = token; this.data = data; } public ResultMsg(int code, Object data) { this.code = code; this.data = data; } public ResultMsg(int code, String message, Object data) { this.code = code; this.message = message; this.data = data; } } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/FileUploadUtil.java /** * Project Name:meatball-admin * File Name:FileUpload.java * Package Name:com.meatball.component * Date:2017年10月12日下午10:19:16 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.utils; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSON; import com.meatball.component.properties.Upload; import com.meatball.utils.DateUtil; import com.meatball.vo.FileUploadResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * @Title: FileUpload.java * @Package com.meatball.component * @Description: TODO(上传) * @author 張翔宇 * @date 2017年10月12日 下午10:19:16 * @version V1.0 */ @Api(tags = "文件上传") @Controller public class FileUploadUtil { private Logger log = LoggerFactory.getLogger(FileUploadUtil.class); @Resource private ResourceLoader resourceLoader; @Resource private Upload upload; /** * @Title: upload * @Description: TODO(上传) * @param file * @param request * @return String 返回类型 */ @ApiOperation(value = "文件上传") @RequestMapping("/upload") @ResponseBody public List<FileUploadResponse> upload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) { List<FileUploadResponse> list = new ArrayList<FileUploadResponse>(); // 获取文件存放根路径 String basePath = upload.getBasePath(); // 文件存放分支路径 String location = DateUtil.format(new Date(), "yyyy-MM-dd") + "/"; // 文件类型 String contentType = ""; // 原文件名称 String fileName = ""; // 存放名称 String saveName = ""; // 图片后缀 String imgSuffix = ""; // 判断文件夹是否存在,不存在则 File targetFile = new File(basePath + location); if(!targetFile.exists()){ targetFile.setWritable(true, false); targetFile.mkdirs(); } for(MultipartFile file : files) { FileUploadResponse rs = new FileUploadResponse(); contentType = file.getContentType(); fileName = file.getOriginalFilename(); imgSuffix = fileName.substring(fileName.lastIndexOf(".")); saveName = new Date().getTime() + imgSuffix; try { // java7中新增特性 // ATOMIC_MOVE 原子性的复制 // COPY_ATTRIBUTES 将源文件的文件属性信息复制到目标文件中 // REPLACE_EXISTING 替换已存在的文件 Files.copy(file.getInputStream(), Paths.get(upload.getBasePath() + location, saveName), StandardCopyOption.REPLACE_EXISTING); rs.setContentType(contentType); rs.setFileName(fileName); rs.setUrl(Base64Util.encodeData(location + saveName) + imgSuffix); // rs.setUrl(location + fileName); rs.setType("success"); } catch (Exception e) { rs.setType("fail"); rs.setMsg("文件上传失败!"); log.error("上传文件失败," + e); } list.add(rs); } //返回json log.info(JSON.toJSONString(list)); return list; } /** * @Title: getFile * @Description: TODO(获取图片) * @param url * @return ResponseEntity<?> 返回类型 */ @GetMapping("/{url:.+}") @ResponseBody public ResponseEntity<?> getFile(@PathVariable String url) { url = url.substring(0, url.lastIndexOf(".")); try { return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(upload.getBasePath() + Base64Util.decodeData(url)).toString())); // return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(uploadProperties.getBasePath() + path + filename).toString())); } catch (Exception e) { return ResponseEntity.notFound().build(); } } } <file_sep>/yikatong-startup/src/main/test/com/meatball/test/EnumTest.java /** * Project Name:meatball-startup * File Name:EnumTest.java * Package Name:com.meatball.test * Date:2018年3月22日下午3:56:30 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.test; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * @Title: EnumTest.java * @Package com.meatball.test * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2018年3月22日 下午3:56:30 * @version V1.0 */ public enum EnumTest { RESERVED(0), PING(1), PING_ACK(2), KEY_EXCHANGE(3), KEY_EXCHANGE_ACK(4), CONNECT(5), CONNECT_ACK(6), DISCONNECT(7), KEEP_ALIVE( 8), KEEP_ALIVE_ACK(9) ; private final int value; /** * enum lookup map */ private static final Map<Integer, EnumTest> lookup = new HashMap<Integer, EnumTest>(); static { for (EnumTest s : EnumSet.allOf(EnumTest.class)) { lookup.put(s.getValue(), s); } } EnumTest(int value) { this.value = value; } public int getValue() { return value; } public static EnumTest lookup(int value) { return lookup.get(value); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/service/RechargeApiService.java /** * Project Name:meatball-rest * File Name:RechargeApiService.java * Package Name:com.meatball.api.ykt.service * Date:2018年3月16日上午10:10:51 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.service; import com.meatball.api.ykt.parems.AccountCreateParams; import com.meatball.api.ykt.parems.AccountModifyParams; import com.meatball.api.ykt.parems.CancelAmountParams; import com.meatball.api.ykt.parems.ComsumeAmountParams; import com.meatball.api.ykt.parems.RechargeAmountParams; import com.meatball.api.ykt.parems.RefundAmountParams; import com.meatball.vo.ResultMsg; /** * @Title: RechargeApiService.java * @Package com.meatball.api.ykt.service * @Description: TODO(充值类接口) * @author jw * @date 2018年3月16日 上午10:10:51 * @version V1.0 */ public interface RechargeApiService { /** * @Title: getCreateCardResult * @Description: TODO(获取系统建卡结果) * @param params 系统建卡参数类 * @return * @return ResultMsg 返回 账户基本信息(包含虚拟卡号在内的基本信息) */ public ResultMsg getCreateCardResult(AccountCreateParams params) throws Exception; /** * @Title: getRechargeResult * @Description: TODO(获取充值操作结果) * @param params 操作金额参数类 * @return * @return ResultMsg 返回 是否充值成功和余额等信息(如不成功返回失败原因) */ public ResultMsg getRechargeResult(RechargeAmountParams params); /** * @Title: getComsumeResult * @Description: TODO(获取消费操作结果) * @param params 操作金额参数类 * @return * @return ResultMsg 返回 是否成功和余额等信息(如不成功返回失败原因) */ public ResultMsg getComsumeResult(ComsumeAmountParams params); /** * @Title: getRefundResult * @Description: TODO(获取退款操作结果) * @param params 操作金额参数类 * @return * @return ResultMsg 返回 是否成功和余额等信息(如不成功返回失败原因) */ public ResultMsg getRefundResult(RefundAmountParams params); /** * @Title: getCancelResult * @Description: TODO(获取撤销操作结果) * @param params * @return * @return ResultMsg 返回类型 */ public ResultMsg getCancelResult(CancelAmountParams params); /** * @Title: getModifyCardResult * @Description: TODO(获取账户修改信息结果) * @param params * @return * @return ResultMsg 返回类型 */ public ResultMsg getModifyCardResult(AccountModifyParams params); } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/UUIDUtil.java /** * Project Name:meatball-core * File Name:UUIDUtil.java * Package Name:com.meatball.utils * Date:2017年10月11日下午4:49:27 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.utils; import java.util.UUID; /** * @Title: UUIDUtil.java * @Package com.meatball.utils * @Description: TODO(生成ID) * @author 張翔宇 * @date 2017年10月11日 下午4:49:27 * @version V1.0 */ public class UUIDUtil { public static String uuid() { return UUID.randomUUID().toString().replaceAll("-", ""); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/user/parems/UserParems.java /** * Project Name:meatball-rest * File Name:UserParems.java * Package Name:com.meatball.api.user.parems * Date:2018年3月4日下午3:48:58 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.user.parems; import java.io.Serializable; /** * @Title: UserParems.java * @Package com.meatball.api.user.parems * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2018年3月4日 下午3:48:58 * @version V1.0 */ public class UserParems implements Serializable { private static final long serialVersionUID = 1L; // private String token; // private String userId; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/PayResultParams.java /** * Project Name:meatball-rest * File Name:PayResultParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月13日下午4:53:09 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Title: PayResultParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(扫码支付结果信息) * @author jw * @date 2018年3月13日 下午4:53:09 * @version V1.0 */ @Data public class PayResultParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="交易结果(0:成功 1:失败)", example="0") private int resultCode; @ApiModelProperty(value="支付结果的详细描述信息", example="微信支付成功20元") private String resultMsg; @ApiModelProperty(value="订单号", example="1123456") private String number; @ApiModelProperty(value = "支付方式(1:微信,2:支付宝)", example="1") private Integer payType; @ApiModelProperty(value="订单类别(1充值、2消费、3退款)", example="1") private int orderType; } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/RechargeRecordParams.java /** * Project Name:meatball-rest * File Name:RechargeRecordParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月13日下午4:03:47 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; /** * @Title: RechargeRecordParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(充值记录信息) * @author jw * @date 2018年3月13日 下午4:03:47 * @version V1.0 */ public class RechargeRecordParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="记录id", example="1") private String id; @ApiModelProperty(value="支付方式(1现金2银行卡3微信4支付宝)", example="1") private Integer iPaytype; @ApiModelProperty(value="支付方式名称", example="现金") private String vPayname; @ApiModelProperty(value="充值支付编号(平台交易流水号)", example="11111111") private String vOrderid; @ApiModelProperty(value="账户编号", example="123") private String bAccountid; @ApiModelProperty(value="账户名称", example="张三") private String vAccountname; @ApiModelProperty(value="交易类别(1挂号费、2门诊(处方)费、3住院费)", example="1") private Integer iDealtype; @ApiModelProperty(value="交易类别名称", example="挂号费") private String vDealname; @ApiModelProperty(value="充值金额(带两位小数点)", example="5000.00") private String dBalance; @ApiModelProperty(value="充值状态(0成功 1失败 8撤销 9待支付)", example="0") private Integer iDealstatus; @ApiModelProperty(value="充值时间(yyyy-MM-dd HH:mm:ss)", example="2010-10-10 15:11:12") private String tDealtime; @ApiModelProperty(value="机器编号", example="xxxxxx") private String vMachineid; @ApiModelProperty(value="操作员", example="xxxx") private String vOperator; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getiPaytype() { return iPaytype; } public void setiPaytype(Integer iPaytype) { this.iPaytype = iPaytype; } public String getvPayname() { return vPayname; } public void setvPayname(String vPayname) { this.vPayname = vPayname; } public String getvOrderid() { return vOrderid; } public void setvOrderid(String vOrderid) { this.vOrderid = vOrderid; } public String getbAccountid() { return bAccountid; } public void setbAccountid(String bAccountid) { this.bAccountid = bAccountid; } public String getvAccountname() { return vAccountname; } public void setvAccountname(String vAccountname) { this.vAccountname = vAccountname; } public Integer getiDealtype() { return iDealtype; } public void setiDealtype(Integer iDealtype) { this.iDealtype = iDealtype; } public String getvDealname() { return vDealname; } public void setvDealname(String vDealname) { this.vDealname = vDealname; } public String getdBalance() { return dBalance; } public void setdBalance(String dBalance) { this.dBalance = dBalance; } public Integer getiDealstatus() { return iDealstatus; } public void setiDealstatus(Integer iDealstatus) { this.iDealstatus = iDealstatus; } public String gettDealtime() { return tDealtime; } public void settDealtime(String tDealtime) { this.tDealtime = tDealtime; } public String getvMachineid() { return vMachineid; } public void setvMachineid(String vMachineid) { this.vMachineid = vMachineid; } public String getvOperator() { return vOperator; } public void setvOperator(String vOperator) { this.vOperator = vOperator; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/service/impl/AccountInfoApiServiceImpl.java /** * Project Name:meatball-rest * File Name:AccountInfoApiServiceImpl.java * Package Name:com.meatball.api.ykt.service.impl * Date:2018年3月16日上午10:00:02 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.service.impl; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.meatball.api.ykt.dao.AccountMapper; import com.meatball.api.ykt.dao.RechargeRecordMapper; import com.meatball.api.ykt.model.Account; import com.meatball.api.ykt.dao.ComsumeRecordMapper; import com.meatball.api.ykt.dao.RechargeRecordMapper; import com.meatball.api.ykt.dao.RefundRecordMapper; import com.meatball.api.ykt.model.Account; import com.meatball.api.ykt.model.ComsumeRecord; import com.meatball.api.ykt.model.RechargeRecord; import com.meatball.api.ykt.model.RefundRecord; import com.meatball.api.ykt.parems.AccountInfoParams; import com.meatball.api.ykt.parems.AccountQueryParams; import com.meatball.api.ykt.parems.ConsumeRecordParams; import com.meatball.api.ykt.parems.RechargeRecordParams; import com.meatball.api.ykt.parems.RefundAmountInfoParams; import com.meatball.api.ykt.parems.RefundRecordParams; import com.meatball.api.ykt.service.AccountInfoApiService; import com.meatball.vo.ResultMsg; /** * @Title: AccountInfoApiServiceImpl.java * @Package com.meatball.api.ykt.service.impl * @Description: TODO(账户信息充值记录等查询接口实现类) * @author jw * @date 2018年3月16日 上午10:00:02 * @version V1.0 */ @Service public class AccountInfoApiServiceImpl implements AccountInfoApiService { @Resource private RechargeRecordMapper rechargeRecordMapper; @Resource private AccountMapper accountMapper; @Resource private ComsumeRecordMapper comsumeRecordMapper; @Resource private RefundRecordMapper refundRecordMapper; SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * @Title: setAccountInfo * @Description: TODO(组装充值返回信息) * @param params * @param account * @param msg * @return void 返回类型 */ /** * 账户返回信息 * @param account * @param info * @param msg */ private void setAccountInfo(Account account,AccountInfoParams info,String msg) { info.setId(account.getbId().toString()); info.setResultCode(0); info.setResultMsg(msg); info.setName(account.getvName()); info.setIdcard(account.getvIdcard()); info.setCardNumber(account.getvPatientidcard()); info.setGender(account.getiGender()); info.setTel(account.getvTel()); info.setAddress(account.getvAddress()); info.setBirthday(sdf.format(account.getdBirthday())); info.setSinCard(account.getvSincard()); info.setHealthCard(account.getvHealthcard()); info.setBalance(String.valueOf(account.getdBalance())); info.setCreateDate(sdf1.format(account.gettCreatedate())); } /** * 余额查询信息 * @param params * @param account * @param info * @param msg */ private void setRefundAmountInfo(AccountQueryParams params,Account account,RefundAmountInfoParams info,String msg){ info.setResultCode(0); info.setResultMsg(msg); info.setType(params.getType()); info.setNumber(account.getvTel()); info.setName(account.getvName()); info.setCreateDate(sdf1.format(account.gettCreatedate())); info.setBalance(String.valueOf(account.getdBalance())); } /** * 消费记录返回信息 * @param comsumeRecord * @return */ private List<ConsumeRecordParams> setConsumeRecordBy(List<ComsumeRecord> comsumeRecord){ if(comsumeRecord.size()>0){ List<ConsumeRecordParams> ls = new ArrayList<>(); for(int i =0;i<comsumeRecord.size();i++){ ConsumeRecordParams info = new ConsumeRecordParams(); info.setId(comsumeRecord.get(i).getbId().toString()); info.setiPaytype(comsumeRecord.get(i).getiPaytype()); info.setvPayname(comsumeRecord.get(i).getvPayname()); info.setvPaymentid(comsumeRecord.get(i).getvPaymentid()); info.setbAccountid(comsumeRecord.get(i).getbAccountid().toString()); info.setvAccountname(comsumeRecord.get(i).getvAccountname()); info.setiDealtype(comsumeRecord.get(i).getiDealtype()); info.setvDealname(comsumeRecord.get(i).getvDealname()); info.setdBalance(String.valueOf(comsumeRecord.get(i).getdBalance())); info.setiDealstatus(comsumeRecord.get(i).getiDealstatus()); info.settDealtime(sdf1.format(comsumeRecord.get(i).gettDealtime())); info.setvMachineid(comsumeRecord.get(i).getvMachineid()); info.setvOperator(comsumeRecord.get(i).getvOperator()); ls.add(info); } return ls; }else{ return null; } } /** * 充值记录返回信息 * @param RechargeRecord * @return */ private List<RechargeRecordParams> setRechargeRecord(List<RechargeRecord> RechargeRecord){ if(RechargeRecord.size()>0){ List<RechargeRecordParams> ls = new ArrayList<>(); for(int i =0;i<RechargeRecord.size();i++){ RechargeRecordParams info = new RechargeRecordParams(); info.setId(RechargeRecord.get(i).getbId().toString()); info.setiPaytype(RechargeRecord.get(i).getiPaytype()); info.setvPayname(RechargeRecord.get(i).getvPayname()); info.setvOrderid(RechargeRecord.get(i).getvOrderid()); info.setbAccountid(RechargeRecord.get(i).getbAccountid().toString()); info.setvAccountname(RechargeRecord.get(i).getvAccountname()); info.setiDealtype(RechargeRecord.get(i).getiDealtype()); info.setvDealname(RechargeRecord.get(i).getvDealname()); info.setdBalance(String.valueOf(RechargeRecord.get(i).getdBalance())); info.setiDealstatus(RechargeRecord.get(i).getiDealstatus()); info.settDealtime(sdf1.format(RechargeRecord.get(i).gettDealtime())); info.setvMachineid(RechargeRecord.get(i).getvMachineid()); info.setvOperator(RechargeRecord.get(i).getvOperator()); ls.add(info); } return ls; }else{ return null; } } /** * 退款记录返回信息 * @param RechargeRecord * @return */ private List<RefundRecordParams> setAccountInfo(List<RefundRecord> RefundRecord){ if(RefundRecord.size()>0){ List<RefundRecordParams> ls = new ArrayList<>(); for(int i =0;i<RefundRecord.size();i++){ RefundRecordParams info = new RefundRecordParams(); info.setId(RefundRecord.get(i).getbId().toString()); info.setiDealstatus(RefundRecord.get(i).getiDealstatus()); info.setiPaytype(RefundRecord.get(i).getiPaytype()); info.setvPayname(RefundRecord.get(i).getvPayname()); info.setvPaymentid(RefundRecord.get(i).getvPaymentid()); info.setvAccountname(RefundRecord.get(i).getvAccountname()); info.setbAccountid(RefundRecord.get(i).getbAccountid().toString()); info.setiDealtype(RefundRecord.get(i).getiDealtype()); info.setvDealname(RefundRecord.get(i).getvDealname()); info.setdBalance(String.valueOf(RefundRecord.get(i).getdBalance())); info.settDealtime(sdf1.format(RefundRecord.get(i).gettDealtime())); info.setvMachineid(RefundRecord.get(i).getvMachineid()); info.setvOperator(RefundRecord.get(i).getvOperator()); info.setvPic(RefundRecord.get(i).getvPic()); ls.add(info); } return ls; }else{ return null; } } /** * 账户信息查询 */ @Override public ResultMsg getAccountInfoBy(AccountQueryParams params) { Account account = null; //身份证号 String idcard = null; //就诊卡号 String cardNumber = null; //社保卡号 String sinCard = null; //居民健康卡号 String healthCard = null; AccountInfoParams infoParams = new AccountInfoParams(); ResultMsg msg = new ResultMsg(200, infoParams); /*1、先查询账户是否存在*/ switch (params.getType()) { case 1://身份证号 idcard = params.getNumber(); account = accountMapper.selectAccountByIdcard(idcard); setAccountInfo(account,infoParams,"操作成功"); break; case 2://就诊卡号 cardNumber = params.getNumber(); account = accountMapper.selectAccountByPatientidcard(cardNumber); setAccountInfo(account,infoParams,"操作成功"); break; case 3://社保卡号 sinCard = params.getNumber(); account = accountMapper.selectAccountBySincard(sinCard); setAccountInfo(account,infoParams,"操作成功"); break; case 4://居民健康卡号 healthCard = params.getNumber(); account = accountMapper.selectAccountByHealthcard(healthCard); setAccountInfo(account,infoParams,"操作成功"); break; default: infoParams.setResultCode(1); infoParams.setResultMsg("请传入正确的卡类别"); break; } return msg; } /** * 余额查询 */ @Override public ResultMsg getAccountBalanceBy(AccountQueryParams params) { Account account = null; //身份证号 String idcard = null; //就诊卡号 String cardNumber = null; //社保卡号 String sinCard = null; //居民健康卡号 String healthCard = null; RefundAmountInfoParams info = new RefundAmountInfoParams(); ResultMsg msg = new ResultMsg(200, info); /*1、先查询账户是否存在,如果存在则查询账户信息*/ switch (params.getType()) { case 1://身份证号 idcard = params.getNumber(); account = accountMapper.selectAccountByIdcard(idcard); setRefundAmountInfo(params,account,info,"操作成功"); break; case 2://就诊卡号 cardNumber = params.getNumber(); account = accountMapper.selectAccountByPatientidcard(cardNumber); setRefundAmountInfo(params,account,info,"操作成功"); break; case 3://社保卡号 sinCard = params.getNumber(); account = accountMapper.selectAccountBySincard(sinCard); setRefundAmountInfo(params,account,info,"操作成功"); break; case 4://居民健康卡号 healthCard = params.getNumber(); account = accountMapper.selectAccountByHealthcard(healthCard); setRefundAmountInfo(params,account,info,"操作成功"); break; default: info.setResultCode(1); info.setResultMsg("请传入正确的卡类别"); break; } return msg; } /** * 充值记录查询 */ @Override public ResultMsg getRechargeRecordBy(AccountQueryParams params) { Account account = null; List<RechargeRecord> rechargeRecord = null; //身份证号 String idcard = null; //就诊卡号 String cardNumber = null; //社保卡号 String sinCard = null; //居民健康卡号 String healthCard = null; Long uid= null; List<RechargeRecordParams> setRechargeRecord = new ArrayList<>(); /*1、先查询账户是否存在,如果存在则查询账户信息*/ switch (params.getType()) { case 1://身份证号 idcard = params.getNumber(); account = accountMapper.selectAccountByIdcard(idcard); uid= account.getbId(); rechargeRecord = rechargeRecordMapper.selectBAccountid(uid); setRechargeRecord = setRechargeRecord(rechargeRecord); break; case 2://就诊卡号 cardNumber = params.getNumber(); account = accountMapper.selectAccountByPatientidcard(cardNumber); uid= account.getbId(); rechargeRecord = rechargeRecordMapper.selectBAccountid(uid); setRechargeRecord = setRechargeRecord(rechargeRecord); break; case 3://社保卡号 sinCard = params.getNumber(); account = accountMapper.selectAccountBySincard(sinCard); uid= account.getbId(); rechargeRecord = rechargeRecordMapper.selectBAccountid(uid); setRechargeRecord = setRechargeRecord(rechargeRecord); break; case 4://居民健康卡号 healthCard = params.getNumber(); account = accountMapper.selectAccountByHealthcard(healthCard); uid= account.getbId(); rechargeRecord = rechargeRecordMapper.selectBAccountid(uid); setRechargeRecord = setRechargeRecord(rechargeRecord); break; default: break; } ResultMsg msg = new ResultMsg(200, setRechargeRecord); return msg; } /** * 消费记录查询 */ @Override public ResultMsg getConsumeRecordBy(AccountQueryParams params) { Account account = null; List<ComsumeRecord> comsumeRecord = null; //身份证号 String idcard = null; //就诊卡号 String cardNumber = null; //社保卡号 String sinCard = null; //居民健康卡号 String healthCard = null; Long id = null; ConsumeRecordParams infoParams = new ConsumeRecordParams(); List<ConsumeRecordParams> setConsumeRecordBy = new ArrayList<>(); /*1、先查询账户是否存在*/ switch (params.getType()) { case 1://身份证号 idcard = params.getNumber(); account = accountMapper.selectAccountByIdcard(idcard); id = account.getbId(); comsumeRecord = comsumeRecordMapper.selectBybAccountid(id); setConsumeRecordBy = setConsumeRecordBy(comsumeRecord); break; case 2://就诊卡号 cardNumber = params.getNumber(); account = accountMapper.selectAccountByPatientidcard(cardNumber); id = account.getbId(); comsumeRecord = comsumeRecordMapper.selectBybAccountid(id); setConsumeRecordBy = setConsumeRecordBy(comsumeRecord); break; case 3://社保卡号 sinCard = params.getNumber(); account = accountMapper.selectAccountBySincard(sinCard); id = account.getbId(); comsumeRecord = comsumeRecordMapper.selectBybAccountid(id); setConsumeRecordBy = setConsumeRecordBy(comsumeRecord); break; case 4://居民健康卡号 healthCard = params.getNumber(); account = accountMapper.selectAccountByHealthcard(healthCard); id = account.getbId(); comsumeRecord = comsumeRecordMapper.selectBybAccountid(id); setConsumeRecordBy = setConsumeRecordBy(comsumeRecord); break; default: break; } ResultMsg msg = new ResultMsg(200, setConsumeRecordBy); return msg; } /** * 退款记录查询 */ @Override public ResultMsg getRefundRecordBy(AccountQueryParams params) { Account account = null; List<RefundRecord> refundRecord = null; //身份证号 String idcard = null; //就诊卡号 String cardNumber = null; //社保卡号 String sinCard = null; //居民健康卡号 String healthCard = null; Long id = null; List<RefundRecordParams> setAccountInfo = new ArrayList<>(); /*1、先查询账户是否存在*/ switch (params.getType()) { case 1://身份证号 idcard = params.getNumber(); account = accountMapper.selectAccountByIdcard(idcard); id = account.getbId(); refundRecord = refundRecordMapper.selectBybAccountid(id); setAccountInfo = setAccountInfo(refundRecord); break; case 2://就诊卡号 cardNumber = params.getNumber(); account = accountMapper.selectAccountByPatientidcard(cardNumber); id = account.getbId(); refundRecord = refundRecordMapper.selectBybAccountid(id); setAccountInfo = setAccountInfo(refundRecord); break; case 3://社保卡号 sinCard = params.getNumber(); account = accountMapper.selectAccountBySincard(sinCard); id = account.getbId(); refundRecord = refundRecordMapper.selectBybAccountid(id); setAccountInfo = setAccountInfo(refundRecord); break; case 4://居民健康卡号 healthCard = params.getNumber(); account = accountMapper.selectAccountByHealthcard(healthCard); id = account.getbId(); refundRecord = refundRecordMapper.selectBybAccountid(id); setAccountInfo = setAccountInfo(refundRecord); break; default: break; } ResultMsg msg = new ResultMsg(200, setAccountInfo); return msg; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/controller/OrderApiController.java /** * Project Name:meatball-rest * File Name:OrderApiController.java * Package Name:com.meatball.api.ykt.controller * Date:2018年3月13日下午4:14:07 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.meatball.api.ykt.parems.AliCallBackParams; import com.meatball.api.ykt.parems.AliOrderParams; import com.meatball.api.ykt.parems.MobileCallBackParams; import com.meatball.api.ykt.parems.MobileParams; import com.meatball.api.ykt.parems.PayOrderParams; import com.meatball.api.ykt.parems.PayResultParams; import com.meatball.api.ykt.parems.WxCallBackParams; import com.meatball.api.ykt.parems.WxOrderParams; import com.meatball.api.ykt.service.OrderApiForAlipayService; import com.meatball.api.ykt.service.OrderApiForWeixinService; import com.meatball.api.ykt.service.OrderService; import com.meatball.component.OperateLog; import com.meatball.vo.ResultMsg; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import springfox.documentation.annotations.ApiIgnore; /** * @Title: OrderApiController.java * @Package com.meatball.api.ykt.controller * @Description: TODO(下单类接口) * @author jw * @date 2018年3月13日 下午4:14:07 * @version V1.0 */ @Api(tags = "下单接口") @RestController @RequestMapping("/api/ykt/order") public class OrderApiController { @Resource private OrderApiForAlipayService alipayService; @Resource private OrderApiForWeixinService weixinService; @Resource private OrderService orderService; @ApiOperation(value = "微信下单", notes = "返回:扫码支付信息") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayOrderParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/wxOrder") @OperateLog("微信下单") @ApiIgnore public ResultMsg wxOrder(@RequestBody WxOrderParams params) { return weixinService.getWeixinOrderResult(params); } @ApiOperation(value = "支付宝下单", notes = "返回:扫码支付信息") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayOrderParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/aliOrder") @OperateLog("支付宝下单") @ApiIgnore public ResultMsg aliOrder(@RequestBody AliOrderParams params) { return alipayService.aliOrder(params); } @ApiOperation(value = "移动下单", notes = "返回:扫码支付信息") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayOrderParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/mobileOrder") @OperateLog("移动下单") public ResultMsg mobileOrder(@RequestBody MobileParams params) { return orderService.mobileOrder(params); } @ApiOperation(value = "移动支付支付结果回调", notes = "返回:扫码支付的结果") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayResultParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/mobileCallBack") @OperateLog("移动支付支付结果回调") public ResultMsg mobileCallBack(@RequestBody MobileCallBackParams params) { return orderService.mobileCallBack(params); } @ApiOperation(value = "微信回调", notes = "返回:扫码支付的结果") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayResultParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/wxCallBack") @OperateLog("微信回调") @ApiIgnore public ResultMsg wxCallBack(@RequestBody WxCallBackParams params) { return weixinService.getWeixinOrderBackResult(params); } @ApiOperation(value = "支付宝回调", notes = "返回:扫码支付的结果") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = PayResultParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/aliCallBack") @OperateLog("支付宝回调") @ApiIgnore public ResultMsg aliCallBack(@RequestBody AliCallBackParams params) { return new ResultMsg(200); } /** * @Title: wxback * @Description: TODO(微信接口回调操作) * @param request * @return * @return void 返回类型 * @throws Exception */ @PostMapping("/wxback") @OperateLog("微信接口回调") @ApiIgnore public void wxback(HttpServletRequest request, HttpServletResponse response) throws Exception { weixinService.getWxBackMsg(request,response); } /** * @Title: zfbback * @Description: TODO(支付宝接口回调) * @param request * @param response * @throws Exception * @return void 返回类型 */ @PostMapping("/zfbback") @OperateLog("支付宝接口回调") @ApiIgnore public void zfbback(HttpServletRequest request, HttpServletResponse response) throws Exception { alipayService.zfbback(request, response); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/login/service/LoginApiService.java /** * Project Name:meatball-rest * File Name:LoginApiService.java * Package Name:com.meatball.api.login.service * Date:2018年3月2日下午3:25:16 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.login.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.meatball.api.login.parems.LoginParams; import com.meatball.login.service.LoginService; import com.meatball.system.user.model.SysUser; import com.meatball.vo.ResultMsg; /** * @Title: LoginApiService.java * @Package com.meatball.api.login.service * @Description: TODO(登陆权限验证) * @author 張翔宇 * @date 2018年3月2日 下午3:25:16 * @version V1.0 */ @Service public class LoginApiService { @Resource private LoginService loginService; /** * @Title: validate * @Description: TODO(登陆验证) * @param params * @return ResultMsg 返回类型 */ public ResultMsg validate(LoginParams params) { SysUser user = new SysUser(); user.setAccount(params.getAccount()); user.setPassword(params.getPassword()); return loginService.validate(user); } } <file_sep>/yikatong-admin/src/main/java/com/meatball/login/service/impl/LoginServiceImpl.java /** * Project Name:meatball-admin * File Name:LoginService.java * Package Name:com.meatball.login.service * Date:2017年10月9日上午8:52:46 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.login.service.impl; import java.util.Iterator; import java.util.List; import javax.annotation.Resource; import org.apache.ibatis.binding.BindingException; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.meatball.component.TokenComponent; import com.meatball.login.service.LoginService; import com.meatball.system.menu.dao.SysMenuMapper; import com.meatball.system.menu.model.SysMenu; import com.meatball.system.role.dao.SysRoleMapper; import com.meatball.system.role.model.SysRole; import com.meatball.system.user.dao.SysUserMapper; import com.meatball.system.user.model.SysUser; import com.meatball.utils.MD5Util; import com.meatball.utils.PhoneAndEmailCheckUtil; import com.meatball.vo.ResultMsg; /** * @Title: LoginService.java * @Package com.meatball.login.service * @Description: TODO(用户登陆服务类) * @author 張翔宇 * @date 2017年10月9日 上午8:52:46 * @version V1.0 */ @Service public class LoginServiceImpl implements LoginService { private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class); @Resource private SysUserMapper sysUserMapper; @Resource private SysMenuMapper sysMenuMapper; @Resource private TokenComponent tokenComponent; @Resource private SysRoleMapper roleMapper; @Override public ResultMsg validate(SysUser user) throws BindingException { SysUser sysUser = new SysUser(); String message = ""; String token = ""; int code = 200; if(PhoneAndEmailCheckUtil.isPhoneLegal(user.getAccount())) { sysUser.setPhone(user.getAccount()); log.info("用户输入为手机号码!"); } else if(PhoneAndEmailCheckUtil.isEmail(user.getAccount())) { sysUser.setEmail(user.getAccount()); log.info("用户输入为邮箱!"); } else { sysUser.setAccount(user.getAccount()); } try { sysUser = sysUserMapper.selectByProperty(sysUser); sysUser.setVerify(user.getAccount()); Subject subject = SecurityUtils.getSubject(); // 保存用户信息进session subject.getSession().setAttribute("sysUser", sysUser); UsernamePasswordToken upt = new UsernamePasswordToken(user.getAccount(), MD5Util.md5(user.getPassword(), sysUser.getSalt()), false); subject.login(upt); // 获取权限信息 List<SysRole> roles = roleMapper.selectRoleByUserId(sysUser.getId()); subject.getSession().setAttribute("roles", roles); // 获取菜单列表 // 获取权限字符串 StringBuffer perms = new StringBuffer(); roles.forEach(role -> { perms.append(role.getRoleSign()); perms.append(","); }); List<SysMenu> menus = sysMenuMapper.selectAllTreeMenu(); menus = this.deleteNotPermisMenu(menus, perms.toString()); subject.getSession().setAttribute("menus", menus); // 返回消息 message = "验证成功"; token = tokenComponent.createJWT(sysUser.getId()); sysUser.setRolesVo(roles); sysUser.setMenusVo(menus); } catch (Exception e) { code = 401; log.error("错误的用户名或密码"); message = "错误的用户名或密码"; e.printStackTrace(); } return new ResultMsg(code, message, token, null); } /** * @Title: deleteNullChildren * @Description: TODO(递归清除空children) * @param menus * @return List<SysMenu> 返回类型 */ private List<SysMenu> deleteNotPermisMenu(List<SysMenu> menus, String paermis) { Iterator<SysMenu> iterator = menus.iterator(); while(iterator.hasNext()) { SysMenu menu = iterator.next(); if(!paermis.contains(menu.getPerms())) { iterator.remove(); } else { if(!menu.getChildren().isEmpty()) { this.deleteNotPermisMenu(menu.getChildren(), paermis); } } } return menus; } } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/pay/properties/AlipayPayProperties.java /** * Project Name:meatball-core * File Name:PayProperties.java * Package Name:com.meatball.utils.pay.properties * Date:2018年3月19日上午9:10:33 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.utils.pay.properties; import java.io.Serializable; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * @Title: PayProperties.java * @Package com.meatball.utils.pay.properties * @Description: TODO(支付宝支付参数) * @author 張翔宇 * @date 2018年3月19日 上午9:10:33 * @version V1.0 */ @Component @ConfigurationProperties(prefix = "alipay") @PropertySource("classpath:alipay.yml") public class AlipayPayProperties implements Serializable { private static final long serialVersionUID = 1L; // 支付宝网关名 @Value("${open_api_domain}") private String openApiDomain; // @Value("${mcloud_api_domain}") private String mcloudApiDomain; // @Value("${pid}") private String pid; // @Value("${appid}") private String appid; // RSA私钥 @Value("${private_key}") private String privateKey; // RSA公钥 @Value("${public_key}") private String publicKey; // SHA256withRsa对应支付宝公钥 @Value("${alipay_public_key}") private String alipayPublicKey; // 签名类型: RSA->SHA1withRsa,RSA2->SHA256withRsa @Value("${sign_type}") private String signType; // 当面付最大查询次数和查询间隔(毫秒) @Value("${max_query_retry}") private String maxQueryRetry; @Value("${query_duration}") private String queryDuration; // 当面付最大撤销次数和撤销间隔(毫秒) @Value("${max_cancel_retry}") private String maxCancelRetry; @Value("${cancel_duration}") private String cancelDuration; // 交易保障线程第一次调度延迟和调度间隔(秒) @Value("${heartbeat_delay}") private String heartbeatDelay; @Value("${heartbeat_duration}") private String heartbeatDuration; @Value("${notify_url}") private String notifyUrl; /** * @return openApiDomain */ public String getOpenApiDomain() { return openApiDomain; } /** * @param openApiDomain 要设置的 openApiDomain */ public void setOpenApiDomain(String openApiDomain) { this.openApiDomain = openApiDomain; } /** * @return mcloudApiDomain */ public String getMcloudApiDomain() { return mcloudApiDomain; } /** * @param mcloudApiDomain 要设置的 mcloudApiDomain */ public void setMcloudApiDomain(String mcloudApiDomain) { this.mcloudApiDomain = mcloudApiDomain; } /** * @return pid */ public String getPid() { return pid; } /** * @param pid 要设置的 pid */ public void setPid(String pid) { this.pid = pid; } /** * @return appid */ public String getAppid() { return appid; } /** * @param appid 要设置的 appid */ public void setAppid(String appid) { this.appid = appid; } /** * @return privateKey */ public String getPrivateKey() { return privateKey; } /** * @param privateKey 要设置的 privateKey */ public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } /** * @return publicKey */ public String getPublicKey() { return publicKey; } /** * @param publicKey 要设置的 publicKey */ public void setPublicKey(String publicKey) { this.publicKey = publicKey; } /** * @return alipayPublicKey */ public String getAlipayPublicKey() { return alipayPublicKey; } /** * @param alipayPublicKey 要设置的 alipayPublicKey */ public void setAlipayPublicKey(String alipayPublicKey) { this.alipayPublicKey = alipayPublicKey; } /** * @return signType */ public String getSignType() { return signType; } /** * @param signType 要设置的 signType */ public void setSignType(String signType) { this.signType = signType; } /** * @return maxQueryRetry */ public String getMaxQueryRetry() { return maxQueryRetry; } /** * @param maxQueryRetry 要设置的 maxQueryRetry */ public void setMaxQueryRetry(String maxQueryRetry) { this.maxQueryRetry = maxQueryRetry; } /** * @return queryDuration */ public String getQueryDuration() { return queryDuration; } /** * @param queryDuration 要设置的 queryDuration */ public void setQueryDuration(String queryDuration) { this.queryDuration = queryDuration; } /** * @return maxCancelRetry */ public String getMaxCancelRetry() { return maxCancelRetry; } /** * @param maxCancelRetry 要设置的 maxCancelRetry */ public void setMaxCancelRetry(String maxCancelRetry) { this.maxCancelRetry = maxCancelRetry; } /** * @return cancelDuration */ public String getCancelDuration() { return cancelDuration; } /** * @param cancelDuration 要设置的 cancelDuration */ public void setCancelDuration(String cancelDuration) { this.cancelDuration = cancelDuration; } /** * @return heartbeatDelay */ public String getHeartbeatDelay() { return heartbeatDelay; } /** * @param heartbeatDelay 要设置的 heartbeatDelay */ public void setHeartbeatDelay(String heartbeatDelay) { this.heartbeatDelay = heartbeatDelay; } /** * @return heartbeatDuration */ public String getHeartbeatDuration() { return heartbeatDuration; } /** * @param heartbeatDuration 要设置的 heartbeatDuration */ public void setHeartbeatDuration(String heartbeatDuration) { this.heartbeatDuration = heartbeatDuration; } /** * @return notifyUrl */ public String getNotifyUrl() { return notifyUrl; } /** * @param notifyUrl 要设置的 notifyUrl */ public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/service/impl/OrderServiceImpl.java /** * Project Name:meatball-rest * File Name:OderServiceImpl.java * Package Name:com.meatball.api.ykt.service.impl * Date:2018年3月22日下午2:56:15 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.service.impl; import java.util.Date; import java.util.Map; import javax.annotation.Resource; import com.meatball.api.ykt.parems.PayResultParams; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import com.alipay.api.response.AlipayTradePrecreateResponse; import com.meatball.api.ykt.dao.AccountMapper; import com.meatball.api.ykt.dao.ComsumeRecordMapper; import com.meatball.api.ykt.dao.RechargeRecordMapper; import com.meatball.api.ykt.enums.DealTypeEnum; import com.meatball.api.ykt.model.Account; import com.meatball.api.ykt.model.ComsumeRecord; import com.meatball.api.ykt.model.RechargeRecord; import com.meatball.api.ykt.parems.MobileCallBackParams; import com.meatball.api.ykt.parems.MobileParams; import com.meatball.api.ykt.parems.PayOrderParams; import com.meatball.api.ykt.service.OrderService; import com.meatball.api.ykt.service.OperationLogService; import com.meatball.utils.pay.AlipayTradePrecreate; import com.meatball.utils.pay.params.AlipayParams; import com.meatball.utils.pay.weixin.WXTradeService; import com.meatball.vo.ResultMsg; /** * @Title: OderServiceImpl.java * @Package com.meatball.api.ykt.service.impl * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2018年3月22日 下午2:56:15 * @version V1.0 */ @Service public class OrderServiceImpl implements OrderService { @Resource private AccountMapper accountMapper; @Resource private ComsumeRecordMapper comsumeRecordMapper; @Resource private RechargeRecordMapper rechargeRecordMapper; @Resource private AlipayTradePrecreate alipayTradePrecreate; @Resource private WXTradeService wxTradeService; @Resource private OperationLogService operationLogService; @Override public ResultMsg mobileOrder(MobileParams params) { PayOrderParams info = new PayOrderParams(); ResultMsg msg = new ResultMsg(200, info); //查询用户是否存在 Account account = accountMapper.selectByPrimaryKey(params.getUserId()); //如果存在,则组装微信下单信息 if(null != account) { //判断属于哪种订单 switch (params.getOrderType()) { //充值 case 1: // 微信 //组装并生成充值订单 RechargeRecord record = new RechargeRecord(); setRechargeValues(params, account, record, "wx"); rechargeRecordMapper.insertSelective(record); //调用微信下单接口 Double totalFee = Double.parseDouble(params.getBalance()) * 100; Map<String,String> map = wxTradeService.doUnifiedOrder("cz"+record.getbId().toString(), String.valueOf(totalFee.intValue()), record.getbId().toString()); System.out.println("返回信息===="+map); //组装下单结果信息 setResultInfos(info, record.getbId(), map); //插入操作日志 operationLogService.insertOperationLog(params.getMachineId(), "微信预下单充值操作", account.getbId(), account.getvName(), Double.parseDouble(params.getBalance())); // 支付宝 setRechargeValues(params, account, record, "zfb"); rechargeRecordMapper.insertSelective(record); // 发起下单请求 AlipayParams czalipayParams = new AlipayParams(); BeanUtils.copyProperties(params, czalipayParams); czalipayParams.setOrderId("cz" + record.getbId().toString()); AlipayTradePrecreateResponse czplaceOrderResult = alipayTradePrecreate.placeOrder(czalipayParams); setResultInfos(info, record.getbId(), czplaceOrderResult); //插入操作日志 operationLogService.insertOperationLog(params.getMachineId(), "支付宝预下单充值操作", account.getbId(), account.getvName(),Double.parseDouble(params.getBalance())); break; //消费 case 2: // 微信 //组装并生成消费订单 ComsumeRecord crecord = new ComsumeRecord(); setComsumeValues(params, account, crecord, "wx"); comsumeRecordMapper.insertSelective(crecord); //调用微信下单接口 Double dd= Double.parseDouble(params.getBalance()) * 100; Map<String,String> commap = wxTradeService.doUnifiedOrder("xf"+crecord.getbId().toString(), String.valueOf(dd.longValue()), crecord.getbId().toString()); //组装下单结果信息 setResultInfos(info, crecord.getbId(), commap); //插入操作日志 operationLogService.insertOperationLog(params.getMachineId(), "微信预下单消费操作", account.getbId(), account.getvName(),Double.parseDouble(params.getBalance())); // 支付宝 setComsumeValues(params, account, crecord, "zfb"); comsumeRecordMapper.insertSelective(crecord); // 发起下单请求 AlipayParams alipayParams = new AlipayParams(); BeanUtils.copyProperties(params, alipayParams); alipayParams.setOrderId("xf" + crecord.getbId().toString()); AlipayTradePrecreateResponse placeOrderResult = alipayTradePrecreate.placeOrder(alipayParams); setResultInfos(info, crecord.getbId(), placeOrderResult); //插入操作日志 operationLogService.insertOperationLog(params.getMachineId(), "支付宝预下单消费操作", account.getbId(), account.getvName(),Double.parseDouble(params.getBalance())); break; case 3://退款 info.setResultCode(1); info.setResultMsg("系统暂不支持此项业务"); break; default: info.setResultCode(1); info.setResultMsg("请传入正确的订单类型"); break; } } else {//如果不存在,则返回提示 info.setResultCode(1); info.setResultMsg("账户不存在"); } return msg; } /* (非 Javadoc) * <p>Title: mobileCallBack</p> * <p>Description: </p> * @param params * @return * @see com.meatball.api.ykt.service.OderService#mobileCallBack(com.meatball.api.ykt.parems.MobileCallBackParams) */ @Override public ResultMsg mobileCallBack(MobileCallBackParams params) { PayResultParams resultParams = new PayResultParams(); resultParams.setResultCode(1); resultParams.setResultMsg("支付超时"); switch (params.getOrderType()) { case 1: // 充值 // 微信 int time = 0; while (time < 120) { RechargeRecord wx = rechargeRecordMapper.selectByPrimaryKey(params.getWxOrder()); if(wx.getiDealstatus() == 0) { resultParams.setNumber(String.valueOf(wx.getbId())); resultParams.setOrderType(1); resultParams.setPayType(1); resultParams.setResultCode(0); resultParams.setResultMsg("微信支付成功" +wx.getdBalance() + "元"); break; } else { // 支付宝 RechargeRecord zfb = rechargeRecordMapper.selectByPrimaryKey(params.getZfbOrder()); if(zfb.getiDealstatus() == 0) { resultParams.setNumber(String.valueOf(zfb.getbId())); resultParams.setOrderType(1); resultParams.setPayType(2); resultParams.setResultCode(0); resultParams.setResultMsg("支付宝支付成功" +zfb.getdBalance() + "元"); break; } } try { Thread.sleep(1000); time++; } catch (InterruptedException e) { e.printStackTrace(); } } break; case 2: // 消费 // 微信 int timexf = 0; while (timexf < 120) { ComsumeRecord wx = comsumeRecordMapper.selectByPrimaryKey(params.getWxOrder()); if(wx.getiDealstatus() == 0) { resultParams.setNumber(String.valueOf(wx.getbId())); resultParams.setOrderType(2); resultParams.setPayType(1); resultParams.setResultCode(0); resultParams.setResultMsg("微信支付成功" +wx.getdBalance() + "元"); break; } else { // 支付宝 ComsumeRecord zfb = comsumeRecordMapper.selectByPrimaryKey(params.getZfbOrder()); if(zfb.getiDealstatus() == 0) { resultParams.setNumber(String.valueOf(zfb.getbId())); resultParams.setOrderType(2); resultParams.setPayType(2); resultParams.setResultCode(0); resultParams.setResultMsg("支付宝支付成功" +zfb.getdBalance() + "元"); break; } } try { Thread.sleep(1000); timexf++; } catch (InterruptedException e) { e.printStackTrace(); } } break; case 3: // 退款 resultParams.setResultCode(1); resultParams.setResultMsg("此功能暂未开通"); break; default: resultParams.setResultCode(1); resultParams.setResultMsg("请传入正确的订单类别"); break; } return new ResultMsg(200, resultParams); } /** * @Title: setRechargeValues * @Description: TODO(充值记录属性赋值) * @param params * @param account * @param record * @return void 返回类型 */ private void setRechargeValues(MobileParams params, Account account, RechargeRecord record, String payWay) { record.setbId(new Date().getTime()); record.setbAccountid(account.getbId()); record.setvAccountname(account.getvName()); record.setiDealstatus(9); record.setiDealtype(params.getDealType()); record.settDealtime(new Date()); // record.setvDealname(DealTypeEnum.lookup(params.getDealType()).toString()); record.setvMachineid(params.getMachineId()); record.setvOperator(params.getOperatorName()); record.setvOrderid(null); switch (payWay) { case "wx": record.setdBalance(Double.parseDouble(params.getBalance())); record.setvPayname("微信"); record.setiPaytype(3); break; case "zfb": record.setdBalance(Double.parseDouble(params.getBalance())); record.setvPayname("支付宝"); record.setiPaytype(4); break; default: throw new RuntimeException("Invalid payment method.(无效的支付方式。)"); } } /** * @Title: setComsumeValues * @Description: TODO(消费记录属性赋值) * @param params * @param account * @param crecord * @return void 返回类型 */ private void setComsumeValues(MobileParams params, Account account, ComsumeRecord crecord, String payWay) { crecord.setbId(new Date().getTime()); crecord.setbAccountid(account.getbId()); crecord.setvAccountname(account.getvName()); crecord.setiDealstatus(9); crecord.setiDealtype(params.getDealType()); crecord.settDealtime(new Date()); crecord.setvDealname(DealTypeEnum.lookup(params.getDealType()).toString()); crecord.setvMachineid(params.getMachineId()); crecord.setvOperator(params.getOperatorName()); crecord.setvPaymentid(null); switch (payWay) { case "wx": crecord.setdBalance(Double.parseDouble(params.getBalance())); crecord.setvPayname("微信"); crecord.setiPaytype(3); break; case "zfb": crecord.setdBalance(Double.parseDouble(params.getBalance())); crecord.setvPayname("支付宝"); crecord.setiPaytype(4); break; default: throw new RuntimeException("Invalid payment method.(无效的支付方式。)"); } } /** * @Title: setResultInfos * @Description: TODO(组装下单结果信息) * @param info * @param id * @param commap * @return void 返回类型 */ private void setResultInfos(PayOrderParams info, Long id, Map<String, String> commap) { //预下单成功 if("SUCCESS".equals(commap.get("return_code"))) { info.setResultCode(0); info.setResultMsg("移动支付预下单成功"); info.setWxCode(commap.get("code_url")); info.setWxOrder(id.toString()); } else { //预下单失败 info.setResultCode(1); info.setResultMsg(commap.get("return_msg")); } } private void setResultInfos(PayOrderParams info, Long id, AlipayTradePrecreateResponse alipayResponse) { //预下单成功 if(alipayResponse.getCode().equals("10000")) { info.setZfbCode(alipayResponse.getQrCode()); info.setZfbOrder(id.toString()); } else { //预下单失败 info.setResultCode(1); info.setResultMsg(alipayResponse.getSubMsg()); } } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/login/parems/LoginParams.java /** * Project Name:meatball-rest * File Name:LoginParams.java * Package Name:com.meatball.api.login.params * Date:2018年3月2日下午3:01:40 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.login.parems; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @Title: LoginParams.java * @Package com.meatball.api.login.params * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2018年3月2日 下午3:01:40 * @version V1.0 */ @ApiModel public class LoginParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="用户名", example="yijiayun", required = true) private String account; @ApiModelProperty(value="密码", example="123", required = true) private String password; /** * @return account */ public String getAccount() { return account; } /** * @param account 要设置的 account */ public void setAccount(String account) { this.account = account; } /** * @return password */ public String getPassword() { return password; } /** * @param password 要设置的 password */ public void setPassword(String password) { this.password = password; } } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/PhoneAndEmailCheckUtil.java /** * Project Name:meatball-core * File Name:PhoneFormatCheckUtil.java * Package Name:com.meatball.utils * Date:2017年10月7日下午1:37:02 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * @Title: PhoneFormatCheckUtil.java * @Package com.meatball.utils * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2017年10月7日 下午1:37:02 * @version V1.0 */ public class PhoneAndEmailCheckUtil { /** * @Title: isPhoneLegal * @Description: TODO(大陆号码或香港号码均可 ) * @param str * @throws PatternSyntaxException 设定文件 * @return boolean 返回类型 */ public static boolean isPhoneLegal(String str)throws PatternSyntaxException { return isChinaPhoneLegal(str) || isHKPhoneLegal(str); } /** * @Title: isChinaPhoneLegal * @Description: TODO( * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 * 此方法中前三位格式有: * 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147 ) * @param str * @throws PatternSyntaxException 设定文件 * @return boolean 返回类型 */ private static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException { String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } /** * @Title: isHKPhoneLegal * @Description: TODO(香港手机号码8位数,5|6|8|9开头+7位任意数 ) * @param str * @throws PatternSyntaxException 设定文件 * @return boolean 返回类型 */ private static boolean isHKPhoneLegal(String str)throws PatternSyntaxException { String regExp = "^(5|6|8|9)\\d{7}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } /** * @Title: isEmaile * @Description: TODO(正则表达式校验邮箱) * @param emaile * @return boolean 返回类型 */ public static boolean isEmail(String emaile) { String RULE_EMAIL = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"; //正则表达式的模式 Pattern p = Pattern.compile(RULE_EMAIL); //正则表达式的匹配器 Matcher m = p.matcher(emaile); //进行正则匹配 return m.matches(); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/dao/OperationLogMapper.java package com.meatball.api.ykt.dao; import com.meatball.api.ykt.model.OperationLog; /** * @Title: OperationLogMapper.java * @Package com.meatball.api.ykt.dao * @Description: TODO(操作日志dao) * @author jw * @date 2018年3月16日 下午4:46:27 * @version V1.0 */ public interface OperationLogMapper { /** * @Title: deleteByPrimaryKey * @Description: TODO(根据id删除信息) * @param bId * @return * @return int 返回类型 */ int deleteByPrimaryKey(Long bId); /** * @Title: insert * @Description: TODO(新增信息) * @param record * @return * @return int 返回类型 */ int insert(OperationLog record); /** * @Title: insertSelective * @Description: TODO(新增指定字段信息) * @param record * @return * @return int 返回类型 */ int insertSelective(OperationLog record); /** * @Title: selectByPrimaryKey * @Description: TODO(根据id查询信息) * @param bId * @return * @return OperationLog 返回类型 */ OperationLog selectByPrimaryKey(Long bId); /** * @Title: updateByPrimaryKeySelective * @Description: TODO(修改指定字段信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKeySelective(OperationLog record); /** * @Title: updateByPrimaryKey * @Description: TODO(修改信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKey(OperationLog record); }<file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/service/OrderApiForAlipayService.java /** * Project Name:meatball-rest * File Name:OrderApiService.java * Package Name:com.meatball.api.ykt.service * Date:2018年3月15日下午3:44:38 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.meatball.api.ykt.parems.AliOrderParams; import com.meatball.vo.ResultMsg; /** * @Title: OrderApiService.java * @Package com.meatball.api.ykt.service * @Description: TODO(支付宝下单) * @author 張翔宇 * @date 2018年3月15日 下午3:44:38 * @version V1.0 */ public interface OrderApiForAlipayService { /** * @Title: aliOrder * @Description: TODO(支付宝下单) * @param params * @return * @return ResultMsg 返回类型 */ public ResultMsg aliOrder(AliOrderParams params); /** * @Title: zfbback * @Description: TODO(支付宝回调) * @param request * @param response * @return void 返回类型 */ public void zfbback(HttpServletRequest request, HttpServletResponse response); } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/DealTypeEnum.java /** * Project Name:meatball-core * File Name:DealTypeEnum.java * Package Name:com.meatball.utils * Date:2018年3月19日下午5:08:08 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.utils; /** * @Title: DealTypeEnum.java * @Package com.meatball.utils * @Description: TODO(交易类别) * @author jw * @date 2018年3月19日 下午5:08:08 * @version V1.0 */ public enum DealTypeEnum { GHF("挂号费", 1), MZF("门诊(处方)费", 2), ZYF("住院费", 3), YE("余额", 4); private final String key; private final int value; private DealTypeEnum(String key, int value) { this.key = key; this.value = value; } public String getKey() { return this.key; } public int getValue() { return this.value; } } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/QRCodeToBase64.java /** * Project Name:meatball-core * File Name:QRCodeToBase64.java * Package Name:com.meatball.utils * Date:2018年3月17日下午1:39:24 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.utils; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Hashtable; import javax.imageio.ImageIO; import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.codec.binary.Base64; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; /** * @Title: QRCodeToBase64.java * @Package com.meatball.utils * @Description: TODO(二维图片转base64) * @author 張翔宇 * @date 2018年3月17日 下午1:39:24 * @version V1.0 */ public class QRCodeToBase64 { private static final int black = 0xFF000000; private static final int white = 0xFFFFFFFF; public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? black : white); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); ImageIO.write(image, format, file); } public static void createQRImage(String content, int width, int height, String path, String fileName) throws Exception { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); if (StringUtils.isNotBlank(path)) { if (!path.endsWith("/")) { path = path + "/"; } } else { path = ""; } String suffix = "jpg"; if (fileName.indexOf(".") <= -1) { fileName = fileName + "." + suffix; } else { suffix = fileName.split("[.]")[1]; } fileName = path + fileName; File file = new File(fileName); writeToFile(bitMatrix, suffix, file); } public static BufferedImage createQRImageBuffer(String content, int width, int height) { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = null; try { bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException e) { e.printStackTrace(); } BufferedImage image = toBufferedImage(bitMatrix); return image; } public static String qrCodeToBase64(String qr) { BufferedImage qrImageBuffer = QRCodeToBase64.createQRImageBuffer(qr, 300, 300); ByteArrayOutputStream os=new ByteArrayOutputStream(); try { ImageIO.write(qrImageBuffer, "png", os); } catch (IOException e) { e.printStackTrace(); } Base64 base64 = new Base64(); String base64Img = new String(base64.encode(os.toByteArray())); return base64Img; } } <file_sep>/yikatong-core/src/main/java/com/meatball/vo/FileUploadResponse.java /** * Project Name:meatball-core * File Name:FileUploadResponseUtil.java * Package Name:com.meatball.utils * Date:2017年10月13日下午4:22:07 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.vo; /** * @Title: FileUploadResponseUtil.java * @Package com.meatball.utils * @Description: TODO(格式化上传文件) * @author 張翔宇 * @date 2017年10月13日 下午4:22:07 * @version V1.0 */ public class FileUploadResponse { // success || fail private String type; // 消息 private String msg; // 文件类型 private String contentType; // 文件名称 private String fileName; // 上次地址 private String url; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } <file_sep>/pom.xml <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>com.meatball</groupId> <artifactId>yikatong-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>yikatong-admin</module> <module>yikatong-core</module> <module>yikatong-startup</module> <module>yikatong-rest</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <org.apache.shiro.version>1.4.0</org.apache.shiro.version> <org.apache.commons.version>3.6</org.apache.commons.version> <org.mybatis.spring.boot.version>1.3.1</org.mybatis.spring.boot.version> <com.alibaba.druid.version>1.1.6</com.alibaba.druid.version> <com.alibaba.fastjson.version>1.2.39</com.alibaba.fastjson.version> <pagehelper.version>1.2.3</pagehelper.version> <swagger2.version>2.7.0</swagger2.version> <spring-cloud.version>Edgware.SR1</spring-cloud.version> </properties> <dependencies> <!-- SpringBoot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- 监控与管理生产环境 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 开发者模式 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!-- 单元测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${org.mybatis.spring.boot.version}</version> </dependency> <!-- MyBatis 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>${pagehelper.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser --> <!-- <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>1.1</version> </dependency> --> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${com.alibaba.druid.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- JWT token验证 --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> <!-- thymeleaf视图模版引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--启用不严格检查html,第三方前端库会定义一些自己的标签,因此会报错 --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> </dependency> <!-- 字符串处理了 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${org.apache.commons.version}</version> </dependency> <!-- Shiro安全框架 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${org.apache.shiro.version}</version> </dependency> <!-- Shiro 缓存 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${org.apache.shiro.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro --> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${org.apache.shiro.version}</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${com.alibaba.fastjson.version}</version> </dependency> <!-- springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> </dependencies> <!-- 配置java版本 --> <build> <finalName>yikatong</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </pluginManagement> </build> </project><file_sep>/yikatong-core/src/main/java/com/meatball/vo/Page.java /** * Project Name:meatball-core * File Name:Page.java * Package Name:com.meatball.vo * Date:2017年10月13日下午6:01:09 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.vo; import java.io.Serializable; /** * @Title: Page.java * @Package com.meatball.vo * @Description: TODO(分页请求参数) * @author 張翔宇 * @date 2017年10月13日 下午6:01:09 * @version V1.0 * @param <T> */ public class Page implements Serializable{ private static final long serialVersionUID = 1L; // 开始数 private Integer offset; // 每页展示数 private Integer limit; // 排序方式 private String order; public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/CancelAmountParams.java /** * Project Name:meatball-rest * File Name:CancelAmountParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月19日下午3:49:31 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Title: CancelAmountParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(撤销参数类) * @author jw * @date 2018年3月19日 下午3:49:31 * @version V1.0 */ @Data public class CancelAmountParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="证件类别(1:身份证 2:就诊卡 3:社保卡 4:居民健康卡 )", example="1", required = true) private Integer type; @ApiModelProperty(value="证件号码", example="123456", required = true) private String number; @ApiModelProperty(value="金额(带两位小数点)", example="5000.00", required = true) private String balance; @ApiModelProperty(value="订单号", example="123456", required = true) private String orderNumber; @ApiModelProperty(value="订单类别(1充值、2消费)", example="1", required = true) private Integer orderType; @ApiModelProperty(value="机器编号", example="SN9527", required = true) private String machineId ; @ApiModelProperty(value="操作员", example="张三", required = true) private String operatorName; } <file_sep>/yikatong-core/src/main/java/com/meatball/utils/Base64Util.java /** * Project Name:meatball-core * File Name:Base64Util.java * Package Name:com.meatball.utils * Date:2017年10月14日下午5:11:58 * Copyright (c) 2017, <EMAIL> All Rights Reserved. */ package com.meatball.utils; import java.io.UnsupportedEncodingException; import org.apache.tomcat.util.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @Title: Base64Util.java * @Package com.meatball.utils * @Description: TODO() * @author 張翔宇 * @date 2017年10月14日 下午5:11:58 * @version V1.0 */ public class Base64Util { private static final Logger logger = LoggerFactory.getLogger(Base64Util.class); private static final String UTF_8 = "UTF-8"; /** * @Title: decodeData * @Description: TODO(对给定的字符串进行base64解码操作) * @param inputData * @return String 返回类型 */ public static String decodeData(String inputData) { try { if (null == inputData) { return null; } return new String(Base64.decodeBase64(inputData.getBytes(UTF_8)), UTF_8); } catch (UnsupportedEncodingException e) { logger.error(inputData, e); } return null; } /** * @Title: encodeData * @Description: TODO(对给定的字符串进行base64加密操作) * @param inputData * @return String 返回类型 */ public static String encodeData(String inputData) { try { if (null == inputData) { return null; } return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8); } catch (UnsupportedEncodingException e) { logger.error(inputData, e); } return null; } public static void main(String[] args) { System.out.println(Base64Util.encodeData("A")); } } <file_sep>/yikatong-core/src/main/java/com/meatball/component/GlobalExceptionHandler.java /** * Project Name:meatball-core * File Name:GlobalExceptionHandler.java * Package Name:com.meatball.component * Date:2018年1月29日上午11:18:46 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.component; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.meatball.vo.ResultMsg; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureException; /** * @Title: GlobalExceptionHandler.java * @Package com.meatball.component * @Description: TODO(注册全局异常处理) * @author 張翔宇 * @date 2018年1月29日 上午11:18:46 * @version V1.0 */ @RestControllerAdvice public class GlobalExceptionHandler { /** * @Title: allExceptionHandler * @Description: TODO(制定权限不足异常) * @param request * @param exception * @throws Exception * @return Map<String,Object> 返回类型 */ @ExceptionHandler(value = UnauthorizedException.class) public ResultMsg unauthorizedException(UnauthorizedException e) throws Exception { return new ResultMsg(403, "权限不足,请联系系统管理员。"); } /** * @Title: expiredJwtException * @Description: TODO(权限校验) * @param e * @return ResultMsg 返回类型 */ @ExceptionHandler(value = ExpiredJwtException.class) public ResultMsg expiredJwtException(ExpiredJwtException e) { return new ResultMsg(403, "权限令牌已经过期。"); } /** * @Title: SignatureException * @Description: TODO(权限校验) * @param e * @return ResultMsg 返回类型 */ @ExceptionHandler(value = SignatureException.class) public ResultMsg signatureException(SignatureException e) { return new ResultMsg(403, "非法的权限令牌。"); } /** * @Title: SignatureException * @Description: TODO(权限校验) * @param e * @return ResultMsg 返回类型 */ @ExceptionHandler(value = MalformedJwtException.class) public ResultMsg malformedJwtException(MalformedJwtException e) { return new ResultMsg(403, "非法的权限令牌。"); } /** * @Title: authorizationExceptionHandler * @Description: TODO(请求被拒绝) * @param e * @return ResultMsg 返回类型 */ @ExceptionHandler(value = AuthorizationException.class) public ResultMsg authorizationExceptionHandler(AuthorizationException e) { return new ResultMsg(403, "权限认证失败。"); } /** * @Title: nullPointerExceptionHandler * @Description: TODO(空异常) * @param exception * @return ResultMsg 返回类型 */ @ExceptionHandler(value = NullPointerException.class) public ResultMsg nullPointerExceptionHandler(NullPointerException e) { e.printStackTrace(); return new ResultMsg(500, "The necessary parameters cannot be empty.(必要参数不能为空。)"); } /** * @Title: runtimeExceptionHandler * @Description: TODO(这里用一句话描述这个方法的作用) * @param e * @return * @return ResultMsg 返回类型 */ @ExceptionHandler(value = RuntimeException.class) public ResultMsg runtimeExceptionHandler(RuntimeException e) { e.printStackTrace(); return new ResultMsg(500, "系统繁忙。"); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/model/RefundRecord.java package com.meatball.api.ykt.model; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; /** * @Title: RefundRecord.java * @Package com.meatball.api.ykt.model * @Description: TODO(退款记录Model) * @author jw * @date 2018年3月16日 下午3:04:44 * @version V1.0 */ public class RefundRecord { private Long bId; //退款方式(1现金2银行卡3微信4支付宝5余额) private Integer iPaytype; //退款方式名称 private String vPayname; //退款支付编号(平台交易流水号) private String vPaymentid; //账户编号 private Long bAccountid; //账户名称 private String vAccountname; //交易类别(1挂号费、2门诊(处方)费、3住院费、4余额) private Integer iDealtype; //交易类别名称 private String vDealname; //退款金额 private double dBalance; //退款状态(0成功 1失败8撤销 9待支付) private Integer iDealstatus; //退款时间 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date tDealtime; //机器编号 private String vMachineid; //操作员 private String vOperator; //身份证照片 private String vPic; public Long getbId() { return bId; } public void setbId(Long bId) { this.bId = bId; } public Integer getiPaytype() { return iPaytype; } public void setiPaytype(Integer iPaytype) { this.iPaytype = iPaytype; } public String getvPayname() { return vPayname; } public void setvPayname(String vPayname) { this.vPayname = vPayname == null ? null : vPayname.trim(); } public String getvPaymentid() { return vPaymentid; } public void setvPaymentid(String vPaymentid) { this.vPaymentid = vPaymentid == null ? null : vPaymentid.trim(); } public Long getbAccountid() { return bAccountid; } public void setbAccountid(Long bAccountid) { this.bAccountid = bAccountid; } public String getvAccountname() { return vAccountname; } public void setvAccountname(String vAccountname) { this.vAccountname = vAccountname == null ? null : vAccountname.trim(); } public Integer getiDealtype() { return iDealtype; } public void setiDealtype(Integer iDealtype) { this.iDealtype = iDealtype; } public String getvDealname() { return vDealname; } public void setvDealname(String vDealname) { this.vDealname = vDealname == null ? null : vDealname.trim(); } public double getdBalance() { return dBalance; } public void setdBalance(double dBalance) { this.dBalance = dBalance; } public Integer getiDealstatus() { return iDealstatus; } public void setiDealstatus(Integer iDealstatus) { this.iDealstatus = iDealstatus; } public Date gettDealtime() { return tDealtime; } public void settDealtime(Date tDealtime) { this.tDealtime = tDealtime; } public String getvMachineid() { return vMachineid; } public void setvMachineid(String vMachineid) { this.vMachineid = vMachineid == null ? null : vMachineid.trim(); } public String getvOperator() { return vOperator; } public void setvOperator(String vOperator) { this.vOperator = vOperator == null ? null : vOperator.trim(); } public String getvPic() { return vPic; } public void setvPic(String vPic) { this.vPic = vPic == null ? null : vPic.trim(); } }<file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/controller/QueryApiController.java package com.meatball.api.ykt.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.meatball.api.ykt.parems.AccountInfoParams; import com.meatball.api.ykt.parems.AccountQueryParams; import com.meatball.api.ykt.parems.ConsumeRecordParams; import com.meatball.api.ykt.parems.RechargeRecordParams; import com.meatball.api.ykt.parems.RefundAmountInfoParams; import com.meatball.api.ykt.parems.RefundRecordParams; import com.meatball.api.ykt.service.AccountInfoApiService; import com.meatball.component.OperateLog; import com.meatball.vo.ResultMsg; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * @Title: QueryApiController.java * @Package com.meatball.api.ykt.controller * @Description: TODO(查询类接口) * @author jw * @date 2018年3月13日 上午11:16:15 * @version V1.0 */ @Api(tags = "查询接口") @RestController @RequestMapping("/api/ykt/query") public class QueryApiController { @Resource private AccountInfoApiService accountInfoApiService; @ApiOperation(value = "账户信息查询", notes = "返回:账户基本信息(包含虚拟卡号在内的基本信息)") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = AccountInfoParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/queryAccountInfo") @OperateLog("账户信息查询") public ResultMsg queryAccountInfo(@RequestBody AccountQueryParams params) { return accountInfoApiService.getAccountInfoBy(params); } @ApiOperation(value = "余额查询", notes = "返回:账户余额") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = RefundAmountInfoParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/queryBalance") @OperateLog("余额查询") public ResultMsg queryBalance(@RequestBody AccountQueryParams params) { return accountInfoApiService.getAccountBalanceBy(params); } @ApiOperation(value = "充值记录查询", notes = "返回:充值记录列表(包含充值方式、金额、时间等基本信息)") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = RechargeRecordParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/queryRecharge") @OperateLog("充值记录查询") public ResultMsg queryRecharge(@RequestBody AccountQueryParams params) { return accountInfoApiService.getRechargeRecordBy(params); } @ApiOperation(value = "消费记录查询", notes = "返回:消费记录列表(包含金额、时间等基本信息)") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = ConsumeRecordParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/queryConsume") @OperateLog("消费记录查询") public ResultMsg queryConsume(@RequestBody AccountQueryParams params) { return accountInfoApiService.getConsumeRecordBy(params); } @ApiOperation(value = "退款记录查询", notes = "返回:退款记录列表(包含金额、时间等基本信息)") @ApiResponses({ @ApiResponse(code = 200, message = "权限验证成功", response = RefundRecordParams.class), @ApiResponse(code = 201, message = "请求成功并且服务器创建了新的资源", response = Void.class), @ApiResponse(code = 401, message = "用户名或密码错", response = Void.class), @ApiResponse(code = 403, message = "权限认证失败", response = Void.class), @ApiResponse(code = 404, message = "请求的资源不存在", response = Void.class) }) @PostMapping("/queryRefund") @OperateLog("退款记录查询") public ResultMsg queryRefund(@RequestBody AccountQueryParams params) { return accountInfoApiService.getRefundRecordBy(params); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/dao/RechargeRecordMapper.java package com.meatball.api.ykt.dao; import java.util.List; import com.meatball.api.ykt.model.RechargeRecord; /** * @Title: RechargeRecordMapper.java * @Package com.meatball.api.ykt.dao * @Description: TODO(充值记录dao) * @author jw * @date 2018年3月16日 下午4:01:02 * @version V1.0 */ public interface RechargeRecordMapper { /** * @Title: deleteByPrimaryKey * @Description: TODO(根据id删除信息) * @param bId * @return * @return int 返回类型 */ int deleteByPrimaryKey(Long bId); /** * @Title: insert * @Description: TODO(新增信息) * @param record * @return * @return int 返回类型 */ int insert(RechargeRecord record); /** * @Title: insertSelective * @Description: TODO(新增指定字段信息) * @param record * @return * @return int 返回类型 */ int insertSelective(RechargeRecord record); /** * @Title: selectByPrimaryKey * @Description: TODO(根据id查询信息) * @param bId * @return * @return RechargeRecord 返回类型 */ RechargeRecord selectByPrimaryKey(Long bId); /** * @Title: updateByPrimaryKeySelective * @Description: TODO(修改指定字段信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKeySelective(RechargeRecord record); /** * @Title: updateByPrimaryKey * @Description: TODO(修改信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKey(RechargeRecord record); /** * @Title: selectByPrimaryKey * @Description: TODO(根据id查询信息) * @param bId * @return * @return RechargeRecord 返回类型 */ List<RechargeRecord> selectBAccountid(Long bAccountid); /** * @Title: selectSuccessRechargeRecord * @Description: TODO(根据订单号查询充值成功的充值记录) * @param bId * @return * @return RechargeRecord 返回类型 */ RechargeRecord selectSuccessRechargeRecord(long bId); }<file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/RechargeAmountParams.java /** * Project Name:meatball-rest * File Name:OperationalAmountParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月13日下午3:26:39 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Title: OperationalAmountParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(充值金额参数类) * @author jw * @date 2018年3月13日 下午3:26:39 * @version V1.0 */ @Data public class RechargeAmountParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="证件类别(1:身份证 2:就诊卡 3:社保卡 4:居民健康卡)", example="1", required = true) private Integer type; @ApiModelProperty(value="证件号码", example="123456", required = true) private String number; @ApiModelProperty(value="金额(带两位小数点)", example="0.01", required = true) private String balance; @ApiModelProperty(value="支付方式(1 现金、2 银行卡、3 移动支付、4 医佳云)", example="3", required = true) private Integer payType; @ApiModelProperty(value="交易类别(1挂号费、2门诊(处方)费、3住院费)", example="1", hidden = true) private Integer dealType; @ApiModelProperty(value="机器编号", example="SN9527", required = true) private String machineId ; @ApiModelProperty(value="操作员", example="张三", required = true) private String operatorName; } <file_sep>/yikatong-core/src/main/java/com/meatball/component/ErrorLog.java package com.meatball.component; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @ClassName: SystemServiceLog * @Description: TODO(自定义注解 异常日志 拦截service) * @author 張翔宇 * @date 2017年4月17日 下午3:06:29 * */ @Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ErrorLog { String value() default ""; } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/model/PayCallbackRecord.java package com.meatball.api.ykt.model; import java.util.Date; /** * @Title: PayCallbackRecord.java * @Package com.meatball.api.ykt.model * @Description: TODO(支付平台回调记录Model) * @author jw * @date 2018年3月16日 下午3:04:10 * @version V1.0 */ public class PayCallbackRecord { private Long bId; //回调时间 private Date tTime; //订单编号(充值消费退款记录编号) private String vOrderid; //支付平台 private String vPayplatform; //交易流水号 private String vDealno; //下单时间 private Date tOrdertime; //支付时间 private Date tPaytime; //交易金额 private double dBalance; //交易类别(1挂号费、2门诊(处方)费、3住院费) private Integer iDealtype2; //交易类别名称 private String vDealname; //交易结果 private String vResult; //账户编号 private Long bAccountid; //账户名称 private String vAccountname; //银行类别 private String vBank; //商户编号 private String vMerchantid; public Long getbId() { return bId; } public void setbId(Long bId) { this.bId = bId; } public Date gettTime() { return tTime; } public void settTime(Date tTime) { this.tTime = tTime; } public String getvOrderid() { return vOrderid; } public void setvOrderid(String vOrderid) { this.vOrderid = vOrderid == null ? null : vOrderid.trim(); } public String getvPayplatform() { return vPayplatform; } public void setvPayplatform(String vPayplatform) { this.vPayplatform = vPayplatform == null ? null : vPayplatform.trim(); } public String getvDealno() { return vDealno; } public void setvDealno(String vDealno) { this.vDealno = vDealno == null ? null : vDealno.trim(); } public Date gettOrdertime() { return tOrdertime; } public void settOrdertime(Date tOrdertime) { this.tOrdertime = tOrdertime; } public Date gettPaytime() { return tPaytime; } public void settPaytime(Date tPaytime) { this.tPaytime = tPaytime; } public double getdBalance() { return dBalance; } public void setdBalance(double dBalance) { this.dBalance = dBalance; } public Integer getiDealtype2() { return iDealtype2; } public void setiDealtype2(Integer iDealtype2) { this.iDealtype2 = iDealtype2; } public String getvDealname() { return vDealname; } public void setvDealname(String vDealname) { this.vDealname = vDealname == null ? null : vDealname.trim(); } public String getvResult() { return vResult; } public void setvResult(String vResult) { this.vResult = vResult == null ? null : vResult.trim(); } public Long getbAccountid() { return bAccountid; } public void setbAccountid(Long bAccountid) { this.bAccountid = bAccountid; } public String getvAccountname() { return vAccountname; } public void setvAccountname(String vAccountname) { this.vAccountname = vAccountname == null ? null : vAccountname.trim(); } public String getvBank() { return vBank; } public void setvBank(String vBank) { this.vBank = vBank == null ? null : vBank.trim(); } public String getvMerchantid() { return vMerchantid; } public void setvMerchantid(String vMerchantid) { this.vMerchantid = vMerchantid == null ? null : vMerchantid.trim(); } }<file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/AccountModifyParams.java /** * Project Name:meatball-rest * File Name:AccountModifyParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月21日上午9:46:58 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import java.util.Date; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Title: AccountModifyParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(账户修改参数类) * @author jw * @date 2018年3月21日 上午9:46:58 * @version V1.0 */ @Data public class AccountModifyParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="用户id", example="123456", required = true) private String userId; @ApiModelProperty(value="姓名", example="张三", required = true) private String name; @ApiModelProperty(value="身份证号", example="512341199010101111") private String idcard; @ApiModelProperty(value="就诊卡号", example="1555555555") private String cardNumber; @ApiModelProperty(value="性别(1 男 2女)", example="1") private int gender; @ApiModelProperty(value="电话", example="13500000000") private String tel; @ApiModelProperty(value="住址", example="四川省成都市xx区xx街道") private String address; @ApiModelProperty(value="出生日期 (YYYY-MM-DD)", example="1990-10-10") private Date birthday; @ApiModelProperty(value="社保卡号", example="1555555555") private String sinCard; @ApiModelProperty(value="居民健康卡号", example="1555555555") private String healthCard; @ApiModelProperty(value="支付密码", example="xxxxxx") private String vPaymentcode; @ApiModelProperty(value="指纹", example="xxxxxx") private String vFingerprint; } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/PayOrderParams.java /** * Project Name:meatball-rest * File Name:PayOrderParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月13日下午5:17:41 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; /** * @Title: PayOrderParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(扫码支付信息) * @author jw * @date 2018年3月13日 下午5:17:41 * @version V1.0 */ public class PayOrderParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="操作结果(0:成功 1:失败)", example="0") private int resultCode; @ApiModelProperty(value="操作结果的详细描述信息", example="操作成功") private String resultMsg; @ApiModelProperty(value="微信二维码", example="weixin://wxpay/bizpayurl?pr=ENaKyJK") private String wxCode; @ApiModelProperty(value="微信订单号", example="123456") private String wxOrder; @ApiModelProperty(value="支付宝二维码", example="xxxxxxx") private String zfbCode; @ApiModelProperty(value="支付宝订单号", example="123456") private String zfbOrder; public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public String getResultMsg() { return resultMsg; } public void setResultMsg(String resultMsg) { this.resultMsg = resultMsg; } public String getWxCode() { return wxCode; } public void setWxCode(String wxCode) { this.wxCode = wxCode; } public String getWxOrder() { return wxOrder; } public void setWxOrder(String wxOrder) { this.wxOrder = wxOrder; } public String getZfbCode() { return zfbCode; } public void setZfbCode(String zfbCode) { this.zfbCode = zfbCode; } public String getZfbOrder() { return zfbOrder; } public void setZfbOrder(String zfbOrder) { this.zfbOrder = zfbOrder; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/AccountInfoParams.java /** * Project Name:meatball-rest * File Name:AccountInfoParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月13日下午2:54:23 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; /** * @Title: AccountInfoParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(账户详细信息) * @author jw * @date 2018年3月13日 下午2:54:23 * @version V1.0 */ public class AccountInfoParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="操作结果(0:成功 1:失败)", example="0") private int resultCode; @ApiModelProperty(value="操作结果的详细描述信息", example="操作成功") private String resultMsg; @ApiModelProperty(value="账户id", example="1") private String id; @ApiModelProperty(value="姓名", example="张三") private String name; @ApiModelProperty(value="身份证号", example="512341199010101111") private String idcard; @ApiModelProperty(value="就诊卡号", example="1555555555") private String cardNumber; @ApiModelProperty(value="性别(1 男 2女)", example="1") private int gender; @ApiModelProperty(value="电话", example="13500000000") private String tel; @ApiModelProperty(value="住址", example="四川省成都市xx区xx街道") private String address; @ApiModelProperty(value="出生日期 (yyyy-MM-dd)", example="1990-10-10") private String birthday; @ApiModelProperty(value="社保卡号", example="1555555555") private String sinCard; @ApiModelProperty(value="居民健康卡号", example="1555555555") private String healthCard; @ApiModelProperty(value="账户余额(带两位小数点)", example="5000.00") private String balance; @ApiModelProperty(value="创建时间 (yyyy-MM-dd HH:mm:ss)", example="2010-10-10 15:11:12") private String createDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public String getResultMsg() { return resultMsg; } public void setResultMsg(String resultMsg) { this.resultMsg = resultMsg; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSinCard() { return sinCard; } public void setSinCard(String sinCard) { this.sinCard = sinCard; } public String getHealthCard() { return healthCard; } public void setHealthCard(String healthCard) { this.healthCard = healthCard; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } } <file_sep>/yikatong-core/src/main/resources/static/lib/layui/lay/modules/echoform.js /** * 表单回显 * @author xiangyu.zhang */ layui.define(function(exports) { var $ = layui.$; $.fn.echoform = function(data){ return this.each(function(){ var formElem, name; if(data == null){this.reset(); return; } for(var i = 0; i < this.length; i++){ formElem = this.elements[i]; //checkbox的name可能是name[]数组形式 name = (formElem.type == "checkbox")? formElem.name.replace(/(.+)\[\]$/, "$1") : formElem.name; if(data[name] == undefined) continue; switch(formElem.type) { case "checkbox": if(data[name] == ""){ formElem.checked = false; }else{ //数组查找元素 if(data[name] == true){ formElem.checked = true; }else{ formElem.checked = false; } } break; case "radio": if(data[name] == 0){ formElem.checked = true; }else if(formElem.value == 1){ formElem.checked = true; } break; case "date": formElem.value = TimeObjectUtil.longMsTimeConvertToDate(data[name]); break; /*case "text": if(isDate(TimeObjectUtil.longMsTimeConvertToDate(data[name])) && data[name].length == 10) { formElem.value = TimeObjectUtil.longMsTimeConvertToDateTime(data[name]); } else { console.log(data[name].toString().length +' ' + data[name]) formElem.value = data[name]; } if(typeof(data[name].length) == 'undefined' && data[name].toString().length >= 13) { formElem.value = TimeObjectUtil.longMsTimeConvertToDateTime(data[name]); } else { formElem.value = data[name]; } break;*/ case "button": break; default: formElem.value = data[name]; } } }); }; exports('echoform', this); }); <file_sep>/yikatong-rest/src/main/java/com/meatball/api/user/service/UserApiService.java /** * Project Name:meatball-rest * File Name:UserApiService.java * Package Name:com.meatball.api.user.service * Date:2018年3月4日下午3:51:06 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.user.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.meatball.api.user.parems.UserParems; import com.meatball.component.TokenComponent; import com.meatball.system.user.model.SysUser; import com.meatball.system.user.service.UserService; import com.meatball.vo.ResultMsg; /** * @Title: UserApiService.java * @Package com.meatball.api.user.service * @Description: TODO(用户信息) * @author 張翔宇 * @date 2018年3月4日 下午3:51:06 * @version V1.0 */ @Service public class UserApiService { @Resource private UserService service; @Resource private TokenComponent tokenComponent; /** * @Title: info * @Description: TODO(用户详情) * @param token * @return ResultMsg 返回类型 */ public ResultMsg info(UserParems parems) { long userId = tokenComponent.parseJWT(parems.getToken()); SysUser sysUser = service.info(userId); return new ResultMsg(200, sysUser); } } <file_sep>/README.md # yikatong-parent 一卡通 <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/service/impl/OrderApiForAlipayServiceImpl.java /** * Project Name:meatball-rest * File Name:OrderApiServiceImpl.java * Package Name:com.meatball.api.ykt.service.impl * Date:2018年3月15日下午3:44:59 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.service.impl; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import com.alipay.api.response.AlipayTradePrecreateResponse; import com.meatball.api.ykt.dao.AccountMapper; import com.meatball.api.ykt.dao.ComsumeRecordMapper; import com.meatball.api.ykt.dao.PayCallbackRecordMapper; import com.meatball.api.ykt.dao.RechargeRecordMapper; import com.meatball.api.ykt.enums.DealTypeEnum; import com.meatball.api.ykt.model.Account; import com.meatball.api.ykt.model.ComsumeRecord; import com.meatball.api.ykt.model.PayCallbackRecord; import com.meatball.api.ykt.model.RechargeRecord; import com.meatball.api.ykt.parems.AliOrderParams; import com.meatball.api.ykt.parems.PayOrderParams; import com.meatball.api.ykt.service.OrderApiForAlipayService; import com.meatball.utils.AlipayResRedder; import com.meatball.utils.DateUtil; import com.meatball.utils.QRCodeToBase64; import com.meatball.utils.pay.AlipayTradePrecreate; import com.meatball.utils.pay.params.AlipayParams; import com.meatball.vo.ResultMsg; /** * @Title: OrderApiServiceImpl.java * @Package com.meatball.api.ykt.service.impl * @Description: TODO(支付宝下单) * @author 張翔宇 * @date 2018年3月15日 下午3:44:59 * @version V1.0 */ @Service public class OrderApiForAlipayServiceImpl implements OrderApiForAlipayService { @Resource private AlipayTradePrecreate alipayTradePrecreate; @Resource private ComsumeRecordMapper comsumeRecordMapper; @Resource private PayCallbackRecordMapper payCallbackRecordMapper; @Resource private RechargeRecordMapper rechargeRecordMapper; @Resource private AccountMapper accountMapper; // 测试 @Override public ResultMsg aliOrder(AliOrderParams params) { // 发起预下单操作 AlipayParams aliParams = new AlipayParams(); BeanUtils.copyProperties(params, aliParams); AlipayTradePrecreateResponse payResult = alipayTradePrecreate.placeOrder(aliParams); PayOrderParams result = new PayOrderParams(); if(payResult.getCode().equals("10000")) { // result.setZfbCode(QRCodeToBase64.qrCodeToBase64(payResult.getQrCode())); result.setZfbOrder(payResult.getOutTradeNo()); } return new ResultMsg(200, "预下单成功", result); } @Override public void zfbback(HttpServletRequest request, HttpServletResponse response) { //获取支付宝POST过来反馈信息 Map<String, String> maps = AlipayResRedder.read(request); // 验签结果 boolean verify = alipayTradePrecreate.verifySignature(maps); if(maps.get("trade_status").equals("TRADE_SUCCESS") && verify) { // 获取订单号 String outTradeNo = maps.get("out_trade_no"); // 获取订单类型 String orderType = outTradeNo.substring(0, 2); switch (orderType) { case "cz": // 查询出充值订单 RechargeRecord rechargeRecord = rechargeRecordMapper.selectByPrimaryKey(Long.valueOf(outTradeNo.substring(2, outTradeNo.length()))); // 设置交易流水号 rechargeRecord.setvOrderid(maps.get("trade_no")); ComsumeRecord comsumeRecord = new ComsumeRecord(); comsumeRecord.setvPaymentid(rechargeRecord.getvOrderid()); BeanUtils.copyProperties(rechargeRecord, comsumeRecord); // 插入回调表数据 this.insertPayCallbackRecord(maps, comsumeRecord); // 更新交易状态 rechargeRecord.setiDealstatus(0); // 更新信息 rechargeRecordMapper.updateByPrimaryKeySelective(rechargeRecord); // 维护账户余额 // 查询用户信息 Account account = accountMapper.selectByPrimaryKey(rechargeRecord.getbAccountid()); account.setdBalance(rechargeRecord.getdBalance() + account.getdBalance()); accountMapper.updateByPrimaryKeySelective(account); break; case "xf": // 查询出当前消费订单 System.out.println(outTradeNo.substring(2, outTradeNo.length())); ComsumeRecord record = comsumeRecordMapper.selectByPrimaryKey(Long.valueOf(outTradeNo.substring(2, outTradeNo.length()))); // 插入回调表数据 this.insertPayCallbackRecord(maps, record); // 设置交易流水号 record.setvPaymentid(maps.get("trade_no")); // 更新交易状态 record.setiDealstatus(0); // 更新信息 comsumeRecordMapper.updateByPrimaryKeySelective(record); break; default: throw new RuntimeException("订单类型不存在。"); } } // 执行完成,向支付宝发送停止异步请求 try { PrintWriter out = response.getWriter(); out.println("success"); out.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @Title: insertPayCallbackRecord * @Description: TODO(保存回调信息) * @param map * @return void 返回类型 */ private void insertPayCallbackRecord(Map<String, String> map, ComsumeRecord comsumeRecord) { PayCallbackRecord record = new PayCallbackRecord(); record.settTime(new Date()); record.setvOrderid(map.get("out_trade_no")); record.setvPayplatform("支付宝"); record.setvDealno(map.get("trade_no")); record.settOrdertime(DateUtil.parseTime(map.get("gmt_create"))); record.settPaytime(DateUtil.parseTime(map.get("gmt_payment"))); record.setdBalance(Double.parseDouble(map.get("total_amount"))); record.setiDealtype2(comsumeRecord.getiDealtype()); record.setvDealname(DealTypeEnum.lookup(comsumeRecord.getiDealtype()).toString()); record.setvResult("成功"); record.setbAccountid(comsumeRecord.getbAccountid()); record.setvAccountname(comsumeRecord.getvAccountname()); record.setvMerchantid(map.get("seller_id")); payCallbackRecordMapper.insertSelective(record); } } <file_sep>/yikatong-startup/src/main/java/com/meatball/MeatballApplication.java package com.meatball; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @Title: MeatballApplication.java * @Package com.meatball * @Description: TODO(启动类) * @author 張翔宇 * @date 2017年10月10日 下午12:17:06 * @version V1.0 */ @MapperScan("**.dao") @SpringBootApplication //@EnableEurekaClient public class MeatballApplication { private static final Logger log = LoggerFactory.getLogger(MeatballApplication.class); public static void main(String[] args) { SpringApplication application = new SpringApplication(MeatballApplication.class); application.setBannerMode(Banner.Mode.OFF); application.run(args); log.info("Service startup complete. (服务启动完成。)"); } } <file_sep>/yikatong-core/src/main/java/com/meatball/component/SpringUtil.java /** * Project Name:meatball-core * File Name:SpringUtil.java * Package Name:com.meatball.component * Date:2018年2月7日下午4:24:22 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @Title: SpringUtil.java * @Package com.meatball.component * @Description: TODO(普通类获取springbean) * @author 張翔宇 * @date 2018年2月7日 下午4:24:22 * @version V1.0 */ @Component public class SpringUtil implements ApplicationContextAware { Logger log = LoggerFactory.getLogger(SpringUtil.class); private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } log.info("Common class get SpringBean is loads successfully. (普通类获取SpringBean模块加载成功。)"); } /** * @Title: getApplicationContext * @Description: TODO(获取applicationContext) * @return ApplicationContext 返回类型 */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * @Title: getBean * @Description: TODO(通过name获取 Bean.) * @param name * @return Object 返回类型 */ public static Object getBean(String name){ return getApplicationContext().getBean(name); } /** * @Title: getBean * @Description: TODO(通过class获取Bean.) * @param clazz * @return T 返回类型 */ public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } /** * @Title: getBean * @Description: TODO(通过name,以及Clazz返回指定的Bean) * @param name * @param clazz * @return T 返回类型 */ public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/parems/RefundAmountParams.java /** * Project Name:meatball-rest * File Name:RefundAmountParams.java * Package Name:com.meatball.api.ykt.parems * Date:2018年3月17日下午2:32:38 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.ykt.parems; import java.io.Serializable; import io.swagger.annotations.ApiModelProperty; /** * @Title: RefundAmountParams.java * @Package com.meatball.api.ykt.parems * @Description: TODO(退款金额参数类) * @author jw * @date 2018年3月17日 下午2:32:38 * @version V1.0 */ public class RefundAmountParams implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value="卡类别(1:身份证 2:就诊卡 3:社保卡 4:居民健康卡)", example="1", required = true) private int type; @ApiModelProperty(value="号码", example="123456", required = true) private String number; @ApiModelProperty(value="金额(带两位小数点)", example="5000.00", required = true) private String balance; /* @ApiModelProperty(value="退款方式(1线上、2线下)", example="1", required = true) private int payType; @ApiModelProperty(value="线上支付平台的交易流水号(注:线上退款必须提供)", example="xxxxxxxx") private String dealId; @ApiModelProperty(value="线下的订单号(注:线下退款必须提供)", example="xxxxxxxx") private String orderId; @ApiModelProperty(value="线下类别(1住院费、2账户余额)", example="1", required = true) private int dealType;*/ @ApiModelProperty(value="身份证照片路径", example="xxxxxxxx", required = true) private String pic; @ApiModelProperty(value="机器编号", example="xxxxx", required = true) private String machineId ; @ApiModelProperty(value="操作员", example="张三", required = true) private String operatorName; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number == null ? null : number.trim(); } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getMachineId() { return machineId; } public void setMachineId(String machineId) { this.machineId = machineId; } public String getOperatorName() { return operatorName; } public void setOperatorName(String operatorName) { this.operatorName = operatorName; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/user/controller/UserApiController.java /** * Project Name:meatball-rest * File Name:UserApiController.java * Package Name:com.meatball.api.user.controller * Date:2018年3月4日下午3:45:54 * Copyright (c) 2018, <EMAIL> All Rights Reserved. */ package com.meatball.api.user.controller; import javax.annotation.Resource; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.meatball.api.user.parems.UserParems; import com.meatball.api.user.service.UserApiService; import com.meatball.vo.ResultMsg; import springfox.documentation.annotations.ApiIgnore; /** * @Title: UserApiController.java * @Package com.meatball.api.user.controller * @Description: TODO(用一句话描述该文件做什么) * @author 張翔宇 * @date 2018年3月4日 下午3:45:54 * @version V1.0 */ @ApiIgnore @RestController @RequestMapping("/api/user") public class UserApiController { @Resource private UserApiService service; /** * @Title: info * @Description: TODO(用户详情信息) * @param token * @return ResultMsg 返回类型 */ @PostMapping("/info") @RequiresPermissions("system:user:info") public ResultMsg info(@RequestBody UserParems parems) { return service.info(parems); } } <file_sep>/yikatong-rest/src/main/java/com/meatball/api/ykt/dao/ComsumeRecordMapper.java package com.meatball.api.ykt.dao; import java.util.List; import com.meatball.api.ykt.model.ComsumeRecord; /** * @Title: ComsumeRecordMapper.java * @Package com.meatball.api.ykt.dao * @Description: TODO(消费记录dao) * @author jw * @date 2018年3月16日 下午4:46:11 * @version V1.0 */ public interface ComsumeRecordMapper { /** * @Title: deleteByPrimaryKey * @Description: TODO(根据id删除信息) * @param bId * @return * @return int 返回类型 */ int deleteByPrimaryKey(Long bId); /** * @Title: insert * @Description: TODO(新增信息) * @param record * @return * @return int 返回类型 */ int insert(ComsumeRecord record); /** * @Title: insertSelective * @Description: TODO(新增指定字段信息) * @param record * @return * @return int 返回类型 */ int insertSelective(ComsumeRecord record); /** * @Title: selectByPrimaryKey * @Description: TODO(根据id查询信息) * @param bId * @return * @return ComsumeRecord 返回类型 */ ComsumeRecord selectByPrimaryKey(Long bId); /** * @Title: updateByPrimaryKeySelective * @Description: TODO(修改指定字段信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKeySelective(ComsumeRecord record); /** * @Title: updateByPrimaryKey * @Description: TODO(修改信息) * @param record * @return * @return int 返回类型 */ int updateByPrimaryKey(ComsumeRecord record); /** * @Title: selectSuccessComsumeRecord * @Description: TODO(根据订单号查询消费成功的消费记录) * @param bId * @return * @return ComsumeRecord 返回类型 */ ComsumeRecord selectSuccessComsumeRecord(long bId); /** * @Title: selectSuccessComsumeRecord * @Description: TODO(根据订单号查询消费成功的消费记录) * @param bId * @return * @return ComsumeRecord 返回类型 */ List<ComsumeRecord> selectBybAccountid(long bAccountid); }
0fb7a2ed774983f2ac12c8403b6269808219e9bc
[ "JavaScript", "Java", "Maven POM", "Markdown" ]
44
Java
zhangzh56/yikatong-parent
47e8f627ba3471eff71f593189e82c6f08ceb1a3
e605b4025c934fb4099d5c321faa3a48703f8ff7
refs/heads/master
<file_sep>// definisco le mie variabili var openMenu = $(".header-right > a"); var closeMenu = $( ".close"); var burgerMenu = $(".hamburger-menu") //apro il menu $(openMenu).click( function() { $(burgerMenu).addClass("active"); } ); // chiudo il menu $(closeMenu).click( function(){ $(burgerMenu).removeClass("active"); } );
40af0195da56c10fc6b231ecfe8062000e3cef30
[ "JavaScript" ]
1
JavaScript
denniolimpio/js-jq-hamburger
d2c97f7f8147f70f56b89e8e0228768cb1396322
00915ef3e40b2da52136a03f6927ce3f6c44c207
refs/heads/master
<repo_name>afzal-p/pagila-hw3<file_sep>/sql/01.sql /* * Select the title of all 'G' rated movies that have the 'Trailers' special feature. */ SELECT title FROM (SELECT film_id,title,rating,unnest(special_features) FROM film) as temp WHERE rating = 'G' and unnest='Trailers' ORDER BY title DESC; <file_sep>/sql/03.sql /* * Management is planning on purchasing new inventory. * Films with special features cost more to purchase than films without special features, * and so management wants to know if the addition of special features impacts revenue from movies. * * Write a query that for each special_feature, calculates the total profit of all movies rented with that special feature. * * HINT: * Start with the query you created in pagila-hw1 problem 16, but add the special_features column to the output. * Use this query as a subquery in a select statement similar to answer to the previous problem. */ SELECT special_feature, sum(profit) AS profit FROM (SELECT unnest(special_features) as special_feature, profit FROM (SELECT film.title, special_features, sum(payment.amount) AS profit FROM payment JOIN rental USING (rental_id) JOIN inventory USING (inventory_id) JOIN film USING (film_id) GROUP BY film.title,special_features ORDER BY profit DESC) as temp) as temp2 GROUP BY special_feature ORDER BY special_feature; <file_sep>/sql/02.sql /* * Count the number of movies that contain each type of special feature. */ SELECT ft AS special_features, count(*) FROM film, unnest(film.special_features) as ft GROUP BY ft ORDER BY ft ASC; <file_sep>/sql/05.sql /* * List the title of all movies that have both the 'Behind the Scenes' and the 'Trailers' special_feature * * HINT: * Create a select statement that lists the titles of all tables with the 'Behind the Scenes' special_feature. * Create a select statement that lists the titles of all tables with the 'Trailers' special_feature. * Inner join the queries above. */ SELECT temp1.title FROM (SELECT title FROM (SELECT title,unnest(special_features) AS special_feature FROM film) as temp WHERE special_feature = 'Behind the Scenes') as temp1 INNER JOIN (SELECT title FROM (SELECT title,unnest(special_features) AS special_feature FROM film) as temp WHERE special_feature = 'Trailers') as temp2 ON temp2.title=temp1.title ORDER BY temp1.title; <file_sep>/sql/07.sql /* * List all actors with Bacall Number 2; * That is, list all actors that have appeared in a film with an actor that has appeared in a film with 'RUSSEL BACALL', * but do not include actors that have Bacall Number < 2. */ SELECT DISTINCT first_name || ' ' || last_name AS "Actor Name" FROM actor JOIN film_actor USING (actor_id) JOIN film USING (film_id) WHERE film.title IN (SELECT title from film JOIN film_actor USING (film_id) WHERE actor_id IN( SELECT DISTINCT(a2.actor_id) FROM actor a1 JOIN film_actor fa1 ON a1.actor_id = fa1.actor_id JOIN film_actor fa2 ON fa1.film_id = fa2.film_id JOIN actor a2 ON fa2.actor_id = a2.actor_id WHERE a1.actor_id = 112 AND a2.actor_id != 112)) AND actor_id NOT IN (SELECT DISTINCT(a2.actor_id) FROM actor a1 JOIN film_actor fa1 ON a1.actor_id = fa1.actor_id JOIN film_actor fa2 ON fa1.film_id = fa2.film_id JOIN actor a2 ON fa2.actor_id = a2.actor_id WHERE a1.actor_id = 112) ORDER BY "Actor Name"; <file_sep>/sql/04.sql /* * List the name of all actors who have appeared in a movie that has the 'Behind the Scenes' special_feature */ SELECT DISTINCT(first_name || ' ' || last_name) AS "Actor Name" FROM actor JOIN film_actor USING (actor_id) JOIN film USING (film_id) WHERE film_id IN (SELECT film_id FROM (SELECT film_id,unnest(special_features) AS special_feature FROM film) as temp WHERE special_feature = 'Behind the Scenes') ORDER BY first_name || ' ' || last_name;
697cc318e4dd88ca1d29863fb0da0df11fc56015
[ "SQL" ]
6
SQL
afzal-p/pagila-hw3
9f7cb0d400a42ec6264f8555cbbfea648ed382c4
6aacb29c497b243a5fd96821debb03f35ee0ffbf
refs/heads/master
<file_sep>const jwt= require('jsonwebtoken'); module.exports= function(req, res ,next){ // leer el token del header const token= req.header('x-auth-token'); // recisar si no hay token if(!token){ return res.status(401).json({msg:'No hay token, permiso denegado '}) } // validar el token try{ const cifrado= jwt.verify(token,process.env.SECRETA); req.usuario= cifrado.usuario; next(); }catch(error){ res.status(401).json({msg:'Token no valido'}); } }
3f3dad0049e91807ef26c8f27cdce38d84ea0eb3
[ "JavaScript" ]
1
JavaScript
RocioCentu/Merntasks-React-Servidor
b87c698d12ddd2e00f72989e3bf58bbf2d5117db
e47b3619392f4afdc905d5fb991c067ad3d4fd40
refs/heads/master
<file_sep>package com.akexorcist.example.akexorcistprofile.vo <file_sep>package com.akexorcist.example.feature_blogger.ui.blogger import android.view.View import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.view_holder_blogger_profile.blogger_image_view_profile as imageViewProfile import kotlinx.android.synthetic.main.view_holder_blogger_profile.blogger_text_view_name as textViewName class ProfileViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setProfileImage(url: String?) { url?.let { Glide.with(itemView.context).load(url).into(imageViewProfile) } } fun setName(name: String?) { name?.let { textViewName.text = name } ?: run { textViewName.text = "" } } fun setOnClickListener(listener: () -> Unit) { itemView.setOnClickListener { listener() } } }<file_sep>package com.akexorcist.example.feature_github.ui.github import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.view_holder_github_repo.github_text_view_description as textViewDescription import kotlinx.android.synthetic.main.view_holder_github_repo.github_text_view_language as textViewLanguage import kotlinx.android.synthetic.main.view_holder_github_repo.github_text_view_license as textViewLicense import kotlinx.android.synthetic.main.view_holder_github_repo.github_text_view_name as textViewName class RepoViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setName(name: String?) { name?.let { textViewName.text = it } ?: run { textViewName.text = "" } } fun setDescription(description: String?) { description?.let { textViewDescription.text = it } ?: run { textViewDescription.text = "" } } fun setLanguage(language: String?) { language?.let { textViewLanguage.text = it textViewLanguage.visibility = View.VISIBLE } ?: run { textViewLanguage.text = "" textViewLanguage.visibility = View.GONE } } fun setLicense(license: String?) { license?.let { textViewLicense.text = it textViewLicense.visibility = View.VISIBLE } ?: run { textViewLicense.text = "" textViewLicense.visibility = View.GONE } } fun setOnClickListener(listener: () -> Unit) { itemView.setOnClickListener { listener() } } }<file_sep>package com.akexorcist.example.feature_stackoverflow.ui.stackoverflow import android.view.View import androidx.recyclerview.widget.RecyclerView import com.akexorcist.example.feature_stackoverflow.R import com.bumptech.glide.Glide import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_image_view_profile as imageViewProfile import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_bronze_count as textViewBronzeCount import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_gold_count as textViewGoldCount import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_location as textViewLocation import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_name as textViewName import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_reputation as textViewReputation import kotlinx.android.synthetic.main.view_holder_stackoverflow_profile.stackoverflow_text_view_silver_count as textViewSilverCount class ProfileViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setProfileImage(url: String?) { url?.let { Glide.with(itemView.context).load(url).into(imageViewProfile) } } fun setName(name: String?) { name?.let { textViewName.text = name } ?: run { textViewName.text = "" } } fun setLocation(location: String?) { location?.let { textViewLocation.text = location textViewLocation.visibility = View.VISIBLE } ?: run { textViewLocation.text = "" textViewLocation.visibility = View.INVISIBLE } } fun setReputation(reputation: Int) { textViewReputation.text = itemView.resources.getString(R.string.reputations, reputation) } fun setGoldCount(count: Int) { textViewGoldCount.text = count.toString() } fun setSilverCount(count: Int) { textViewSilverCount.text = count.toString() } fun setBronzeCount(count: Int) { textViewBronzeCount.text = count.toString() } fun setOnClickListener(listener: () -> Unit) { itemView.setOnClickListener { listener() } } }<file_sep>package com.akexorcist.example.feature_github.ui.github import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.transition.TransitionManager import com.akexorcist.example.feature_github.R import com.akexorcist.example.feature_github.api.GithubConfig import com.akexorcist.example.feature_github.api.GithubManager import com.akexorcist.example.feature_github.util.converter.GithubConverter import com.akexorcist.example.feature_github.vo.ui.Profile import com.akexorcist.example.feature_github.vo.ui.Repo import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlinx.android.synthetic.main.activity_github.github_layout_root as layoutRoot import kotlinx.android.synthetic.main.activity_github.github_progress_bar_content_loading as progressBarContentLoading import kotlinx.android.synthetic.main.activity_github.github_recycler_view_info as recyclerViewProfile import kotlinx.android.synthetic.main.activity_github.github_text_view_empty_response as textViewEmptyResponse import kotlinx.android.synthetic.main.activity_github.github_text_view_service_error as textViewServiceError class GithubActivity : AppCompatActivity() { private val adapter = GithubInfoAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_github) initRecyclerView() getProfile() showLoading() } private fun initRecyclerView() { adapter.setOnUrlClickListener { url -> openExternalWeb(url) } recyclerViewProfile.adapter = adapter recyclerViewProfile.layoutManager = LinearLayoutManager(this) } private fun getProfile() { GithubManager.api.getProfile(GithubConfig.USER) .enqueue(object : Callback<com.akexorcist.example.feature_github.vo.api.Profile> { override fun onFailure(call: Call<com.akexorcist.example.feature_github.vo.api.Profile>, t: Throwable) { showError() } override fun onResponse( call: Call<com.akexorcist.example.feature_github.vo.api.Profile>, response: Response<com.akexorcist.example.feature_github.vo.api.Profile> ) { val result: com.akexorcist.example.feature_github.vo.api.Profile? = response.body() result?.let { updateProfile(GithubConverter.profile(it)) } ?: run { showError() } } }) } private fun getRepoList() { GithubManager.api.getRepoList(GithubConfig.USER, "pushed") .enqueue(object : Callback<List<com.akexorcist.example.feature_github.vo.api.Repo>> { override fun onFailure(call: Call<List<com.akexorcist.example.feature_github.vo.api.Repo>>, t: Throwable) { showError() } override fun onResponse( call: Call<List<com.akexorcist.example.feature_github.vo.api.Repo>>, response: Response<List<com.akexorcist.example.feature_github.vo.api.Repo>> ) { val result: List<com.akexorcist.example.feature_github.vo.api.Repo>? = response.body() result?.let { updateRepoList(GithubConverter.repo(it)) showSuccess() } ?: run { showError() } } }) } private fun updateProfile(profile: Profile) { adapter.setProfile(profile) getRepoList() } private fun updateRepoList(repoList: List<Repo>) { adapter.setRepoList(repoList) adapter.notifyDataSetChanged() } private fun showLoading() { progressBarContentLoading.show() recyclerViewProfile.visibility = View.INVISIBLE textViewEmptyResponse.visibility = View.INVISIBLE textViewServiceError.visibility = View.INVISIBLE TransitionManager.beginDelayedTransition(layoutRoot) } private fun showSuccess() { progressBarContentLoading.hide() recyclerViewProfile.visibility = View.VISIBLE textViewEmptyResponse.visibility = View.INVISIBLE textViewServiceError.visibility = View.INVISIBLE TransitionManager.beginDelayedTransition(layoutRoot) } private fun showEmpty() { progressBarContentLoading.hide() recyclerViewProfile.visibility = View.INVISIBLE textViewEmptyResponse.visibility = View.VISIBLE textViewServiceError.visibility = View.INVISIBLE TransitionManager.beginDelayedTransition(layoutRoot) } private fun showError() { progressBarContentLoading.hide() recyclerViewProfile.visibility = View.INVISIBLE textViewEmptyResponse.visibility = View.INVISIBLE textViewServiceError.visibility = View.VISIBLE TransitionManager.beginDelayedTransition(layoutRoot) } private fun openExternalWeb(url: String) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } } <file_sep>dsn=https://ed9d5d4953f74f1cb9156a59b0be911b@sentry.io/1409770 defaults.project=debugging defaults.org=sleeping-for-less auth.token=<PASSWORD> environment=production<file_sep>package com.akexorcist.example.feature_blogger.ui.blogger import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer class TitleViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer<file_sep>package com.akexorcist.example.feature_stackoverflow.ui.stackoverflow import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer class TitleViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer<file_sep>package com.akexorcist.example.feature_stackoverflow.ui.stackoverflow import android.view.View import androidx.recyclerview.widget.RecyclerView import com.akexorcist.example.feature_stackoverflow.R import com.akexorcist.example.feature_stackoverflow.constant.TimelineType import kotlinx.android.extensions.LayoutContainer import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle import java.util.* import kotlinx.android.synthetic.main.view_holder_stackoverflow_activity.stackoverflow_text_view_date as textViewDate import kotlinx.android.synthetic.main.view_holder_stackoverflow_activity.stackoverflow_text_view_title as textViewTitle import kotlinx.android.synthetic.main.view_holder_stackoverflow_activity.stackoverflow_text_view_type as textViewType class ActivityViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setType(type: String?) { type?.let { textViewType.text = getType(it) } ?: run { textViewType.text = "" } } fun setTitle(title: String?) { title?.let { textViewTitle.text = it } ?: run { textViewTitle.text = "" } } fun setDate(date: Long) { val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) .withLocale(Locale.getDefault()) .withZone(ZoneId.systemDefault()) textViewDate.text = formatter.format(Instant.ofEpochSecond(date)) } private fun getType(type: String): String = when (type) { TimelineType.ANSWERED -> itemView.resources.getString(R.string.timeline_type_answered) TimelineType.BADGE -> itemView.resources.getString(R.string.timeline_type_badge) TimelineType.COMMENTED -> itemView.resources.getString(R.string.timeline_type_commented) TimelineType.REVISION -> itemView.resources.getString(R.string.timeline_type_revision) else -> "-" } }<file_sep>package com.akexorcist.example.feature_github.ui.github import android.view.View import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.view_holder_github_profile.github_image_view_profile as imageViewProfile import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_company as textViewCompany import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_follower_count as textViewFollowerCount import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_following_count as textViewFollowingCount import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_gist_count as textViewGistCount import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_location as textViewLocation import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_name as textViewName import kotlinx.android.synthetic.main.view_holder_github_profile.github_text_view_repository_count as textViewRepoCount class ProfileViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setProfileImage(url: String?) { url?.let { Glide.with(itemView.context).load(url).into(imageViewProfile) } } fun setName(name: String?) { name?.let { textViewName.text = name } ?: run { textViewName.text = "" } } fun setCompany(company: String?) { company?.let { textViewCompany.text = company textViewCompany.visibility = View.VISIBLE } ?: run { textViewCompany.text = "" textViewCompany.visibility = View.INVISIBLE } } fun setLocation(location: String?) { location?.let { textViewLocation.text = location textViewLocation.visibility = View.VISIBLE } ?: run { textViewLocation.text = "" textViewLocation.visibility = View.INVISIBLE } } fun setRepoCount(count: Int) { textViewRepoCount.text = count.toString() } fun setGistCount(count: Int) { textViewGistCount.text = count.toString() } fun setFollowerCount(count: Int) { textViewFollowerCount.text = count.toString() } fun setFollowingCount(count: Int) { textViewFollowingCount.text = count.toString() } fun setOnClickListener(listener: () -> Unit) { itemView.setOnClickListener { listener() } } }<file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: "kotlin-kapt" apply plugin: 'io.sentry.android.gradle' android { compileSdkVersion 29 defaultConfig { applicationId "com.akexorcist.example.akexorcistprofile" minSdkVersion 19 targetSdkVersion 29 versionCode 10013 versionName "1.0.13" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } dynamicFeatures = [":feature_github", ":feature_blogger", ":feature_stackoverflow"] compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } sentry { autoProguardConfig true autoUpload false } androidExtensions { experimental = true } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) api "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" api 'androidx.appcompat:appcompat:1.1.0-rc01' api 'androidx.recyclerview:recyclerview:1.0.0' api 'androidx.cardview:cardview:1.0.0' api 'androidx.core:core-ktx:1.2.0-alpha02' api 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.3.0-alpha02' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha02' api 'com.squareup.retrofit2:converter-gson:2.6.0' api 'com.squareup.retrofit2:retrofit:2.6.0' api 'com.squareup.okhttp3:okhttp:3.13.1' api 'com.squareup.okhttp3:logging-interceptor:3.13.1' api 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.2' api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.2' api('com.karumi:dexter:5.0.0') { exclude group: 'com.android.support' } api 'com.jakewharton.threetenabp:threetenabp:1.1.0' testImplementation 'org.threeten:threetenbp:1.3.6' api 'com.github.bumptech.glide:glide:4.9.0' kapt 'com.github.bumptech.glide:compiler:4.9.0' api 'com.rilixtech:materialfancybuttons:1.8.7' api 'com.rilixtech:devicon-typeface:2.0.0.3' api 'com.rilixtech:foundation-icons-typeface:3.0.0.3' api 'com.google.android.play:core:1.6.1' api 'io.sentry:sentry-android:1.7.20' api 'org.slf4j:slf4j-nop:1.7.25' } <file_sep>package com.akexorcist.example.akexorcistprofile import com.google.android.play.core.splitcompat.SplitCompatApplication import com.jakewharton.threetenabp.AndroidThreeTen import io.sentry.Sentry import io.sentry.android.AndroidSentryClientFactory class MainApplication : SplitCompatApplication() { override fun onCreate() { super.onCreate() AndroidThreeTen.init(this) Sentry.init(AndroidSentryClientFactory(applicationContext)) } }<file_sep>package com.akexorcist.example.feature_blogger.ui.blogger import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import org.threeten.bp.OffsetDateTime import org.threeten.bp.ZoneId import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle import java.util.* import kotlinx.android.synthetic.main.view_holder_blogger_post.blogger_text_view_title as textViewTitle import kotlinx.android.synthetic.main.view_holder_blogger_post.blogger_text_view_updated_date as textViewUpdatedDate class PostViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun setTitle(title: String?) { title?.let { textViewTitle.text = it } ?: run { textViewTitle.text = "" } } fun setUpdatedDate(date: String?) { date?.let { val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) .withLocale(Locale.getDefault()) .withZone(ZoneId.systemDefault()) textViewUpdatedDate.text = formatter.format(OffsetDateTime.parse(it)) } ?: run { textViewUpdatedDate.text = "" } } fun setOnClickListener(listener: () -> Unit) { itemView.setOnClickListener { listener() } } }
7e565114b3412ccd39977ca07c3bb68298976c75
[ "Kotlin", "INI", "Gradle" ]
13
Kotlin
akexorcist/Android-AkexorcistProfile
9d3ac849a3d047afacf36a19b5c2423d504a26b9
6155f463b0523e3121a14ceb40b449083dc08b75
refs/heads/master
<file_sep>import Vue from 'vue' import Vuex from 'vuex' import firebase from "firebase/app"; import router from '../router' import db from '../main' Vue.use(Vuex) const usuarioLogged = (commit, payload) => { if (payload != null) { const { email, uid } = payload commit('setUsuario', { email, uid }) }else { commit('setUsuario', null) } } export default new Vuex.Store({ state: { usuario: '', error: '', tareas: [], tarea: {}, carga:false, }, mutations: { setUsuario(state, payload){ state.usuario = payload }, setError(state, payload){ state.error = payload }, setTareas(state, tareas) { state.tareas = tareas }, setTarea(state, tarea) { state.tarea = tarea }, removerTarea(state, id) { state.tareas = state.tareas.filter(item => { return item.id !== id }) }, cargarFirebase(state, payload){ state.carga = payload } }, actions: { crearUsuario({commit}, payload){ const { email, password } = payload firebase.auth().createUserWithEmailAndPassword(email, password) .then(res => { usuarioLogged(commit, res.user) router.push({ name: 'inicio' }) // Crear una colección db.collection(res.user.email).add({ nombre: 'Tarea de ejemplo' }) .then(() => { router.push({name:'inicio'}) }) }) .catch(function (error) { console.log(error.message) commit('setError', error.message) }); }, ingresoUsuario({commit}, payload){ const { email, password } = payload firebase.auth().signInWithEmailAndPassword(email, password) .then(res => { usuarioLogged(commit, res.user) router.push({ name: 'inicio' }) }) .catch(function (error) { console.log(error.message) commit('setError', error.message) }); }, detectarUsuario({commit}, payload){ usuarioLogged(commit, payload) }, cerrarSesion({commit}){ firebase.auth().signOut() commit('setUsuario', null) router.push({ name: 'ingreso' }) }, getTareas: async ({ commit, state }) => { let tareas = [] commit('cargarFirebase', true) const snapshots = await db.collection(state.usuario.email).get() await snapshots.forEach(doc => { tareas.push({ id: doc.id, ...doc.data(), }) }); commit('cargarFirebase', false) commit('setTareas', tareas) }, getTarea: async ({ commit, state }, id) => { const doc = await db.collection(state.usuario.email).doc(id).get() commit('setTarea', { id: doc.id, ...doc.data(), }) }, editarTarea({ commit, state }, { id, nombre }) { db.collection(state.usuario.email).doc(id).update({ nombre }) .then(() => { router.push({ name: 'inicio' }) }) }, agregarTarea({ commit, state }, nombre) { db.collection(state.usuario.email).add({ nombre }) .then(doc => { router.push({ name: 'inicio' }) }) }, eliminarTarea({ commit, state }, id) { db.collection(state.usuario.email).doc(id).delete() .then(() => { console.log('Tarea eliminada') commit('removerTarea', id) }) } }, modules: { }, getters: { existeUsuario(state){ return !(state.usuario === null || state.usuario === undefined || state.usuario === '') } } }) <file_sep>import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import firebase from "firebase/app"; import { BootstrapVue, IconsPlugin } from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' // Install BootstrapVue Vue.use(BootstrapVue) // Optionally install the BootstrapVue icon components plugin Vue.use(IconsPlugin) // Add the Firebase products that you want to use require("firebase/auth"); require("firebase/firestore"); const firebaseConfig = { apiKey: "<KEY>", authDomain: "crud-udemy-luijo.firebaseapp.com", databaseURL: "https://crud-udemy-luijo.firebaseio.com", projectId: "crud-udemy-luijo", storageBucket: "crud-udemy-luijo.appspot.com", messagingSenderId: "95618741045", appId: "1:95618741045:web:66968c746574738ac2527c" }; // Initialize Firebase const app = firebase.initializeApp(firebaseConfig); export default app.firestore(); Vue.config.productionTip = false firebase.auth().onAuthStateChanged(user => { console.log(user) if (user) { const { email, uid } = user store.dispatch('detectarUsuario', { email, uid }) }else{ store.dispatch('detectarUsuario', null) } new Vue({ router, store, render: h => h(App) }).$mount('#app') }) <file_sep>import firebase from 'firebase/app' import firestore from 'firebase/firestore' const firebaseConfig = { apiKey: "<KEY>", authDomain: "crud-udemy-luijo.firebaseapp.com", databaseURL: "https://crud-udemy-luijo.firebaseio.com", projectId: "crud-udemy-luijo", storageBucket: "crud-udemy-luijo.appspot.com", messagingSenderId: "95618741045", appId: "1:95618741045:web:66968c746574738ac2527c" }; // Initialize Firebase const app = firebase.initializeApp(firebaseConfig); export default app.firestore();<file_sep>Vue.component('saludo', { template: ` <div> <h3>{{saludo}}</h3> cdscscs </div> `, data() { return { saludo: "h<NAME>undo", } } })
51ee1e2246e8db0edd428da1c52fe111fa3c458c
[ "JavaScript" ]
4
JavaScript
DayLui-Ve/curso-vuejs
d42971689a66ececd8684e534ce938d01318ed80
a960027c46892b4601d5661de9ab9a703450b6f3
refs/heads/master
<file_sep>import React, { Component } from 'react' import './App.css' import Display from '../components/utils/display/Display'; import Actions from '../components/json/Actions'; import Intro from '../components/intro/Intro'; import sha1 from 'js-sha1'; import Axios from 'axios'; const initialState = { numero_casas: 2, token: "", cifrado: "vjg kpvgtpgv? ku vjcv vjkpi uvknn ctqwpf? jqogt ukoruqp", decifrado: "", resumo_criptografico: "" } class App extends Component { state = { ...initialState } valueToShow = `Clique no botão "Mostrar o valor cifrado" para exibir o valor a ser decifrado.` constructor() { super() this.update = this.update.bind(this) this.send = this.send.bind(this) } update(obj) { if (obj.decifrado !== "") { const hash = sha1.create(); hash.update(obj.decifrado) obj.resumo_criptografico = hash.hex(); this.valueToShow = obj.decifrado } else { this.valueToShow = obj.cifrado } this.setState(obj); } send() { const criptografia = { ...this.state } const blob = new Blob([JSON.stringify(criptografia)], {type : 'application/json'}); const answer = new File([blob], 'answer.json'); const bodyFormData = new FormData(); bodyFormData.set('answer', answer); Axios({ method: 'POST', url: `https://api.codenation.dev/v1/challenge/dev-ps/submit-solution?token=${criptografia.token}`, data: bodyFormData, headers: { 'Content-Type': 'multipart/form-data' } }).then((res) => { this.valueToShow = `Criptografia enviada com sucesso. Score: ${res.data.score}` this.setState(criptografia) }) } render() { return ( <div className="App"> <header className="App-header">Criptografia de Júlio César</header> <Intro /> <div className="btn-group"> <Actions id="cifrado" value="Mostrar o valor cifrado" initial={this.state} action={this.update} /> <Actions id="decifrado" value="Mostrar o valor decifrado" initial={this.state} action={this.update} /> <Actions id="enviar" value="Enviar o objeto descriptografado" initial={this.state} action={this.send} /> </div> <Display value={this.valueToShow} /> </div> ) } } export default App <file_sep>import React from 'react' import './Display.css' export default props => ( <div className='display'><p>{props.value}</p></div> )<file_sep>import Button from '../utils/button/Button' import '../utils/button/Button.css' import React, { Component } from 'react' import Axios from 'axios'; export default class Actions extends Component { state = { ...this.props.initial } action = undefined; constructor(props) { super(props) this.getCifrado = this.getCifrado.bind(this) this.getDecifrado = this.getDecifrado.bind(this) switch (this.props.id) { case "cifrado": this.action = this.getCifrado break case "decifrado": this.action = this.getDecifrado break default: this.action = this.props.action break; } } getCifrado() { Axios({ method: 'get', url: `https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=${this.state.token}`, }).then((response) => { this.setState(response.data) this.props.action(this.state) }); } getDecifrado() { const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; const cifrado = this.props.initial.cifrado; let criptografia = { ...this.props.initial }; if (cifrado === "") { console.log("Cifrado não encontrado") } else if (criptografia.decifrado !== "") { console.log("Criptografia já decifrada") } else { for (let i = 0; i < cifrado.length; i++) { if (cifrado.charAt(i).match(/\W/g)) { criptografia.decifrado += cifrado.charAt(i) } else { for (let j = 0; j < alphabet.length; j++) { if (alphabet[j] === cifrado.charAt(i)) { criptografia.decifrado += alphabet[j - criptografia.numero_casas] } } } } } criptografia.decifrado = criptografia.decifrado.toLowerCase() this.props.action(criptografia) } render() { return ( <div className='button__container'> <Button id={this.props.id} onClick={this.action} value={this.props.value} /> </div> ) } } <file_sep>declare module 'js-sha1'; module.exports = 'js-sha1';
678419d8454617d434a8b0d9ae733434cfe4b6bd
[ "JavaScript", "TypeScript" ]
4
JavaScript
salazenas/ad-challenge
20706a6424199049aad05c4b13a357104eec6d85
b44d43ba2cbeadfbf79bf37eae93206cf0862c53
refs/heads/master
<file_sep>q1 = c(252,586,72) q2 = c(1687,2444,380) q3 = c(302,764,338) q4 = c(2337,6049,915) q5 = c(66,1298,30) q6 = c(990,1951,28) q7 = c(710,3678,42) q8 = c(2145,4779,277) q9 = c(137,406,262) q10 = c(732,1250,64) q11 = c(963,2350,627) q12 = c(1729,2476,370) q13 = c(2127,4294,755) q14 = c(1708,2574,110) q16 = c(1507,2893,499) q17 = c(256,492,15) q18 = c(55,406,6) q19 = c(293,619,51) q20 = c(158,538,18) q21 = c(2153,3707,42) q22 = c(372,1243,369) q23 = c(929,1868,203) q24 = c(477,677,335) q25 = c(243,280,28) q26 = c(628,804,37) depa = data.frame(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11,q12 ,q13,q14,q16,q17,q18,q19,q20,q21,q22,q23,q24,q25,q26) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Provincias","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(depa),main = "Accidents for departments 2014", ylab = "Accidents",names.arg = nombresx,col = rainbow(3) ,beside = TRUE,ylim = c(0,7000),las = 3) legend(x = 70,y = 7000,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep># Proyecto_Inferencia_Variacional_CM274 Proyecto del curso de Introducción a la Estadística y Probabilidad <file_sep>d1 = c(140,283,249) d2 = c(795,1982,383) d3 = c(212,433,439) d4 = c(1674,3411,2507) d5 = c(396,1125,281) d6 = c(721,1728,72) d7 = c(958,3743,233) d8 = c(812,3100,518) d9 = c(65,344,189) d10 = c(219,993,189) d11 = c(949,1998,307) d12 = c(909,1228,1193) d13 = c(2030,3874,867) d14 = c(1467,2977,132) d15 = c(1453,1954,565) d16 = c(210,589,27) d17 = c(158,670,83) d18 = c(102,99,465) d19 = c(63,51,349) d20 = c(1777,2652,714) d21 = c(473,1222,92) d22 = c(521,1806,354) d23 = c(336,461,331) d24 = c(257,307,11) d25 = c(26,16,753) departamentos = data.frame(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12 ,d13,d14,d15,d16,d17,d18,d19,d20,d21,d22,d23,d24,d25) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Region","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(departamentos),main = "Accidents for departments 2016",ylab = "Accidentes",names.arg = nombresx,col = rainbow(3) ,beside = TRUE,ylim = c(0,4000),las = 3) legend(x = 70,y = 4000,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep>a1 = c(52234,75471,3570) a2 = c(52150,81401,10219) a3 = c(37746,67529,8862) a4 = c(42654,85629,13270) a5 = c(36324,86896,9165) a6 = c(35577,68138,25880) tf = data.frame(a1,a2,a3,a4,a5,a6) barplot(as.matrix(tf),names.arg = c("2011","2012","2013","2014","2015", "2016") ,main = "Type of transport",xlab = "Year",ylab = "Number of accidents" ,ylim = c(0,90000),col = rainbow(3) ,beside = TRUE,las = 0) legend(x = 19,y = 85500,legend = c("publico","privado","no identificado"), cex=0.5 , fill=rainbow(3),text.font = 4) <file_sep>#LIMA material = c(26031,19957,16554,26566,27191,26049) total = c(51375,53111,51216,55699,58079,58007) plot(total~material,main = "Grafica de accidentes en lima",xlab = "Material damage" ,ylab = "Total",type = "o",col = "green") #lm servira para hallar los coeficientes de la ecuacion ecuacion2 = lm(total~material) ecuacion2 #sale intercept = 4.338e+04 , material = 4.723e-01 #entonces la ecuacion es total=4.338e+04+4.723e-01*material abline(ecuacion2) summary(ecuacion2) plot(ecuacion2) ks.test(ecuacion2$residuals,"pnorm") #Al hacer esto nos sale el p-valor = 0.003772 lo cual es un p-valor bajo #menor que 0.05 entonces quiere decir que esta regresion no necesita de mas variables dwtest(total~material) #En este caso, con un p-valor de 0.05108 no podemos rechazar la hipótesis de que los residuos son independientes. <file_sep>#LIMA nofatal = c(26752,30903,16486,28812,30161,31658) total = c(51375,53111,51216,55699,58079,58007) plot(total~nofatal,main = "Grafica de accidentes en lima",xlab = "Number of wounded" ,ylab = "Total",type = "o",col = "red") #lm servira para hallar los coeficientes de la ecuacion ecuacion3 = lm(total~nofatal) ecuacion3 #sale intercept = 4.434e(+0.4) , heridos = 3.728e^(-01) #entonces la ecuacion es total = 4.434e(+0.4)+3.728e^(-01)*heridos abline(ecuacion3) summary(ecuacion3) plot(ecuacion3) ks.test(ecuacion3$residuals,"pnorm") #Al hacer esto nos sale el p-valor = 0.003772 lo cual es un p-valor bajo #menor que 0.05 entonces quiere decir que esta regresion no necesita de mas variables dwtest(total~nofatal) #En este caso, con un p-valor de 0.01178 no podemos rechazar la hipótesis de que los residuos son independientes. <file_sep>e1 = c(342,496,28) e2 = c(1373,2420,376) e3 = c(125,316,265) e4 = c(2288,5426,250) e5 = c(550,1053,43) e6 = c(1043,2065,38) e7 = c(1391,2796,29) e8 = c(1820,3026,202) e9 = c(175,303,2) e10 = c(697,1065,27) e11 = c(864,1916,116) e12 = c(1752,2755,238) e13 = c(2512,3116,202) e14 = c(2390,2297,160) e15 = c(1821,3099,91) e16 = c(455,565,11) e17 = c(72,252,8) e18 = c(150,678,10) e19 = c(165,426,8) e20 = c(2846,3144,71) e21 = c(681,1187,372) e22 = c(793,1302,46) e23 = c(554,877,96) e24 = c(245,190,7) e25 = c(828,915,4) departa = data.frame(e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12 ,e13,e14,e15,e16,e17,e18,e19,e20,e21,e22,e23,e24,e25) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Region","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(departa),main = "Accidents for departments 2011" ,ylab = "Accidents",cex.nombresx = 0.5,names.arg = nombresx ,col = rainbow(3) ,beside = TRUE,ylim = c(0,6000),las = 3) legend(x = 70,y = 5500,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep>#LIMA fatal = c(328,146,270,320,727,517) total = c(51375,53111,51216,55699,58079,58007) plot(total~fatal,main = "Grafica de accidentes en lima",ylab = "Total" ,xlab = "Muertes",type = "o",col = "blue") #lm servira para hallar los coeficientes de la ecuacion ecuacion = lm(total~fatal) ecuacion #sale intercept = 50055.01 , fatal = 11.77 #entonces la ecuacion es total=50055.01+11.77*fatal abline(ecuacion) summary(ecuacion) plot(ecuacion) ks.test(ecuacion$residuals,"pnorm") #Al hacer esto nos sale el p-valor = 0.06559 lo cual es un p-valor alto #menor que 0.1 entonces quiere decir que para un 10% de significacion los residuos no #siguen una distribucion normal pero para un 5% no podemos rechazar la hipotesis nula dwtest(total~fatal) #En este caso, con un p-valor de 0.06559 no podemos rechazar la hipótesis de que los residuos son independientes. <file_sep>cantidad = c(110341,121621,118809,123786,117048,116659) accidentes = data.frame(cantidad) nombresx = c("2011","2012","2013","2014","2015","2016") x <- barplot(as.matrix(accidentes),main = "Accidents for year" ,xlab = "Year",ylab = "Accidents" ,names.arg = nombresx,ylim = c(0,140000) ,col = rainbow(6),beside = TRUE,space = 0.2) <file_sep>q1 = c(271,549,120) q2 = c(1153,1983,576) q3 = c(209,343,663) q4 = c(1215,5100,1051) q5 = c(371,1569,50) q6 = c(1018,1658,17) q7 = c(947,2976,591) q8 = c(1452,3587,352) q9 = c(151,515,117) q10 = c(664,838,226) q11 = c(530,2002,63) q12 = c(1340,2019,45) q13 = c(1915,3876,831) q14 = c(1905,2450,45) q15 = c(1277,2799,375) q16 = c(301,514,10) q17 = c(186,506,16) q18 = c(91,647,14) q19 = c(141,322,15) q20 = c(1755,3549,27) q21 = c(524,1142,138) q22 = c(514,1729,11) q23 = c(303,702,84) q24 = c(149,146,178) q25 = c(149,788,118) depa = data.frame(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11,q12 ,q13,q14,q15,q16,q17,q18,q19,q20,q21,q22,q23,q24,q25) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Provincias","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(depa),main = "Accidents for departments 2015", ylab = "Accidents",names.arg = nombresx,col = rainbow(3) ,beside = TRUE,ylim = c(0,6000),las = 3) legend(x = 70,y = 6000,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep>b1 = c(363,592,21) b2 = c(1572,2456,333) b3 = c(240,379,405) b4 = c(2918,6336,174) b5 = c(553,1239,12) b6 = c(1356,2149,61) b7 = c(1547,3119,48) b8 = c(1420,3034,1109) b9 = c(107,344,196) b10 = c(943,897,213) b11 = c(1715,2589,311) b12 = c(1829,2408,983) b13 = c(2512,3793,922) b14 = c(2523,2736,227) b15 = c(1937,3184,74) b16 = c(295,547,63) b17 = c(148,414,11) b18 = c(218,413,156) b19 = c(153,419,69) b20 = c(2775,3984,214) b21 = c(969,1274,215) b22 = c(1009,1518,168) b23 = c(560,1281,110) b24 = c(331,281,10) b25 = c(953,891,38) departament = data.frame(b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12 ,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Provincias","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(departament),main = "Accidentes por departamento 2012",ylab = "Accidentes",names.arg = nombresx,col = rainbow(3) ,beside = TRUE,ylim = c(0,7000),las = 2) legend(x = 70,y = 7000,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep>q1 = c(264,472,55) q2 = c(1546,2042,727) q3 = c(228,1004,287) q4 = c(2893,5991,413) q5 = c(475,1142,246) q6 = c(804,1808,75) q7 = c(984,1783,91) q8 = c(1705,3245,1368) q9 = c(125,457,133) q10 = c(721,1053,51) q11 = c(1215,2841,325) q12 = c(1442,3150,463) q13 = c(2251,3950,930) q14 = c(1784,2499,262) q15 = c(1245,2679,179) q16 = c(177,332,38) q17 = c(76,350,104) q18 = c(284,792,52) q19 = c(186,438,33) q20 = c(3154,3530,303) q21 = c(533,1014,500) q22 = c(626,1404,180) q23 = c(642,775,417) q24 = c(427,339,52) q25 = c(519,923,140) depa = data.frame(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11,q12 ,q13,q14,q15,q16,q17,q18,q19,q20,q21,q22,q23,q24,q25) nombresx = c("Amazonas","Ancash","Apurimac","Arequipa", "Ayacucho","Cajamarca","Callao","Cusco","Huancavelica","Huanuco", "Ica","Junin","La Libertad","Lambayeque","Lima Provincias","Loreto","Madre de Dios", "Moquegua","Pasco","Piura","Puno","<NAME>","Tacna","Tumbes","Ucayali") x <- barplot(as.matrix(depa),main = "Accidents for departments 2013", ylab = "Accidents",names.arg = nombresx,col = rainbow(3) ,beside = TRUE,ylim = c(0,7000),las = 3) legend(x = 70,y = 7000,legend = c("publico","privado","no identificado"), cex=0.6 , fill=rainbow(3),text.font = 4) <file_sep>#LIMA cantidad = c(51356,53111,51216,55699,58079,58007) invasion = c(22597,24962,16082,21500,15275,11891) velocidad = c(23624,29901,21869,23895,14636,13864) semaforo = c(11144,9985,9629,10750,2207,1392) year = c(2011,2012,2013,2014,2015,2016) tabla = data.frame(cantidad,velocidad,invasion,semaforo,row.names = year) tabla ecuacion = lm(cantidad~velocidad+invasion+semaforo) ecuacion #cantidad = 57155.2074-0.2402*velocidad+0.4062*invasion-0.6738*semaforo summary(ecuacion) #Vamos a calcular el valor de correlacion cor(cantidad,velocidad) cor(tabla) cor.test(cantidad,velocidad) #El p-valor asociado a este contraste es de 0.1135 > 0.05, por lo que #no rechazamos la hip??tesis de que la correlaci??n lineal entre estas dos variables sea 0.
6f619dccffbb9df21fc8769b8ebce905c0ef4959
[ "Markdown", "R" ]
13
R
AnthonyLzq/Proyecto_Inferencia_Variacional_CM274
390b17075594c76d0b3b38a1aa98fda7acbf5dde
1766cee739dd2ae4bad715ba39aea1eacdbe867b
refs/heads/main
<repo_name>Ryan-Marchildon/architecture-sandbox<file_sep>/src/allocation/service_layer/handlers.py from typing import Optional from datetime import date from src.utils.logger import log from src.allocation.domain import model, events, commands from src.allocation.service_layer import unit_of_work from src.allocation.adapters import email, redis_eventpublisher class InvalidSku(Exception): pass def is_valid_sku(sku, batches): return sku in {batch.sku for batch in batches} def send_out_of_stock_notification( event: events.OutOfStock, uow: unit_of_work.AbstractUnitOfWork ): email.send( "<EMAIL>", f"Out of stock for {event.sku}", ) def add_batch( event: commands.CreateBatch, uow: unit_of_work.AbstractUnitOfWork, ): with uow: product = uow.products.get(sku=event.sku) if product is None: product = model.Product(event.sku, batches=[]) uow.products.add(product) product.batches.append(model.Batch(event.ref, event.sku, event.qty, event.eta)) uow.commit() def allocate(event: commands.Allocate, uow: unit_of_work.AbstractUnitOfWork) -> str: line = model.OrderLine(event.orderid, event.sku, event.qty) with uow: product = uow.products.get(sku=line.sku) if product is None: raise InvalidSku(f"Invalid sku {line.sku}") batchref = product.allocate(line) uow.commit() return batchref def deallocate(event: commands.Deallocate, uow: unit_of_work.AbstractUnitOfWork): line = model.OrderLine(event.orderid, event.sku, event.qty) with uow: product = uow.products.get(sku=line.sku) if product is None: raise InvalidSku(f"Invalid sku {line.sku}") for batch in product.batches: if line in batch._allocations: batch.deallocate(line) uow.commit() return batch.reference else: raise model.OrderNotFound( f"Could not find an allocation for line {line.orderid}" ) def change_batch_quantity( event: commands.ChangeBatchQuantity, uow: unit_of_work.AbstractUnitOfWork ): with uow: product = uow.products.get_by_batchref(batchref=event.ref) product.change_batch_quantity(ref=event.ref, qty=event.qty) uow.commit() def publish_allocation_event( event: events.Allocated, uow: unit_of_work.AbstractUnitOfWork, ): redis_eventpublisher.publish("line_allocated", event) <file_sep>/src/allocation/service_layer/messagebus.py from src.allocation.domain.model import OutOfStock from typing import Dict, Type, List, Callable, Union from tenacity import Retrying, RetryError, stop_after_attempt, wait_exponential from src.utils.logger import log from src.allocation.domain import commands, events from src.allocation.service_layer import handlers, unit_of_work Message = Union[commands.Command, events.Event] def handle(message: Message, uow: unit_of_work.AbstractUnitOfWork) -> list: results = [] queue = [message] while queue: message = queue.pop(0) if isinstance(message, events.Event): handle_event(message, queue, uow) elif isinstance(message, commands.Command): cmd_result = handle_command(message, queue, uow) results.append(cmd_result) else: raise Exception(f"{message} was not an Event or Command") return results def handle_event( event: events.Event, queue: List[Message], uow: unit_of_work.AbstractUnitOfWork ): for handler in EVENT_HANDLERS[type(event)]: try: for attempt in Retrying( stop=stop_after_attempt(3), wait=wait_exponential() ): with attempt: log.debug(f"handling event {event} with handler {handler}") handler(event, uow=uow) queue.extend(uow.collect_new_events()) except RetryError as retry_failure: log.error( "Failed to handle event %s times, giving up!", retry_failure.last_attempt.attempt_number, ) continue def handle_command( command: commands.Command, queue: List[Message], uow: unit_of_work.AbstractUnitOfWork, ): log.debug(f"handling command {command}") try: handler = COMMAND_HANDLERS[type(command)] result = handler(command, uow=uow) queue.extend(uow.collect_new_events()) return result except Exception: log.exception(f"Exception handling command {command}") raise EVENT_HANDLERS = { events.OutOfStock: [handlers.send_out_of_stock_notification], events.Allocated: [handlers.publish_allocation_event], } # type: Dict[Type[events.Event], List[Callable]] COMMAND_HANDLERS = { commands.Allocate: handlers.allocate, commands.Deallocate: handlers.deallocate, commands.CreateBatch: handlers.add_batch, commands.ChangeBatchQuantity: handlers.change_batch_quantity, } # type: Dict[Type[commands.Command], Callable] <file_sep>/src/allocation/entrypoints/redis_eventconsumer.py import json import redis from src.utils.logger import log from src.allocation import config from src.allocation.domain import commands from src.allocation.adapters import orm from src.allocation.service_layer import messagebus, unit_of_work r = redis.Redis(**config.get_redis_host_and_port()) def main(): orm.start_mappers() pubsub = r.pubsub(ignore_subscribe_messages=True) pubsub.subscribe("change_batch_quantity") for m in pubsub.listen(): handle_change_batch_quantity(m) def handle_change_batch_quantity(m): log.debug("handling %s", m) data = json.loads(m["data"]) cmd = commands.ChangeBatchQuantity(ref=data["batchref"], qty=data["qty"]) messagebus.handle(cmd, uow=unit_of_work.SqlAlchemyUnitOfWork()) if __name__ == "__main__": main() <file_sep>/tests/e2e/test_api.py from uuid import uuid4 import pytest from tests.random_refs import random_batchref, random_orderid, random_sku from tests.e2e import api_client # NOTE: usefixtures() lets us run a fixture even if we don't need # this fixture object within our test function @pytest.mark.usefixtures("restart_api") def test_happy_path_returns_201_and_allocated_batch(): sku, othersku = random_sku(), random_sku("other") earlybatch = random_batchref(1) laterbatch = random_batchref(2) otherbatch = random_batchref(3) api_client.post_to_add_batch(laterbatch, sku, 100, "2011-01-02") api_client.post_to_add_batch(earlybatch, sku, 100, "2011-01-01") api_client.post_to_add_batch(otherbatch, othersku, 100, None) r = api_client.post_to_allocate(random_orderid(), sku, 3, expect_success=True) assert r.status_code == 201 assert r.json()["batchref"] == earlybatch @pytest.mark.usefixtures("restart_api") def test_unhappy_path_returns_400_and_error_message(): unknown_sku, orderid = random_sku(), random_orderid() r = api_client.post_to_allocate(orderid, unknown_sku, 20, expect_success=False) assert r.status_code == 400 assert r.json()["message"] == f"Invalid sku {unknown_sku}" @pytest.mark.usefixtures("postgres_db") @pytest.mark.usefixtures("restart_api") def test_deallocate(): sku, order1, order2 = random_sku(), random_orderid(), random_orderid() batch = random_batchref() api_client.post_to_add_batch(batch, sku, 100, "2011-01-02") # fully allocate r = api_client.post_to_allocate(order1, sku, 100, expect_success=True) assert r.json()["batchref"] == batch # cannot allocate second order r = api_client.post_to_allocate(order2, sku, 100, expect_success=False) assert r.status_code == 201 assert r.json()["batchref"] == None # tells us it was not allocated # deallocate r = api_client.post_to_deallocate(order1, sku, 100, expect_success=True) assert r.ok # now we can allocate second order r = api_client.post_to_allocate(order2, sku, 100, expect_success=True) assert r.ok assert r.json()["batchref"] == batch<file_sep>/tests/conftest.py import time import shutil import subprocess import requests from requests.exceptions import ConnectionError import pytest import redis from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, clear_mappers from sqlalchemy.exc import OperationalError from src.allocation.adapters.orm import metadata, start_mappers from src.allocation import config @pytest.fixture def in_memory_db(): engine = create_engine("sqlite:///:memory:") metadata.create_all(engine) return engine @pytest.fixture def session_factory(in_memory_db): start_mappers() yield sessionmaker(bind=in_memory_db) clear_mappers() @pytest.fixture def session(session_factory): return session_factory() def wait_for_postgres_spinup(engine): deadline = time.time() + 10 while time.time() < deadline: try: return engine.connect() except OperationalError: time.sleep(0.5) pytest.fail("Postgres never spun up") @pytest.fixture(scope="session") def postgres_db(): engine = create_engine(config.get_postgres_uri()) wait_for_postgres_spinup(engine) metadata.create_all(engine) return engine @pytest.fixture def postgres_session_factory(postgres_db): start_mappers() yield sessionmaker(bind=postgres_db) clear_mappers() @pytest.fixture def postgres_session(postgres_session_factory): return postgres_session_factory() @pytest.fixture def add_stock(postgres_session): """ Adds batches to the postgres DB; for running e2e tests. """ # NOTE: we use 'yield' to specify teardown code without callbacks. # This is a feature of pytest fixtures, see: # https://docs.pytest.org/en/stable/fixture.html#teardown-cleanup-aka-fixture-finalization batches_added = set() skus_added = set() def _add_stock(lines): for ref, sku, qty, eta in lines: postgres_session.execute( "INSERT INTO batches (reference, sku, _purchased_quantity, eta)" " VALUES (:ref, :sku, :qty, :eta)", dict(ref=ref, sku=sku, qty=qty, eta=eta), ) [[batch_id]] = postgres_session.execute( "SELECT id FROM batches WHERE reference=:ref AND sku=:sku", dict(ref=ref, sku=sku), ) batches_added.add(batch_id) skus_added.add(sku) postgres_session.commit() yield _add_stock # NOTE: yields from fixtures produce only one value (will not iterate) # this teardown code runs after the test has finished (yield is 'finalized') for batch_id in batches_added: postgres_session.execute( "DELETE FROM allocations WHERE batch_id=:batch_id", dict(batch_id=batch_id), ) postgres_session.execute( "DELETE FROM batches WHERE id=:batch_id", dict(batch_id=batch_id), ) for sku in skus_added: postgres_session.execute( "DELETE FROM order_lines WHERE sku=:sku", dict(sku=sku), ) postgres_session.commit() def wait_for_webapp_spinup(): deadline = time.time() + 10 url = config.get_api_url() while time.time() < deadline: try: return requests.get(url) except ConnectionError: time.sleep(0.5) pytest.fail("API never spun up") @pytest.fixture def restart_api(): # TODO: add shell command to start flask wait_for_webapp_spinup() def wait_for_redis_spinup(): deadline = time.time() + 10 while time.time() < deadline: try: r = redis.Redis(**config.get_redis_host_and_port()) return r.ping() except OperationalError: time.sleep(0.5) pytest.fail("Redis never spun up") @pytest.fixture def restart_redis_pubsub(): wait_for_redis_spinup() if not shutil.which("docker-compose"): print("skipping restart, assumes running in container") return subprocess.run( ["docker-compose", "restart", "-t", "0", "redis_pubsub"], check=True, ) <file_sep>/src/allocation/domain/model.py """ Domain model for order allocation service. """ from typing import Optional, List, Set from datetime import date from dataclasses import dataclass from src.utils.logger import log from src.allocation.domain import events, commands # ----------------- # DOMAIN EXCEPTIONS # ----------------- class OrderNotFound(Exception): pass class OutOfStock(Exception): pass # -------------- # DOMAIN OBJECTS # -------------- @dataclass( unsafe_hash=True ) # must set unsafe_hash or this gets marked as unhashable type class OrderLine: """ Represents a line on a customer product order. """ orderid: str sku: str qty: int class Batch: """ Represents a batch of stock ordered by the purchasing department, en route from supplier to warehouse. """ # NOTE: with __eq__ and __hash__, we make explicit that Batch # is an entity (instances have persistant identities even if # their values change); in this case the identity is specified # by self.reference def __eq__(self, other): if not isinstance(other, Batch): return False return other.reference == self.reference def __hash__(self): return hash(self.reference) # NOTE: with __gt__ we get to override how sorted() acts on this object, # i.e. how it determines whether one instance is 'greater' than another; # here we sort on eta, with earlier eta coming first (None = already in stock) def __gt__(self, other): if self.eta is None: return False if other.eta is None: return True return self.eta > other.eta def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]): """ Parameters ---------- reference : str Unique identifying reference number for this batch. sku : str Stock keeping unit, identifing the product in this batch. eta : str Estimated time of arrival if shipment; None if already in-stock. """ self.reference = ref self.sku = sku self.eta = eta self._purchased_quantity = qty self._allocations = set() # type: Set[OrderLine] def allocate(self, line: OrderLine): """ Allocates part of a batch to the specified order line. """ if self.can_allocate(line): self._allocations.add(line) else: raise OutOfStock( "Cannot allocate to this batch: skus do not " "match or requested qty is less than available qty." ) def deallocate(self, line: OrderLine): if line in self._allocations: self._allocations.remove(line) else: raise OrderNotFound( f"Could not de-allocate order line; does not exist in this batch." ) def deallocate_one(self) -> OrderLine: return self._allocations.pop() @property def allocated_quantity(self) -> int: return sum(line.qty for line in self._allocations) @property def available_quantity(self) -> int: return self._purchased_quantity - self.allocated_quantity def can_allocate(self, line: OrderLine) -> bool: return self.sku == line.sku and self.available_quantity >= line.qty class Product: """ Our chosen aggregate for this domain service. This will be the single entrypoint into our domain model. """ def __init__(self, sku: str, batches: List[Batch], version_number: int = 0): self.sku = sku self.batches = batches self.version_number = version_number self.events = [] # type: List[events.Event] def allocate(self, line: OrderLine) -> str: """ This implements our earlier domain service for 'allocate'. """ try: batch = next(b for b in sorted(self.batches) if b.can_allocate(line)) batch.allocate(line) self.version_number += 1 self.events.append( events.Allocated( orderid=line.orderid, sku=line.sku, qty=line.qty, batchref=batch.reference, ) ) return batch.reference except StopIteration: self.events.append(events.OutOfStock(line.sku)) return None def change_batch_quantity(self, ref: str, qty: int): batch = next(b for b in self.batches if b.reference == ref) batch._purchased_quantity = qty while batch.available_quantity < 0: # de-allocate line orders from the existing batch # and try to assign them to another available batch line = batch.deallocate_one() self.events.append(commands.Allocate(line.orderid, line.sku, line.qty)) <file_sep>/setup.py import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="Architecture Patterns Sandbox", version="0.0.1", author="<NAME>", description=("A playground for python architecture patterns"), license="BSD", packages=["src", "tests"], long_description=read("README.md"), setup_requires=["black"], install_requires=read("requirements.txt"), )<file_sep>/Dockerfile FROM python:3.9.4-alpine3.13 # basic build dependencies RUN apk add --no-cache --virtual .build-deps gcc g++ postgresql-dev musl-dev python3-dev RUN apk add libpq # add an install our source code COPY src/ /src/ COPY tests/ /tests/ COPY setup.py /setup.py COPY requirements.txt /requirements.txt COPY README.md /README.md RUN python -m pip install --upgrade pip RUN pip install -e / # clean-up RUN apk del --no-cache .build-deps WORKDIR /src <file_sep>/src/allocation/adapters/redis_eventpublisher.py import json from dataclasses import asdict import redis from src.allocation import config from src.allocation.domain import events from src.utils.logger import log r = redis.Redis(**config.get_redis_host_and_port()) def publish(channel, event: events.Event): log.debug("publishing: channel=%s, event=%s", channel, event) r.publish(channel, json.dumps(asdict(event))) <file_sep>/README.md # architecture-sandbox This sandbox contains exercises and patterns from "Architecture Patterns with Python" by <NAME> and <NAME> (O'Reilly, 2020). Essentially, it represents my implementation of the web service they describe. <file_sep>/tests/unit/test_handlers.py from datetime import date import pytest from src.allocation.domain import model, events, commands from src.allocation.adapters.repository import FakeRepository from src.allocation.service_layer import handlers, messagebus from src.allocation.service_layer.unit_of_work import FakeUnitOfWork class TestAddBatch: @staticmethod def test_add_batch_for_new_product(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "DELICIOUS-ARMCHAIR", 100, None), uow ) assert uow.products.get("DELICIOUS-ARMCHAIR") is not None assert uow.committed @staticmethod def test_add_batch_for_existing_product(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "GARISH-RUG", 100, None), uow, ) messagebus.handle(commands.CreateBatch("b2", "GARISH-RUG", 99, None), uow) assert "b2" in [b.reference for b in uow.products.get("GARISH-RUG").batches] class TestAllocate: @staticmethod def test_allocate_returns_allocation(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "SHIFTY-LAMP", 100, None), uow, ) results = messagebus.handle( commands.Allocate("o1", "SHIFTY-LAMP", 10), uow, ) assert results.pop() == "b1" @staticmethod def test_allocate_errors_for_invalid_sku(): uow = FakeUnitOfWork() messagebus.handle(commands.CreateBatch("b1", "A-REAL-SKU", 100, None), uow) with pytest.raises(handlers.InvalidSku, match="Invalid sku NONEXISTENT-SKU"): messagebus.handle(commands.Allocate("o1", "NONEXISTENT-SKU", 10), uow) @staticmethod def test_allocate_commits(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "SHINY-MIRROR", 100, None), uow, ) messagebus.handle( commands.Allocate("o1", "SHINY-MIRROR", 10), uow, ) assert uow.committed is True class TestDeallocate: @staticmethod def test_deallocate_adjusts_available_quantity(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "BLUE-PLINTH", 100, None), uow, ) messagebus.handle( commands.Allocate("o1", "BLUE-PLINTH", 10), uow, ) batch = next( filter( lambda b: b.reference == "b1", uow.products.get("BLUE-PLINTH").batches ), None, ) assert batch.available_quantity == 90 messagebus.handle(commands.Deallocate("o1", "BLUE-PLINTH", 10), uow) assert batch.available_quantity == 100 @staticmethod def test_deallocate_results_in_correct_quantity(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("b1", "BLUE-PLINTH", 100, None), uow, ) messagebus.handle( commands.Allocate("o1", "BLUE-PLINTH", 10), uow, ) messagebus.handle( commands.Allocate("o2", "BLUE-PLINTH", 30), uow, ) batch = next( filter( lambda b: b.reference == "b1", uow.products.get("BLUE-PLINTH").batches ), None, ) assert batch.available_quantity == 60 messagebus.handle(commands.Deallocate("o2", "BLUE-PLINTH", 30), uow) assert batch.available_quantity == 90 @staticmethod def test_trying_to_deallocate_unallocated_batch(): uow = FakeUnitOfWork() messagebus.handle(commands.CreateBatch("b1", "BLUE-PLINTH", 100, None), uow) with pytest.raises(model.OrderNotFound): messagebus.handle(commands.Deallocate("o1", "BLUE-PLINTH", 10), uow) class TestChangeBatchQuantity: @staticmethod def test_changes_available_quantity(): uow = FakeUnitOfWork() messagebus.handle( commands.CreateBatch("batch1", "ADORABLE-STOOL", 100, None), uow ) [batch] = uow.products.get(sku="ADORABLE-STOOL").batches assert batch.available_quantity == 100 messagebus.handle(commands.ChangeBatchQuantity("batch1", 50), uow) assert batch.available_quantity == 50 @staticmethod def test_reallocates_if_necessary(): uow = FakeUnitOfWork() msg_history = [ commands.CreateBatch("batch1", "INDIFFERENT-TABLE", 50, None), commands.CreateBatch("batch2", "INDIFFERENT-TABLE", 50, date.today()), commands.Allocate("order1", "INDIFFERENT-TABLE", 20), commands.Allocate("order2", "INDIFFERENT-TABLE", 20), ] for msg in msg_history: messagebus.handle(msg, uow) [batch1, batch2] = uow.products.get(sku="INDIFFERENT-TABLE").batches assert batch1.available_quantity == 10 assert batch2.available_quantity == 50 messagebus.handle(commands.ChangeBatchQuantity("batch1", 25), uow) # order 1 or order 2 will be de-allocated, so we will have 25 - 20 assert batch1.available_quantity == 5 # and 20 will be re-allocated to the next batch assert batch2.available_quantity == 30 <file_sep>/src/allocation/adapters/repository.py import abc from typing import Set from src.allocation.domain import model from src.allocation.adapters import orm class AbstractProductRepository(abc.ABC): def __init__(self): self.seen = set() # type: Set[model.Product] def add(self, product: model.Product): self._add(product) self.seen.add(product) # note this is Set.add() def get(self, sku) -> model.Product: product = self._get(sku) if product: self.seen.add(product) return product def get_by_batchref(self, batchref) -> model.Product: product = self._get_by_batchref(batchref) if product: self.seen.add(product) return product @abc.abstractmethod def _add(self, product: model.Product): raise NotImplementedError @abc.abstractmethod def _get(self, sku) -> model.Product: raise NotImplementedError @abc.abstractmethod def _get_by_batchref(self, batchref) -> model.Product: raise NotImplementedError @abc.abstractmethod def list(self): raise NotImplementedError class SqlAlchemyRepository(AbstractProductRepository): def __init__(self, session): super().__init__() self.session = session def _add(self, product: model.Product): self.session.add(product) def _get(self, sku: str): return self.session.query(model.Product).filter_by(sku=sku).first() def _get_by_batchref(self, batchref): return ( self.session.query(model.Product) .join(model.Batch) .filter(orm.batches.c.reference == batchref) ).first() def list(self): return self.session.query(model.Product).all() # for mocks during tests class FakeRepository(AbstractProductRepository): def __init__(self, products): super().__init__() self._products = set(products) def _add(self, product): self._products.add(product) def _get(self, sku: str): return next((p for p in self._products if p.sku == sku), None) def _get_by_batchref(self, batchref): return next( (p for p in self._products for b in p.batches if b.reference == batchref), None, ) def list(self): return list(self._products) # fixtures for keeping all of our tests' domain-model dependencies, # so we can keep those dependencies decoupled from our test definitions @staticmethod def for_product(sku, batches, version_number): return FakeRepository([model.Product(sku, batches, version_number)]) <file_sep>/src/allocation/entrypoints/flask_app.py from datetime import datetime from flask import Flask, jsonify, request from src.allocation.domain import commands from src.allocation.adapters import orm from src.allocation.service_layer import handlers, messagebus, unit_of_work orm.start_mappers() app = Flask(__name__) @app.route("/allocate", methods=["POST"]) def allocate_endpoint(): uow = unit_of_work.SqlAlchemyUnitOfWork() try: cmd = commands.Allocate( request.json["orderid"], request.json["sku"], request.json["qty"] ) results = messagebus.handle(cmd, uow) batchref = results.pop(0) except handlers.InvalidSku as e: return jsonify({"message": str(e)}), 400 return jsonify({"batchref": batchref}), 201 @app.route("/deallocate", methods=["POST"]) def deallocate_endpoint(): uow = unit_of_work.SqlAlchemyUnitOfWork() try: cmd = commands.Deallocate( request.json["orderid"], request.json["sku"], request.json["qty"] ) results = messagebus.handle(cmd, uow) batchref = results.pop(0) except handlers.InvalidSku as e: return jsonify({"message": str(e)}), 400 return jsonify({"batchref": batchref}), 201 @app.route("/add_batch", methods=["POST"]) def add_batch(): uow = unit_of_work.SqlAlchemyUnitOfWork() eta = request.json["eta"] if eta is not None: eta = datetime.fromisoformat(eta).date() cmd = commands.CreateBatch( request.json["ref"], request.json["sku"], request.json["qty"], eta ) messagebus.handle(cmd, uow) return "OK", 201 if __name__ == "__main__": app.run(debug=True, port=80)<file_sep>/requirements.txt appdirs==1.4.4 astroid==2.5.2 attrs==20.3.0 black==20.8b1 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 Flask==1.1.2 greenlet==1.0.0 idna==2.10 iniconfig==1.1.1 isort==5.8.0 itsdangerous==1.1.0 Jinja2==2.11.3 lazy-object-proxy==1.6.0 MarkupSafe==1.1.1 mccabe==0.6.1 packaging==20.9 pathspec==0.8.1 pluggy==0.13.1 psycopg2-binary==2.8.6 py==1.10.0 pylint==2.7.2 pyparsing==2.4.7 pytest==6.2.2 redis regex==2021.3.17 requests==2.25.1 SQLAlchemy==1.4.3 tenacity==7.0.0 urllib3==1.26.4 Werkzeug==1.0.1 wrapt==1.12.1
7dc50f590027042b4c013aadd954fd1ebcb390c8
[ "Markdown", "Python", "Text", "Dockerfile" ]
14
Python
Ryan-Marchildon/architecture-sandbox
a039c088ea295a55135e81445f7ac743ed8dbd11
0ea06e7e56bc9e4b631ca6edf2c6812aa8fc9687
refs/heads/master
<repo_name>tmpandolphi/SistemaAeroporto<file_sep>/SistemaAeroporto.c #include <stdio.h> #include <stdlib.h> #include <string.h> /*----------- STRUCTS -----------*/ typedef struct aviao { int id; struct aviao *prox; } Aviao; typedef struct header { Aviao *hLdisp; Aviao *hFdec; Aviao *hFate; Aviao *hLNoAr; } Header; /*----------- FUNCTIONS -----------*/ void menu(){ printf("\n"); printf("Entre a opcao desejada: \n\n"); printf(" 1. Inserir aviao em LDISP; \n"); printf(" 2. Inserir aviao em LNoAR; \n"); printf(" 3. Autorizar decolagem; \n"); printf(" 4. Autorizar aterrissagem; \n"); printf(" 5. Aterrissar; \n"); printf(" 6. Decolar; \n"); printf(" 7. Proximas aterrisagens; \n"); printf(" 8. Proximas decolagens; \n"); printf(" 9. Avioes no terminal; \n"); printf(" 10. Avioes no ar; \n"); printf(" 11. Imprimir relatorio; \n"); printf(" 12. Remover aviao de LDISP; \n"); printf(" 13. Remover aviao de LNoAr; \n"); printf(" 0. Sair; \n"); } Aviao *insereFila(Aviao **p, int i){ Aviao *n = (Aviao *) malloc(sizeof(Aviao)); n->id = i; n->prox = NULL; if( *p == NULL ){ n->prox = *p; *p = n; return *p; } else { Aviao *h = *p; while( h != NULL && (h)->prox != NULL){ h = h->prox; } h->prox = n; } return *p; } Aviao *removerFila(Aviao **p){ if(*p == NULL){ return NULL; } Aviao* aux = *p; *p = (*p)->prox; free(aux); return *p; } int qualAterrissar(Aviao **p){ Aviao* aux = (Aviao*) malloc(sizeof(Aviao)); int i; if(*p == NULL){ return 0; } aux=*p; i = (int) aux->id; return i; } int qualDecolar(Aviao **p){ Aviao* aux = (Aviao*) malloc(sizeof(Aviao)); int i; if(*p == NULL){ return 0; } aux=*p; i = (int) aux->id; return i; } Aviao *removerPosLista(Aviao **p, int i){ Aviao *h = *p; Aviao *a = *p; if(h->id == i){ *p = h->prox; return *p; } while((h)->prox != NULL){ if(h->id == i){ a->prox = h->prox; return *p; } a = h; h = h->prox; } if((h)->prox == NULL && (h)->id == i){ a->prox = NULL; return *p; } else if((h)->id == i) { a->prox = h->prox; return *p; } return *p; } Aviao *insereLista(Aviao **p, int i){ Aviao *n = (Aviao*)malloc(sizeof(Aviao)); n->id = i; n->prox = NULL; if( *p == NULL ){ n->prox = *p; *p = n; printf("%d",i); return *p; } if( i < (*p)->id){ n->prox = *p; *p = n; } Aviao *h = *p; while(h->prox != NULL && h->prox->id < i){ h = h->prox; } if(h->prox == NULL){ h->prox = n; printf("%d",i); return *p; } else { n->prox = h->prox; h->prox = n; } printf("%d",i); return *p; } Aviao *adicionarInicioFila(Aviao **p, int i){ Aviao *n = (Aviao *) malloc(sizeof(Aviao)); n->id = i; n->prox = NULL; if( *p == NULL ){ n->prox = *p; *p = n; return *p; } else { n->prox = *p; *p = n; return *p; } return NULL; } void *imprimirListaOuFila(Aviao **p){ Aviao *h = *p; if(*p == NULL){ //testa se a lista é nula printf("Nao existem avioes para imprimir.\n"); //caso positivo imprime isso e volta para o menu }else{ //caso negativo executa o codigo abaixo. while((h)->prox != NULL){ printf("%d\n", h->id); h = h->prox; } printf("%d\n", h->id); } } void insereRelatorio(char vetor[100][80], int i, int pos, char action[80]){ char texto[80]; char num[3]; strcpy(texto, "Aviao codigo "); sprintf(num, "%d", i); strcat(texto, num); strcat(texto, action); strcpy(vetor[pos], texto); } void escreveRelatorio(char vetor[100][80], int pos){ int i = 0; for(i = 0; i < pos; i++){ printf("%s\n", vetor[i]); } } /*----------- MAIN -----------*/ int main(){ Aviao *LDISP = NULL; Aviao *LNOAR = NULL; Aviao *FDEC = NULL; Aviao *FATE = NULL; char relatorio[100][80]; Header EDAero; EDAero.hFate = FATE; EDAero.hFdec = FDEC; EDAero.hLdisp = LDISP; EDAero.hLNoAr = LNOAR; int opcao, i, p, pos; //Inicializa LDISP e LNOAR for(i = 1 ; i <= 15; i++ ){ insereLista(&LDISP, i); i++; insereLista(&LNOAR, i); } system("cls"); menu(); scanf("%d",&opcao); while (opcao != 0){ switch (opcao) { case 1://OK printf("Entre o numero do aviao que deseja inserir na lista: \n"); scanf(" %d",&i); insereLista(&LDISP, i); system("cls"); printf("Inserido LDISP.\n"); insereRelatorio(relatorio, i, pos, " inserido em LDISP."); pos++; break; case 2://OK printf("Entre o numero do aviao que deseja inserir na lista: \n"); scanf(" %d",&i); insereLista(&LNOAR, i); system("cls"); printf("Inserido LNOAR.\n"); insereRelatorio(relatorio, i, pos, " inserido em LNOAR."); pos++; break; case 3://OK printf("Entre o numero do aviao que deseja autorizar a decolar: \n"); scanf(" %d",&i); printf("Entre a prioridade; 1 - urgente, 0 - normal. \n"); scanf(" %d",&p); if(p == 1){ removerPosLista(&LDISP, i); adicionarInicioFila(&FDEC, i); system("cls"); printf("Aviao %d autorizado a decolar com prioridade. \n", i); insereRelatorio(relatorio, i, pos, " autorizado a decolar com prioridade (LDISP-FDEC)."); pos++; } else { removerPosLista(&LDISP, i); insereFila(&FDEC, i); system("cls"); printf("Aviao %d autorizado a decolar. \n", i); insereRelatorio(relatorio, i, pos, " autorizado a decolar (LDISP-FDEC)."); pos++; } break; case 4://OK printf("Entre o numero do aviao que deseja autorizar a aterrissar: \n"); scanf(" %d",&i); printf("Entre a prioridade; 1 - urgente, 0 - normal. \n"); scanf(" %d",&p); if(p == 1){ removerPosLista(&LNOAR, i); adicionarInicioFila(&FATE, i); system("cls"); printf("Aviao %d autorizado a aterissar com prioridade. \n", i); insereRelatorio(relatorio, i, pos, " autorizado a aterrissar com prioridade (LNOAR-FATE)."); pos++; } else { removerPosLista(&LNOAR, i); insereFila(&FATE, i); system("cls"); printf("Aviao %d autorizado a aterissar. \n", i); insereRelatorio(relatorio, i, pos, " autorizado a aterrissar (LNOAR-FATE)."); pos++; } break; case 5://OK printf("Aterrisar: \n"); i = qualAterrissar(&FATE); removerFila(&FATE); if(i > 0){ insereLista(&LDISP, i); system("cls"); printf("O aviao %d aterrisou. \n", i); insereRelatorio(relatorio, i, pos, " aterrisou (FATE-LDISP)"); pos++; } else { printf("Sem avioes na fila de aterrisagem.\n"); } break; case 6://OK printf("Decolar: \n"); i = qualDecolar(&FDEC); removerFila(&FDEC); if(i > 0){ insereLista(&LNOAR, i); system("cls"); printf("O aviao %d decolou. \n", i); insereRelatorio(relatorio, i, pos, " decolou (FDEC-LNOAR)"); pos++; } else { printf("Sem avioes na fila de decolagem.\n"); } break; case 7: system("cls"); printf("As proximas aterrissagens sao: \n"); imprimirListaOuFila(&FATE); break; case 8: //OK system("cls"); printf("Os avioes decolagens sao: \n"); imprimirListaOuFila(&FDEC); break; case 9: //OK system("cls"); printf("Os avioes no terminal sao: \n"); imprimirListaOuFila(&LDISP); break; case 10://OK system("cls"); printf("Os avioes no ar sao: \n"); imprimirListaOuFila(&LNOAR); break; case 11: system("cls"); printf("\nRelatorio: \n"); escreveRelatorio(relatorio, pos); break; case 12://OK printf("Entre o numero do aviao que deseja remover de LDISP: \n"); scanf(" %d",&i); removerPosLista(&LDISP, i); system("cls"); printf("Removido aviao de LDISP: \n"); insereRelatorio(relatorio, i, pos, " removido de LDISP."); pos++; break; case 13://OK printf("Entre o numero do aviao que deseja remover de LNOAR: \n"); scanf(" %d",&i); removerPosLista(&LNOAR, i); system("cls"); printf("Removido aviao de LNoAr: \n"); insereRelatorio(relatorio, i, pos, " removido de LNOAR."); pos++; break; } menu(); scanf("%d",&opcao); } return 0; }
6389e751d9b6304fa1841eddb44f01b5274538ff
[ "C" ]
1
C
tmpandolphi/SistemaAeroporto
c17e078a449a3a20d86ef9b6af446336ec85c924
948813caa6359411c9bf995d9360887ff3fab77b
refs/heads/master
<repo_name>marcusschonning/react-redux-webpack<file_sep>/app/containers/readme.md Logic for specific components Put all lifecycle functions here <file_sep>/README.md # React Redux boilerplate Boilerplate with redux, react and webpack ### Commands (`sudo `)`npm install` to get dependencies.<br> `webpack` to build development.<br> `webpack -w` to watch for changes and build develop.<br> `webpack -p` to build production ### Example container ```javascript import React from 'react'; import { connect } from 'react-redux'; import { actionFunctionName } from '../actions'; import ComponentName from '../components/ComponentName'; const ComponentContainer = () => { const mapStateToProps = (state) => { return { state: state } } const mapDispatchToProps = (dispatch) => { return { onItemClick: (id) => { dispatch(actionName(id)); }, fetchAll(): () => { dispatch(anotherAction()); } } } class ComponentFetcher extends React.Component { constructor(props) { super(props); } componentWillMount () { this.props.fetchAll(); } render() { return <ComponentName {...this.props} />; } } const ComponentContainer = connect( mapStateToProps, mapDispatchToProps )(ComponentFetcher) //Put whichever element you want the props. export default ComponentContainer ``` <file_sep>/app/actions/index.js import fetch from 'isomorphic-fetch' //Export actions to dispatch reducer //Asyncron dispatch (else just return an object to dispatch): /* export const getAllTodos = (dispatch) => { return (dispatch) => { fetch('./../app/api/getAll.php').then(function(res) { return res.json(); }).then(function(todolist) { dispatch({ type: 'REDUCER_TYPE', value }); }); } } */
873142ac0f51b8ea278ab405c47d7e91d62fe54a
[ "Markdown", "JavaScript" ]
3
Markdown
marcusschonning/react-redux-webpack
999167e43cd9c9d5d3bf6e3edaf059468d732183
d441e749a96624394bfc580ad8e5d4e7f4e530df
refs/heads/master
<repo_name>Andrew-Feely/TicTacToe<file_sep>/TicTacToe/Form1.cs 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 TicTacToe { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Game game = null; private void btnStart_Click(object sender, EventArgs e) { game = new Game(pnlBoard, txtMessageArea); game.ShowWinner += Game_ShowWinner; game.Start(); } private void Game_ShowWinner(Player winner) { MessageBox.Show(winner.PlayerName + " won as " + winner.Mark); } } } <file_sep>/TicTacToe/Game.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TicTacToe { class Game { public Player CurrentPlayer { get; set; } public bool Winner { get; set; } public TextBox[,] GameBoard { get; set; } public Panel GamePanel { get; set; } public List<Player> GamePlayers { get; set; } public int NumberClicks { get; set; } public TextBox MessageArea { get; set; } //default constructor public Game() { } //overloaded constructor public Game(Panel theePanel, TextBox messageArea) { GamePanel = theePanel; GameBoard = new TextBox[3, 3]; MessageArea = messageArea; Winner = false; NumberClicks = 0; GamePlayers = new List<Player>(3); //Create some players //todo: create method GamePlayers.Add(new Player("Cat")); GamePlayers.Add(new Player("Player 1")); GamePlayers.Add(new Player("Player 2")); //players mark GamePlayers[0].Mark = "Paw"; GamePlayers[1].Mark = "X"; GamePlayers[2].Mark = "O"; //current player //todo: make random CurrentPlayer = GamePlayers[1]; //Test msg Area MessageArea.Text = CurrentPlayer.PlayerName + " Plays first"; } public delegate void EndGame(Player winner); public event EndGame ShowWinner; public void Start() { MessageArea.Clear(); Winner = false; NumberClicks = 0; GamePanel.Controls.Clear(); //draw board DrawBoard(); } private void DrawBoard() { int top = 0; int left = 0; for(int row= 0; row <= GameBoard.GetUpperBound(0); row++) { left = 0; for(int col = 0; col <= GameBoard.GetUpperBound(1); col++) { TextBox textBox = new TextBox(); textBox.Multiline = true; textBox.ReadOnly = true; textBox.Font = new System.Drawing.Font("Courier New", 60); textBox.TextAlign = HorizontalAlignment.Center; textBox.Size = new System.Drawing.Size(100, 100); //todo: change to none textBox.BorderStyle = BorderStyle.FixedSingle; textBox.Location = new System.Drawing.Point(left, top); GameBoard[row, col] = textBox; //add txtbox to textBox.Click += TextBox_Click; GamePanel.Controls.Add(textBox); left += 100; } top += 100; } } private void TextBox_Click(object sender, EventArgs e) { //Current player mark TextBox clickedBox = (TextBox)sender; if (clickedBox.Text == "") { MessageArea.Clear(); //clears errors out of msg area NumberClicks++; clickedBox.Text = CurrentPlayer.Mark; //check for winner Winner = CheckForWin(); if (NumberClicks <9 && !Winner) { //switch player NextPlayer(); } else { if(Winner) { MessageArea.Text = CurrentPlayer.PlayerName + " has Won!";//todo: add the number of games won when program can keep track ShowWinner(CurrentPlayer); } else { MessageArea.Text = GamePlayers[0].PlayerName + " has won"; ShowWinner(GamePlayers[0]); } } } else { MessageArea.Text = "Cant click there, illegal move."; } } private bool CheckForWin() { return CheckRows() || CheckColumns() || CheckDiagonal(); } private bool CheckRows() { int rowMarks = 0; for(int row = 0; row <= GameBoard.GetUpperBound(0); row++) { for(int col = 0; col <= GameBoard.GetUpperBound(1); col++) { if(GameBoard[row,col].Text == CurrentPlayer.Mark) { rowMarks++; } } if(rowMarks >= 3) { return true; } else { rowMarks = 0; } } return false; } private bool CheckColumns() { int columnMarks = 0; for (int col = 0; col <= GameBoard.GetUpperBound(1); col++) { for (int row = 0; row <= GameBoard.GetUpperBound(0); row++) { if (GameBoard[row, col].Text == CurrentPlayer.Mark) { columnMarks++; } } if (columnMarks >= 3) { return true; } else { columnMarks = 0; } } return false; } private bool CheckDiagonal() { if (GameBoard[0, 0].Text == CurrentPlayer.Mark && GameBoard[1, 1].Text == CurrentPlayer.Mark && GameBoard[2, 2].Text == CurrentPlayer.Mark) { return true; } else if(GameBoard[2,0].Text == CurrentPlayer.Mark && GameBoard[1, 1].Text == CurrentPlayer.Mark && GameBoard[0,2].Text == CurrentPlayer.Mark) { return true; } else { return false; } } private void NextPlayer() { //brute force bby if(CurrentPlayer.Mark == GamePlayers[1].Mark) { CurrentPlayer = GamePlayers[2]; } else { CurrentPlayer = GamePlayers[1]; } } } } <file_sep>/TicTacToe/Player.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TicTacToe { class Player { public string PlayerName { get; set; } public string Mark { get; set; } public int GamesPlayed { get; set; } public int GamesWon { get; set; } public Player() { } public Player(string theName) { PlayerName = theName; } } }
45b1cceba0ae205392f46b7324e2bd6e0c03cb41
[ "C#" ]
3
C#
Andrew-Feely/TicTacToe
e6d4f77d8bdb53b8f18629ae7bf2d2a35b8e15b3
94305ebc79f2cd51def8d98524f51a64a7eb9514
refs/heads/master
<file_sep>package br.com.livraria.dao; import javax.persistence.NoResultException; import br.com.livraria.models.Editora; /** * * Interface responsável por definir os metodos que acessam informações do banco de dados * * @author Elton * @since 05/02/2016 - 12:21:26 * @version 1.0 */ public interface EditoraDAO extends DAO<Editora, Integer>{ /** * * Método que realiza a busca do objeto informando sua descrição * * @author Elton * @since 06/02/2016 * @version 1.0 * @param descricao Nome da editora * @return O proprio objeto */ public Editora findBy(String descricao) throws NoResultException; } <file_sep>package br.com.livraria.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.support.PagedListHolder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.livraria.bo.ClienteBO; import br.com.livraria.exceptions.BOException; import br.com.livraria.models.Cliente; @Controller @RequestMapping("/cliente") public class ClienteController { private static final Logger logger = Logger.getLogger(ClienteController.class); @Autowired private ClienteBO clienteBO; @RequestMapping(path = "/cadastro", method=RequestMethod.GET) public ModelAndView form(HttpServletRequest request, Cliente cliente, RedirectAttributes redirect){ ModelAndView modelAndView = new ModelAndView("/cadastro/cliente"); int page = ServletRequestUtils.getIntParameter(request, "p", 0); List<Cliente> clientes = clienteBO.list(); PagedListHolder<Cliente> pagedListHolder = new PagedListHolder<Cliente>(clientes); pagedListHolder.setPage(page); pagedListHolder.setPageSize(5); modelAndView.addObject("pagedListHolder", pagedListHolder); return modelAndView; } @RequestMapping(path = "/cadastro", method=RequestMethod.POST) public ModelAndView salvar(HttpServletRequest request, @Valid Cliente cliente, BindingResult bindingResult, RedirectAttributes redirect){ try { if (bindingResult.hasErrors()){ return new ModelAndView("/cadastro/cliente","cliente", cliente); } clienteBO.insert(cliente); redirect.addFlashAttribute("mensagem", "Cliente incluido com sucesso"); } catch (BOException e) { redirect.addFlashAttribute("mensagem", e.getMessage()); redirect.addFlashAttribute("cliente", cliente); } catch (Exception e){ redirect.addFlashAttribute("mensagem", "Ocorreu um erro desconhecido, favor tentar novamente!" + e.getMessage()); redirect.addFlashAttribute("cliente", cliente); logger.error("Ocorreu um erro desconhecido", e); } return new ModelAndView("redirect:cadastro"); } } <file_sep>package br.com.livraria.dao.impl; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import br.com.livraria.dao.DAO; import br.com.livraria.exceptions.DBException; import br.com.livraria.exceptions.IdNotFoundException; /** * * Classe responsavel por realizar a implementacao do DAO Generico para as operacoes de CRUD basica. * * @author Elton * @version 1.0 */ public abstract class DAOImpl<T, K> implements DAO<T, K> { @PersistenceContext private EntityManager em; private Class<T> classe; @SuppressWarnings("unchecked") public DAOImpl() { classe = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; } public void insert(T entity) throws DBException { try { em.persist(entity); } catch (Exception e) { throw new DBException("Erro ao persistir " + e.getMessage()); } } public void update(T entity) throws DBException { try{ em.merge(entity); }catch(Exception e){ throw new DBException("Erro ao atualizar"); } } public void delete(K id) throws DBException, IdNotFoundException { T entity = searchByID(id); if (entity == null) throw new IdNotFoundException(); try{ em.remove(entity); }catch(Exception e){ throw new DBException("Erro ao Remover"); } } public T searchByID(K id) { return em.find(classe, id); } @SuppressWarnings("unchecked") public List<T> getAll() { return em.createQuery( "from " + classe.getName()).getResultList(); } } <file_sep>package br.com.livraria.dao.impl; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.com.livraria.dao.GeneroDAO; import br.com.livraria.models.Genero; /** * * Classe responsável por implementar os metodos definidos na interface de acesso ao banco * * @author Elton * @since 05/02/2016 - 12:23:31 * @version 1.0 */ @Repository public class GeneroDAOImpl extends DAOImpl<Genero, Integer> implements GeneroDAO{ @PersistenceContext private EntityManager em; @Override public Genero findBy(String descricao) throws NoResultException{ String jpql = "select g from Genero g where g.descricao = :descricao"; TypedQuery<Genero> query = em.createQuery(jpql, Genero.class); query.setParameter("descricao", descricao); return query.getSingleResult(); } } <file_sep>package br.com.livraria.bo; import java.util.List; import javax.persistence.NoResultException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.livraria.dao.EditoraDAO; import br.com.livraria.exceptions.BOException; import br.com.livraria.exceptions.DBException; import br.com.livraria.models.Editora; /** * * Classe que possui as regras de negocio da entidade * * @author Elton * @since 05/02/2016 - 12:29:20 * @version 1.0 */ @Service public class EditoraBO { @Autowired private EditoraDAO editoraDAO; @Transactional(rollbackFor = { DBException.class }) public void insert(Editora editora) throws BOException { try { editoraDAO.findBy(editora.getDescricao()); throw new BOException("A editora informada já existe!"); } catch (NoResultException e) { try { editoraDAO.insert(editora); } catch (DBException e1) { throw new BOException("Erro ao inserir uma nova editora!"); } } } @Transactional(readOnly = true) public List<Editora> list(){ return editoraDAO.getAll(); } } <file_sep>package br.com.livraria.dao.impl; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.com.livraria.dao.IdiomaDAO; import br.com.livraria.models.Idioma; /** * * Classe responsável por implementar os metodos definidos na interface de acesso ao banco * * @author Elton * @since 05/02/2016 - 12:23:36 * @version 1.0 */ @Repository public class IdiomaDAOImpl extends DAOImpl<Idioma, Integer> implements IdiomaDAO{ @PersistenceContext private EntityManager em; @Override public Idioma findBy(String descricao) throws NoResultException{ String jpql = "select i from Idioma i where i.descricao = :descricao"; TypedQuery<Idioma> query = em.createQuery(jpql, Idioma.class); query.setParameter("descricao", descricao); return query.getSingleResult(); } } <file_sep>package br.com.livraria.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; import org.springframework.security.core.GrantedAuthority; /** * * Classe responsável por armazenar as informações das Roles dos usuários * * @author Elton * @since 05/02/2016 - 12:19:49 * @version 1.0 */ @Entity @Table(name="TB_ROLE") public class Role implements GrantedAuthority{ private static final long serialVersionUID = 6413949595200735160L; @Id @Size(max=100, message="Nome da role muito grande") @Column(name="ID_ROLE", length=100) private String name; public Role() { } public Role(String name){ this.name = name; } @Override public String getAuthority() { return name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Role other = (Role) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } <file_sep>package br.com.livraria.conf; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * * Classe responsável por configurar o filtro de segurança do Spring Security * * @author Elton * @since 05/02/2016 - 12:26:16 * @version 1.0 */ public class SpringSecurityFilterConfiguration extends AbstractSecurityWebApplicationInitializer{ } <file_sep>package br.com.livraria.dao.impl; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.com.livraria.dao.AutorDAO; import br.com.livraria.models.Autor; /** * * Classe responsável por implementar os metodos definidos na interface de acesso ao banco * * @author Elton * @since 05/02/2016 - 12:23:02 * @version 1.0 */ @Repository public class AutorDAOImpl extends DAOImpl<Autor, Integer> implements AutorDAO{ @PersistenceContext private EntityManager em; @Override public Autor findBy(String descricao) throws NoResultException{ String jpql = "select a from Autor a where a.descricao = :descricao"; TypedQuery<Autor> query = em.createQuery(jpql, Autor.class); query.setParameter("descricao", descricao); return query.getSingleResult(); } } <file_sep>package br.com.livraria.dao.impl; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.com.livraria.dao.ClienteDAO; import br.com.livraria.models.Cliente; /** * * Classe responsável por implementar os metodos definidos na interface de acesso ao banco * * @author Elton * @since 05/02/2016 - 12:23:07 * @version 1.0 */ @Repository public class ClienteDAOImpl extends DAOImpl<Cliente, Integer> implements ClienteDAO{ @PersistenceContext private EntityManager em; @Override public Cliente findBy(String cpf) { String jpql = "select c from Cliente c where c.cpf = :cpf"; TypedQuery<Cliente> query = em.createQuery(jpql, Cliente.class); query.setParameter("cpf", cpf); return query.getSingleResult(); } } <file_sep>package br.com.livraria.dao; import javax.persistence.NoResultException; import org.springframework.stereotype.Service; import br.com.livraria.models.Livro; /** * * Interface responsável por definir os metodos que acessam informações do banco de dados * * @author Elton * @since 05/02/2016 - 12:21:47 * @version 1.0 */ @Service public interface LivroDAO extends DAO<Livro, Integer>{ /** * * Realiza a busca de um livro pelo seu ISBN * * @author Elton * @since 22/02/2016 * @version 1.0 * @param isbn ISBN do livro a ser procurado * @return O proprio objeto * @throws NoResultException Caso o livro não exista essa exceção é lancada */ public Livro findBy(Integer isbn) throws NoResultException; } <file_sep># Sistema de Controle de Estoque e Venda de Livraria Projeto criado para aprendizado do Framework Spring MVC, Spring Security, Testes e posteriormente Spring Data. O sistema consiste em um Controle de Estoque e Venda de uma Livraria. Possuindo controle de usuário, controle de produtos no estoque, controle da venda. Será implementado tambem relatórios de venda e exibição de gráficos e diagramas na home dos usuários. (dashboard) O projeto está hospedado em um servidor de aplicação Tomcat que está em uma micro instância Linux da Amazon juntamente do banco de dados MySQL, e tambem existe outra micro instância Windows na Amazon que está com o Jenkins configurado, realizando o monitoramento do meu github para a cada commit que eu realize no repositório o mesmo faça o build do projeto utilizando o Maven e realize o deploy automaticamente no Tomcat, fazendo o trabalho de Integração Continua do meu projeto. Segue abaixo as documentações referentes ao projeto: - Case (Simples, será aprimorado): https://docs.google.com/document/d/1yptWrq3klzFwBSMtfGoi5Qzo3XoqHukJ_IOT05HlTgs/edit?usp=sharing - UseCase: https://drive.google.com/file/d/0B_49BGpReZr_YTZYSmdDb2kwaDQ/view?usp=sharing - Modelo Relacional Banco: https://drive.google.com/file/d/0B_49BGpReZr_Nk9xNGZla1h2Qlk/view?usp=sharing - Tela Login (será aprimorada): https://drive.google.com/file/d/0B_49BGpReZr_ZDI0emdPT05fZjQ/view?usp=sharing - Tela de Cadastro de livro: https://drive.google.com/file/d/0B_49BGpReZr_azFCc3VfWldsVzg/view?usp=sharing Frameworks/Ferramentas: Eclipse IDE, Spring MVC 4.2.3, Spring Security 4.0.3, JPA(Hibernate), MySQL DB, Materialize como framework CSS, Git. <file_sep>package br.com.livraria.dao; import org.springframework.security.core.userdetails.UserDetailsService; import br.com.livraria.models.Usuario; /** * * Interface responsável por definir os metodos que acessam informações do banco de dados * * @author Elton * @since 05/02/2016 - 12:21:52 * @version 1.0 */ public interface UsuarioDAO extends DAO<Usuario, String>, UserDetailsService{ /** * * Método realiza a busca de um usuário por seu login * * @author Elton * @since 08/02/2016 * @version 1.0 * @param login o email do usuário * @return O próprio objeto */ public Usuario findBy(String login); } <file_sep>package br.com.livraria.controllers; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(HomeController.class); @RequestMapping("/") public String toHome(){ return home(); } @RequestMapping("/home") public String home(){ return "dashboard/home"; } } <file_sep>package br.com.livraria.dao; import javax.persistence.NoResultException; import br.com.livraria.models.Cliente; /** * * Interface responsável por definir os metodos que acessam informações do banco de dados * * @author Elton * @since 05/02/2016 - 12:21:21 * @version 1.0 */ public interface ClienteDAO extends DAO<Cliente, Integer>{ /** * * Realiza a busca do cliente por cpf * * @author Elton * @since 17/02/2016 * @version 1.0 * @param cpf Cpf do cliente a qual deseja pesquisar * @return O proprio objeto */ public Cliente findBy(String cpf) throws NoResultException; } <file_sep>package br.com.livraria.models.enums; /** * * Enum criado para armazenar os tipos de pagamento * * @author Elton * @since 05/02/2016 - 12:27:53 * @version 1.0 */ public enum TipoPagamento { DINHEIRO,CARTAO; } <file_sep>package br.com.livraria.dao.impl; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.com.livraria.dao.LivroDAO; import br.com.livraria.models.Livro; /** * * Classe responsável por implementar os metodos definidos na interface de acesso ao banco * * @author Elton * @since 05/02/2016 - 12:23:48 * @version 1.0 */ @Repository public class LivroDAOImpl extends DAOImpl<Livro, Integer> implements LivroDAO{ @PersistenceContext private EntityManager em; @Override public Livro findBy(Integer isbn) throws NoResultException { String jpql = "select l from Livro l where l.isbn = :isbn"; TypedQuery<Livro> query = em.createQuery(jpql, Livro.class); query.setParameter("isbn", isbn); return query.getSingleResult(); } } <file_sep>package br.com.livraria.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.support.PagedListHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.livraria.bo.RoleBO; import br.com.livraria.bo.UsuarioBO; import br.com.livraria.exceptions.BOException; import br.com.livraria.models.Role; import br.com.livraria.models.Usuario; @Controller @RequestMapping("/usuario") public class UsuarioController { private static final Logger logger = Logger.getLogger(UsuarioController.class); @Autowired private UsuarioBO usuarioBO; @Autowired private RoleBO roleBO; private List<Role> roles; @RequestMapping(path = "/cadastro", method=RequestMethod.GET) public ModelAndView form(HttpServletRequest request, Usuario usuario, RedirectAttributes redirect){ ModelAndView modelAndView = new ModelAndView("/cadastro/usuario"); int page = ServletRequestUtils.getIntParameter(request, "p", 0); carregarCombos(); List<Usuario> usuarios = usuarioBO.list(); modelAndView.addObject("roles", roles); PagedListHolder<Usuario> pagedListHolder = new PagedListHolder<Usuario>(usuarios); pagedListHolder.setPage(page); pagedListHolder.setPageSize(5); modelAndView.addObject("pagedListHolder", pagedListHolder); return modelAndView; } @RequestMapping(path = "/cadastro", method=RequestMethod.POST) public ModelAndView salvar(HttpServletRequest request, @Valid Usuario usuario, BindingResult bindingResult, RedirectAttributes redirect){ try { if (bindingResult.hasErrors()){ carregarCombos(); return new ModelAndView("/cadastro/usuario","usuario", usuario).addObject("roles", roles); } if (usuario.validarSenha() == false){ throw new BOException("As senhas não correspondem"); } //Realizar codificação da senha antes de inserir no banco BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); usuario.setPassword(<PASSWORD>.encode(usuario.getPassword())); usuarioBO.insert(usuario); redirect.addFlashAttribute("mensagem", "Usuário incluido com sucesso"); } catch (BOException e) { redirect.addFlashAttribute("mensagem", e.getMessage()); redirect.addFlashAttribute("usuario", usuario); } catch (Exception e){ redirect.addFlashAttribute("mensagem", "Ocorreu um erro desconhecido, favor tentar novamente!" + e.getMessage()); redirect.addFlashAttribute("usuario", usuario); logger.error("Ocorreu um erro desconhecido", e); } return new ModelAndView("redirect:cadastro"); } public void carregarCombos(){ roles = roleBO.list(); } } <file_sep>package br.com.livraria.builders; public class AutorBuilder { } <file_sep>package br.com.livraria.bo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.livraria.dao.RoleDAO; import br.com.livraria.exceptions.DBException; import br.com.livraria.models.Role; /** * * Classe que possui as regras de negocio da entidade * * @author Elton * @since 05/02/2016 - 12:28:16 * @version 1.0 */ @Service public class RoleBO { @Autowired private RoleDAO roleDAO; @Transactional(readOnly = true) public List<Role> list(){ return roleDAO.getAll(); } } <file_sep>package br.com.livraria.converters; import java.util.ArrayList; import java.util.List; import org.springframework.core.convert.converter.Converter; import br.com.livraria.models.Role; public class StringArrayToListRole implements Converter<String[], List<Role>>{ @Override public List<Role> convert(String[] array) { List<Role> arrayList = new ArrayList<Role>(); for (int i = 0; i < array.length; i++) { Role role = new Role(); role.setName(array[i]); arrayList.add(role); } return arrayList; } }
987b617dc359af791623682a82e9f25ed0cdfd74
[ "Markdown", "Java" ]
21
Java
eltonnuness/livraria-web
e2e42951108c439174419a27c71c47a895f52cfd
51ec7b7199c0d089b72d9a2f854c3b12af9018f0
refs/heads/master
<file_sep><div class="bottombar"> <div class="button prev"><?=tg('vorige')?></div> <div class="button exit"><?=tg('afsluiten')?></div> <div class="button next"><?=tg('volgende')?></div> </div> <script type="text/javascript"> $(document).ready(function(){ $('#telefoon .bottombar .exit').click(function(){ showMessageBox({ message: $('[warning=echt-afsluiten]').text(), type: 'warning', top: 50, width: 250, height: 150, onClose: function(res) { if (res == 'ok') BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_AFSLUITEN ); } }); }); $('#telefoon .bottombar .next').click(function(){ BRISToezicht.Telefoon.onNext(); }); $('#telefoon .bottombar .prev').click(function(){ BRISToezicht.Telefoon.onPrevious(); }); }); </script><file_sep>DROP TABLE IF EXISTS `custom_report_data_155_pbm_sub_taak`; DROP TABLE IF EXISTS `custom_report_data_155_pbm_taak`; CREATE TABLE custom_report_data_155_pbm_taak ( id int(11) NOT NULL AUTO_INCREMENT, dossier_id int(11) NOT NULL, pbm_taak_name varchar(255) DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_custom_report_data_155_pbm_taak_dossiers_id FOREIGN KEY (dossier_id) REFERENCES dossiers (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE custom_report_data_155_pbm_sub_taak ( id int(11) NOT NULL AUTO_INCREMENT, taak_id int(11) DEFAULT NULL, risico_blootstelling varchar(255) DEFAULT NULL, wxbxe_w float DEFAULT NULL, wxbxe_b float DEFAULT NULL, wxbxe_r float DEFAULT NULL, bronmaatregelen varchar(255) DEFAULT NULL, pbm varchar(255) DEFAULT NULL, wxbxe_e float DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_custom_report_data_155_pbm_sub_taak_taak_id FOREIGN KEY (taak_id) REFERENCES custom_report_data_155_pbm_taak (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; DELETE FROM `teksten` WHERE FALSE OR `string` LIKE '%rapportage_pago_pbm%' OR `string` LIKE '%edit_sub_task_form%' OR `string` LIKE '%show_pago_pbm_form%' OR `string` LIKE '%show_pago_pbm_sub_taak_form%' ; -- REPLACE INTO `teksten` (`string`,`tekst`,`timestamp`,`lease_configuratie_id`) VALUES ('dossiers.bewerken::rapportage_pbm.header','Persoonlijke beschermingsmiddelen (PBM) (betaversie)',NOW(),0) ,('dossiers.rapportage_pbm::pbm','PBM',NOW(),0) ,('dossiers.rapportage_pbm::bronmaatregelen','Bronmaatregelen',NOW(),0) ,('dossiers.rapportage_pbm::wxbxe','R=WxBxE ',NOW(),0) ,('dossiers.rapportage_pbm::risico_blootstelling','Risico/blootstelling',NOW(),0) ,('dossiers.rapportage_pbm::kritieke_taak','Kritieke taak',NOW(),0) ,('dossiers.rapportage_pbm::no_items_found','Er zijn nog geen gegevens ingevoerd.',NOW(),0) ,('dossiers.show_pbm_form::kritieke_taak','Kritieke taak ',NOW(),0) ,('dossiers.show_pbm_form::successfully_saved','Succesvol opgeslagen',NOW(),0) ,('dossiers.show_pbm_form::error_not_saved','Er is een fout opgetreden. De gegevens zijn niet succesvol opgeslagen.',NOW(),0) ,('dossiers.show_pbm_risk_form::risico_blootstelling','Risico/blootstelling',NOW(),0) ,('dossiers.show_pbm_risk_form::bronmaatregelen','Bronmaatregelen',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_w','W',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_r','R=WxBxE',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_b','B',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_e','E',NOW(),0) ,('dossiers.show_pbm_risk_form::pbm','PBM',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_b','B',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_e','E',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_w','W',NOW(),0) ,('dossiers.show_pbm_risk_form::wxbxe_r','R=WXBXE',NOW(),0) ,('dossiers.show_pbm_risk_form::successfully_saved','Succesvol opgeslagen',NOW(),0) ,('dossiers.show_pbm_risk_form::error_not_saved','Er is een fout opgetreden. De gegevens zijn niet succesvol opgeslagen.',NOW(),0) ; ALTER TABLE custom_report_data_155_pbm_sub_taak MODIFY taak_id INT(11) NOT NULL; ALTER TABLE custom_report_data_155_pbm_sub_taak DROP COLUMN wxbxe_r; <file_sep><?php class FillGrondslagTekstenTabel { private $CI; public function __construct() { $this->CI = get_instance(); } public function run() { $data = array(); echo "Cleaning up...\n"; $this->CI->db->query( 'DELETE FROM bt_grondslag_teksten WHERE 1' ); $this->CI->db->query( 'ALTER TABLE bt_grondslag_teksten AUTO_INCREMENT = 1' ); echo "Loading...\n"; $res = $this->CI->db->query( 'SELECT * FROM bt_vraag_grndslgn;' ); $rows = $res->result(); $res->free_result(); echo "Processing...\n"; foreach ($rows as $row) { $artikel = preg_replace( '/artikel\s+/i', '', $row->artikel ); if (!isset( $data[$row->grondslag_id] )) $data[$row->grondslag_id] = array(); if (!isset( $data[$row->grondslag_id][$artikel] ) || !$data[$row->grondslag_id][$artikel]) $data[$row->grondslag_id][$artikel] = $row->tekst; else if ($row->tekst && $row->tekst != $data[$row->grondslag_id][$artikel]) echo "LET OP: verschil gevonden in {$row->grondslag_id}, {$row->artikel}\n"; } echo "Inserting...\n"; if (!$this->CI->dbex->prepare( 'fgtt', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, tekst) VALUES (?, ?, ?)' )) throw new Exception( 'Prepared statement preparation error.' ); foreach ($data as $grondslag_id => &$artikelen) foreach ($artikelen as $artikel => $tekst) { if (!$this->CI->dbex->execute( 'fgtt', array( $grondslag_id, $artikel, $tekst ? $tekst : '' ) )) throw new Exception( 'Prepared statement execution error.' ); $artikelen[$artikel] = $this->CI->db->insert_id(); } echo "Updating...\n"; if (!$this->CI->dbex->prepare( 'fgtt2', 'UPDATE bt_vraag_grndslgn SET grondslag_tekst_id = ? WHERE id = ?' )) throw new Exception( 'Prepared statement preparation error (2).' ); foreach ($rows as $row) { $artikel = preg_replace( '/artikel\s+/i', '', $row->artikel ); if (!$this->CI->dbex->execute( 'fgtt2', array( $data[$row->grondslag_id][$artikel], $row->id ) )) { echo "\n";var_dump(array($data[$row->grondslag_id][$artikel], $row->id));echo "\n"; throw new Exception( 'Prepared statement execution error (2).' ); } } } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruikers_collegas')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => $gebruiker->volledige_naam, 'width' => '920px' )); ?> <form name="form" method="post"> <?=tg('collega_info', $gebruiker->volledige_naam)?> <div style="padding-left: 40px;"> <table cellpadding="0" cellspacing="0"> <tr> <td><input type="checkbox" id="is_all" <?=$is_all_checked ? 'checked ':''?> /></td> <td>&nbsp;</td> </tr> <? foreach ($alle_gebruikers as $c): ?> <? if ($c->id==$gebruiker->id) continue; ?> <tr> <td><input class="colleague" <?=isset($collegas[$c->id])?'checked ':''?>type="checkbox" name="collega_<?=$c->id?>" id="collega_<?=$c->id?>" /></td> <td><?=$c->get_status()?></td> </tr> <? endforeach; ?> <tr> <td colspan="2"><input type="submit" value="<?=tgng('form.opslaan')?>" /></td> </tr> </table> </div> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $(document).ready(function(){ $('#is_all').click(function(){ $('.colleague').attr('checked', $(this).is(':checked')); }); $('.colleague').click(function(){ var is_all=true; $('.colleague').each(function( index ){ is_all = !$(this).is(':checked') ? false : is_all; }); $('#is_all').attr('checked', is_all ); }); }); </script><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Checklist export')); ?> <form method="POST" enctype="multipart/form-data"> <p> Via deze pagina kan een csv bestand worden geexporteerd.<br/> De gegenereerde CSV bestanden zijn compatibel met het formaat dat gebruikt wordt voor de checklist import functionaliteit. </p> <table> <tr> <th style="text-align:left">Klant:</th> <td> <select name="checklistgroep_id"> <option value="" disabled selected>-- selecteer checklistgroep --</option> <? foreach ($checklistgroepen as $checklistgroep): ?> <option <?=$checklistgroep->id == $checklistgroep_id?'selected':''?> value="<?=$checklistgroep->id?>"><?=$checklistgroep->naam?></option> <? endforeach; ?> </select> </td> </tr> <!-- <tr> <th style="text-align:left">Encoding:</th> <td> <select name="encoding"> <? foreach (array( 'ISO-8859-1', 'ASCII', 'CP437', 'Windows-1252', 'UTF-8' ) as $e): ?> <option <?=$e==$encoding?'selected':''?> value="<?=$e?>"><?=$e?></option> <? endforeach; ?> </select> </td> </tr> --> </table> <p> <input type="submit" value="Genereren" /> <span style="font-style:italic; display: none">Even geduld a.u.b....</span> </p> </form> <script type="text/javascript"> /* $(document).ready(function(){ $('form').submit(function(){ $('[type=submit]').attr( 'disabled', 'disabled' ); $('[type=submit]').next().show(); return true; }); }); */ </script> <? $this->load->view('elements/footer'); ?> <file_sep>-- Get some IDs in temporary variables SELECT @klant_id_imotep:=id FROM klanten WHERE naam = 'Imotep'; SELECT @klant_id_cebes:=id FROM klanten WHERE naam = 'Cebes'; SELECT @klant_id_vr_twente:=id FROM klanten WHERE naam = '<NAME>'; SELECT @ws_id:=id FROM webservice_applicaties WHERE naam = 'Breed SOAP koppelvlak'; -- Limit some of the webservice accounts to specific 'klant_id' values INSERT INTO webservice_accounts SET webservice_applicatie_id = @ws_id, omschrijving = 'VR Twente', gebruikersnaam = '<EMAIL>', wachtwoord = sha1('twente'), actief = 1, alle_klanten = 1, alle_components = 1, klant_id = @klant_id_vr_twente; -- Insert the data for VR Twente INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_twente, target_id = @klant_id_imotep; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_twente, target_id = @klant_id_vr_twente; <file_sep>ALTER TABLE `bt_checklisten` ADD `standaard_gebruik_grondslagen` TINYINT NULL DEFAULT NULL, ADD `standaard_gebruik_richtlijnen` TINYINT NULL DEFAULT NULL, ADD `standaard_gebruik_aandachtspunten` TINYINT NULL DEFAULT NULL; ALTER TABLE `bt_hoofdgroepen` ADD `standaard_gebruik_grondslagen` TINYINT NULL DEFAULT NULL, ADD `standaard_gebruik_richtlijnen` TINYINT NULL DEFAULT NULL, ADD `standaard_gebruik_aandachtspunten` TINYINT NULL DEFAULT NULL; ALTER TABLE `bt_vragen` ADD `gebruik_grondslagen` TINYINT NULL DEFAULT NULL, ADD `gebruik_richtlijnen` TINYINT NULL DEFAULT NULL, ADD `gebruik_aandachtspunten` TINYINT NULL DEFAULT NULL; -- voor alle HUIDIGE vragen, markeer dat ze hun eigen instellingen hebben! UPDATE bt_vragen SET gebruik_grondslagen = 1; UPDATE bt_vragen SET gebruik_richtlijnen = 1; UPDATE bt_vragen SET gebruik_aandachtspunten = 1; <file_sep>PDFAnnotator.GUI.Menu.Drawing = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( menu, config ) { this._super( menu ); this.options = config.options; this.transparencyChoices = config.transparencyChoices; this.currentTransparency = config.currentTransparency; this.selectedClass = config.selectedClass; this.checkedClass = config.checkedClass; this.showOverview = config.showOverview; this.rotations = [ 0, 90, 180, 270 ]; var thiz = this; this.transparencyChoices.click(function(){ var transparency = $(this).attr( 'transparency' ); if (transparency != undefined || transparency != null) { var container, engine=thiz.getMenu().getGUI().getEngine(); engine.setPageTransparency( parseFloat( transparency ) ); thiz.currentTransparency.text( Math.round(parseFloat( transparency ) * 100) + '%' ); } }); thiz.currentTransparency.text( Math.round(parseFloat( config.initialTransparency ) * 100) + '%' ); /* register DOM events */ var showWarning = function() { alert( 'U kunt de tekening niet meer roteren of spiegelen zodra u een of meerdere annotaties geplaatst heeft.' ); }; for (var i=0; i<this.rotations.length; ++i) { $(thiz.options[i]).attr( 'rotation', this.rotations[i] ); $(thiz.options[i]).click(function(){ var engine = thiz.getMenu().getGUI().getEngine(); if (!engine.isPageTransformLocked()) { engine.setPageRotation( parseInt( $(this).attr('rotation') ) ); } else showWarning(); }); } $(thiz.options[4]).click(function(){ var engine = thiz.getMenu().getGUI().getEngine(); if (!engine.isPageTransformLocked()) engine.togglePageHorizontalFlip(); else showWarning(); }); $(thiz.options[5]).click(function(){ var engine = thiz.getMenu().getGUI().getEngine(); if (!engine.isPageTransformLocked()) engine.togglePageVerticalFlip(); else showWarning(); }); thiz.showOverview.click(function(){ var engine = thiz.getMenu().getGUI().getEngine(); engine.showOverviewWindow(); }); }, initialize: function() { /* register engine events */ var thiz = this; this.menu.gui.engine.on( 'pagetransformchanged', function( engine, pagetransform ){ // handle showing current rotation for (var i=0; i<thiz.rotations.length; ++i) { $(thiz.options[i]).removeClass( thiz.checkedClass ); if (pagetransform.rotation == thiz.rotations[i]) $(thiz.options[i]).addClass( thiz.checkedClass ); } // handle flipping horizontally $(thiz.options[4]).removeClass( thiz.checkedClass ); if (pagetransform.flipH) $(thiz.options[4]).addClass( thiz.checkedClass ); // handle flipping vertically $(thiz.options[5]).removeClass( thiz.checkedClass ); if (pagetransform.flipV) $(thiz.options[5]).addClass( thiz.checkedClass ); }); } }); <file_sep>PDFAnnotator.HelperWindow = PDFAnnotator.Base.extend({ init: function( owner, config ) { /* call inherited constructor */ this._super(); /* store owner */ this.owner = owner; /* setup visuals */ this.visuals = $('<div>') .addClass( 'HelperWindow' ) .css( 'width', config.width || '400px' ) .css( 'height', config.height || '400px' ) .css( 'position', 'absolute' ) .css( 'left', config.left || '200px' ) .css( 'top', config.top || '100px' ) .css( 'z-index', 50 ) .appendTo( config.container ); this.handles = []; if (config.moveable) { /* not really an Editable object, but we have a visuals jQuery collection and a moveRelative function, which is all that matters! */ this.addHandle( new PDFAnnotator.Handle.Move( this ) ); } }, addHandle: function( handle ) { this.handles.push( handle ); handle.show(); }, show: function() { this.visuals.show(); // re-show handles to (possibly) reposition them for (var i=0; i<this.handles.length; ++i) this.handles[i].show(); }, hide: function() { this.visuals.hide(); }, isVisible: function() { return this.visuals.is(':visible'); }, /* here so we can be treated like an Editable object. */ moveRelative: function( relx, rely ) { this.visuals.each(function(){ var thiz = $(this); thiz.css({ left: parseInt( thiz.css('left') ) + relx, top: parseInt( thiz.css('top') ) + rely }); }); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <form method="POST" enctype="multipart/form-data"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Afbeeldingbeheer', 'width' => '920px' ) ); ?> <? if ($uploaded): ?> <p> Afbeelding succesvol ge&uuml;pload. </p> <? endif; ?> <table style="width:auto; min-width: 400px"> <tr> <th style="text-align:left">Bestand:</th> <td> <input type="file" name="image" /> </td> </tr> <tr> <th style="text-align:left">Modus:</th> <td> <select name="mode"> <option value="new">Sla op als nieuwe afbeelding</option> <option value="override">Vervang inhoud bestaande afbeelding</option> </select> <select name="replace" class="hidden"> <? foreach ($images as $image): ?> <option value="<?=$image->id?>"><?=$image->filename?> (<?=$image->width?>x<?=$image->height?>)</option> <? endforeach; ?> </select> </td> </tr> </table> <p> <input type="submit" value="Opslaan" /> </p> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Afbeeldingen overzicht', 'width' => '920px' ) ); ?> <table style="width:auto; min-width: 400px"> <tr> <th style="text-align:left">Afbeelding</th> <th style="text-align:left">Bestandsnaam</th> <th style="text-align:left">Formaat</th> <th style="text-align:left">Grootte</th> <th style="text-align:left">Opties</th> </tr> <? foreach ($images as $image): ?> <tr> <td><img src="<?=site_url( $image->get_url() )?>" /></td> <td><?=$image->filename?></td> <td><?=$image->width?> x <?=$image->height?></td> <td><?=strlen($image->data)?> bytes</td> <td><a href="javascript:void(0);" onclick="if (confirm('Afbeelding werkelijk verwijderen?')) location.href='<?=site_url('/admin/image_delete/' . $image->id)?>';"><img src="<?=site_url('/files/images/delete.png')?>" /></a></td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <script type="text/javascript"> $('select[name=mode]').change(function(){ $('select[name=replace]')[ (this.value == 'override') ? 'show' : 'hide' ](); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE `dossiers` ADD `bag_identificatie_nummer` VARCHAR( 64 ) NULL DEFAULT NULL , ADD `xy_coordinaten` VARCHAR( 64 ) NULL DEFAULT NULL; <file_sep><? require_once 'base.php'; class DeelplanThemaResult extends BaseResult { function DeelplanThemaResult( &$arr ) { parent::BaseResult( 'deelplanthema', $arr ); } } class DeelplanThema extends BaseModel { function DeelplanThema() { parent::BaseModel( 'DeelplanThemaResult', 'deelplan_themas' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'thema', 'thema_id' ); } function get_by_deelplan( $deelplan_id ) { if (!$this->dbex->is_prepared( 'get_themas_by_deelplan' )) $this->dbex->prepare( 'get_themas_by_deelplan', ' SELECT * FROM deelplan_themas WHERE deelplan_id = ? ORDER BY id ' ); $res = $this->dbex->execute( 'get_themas_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) $result[ $row->thema_id ] = $this->getr( $row ); $res->free_result(); return $result; } function set_for_deelplan( $deelplan_id, array $thema_ids, array $current_themas ) { // changes? $change_detected = false; if (sizeof( $current_themas ) == sizeof( $thema_ids )) { foreach ($thema_ids as $thema_id) if (!isset( $current_themas[$thema_id] )) { $change_detected = true; break; } if (!$change_detected) return false; } // delete current $this->db->from( 'deelplan_themas' ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->delete(); // add new $this->dbex->prepare( 'set_deelplan_thema', 'INSERT INTO deelplan_themas (deelplan_id, thema_id) VALUES (?, ?)' ); foreach ($thema_ids as $thema_id) { $args = array( 'deelplan_id' => $deelplan_id, 'thema_id' => $thema_id, ); $this->dbex->execute( 'set_deelplan_thema', $args ); } return true; } } <file_sep>ALTER TABLE `deelplan_uploads` DROP `data`; <file_sep><? require_once 'base.php'; class DeelplanAandachtspuntResult extends BaseResult { function DeelplanAandachtspuntResult( &$arr ) { parent::BaseResult( 'deelplanaandachtspunt', $arr ); } } class DeelplanAandachtspunt extends BaseModel { function DeelplanAandachtspunt() { parent::BaseModel( 'DeelplanAandachtspuntResult', 'deelplan_aandachtspunten', true ); } public function check_access( BaseResult $object ) { // disabled for model } function add( $deelplan_id, $toetser, $datum, $tekst, $grondslag, $globaal ) { /* if (!$this->dbex->is_prepared( 'DeelplanAandachtspunt::add' )) $this->dbex->prepare( 'DeelplanAandachtspunt::add', 'INSERT INTO deelplan_aandachtspunten (deelplan_id, toetser, datum, tekst, grondslag, globaal) VALUES (?, ?, ?, ?, ?, ?)' ); $args = array( 'deelplan_id' => $deelplan_id, 'toetser' => $toetser, 'datum' => date('Y-m-d', strtotime( $datum ) ), 'tekst' => $tekst, 'grondslag' => $grondslag, 'globaal' => $globaal ? 'ja' : 'nee', ); $this->dbex->execute( 'DeelplanAandachtspunt::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $args['id'] = $id; return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'deelplan_id' => $deelplan_id, 'toetser' => $toetser, 'datum' => (get_db_type() == 'oracle') ? array('format_string' => get_db_literal_for_date("?"), 'data' => date('Y-m-d', strtotime( $datum ) )) : date('Y-m-d', strtotime( $datum ) ), 'tekst' => $tekst, 'grondslag' => $grondslag, 'globaal' => $globaal ? 'ja' : 'nee', ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'isscss' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } function get_by_deelplan_id( $deelplan_id, $assoc=false ) { return $this->search( array( 'deelplan_id' => $deelplan_id ), null, $assoc ); } function verwijder_voor_deelplan( $deelplan_id ) { $this->db->query( 'DELETE FROM deelplan_aandachtspunten WHERE deelplan_id = ' . intval( $deelplan_id ) ); } } <file_sep>INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (M+P)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 2), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4); INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (P)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 1), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4); INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (M+P+T)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 2), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 2), (NULL, @rol_id, 27, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4); INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (P+T)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 1), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 2), (NULL, @rol_id, 27, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4); INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (T)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 1), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 1), (NULL, @rol_id, 27, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4); INSERT INTO `rollen` (`id`, `naam`, `type`, `klant_id`, `gemaakt_op`, `gemaakt_door_gebruiker_id`, `is_beheer_default`, `is_toezichthouder_default`) VALUES (NULL, '[BL] Klant (M+T)', 'normaal', NULL, NOW(), 1, 0, 0); SET @rol_id = LAST_INSERT_ID(); INSERT INTO `rol_rechten` (`id`, `rol_id`, `recht`, `modus`) VALUES (NULL, @rol_id, 1, 1), (NULL, @rol_id, 10, 4), (NULL, @rol_id, 11, 2), (NULL, @rol_id, 12, 4), (NULL, @rol_id, 13, 4), (NULL, @rol_id, 14, 4), (NULL, @rol_id, 15, 1), (NULL, @rol_id, 16, 1), (NULL, @rol_id, 17, 2), (NULL, @rol_id, 18, 2), (NULL, @rol_id, 19, 1), (NULL, @rol_id, 2, 2), (NULL, @rol_id, 20, 1), (NULL, @rol_id, 21, 1), (NULL, @rol_id, 22, 1), (NULL, @rol_id, 23, 1), (NULL, @rol_id, 24, 1), (NULL, @rol_id, 26, 1), (NULL, @rol_id, 27, 2), (NULL, @rol_id, 3, 4), (NULL, @rol_id, 4, 4), (NULL, @rol_id, 5, 4), (NULL, @rol_id, 6, 4), (NULL, @rol_id, 7, 2), (NULL, @rol_id, 8, 4), (NULL, @rol_id, 9, 4);<file_sep><div class="nlaf_TabContent"> <div class="documenten bestanden"> <div class="hidden image-set"> <!-- bescheiden --> <? $guids = load_current_guids(); $pdf_annotator_document = array(); foreach ($guids->get_document_guids() as $guid) { try { $document = Document::restore_state( $guid ); } catch (Exception $e) { $document = null; } if ($document) $pdf_annotator_document[$document->get_external_data_by_key( 'document_id' )] = $document; } ?> <? foreach ($bescheiden as $i => $bescheid): ?> <? if ($document = @$pdf_annotator_document[$bescheid->id]): ?> <? if($document->get_working_data()):?> <? foreach ($document->get_working_data() as $page): ?> <? if ($page['pagenumber'] != 1) continue; ?> <? $page['pagenumber']=1;?> <? if ($page['numslices']): ?> <div bescheid_id="<?=$bescheid->id?>" class="bestand" style="border:0;margin:0;padding:0;width:430px;"> <? for ($i=0; $i<1; ++$i): ?> <img style="width: 100%" target_url="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'] . chr(65+$i), strtotime($document->get_timestamp('created_at')), $page['version'], $document->get_guid() )?>" src="/files/images/s.gif" /> <? endfor; ?> </div> <? else: ?> <img bescheid_id="<?=$bescheid->id?>" class="bestand" style="width: 430px" target_url="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'], strtotime($document->get_timestamp('created_at')), $page['version'], $document->get_guid() )?>" src="/files/images/s.gif" /> <? endif; ?> <? endforeach; ?> <? else:?> <img bescheid_id="<?=$bescheid->id?>" class="bestand" width="430" src="<?=site_url('/files/images/pdfview-nog-niet-geladen.png')?>" target_url="<?=site_url('/pdfview/bescheiden/' . $bescheid->id)?>" /> <? endif; ?> <? else: ?> <img bescheid_id="<?=$bescheid->id?>" class="bestand" width="430" src="<?=site_url('/files/images/pdfview-nog-niet-geladen.png')?>" target_url="<?=site_url('/pdfview/bescheiden/' . $bescheid->id)?>" /> <? endif; ?> <? endforeach; ?> </div> <table class="lijst" cellpadding="0" cellspacing="0" border="0" mode="dual"> <tr> <td class="bestand" rowspan="3"> <div class="container"> <!-- controls --> <div class="controls"><img style="z-index: 10" class="control vorige" src="<?=site_url('/files/images/nlaf/vorige-bestand.png')?>" /></div> <div class="controls"><img style="z-index: 10" class="control volgende" src="<?=site_url('/files/images/nlaf/volgende-bestand.png')?>" /></div> <div class="controls"><img style="z-index: 10" class="control pdfannotator <?=$pdf_annotator_allow ? '' : 'hidden'?>" src="<?=site_url('/files/images/nlaf/naar-pdfannotator.png')?>"/></div> <div class="controls"><img style="z-index: 10" class="control zoom-in" src="<?=site_url('/files/images/nlaf/zoom-in.png')?>" /></div> <div class="controls"><div style="z-index: 10; cursor: default;" class="control aantal"></div></div> <div class="controls"> <div class="control info-blok"> <input type="button" value="Maak relevant" class="maak-relevant"/> <div class="info-naam"><?=tg('document_naam')?> <span></span></div> </div> </div> </div> </td> <td class="lijst-header"> <table cellspacing="0" cellpadding="0" border="0" style="width:100%"> <tr> <td style="width:100%" class="header"></td> <td> <nobr> <img src="<?=site_url('/files/images/nlaf/mode-dual.png')?>" class="hidden document-view-mode" switch-to-mode="dual" mode="details" /> <img src="<?=site_url('/files/images/nlaf/mode-details.png')?>" class="document-view-mode" switch-to-mode="details" mode="dual" /> </nobr> </td> <td> <label> <nobr> <input type="radio" name="document-filter" value="relevant" /> <?=tg('relevant')?> </nobr> </label> </td> <td> <label> <nobr> <input type="radio" name="document-filter" value="alles" checked /> <?=tg('alles')?> </nobr> </label> </td> <td> <div id="nlaf_DocumentenTerug" class="inlineblock"><?=tg('terug_naar_overzicht')?></div> </td> </tr> </table> </td> </tr> <tr> <td class="kolom-header"> <table style="width:100%" cellspacing="0" cellpadding="0" border="0"> <tr> <td style="width: 150px"><?=tg('naam')?></td> <td style="width: 65px"><?=tg('datum')?></td> <td><?=tg('omschrijving')?></td> </tr> </table> </td> </tr> <tr> <td class="dataregels"> <div> <table style="width:100%" cellspacing="0" cellpadding="0" border="0"> </table> </div> </td> </tr> </table> <table class="lijst hidden" cellpadding="0" cellspacing="0" border="0" mode="details"> <tr> <td class="lijst-header"> <table cellspacing="0" cellpadding="0" border="0" style="width:100%"> <tr> <td style="width:100%" class="header"></td> <td> <nobr> <img src="<?=site_url('/files/images/nlaf/mode-dual.png')?>" class="hidden document-view-mode" switch-to-mode="dual" mode="details" /> <img src="<?=site_url('/files/images/nlaf/mode-details.png')?>" class="document-view-mode" switch-to-mode="details" mode="dual" /> </nobr> </td> <td> <label> <nobr> <input type="radio" name="document-filter2" value="relevant" /> <?=tg('relevant')?> </nobr> </label> </td> <td> <label> <nobr> <input type="radio" name="document-filter2" value="alles" checked /> <?=tg('alles')?> </nobr> </label> </td> <td> <div id="nlaf_FotosTerug" class="inlineblock"><?=tg('terug_naar_overzicht')?></div> </td> </tr> </table> </td> </tr> <tr> <td class="kolom-header"> <table style="width:100%" cellspacing="0" cellpadding="0" border="0"> <tr> <td style="width: 37px">&nbsp;</td> <td style="width: 200px"><?=tg('naam')?></td> <td style="width: 80px"><?=tg('datum')?></td> <td style="width: 100px"><?=tg('specificatie')?></td> <td><?=tg('omschrijving')?></td> <td style="width: 100px"><?=tg('auteur')?></td> <td style="width: 140px">&nbsp;</td> </tr> </table> </td> </tr> <tr> <td class="dataregels"> <div> <table style="width:100%" cellspacing="0" cellpadding="0" border="0"> </table> </div> </td> </tr> </table> </div> </div> <script type="text/javascript"> $(document).ready(function(){ var selectImage = function( images, index ) { $('.nlaf_TabContent .documenten .aantal').text( $('.XvanY').text().replace( /\$1/, (index+1) ).replace( /\$2/, images.length ) ); var img = $(images[index]); img.removeClass('hidden'); var data = img.data('image'); var relBtn = $('.nlaf_TabContent .documenten input.maak-relevant'); if (data.relevant) { relBtn.attr('maak-bescheid-relevant', 'nee'); relBtn.attr('value', 'Maak niet relevant' ); } else { relBtn.attr('maak-bescheid-relevant', 'ja'); relBtn.attr('value', 'Maak relevant' ); } relBtn.attr( 'bescheid_id', data.bescheid_id ); $('.nlaf_TabContent .documenten .info-naam span').text( data.bestandsnaam ); $('.nlaf_TabContent .documenten [bestand-index]').removeClass('selected'); $('.nlaf_TabContent .documenten [bestand-index=' + index + ']').addClass('selected'); } var selectDiffImage = function( cont, diff ) { var images = cont.children( '[bescheid_id]' ); for (var i=0; i<images.size(); ++i) if (!$(images[i]).hasClass('hidden')) { $(images[i]).addClass('hidden'); var j = (i + diff); if (j < 0) j += images.size(); j = j % images.size(); selectImage( images, j ); break; } }; // handle switching images $('.nlaf_TabContent .documenten tr[bestand-index]').live('click', function(){ var images = $('.nlaf_TabContent .documenten .container').children( '[bescheid_id]' ); images.filter(':not(.hidden)').removeClass('hidden'); // make sure no duplicates images.filter(':not(.hidden)').addClass('hidden'); selectImage( images, parseInt( $(this).attr('bestand-index') ) ); }); // handle image controls $('.nlaf_TabContent .documenten .control.vorige').click(function(){ selectDiffImage( $(this).parents('.container'), -1 ); }); $('.nlaf_TabContent .documenten .control.volgende').click(function(){ selectDiffImage( $(this).parents('.container'), 1 ); }); // handle switching to dual/details $('.nlaf_TabContent .documenten img[switch-to-mode]').click(function(){ var base = $(this).parents('.documenten'); var mode = $(this).attr('switch-to-mode'); // hide/show correct tables base.find( '[mode][mode!=' + mode + ']' ).hide(); base.find( '[mode=' + mode + ']' ).show(); }); // handle switching relevant/alles $('[name=document-filter], [name=document-filter2]').change(function(){ // make sure both sets of filters show the same value var value = this.value; $('[name=document-filter], [name=document-filter2]').each(function(){ if (this.value == value) this.checked = true; }); // update list if (value == 'relevant') BRISToezicht.Toets.Bescheiden.loadRelevant(); else BRISToezicht.Toets.Bescheiden.loadAlles(); }); // handle switching to pdf annotator $('.documenten .pdfannotator').click(function(){ var num_runs = 0; var bescheid_img = BRISToezicht.Toets.Bescheiden.getVisibleBescheidenImage(); var bescheid_id = (bescheid_img && bescheid_img.size()) ? bescheid_img.attr('bescheid_id') : null; if (!bescheid_id) { alert( '<?=tg('selecteer_eerst_een_bescheiden_om_te_annoteren')?>' ); return; } else { current_bescheiden_id = bescheid_id; } if (!$.browser.msie) { if (!BRISToezicht.OfflineKlaar.isKlaarVoorOffline()) { alert( '<?=tg('de_applicatie_is_nog_niet_klaar_voor_offline_gebruik_even_geduld_aub')?>' ); return; } } if (!BRISToezicht.Toets.PDFAnnotator.haveBescheidenId( bescheid_id )) { alert( '<?=tg('dit_bescheiden_is_niet_beschikbaar_in_de_pdf_annotator')?>' ); return; } // show Terug button $('#nlaf_HeaderTerug div').show(); // hide "Open toezichtvoortgang" button $('#nlaf_NaarToezichtVoortgang').hide(); // install one-time-handler to header terug button to restore state $('#nlaf_HeaderTerug div').one('click', function() { num_runs = num_runs + 1; if (current_bescheiden_id == bescheid_id && num_runs == 1) { try { $('#nlaf_NaarToezichtVoortgang').show(); BRISToezicht.Toets.PDFAnnotator.storeLayerState( bescheid_id ); } catch(err) { alert( '<?=tg('er is een exception opgetreden tijdens het opslaan van uw laatste bewerking')?>' ); } } else if (num_runs == 1) { alert( '<?=tg('er ging iets mis tijdens het opslaan van uw laatste bewerking')?>' ); } }); // hide all content panels $('#nlaf_MainPanel').children( ':not(#nlaf_GreenBar):not(#nlaf_Header)' ).hide(); // show target panel $('#nlaf_PDFAnnotator').show(); // select document if (!BRISToezicht.Toets.PDFAnnotator.selectBescheidenId( bescheid_id )) { alert( '<?=tg('interne_fout_bij_het_selecteren_van_het_bescheiden')?>' ); return; } }); // handle switching to zoom-in image-view $('.documenten .zoom-in').click(function(){ if (!BRISToezicht.Toets.Bescheiden.moveBescheidenToImageView()) return; // show Terug button $('#nlaf_HeaderTerug div').show(); // hide "Open toezichtvoortgang" button $('#nlaf_NaarToezichtVoortgang').hide(); // install one-time-handler to header terug button to restore state $('#nlaf_HeaderTerug div').one('click', function(){ BRISToezicht.Toets.Bescheiden.restoreBescheidenFromImageView(); $('#nlaf_NaarToezichtVoortgang').show(); }); // hide all content panels $('#nlaf_MainPanel').children( ':not(#nlaf_GreenBar):not(#nlaf_Header)' ).hide(); // show target panel $('#nlaf_ViewImage').show(); }); // handle switching back to main view $('#nlaf_DocumentenTerug').click(function(){ $('#nlaf_TabList [tab-name=waardeoordeel]').trigger('click'); }); }); </script> <file_sep><?php // webservice server require_once( APPPATH . 'controllers/soap.php' ); // webservice class require_once( APPPATH . 'webservices/soapwoningborg.php' ); // set that we use the above class define( 'WEBSERVICE_SOAP_URL', '/soapwoningborg/' ); // url of our controller below define( 'WEBSERVICE_SOAP_CLASSNAME', 'WoningborgWebservice' ); // Instantiate the 'wrapper' class. This is everything that needs to be done in this file, the actual work is done in the above 'required webservice class'. class SoapWoningborg extends Soap { } <file_sep><?php class CI_DeviceInfo { const FIRST_PART = 'first'; const SYSTEM_PART = 'system'; const REST_PART = 'rest'; const ALL_PART = 'all'; private $agent; private $first_part; private $system_part; private $rest_part; private $good; private $has_ipad; /** Constructor. */ public function __construct() { $this->agent = @ $_SERVER['HTTP_USER_AGENT']; if (preg_match( '/^(.+?)\((.+?)\)(.*?)$/', $this->agent, $matches )) { $this->first_part = $matches[1]; $this->system_part = $matches[2]; $this->rest_part = $matches[3]; $this->good = true; } else $this->good = false; } /** Internal (private) helper. */ private function _match( $part, $regexp, &$matches=null ) { if ($part == self::ALL_PART || !$this->good) $string = $this->agent; else if ($part == self::FIRST_PART) $string = $this->first_part; else if ($part == self::SYSTEM_PART) $string = $this->system_part; else $string = $this->rest_part; return preg_match( $regexp, $string, $matches ); } /** * Returns the user agent - unchanged and unchopped - as it was received by PHP. */ public function get_agent() { return $this->agent; } /** * Returns whether or not this library could make any sense of the user agent. * If this returns true, the part functions will return their resp. parts of * the user agent string. */ public function user_agent_recognized() { return $this->good; } /** * If the user agent was (roughly) recognized, returns the first part of the * user agent. In most modern browsers this will always be "Mozilla/5.0" */ public function get_first_part() { return $this->good ? $this->first_part : $this->agent; } /** * If the user agent was (roughly) recognized, returns the system part of * the user agent (the text between the first set of parentheses.) */ public function get_system_part() { return $this->good ? $this->system_part : ''; } /** * If the user agent was (roughly) recognized, returns the rest part of * the user agent, i.e. everything that followed the first set of parentheses. */ public function get_rest_part() { return $this->good ? $this->rest_part : ''; } /** * Attempts to figure out if the user agent belongs to a tablet type device, as * opposed to a phone or other (pc/desktop) type device. */ public function is_tablet_type() { return // ipad ($this->_match( self::SYSTEM_PART, '/iPad/i' ) && $this->_match( self::SYSTEM_PART, '/Mac/i' )) // android tablets || ($this->_match( self::SYSTEM_PART, '/Android/i' ) && !$this->_match( self::REST_PART, '/Mobile/i' )); } /** * Attempts to figure out if the user agent belongs to a phone type device, as * opposed to a table or other (pc/desktop) type device. */ public function is_phone_type() { return // iphones ($this->_match( self::SYSTEM_PART, '/iPhone/i' ) && $this->_match( self::REST_PART, '/Mobile/i' )) // android phones || ($this->_match( self::SYSTEM_PART, '/Android/i' ) && $this->_match( self::REST_PART, '/Mobile/i' )); } /** * Attempts to figure out if the user agent belongs to anything but a tablet or * a phone (right now: a normal desktop device.) */ public function is_other_type() { return !$this->is_tablet_type() && !$this->is_phone_type(); } /** * Attempts to figure out if the specified user agent belongs to a version of * Internet Explorer. */ public function is_explorer_browser() { return $this->_match( self::SYSTEM_PART, '/MSIE/i' ); } /** * Attempts to figure out if the specified user agent belongs to a version of * Google Chrome. */ public function is_chrome_browser() { return $this->_match( self::REST_PART, '/Chrome/i' ) || $this->_match( self::REST_PART, '/CriOS/i' ); } /** * Attempts to figure out if the specified user agent belongs to a version of * Safari. */ public function is_safari_browser() { return !$this->is_chrome_browser() && $this->_match( self::REST_PART, '/Safari/i' ); } /** * Attempts to figure out if the specified user agent belongs to a version of * Firefox. */ public function is_firefox_browser() { return $this->_match( self::REST_PART, '/Firefox/i' ); } /** * Attempts to figure out if the specified user agent belongs to a device * running on a Windows version. */ public function is_windows_os() { return $this->_match( self::SYSTEM_PART, '/(Windows|WIN64)/i' ); } /** * Attempts to figure out if the specified user agent belongs to a device * running on a Linux version. */ public function is_android_os() { return $this->_match( self::SYSTEM_PART, '/Android/i' ); } /** * Attempts to figure out if the specified user agent belongs to a device * running on a Linux version. */ public function is_linux_os() { return !$this->is_android_os() && $this->_match( self::SYSTEM_PART, '/Linux/i' ); } /** * Attempts to figure out if the specified user agent belongs to a device * running on a Mac OS X version. */ public function is_mac_os() { return $this->_match( self::SYSTEM_PART, '/Mac OS X/i' ); } } <file_sep><?php class ZakenWebserviceModule extends WebserviceModule { private function _check_dossier_data() { // check global variables verify_data_members( array( 'GebruikerId', 'Kenmerk', 'OloNummer', 'Beschrijving', 'AanmaakDatum', 'GeplandDatum', 'AanvraagDatum', 'Adres', 'Opmerkingen', 'Subjecten' ), $this->_data ); // check adres variables if (!is_object( $this->_data->Adres )) throw new DataSourceException( 'Adres data veld is geen object.' ); verify_data_members( array( 'Adres', 'Postcode', 'Woonplaats', 'Kadastraal', 'Sectie', 'Nummer' ), $this->_data->Adres, 'adres gegevens in verzoek' ); // check subject variables if (!is_array( $this->_data->Subjecten )) throw new DataSourceException( 'Subjecten data veld is geen array.' ); foreach ($this->_data->Subjecten as $i => $subject) if (!is_object( $subject )) throw new DataSourceException( 'Subject ' . $i . ' is geen object.' ); else verify_data_members( array( 'Rol', 'Naam', 'Adres', 'Postcode', 'Woonplaats', 'Telefoon', 'Email' ), $subject, 'subject gegevens bij subject ' . $i . ' in verzoek' ); // check gebruiker $gebruiker = $this->CI->gebruiker->get( $this->_data->GebruikerId ); if (!$gebruiker) throw new DataSourceException( 'Ongeldige GebruikerId gespecifieerd.' ); // check klant access if (!$this->_account->mag_bij_klant( $gebruiker->klant_id )) throw new DataSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot klant van opgegeven gebruiker.' ); // check verplichte velden if (!$this->_data->Kenmerk) throw new DataSourceException( 'Leeg kenmerk (identificatienummer) niet toegestaan.' ); if (!$this->_data->Beschrijving) throw new DataSourceException( 'Lege beschrijving (dossiernaam) niet toegestaan.' ); if (!$this->_data->AanmaakDatum) $this->_data->AanmaakDatum = date( 'Y-m-d H:i:s' ); if (!$this->_data->GeplandDatum) $this->_data->GeplandDatum = null; if (!$this->_data->AanvraagDatum) $this->_data->AanvraagDatum = null; return $gebruiker; } public function DossierToevoegen() { // init $this->CI->load->model( 'dossier' ); // check dossier data, en haal gebruiker op $gebruiker = $this->_check_dossier_data(); // // bekijk of dit dossier al bestaat op basis van postcode en huisnummer // if (preg_match( '/\d+(\s*[0-9a-z\-]{0,7})?\s*$/i', $this->_data->Adres->Adres, $matches )) // { // $huisnummer = $matches[0]; // $huisnummer_clean = preg_replace( '/[\s\-]+/', '', $huisnummer ); // $postcode = $this->_data->Adres->Postcode; // $postcode_clean = preg_replace( '/[\s\-]+/', '', $postcode ); // // // kijk of we een dossier kunnen vinden dat bij de klant hoort van de gebruiker waar // // een dossier voor wordt toegevoegd, en dan met het opgegeven postcode en huisnummer // $dossiers = $this->CI->dossier->search( // /* fields */ array(), // /* extra query */ " // (TRIM(_T.locatie_adres) LIKE '%$huisnummer' OR TRIM(_T.locatie_adres) LIKE '%$huisnummer_clean') // AND // (TRIM(_T.locatie_postcode) = '$postcode' OR TRIM(_T.locatie_postcode) = '$postcode_clean') // AND // g.klant_id = '{$gebruiker->klant_id}' // ", // /* assoc */ false, // /* operator */ 'AND', // /* order_by */ '', // /* joins */ 'JOIN gebruikers g ON (_T.gebruiker_id = g.id)' // ); // if (!empty( $dossiers )) // { // if ($dossier = reset( $dossiers )) // { // $this->_output_json( $dossier->id ); // return; // } // } // } // start transactie if ($this->CI->db->_trans_depth != 0) throw new ServerSourceException( 'Interne fout, transactie diepte is niet 0.' ); $this->CI->db->_trans_status = true; $this->CI->db->trans_start(); // voeg dossier toe $this->CI->load->model( 'dossier' ); $dossier_id = $this->CI->dossier->add( $this->_data->Kenmerk, // kenmerk, $this->_data->Beschrijving, // beschrijving, strtotime( $this->_data->AanmaakDatum ), // aanmaak_datum /* unix timestamp */, $this->_data->Adres->Adres, // locatie_adres, $this->_data->Adres->Postcode, // locatie_postcode, $this->_data->Adres->Woonplaats, // locatie_woonplaats, $this->_data->Adres->Kadastraal, // locatie_kadastraal, $this->_data->Adres->Sectie, // locatie_sectie, $this->_data->Adres->Nummer, // locatie_nummer, //VERWIJDERD: $this->_data->AanvraagDatum ? date('Y-m-d', strtotime( $this->_data->AanvraagDatum ) ) : null, // aanvraag_datum /* mysql date */, $this->_data->Opmerkingen, // opmerkingen, '', // photo //VERWIJDERD: $this->_data->GeplandDatum ? date('Y-m-d', strtotime( $this->_data->GeplandDatum ) ) : null, // gepland_datum /* mysql date */, 'koppeling', // herkomst $this->_data->GebruikerId // gebruiker_id ); if (!$dossier_id || !($dossier = $this->CI->dossier->get( $dossier_id ))) throw new ServerSourceException( 'Interne fout, kon dossier niet aan database toevoegen.' ); $dossier->add_create_notificatie(); // zet dossier alsof het net gesynchronised is $this->CI->load->model( 'webserviceapplicatiedossier' ); if (!$this->CI->webserviceapplicatiedossier->zet( $this->_account->webservice_applicatie_id, $dossier_id, date('Y-m-d H:i:s') )) throw new ServerSourceException( 'Interne fout, kon dossier niet registreren als gesynchroniseerd.' ); // voeg subjecten toe $this->CI->load->model( 'dossiersubject' ); foreach ($this->_data->Subjecten as $subject) { if (!($nieuwsubject = $this->CI->dossiersubject->add( $dossier_id, $subject->Rol ))) throw new ServerSourceException( 'Interne fout, kon subject niet aan database toevoegen.' ); if (strlen($subject->Naam) || strlen($subject->Adres) || strlen($subject->Postcode) || strlen($subject->Woonplaats) || strlen($subject->Telefoon) || strlen($subject->Email)) { $nieuwsubject->naam = $subject->Naam; $nieuwsubject->adres = $subject->Adres; $nieuwsubject->postcode = $subject->Postcode; $nieuwsubject->woonplaats = $subject->Woonplaats; $nieuwsubject->telefoon = $subject->Telefoon; $nieuwsubject->email = $subject->Email; if (!$nieuwsubject->save()) throw new ServerSourceException( 'Interne fout, kon subject gegevens niet bijwerken in de database.' ); } } // rond transactie af if (!$this->CI->db->trans_complete()) throw new ServerSourceException( 'Interne fout, transactie kon niet worden gecommit.' ); $this->_output_json( $dossier_id ); } public function DossierBewerken() { // check dossier data, en haal gebruiker op $gebruiker = $this->_check_dossier_data(); // check dossier, en klant id matches verify_data_members( array( 'DossierId' ), $this->_data ); $this->CI->load->model( 'dossier' ); if (!($dossier = $this->CI->dossier->get( $this->_data->DossierId ))) throw new DataSourceException( 'Ongeldige DossierId gespecifieerd.' ); if ($dossier->gearchiveerd || $dossier->verwijderd) throw new DataSourceException( 'Opgegeven dossier is gearchiveerd of verwijderd, kan niet bewerken.' ); if ($dossier->get_gebruiker()->klant_id != $gebruiker->klant_id) throw new DataSourceException( 'Dossier hoort bij andere klant dan opgegeven gebruiker.' ); if ($dossier->herkomst != 'koppeling') throw new DataSourceException( 'Dossier is niet via de webservice aangemaakt, kan niet bijwerken via de webservice.' ); // start transactie if ($this->CI->db->_trans_depth != 0) throw new ServerSourceException( 'Interne fout, transactie diepte is niet 0.' ); $this->CI->db->_trans_status = true; $this->CI->db->trans_start(); // voeg dossier toe $this->CI->load->model( 'dossier' ); $dossier->kenmerk = $this->_data->Kenmerk; $dossier->beschrijving = $this->_data->Beschrijving; $dossier->aanmaak_datum = strtotime( $this->_data->AanmaakDatum ); $dossier->locatie_adres = $this->_data->Adres->Adres; $dossier->locatie_postcode = $this->_data->Adres->Postcode; $dossier->locatie_woonplaats = $this->_data->Adres->Woonplaats; $dossier->locatie_kadastraal = $this->_data->Adres->Kadastraal; $dossier->locatie_sectie = $this->_data->Adres->Sectie; $dossier->locatie_nummer = $this->_data->Adres->Nummer; //VERWIJDERD: $dossier->aanvraag_datum = $this->_data->AanvraagDatum ? date('Y-m-d', strtotime( $this->_data->AanvraagDatum ) ) : null; $dossier->opmerkingen = $this->_data->Opmerkingen; //VERWIJDERD: $dossier->gepland_datum = $this->_data->GeplandDatum ? date('Y-m-d', strtotime( $this->_data->GeplandDatum ) ) : null; $dossier->gebruiker_id = $this->_data->GebruikerId; if (!$dossier->save( true /*trans*/, null /*alias*/, false /* error_on_no_changes */ )) throw new ServerSourceException( 'Interne fout, kon dossier niet bijwerken in database.' ); // voeg subjecten opnieuw toe $this->CI->load->model( 'dossiersubject' ); foreach ($dossier->get_subjecten() as $subject) $subject->delete(); foreach ($this->_data->Subjecten as $subject) { if (!($nieuwsubject = $this->CI->dossiersubject->add( $dossier->id, $subject->Rol ))) throw new ServerSourceException( 'Interne fout, kon subject niet aan database toevoegen.' ); if (strlen($subject->Naam) || strlen($subject->Adres) || strlen($subject->Postcode) || strlen($subject->Woonplaats) || strlen($subject->Telefoon) || strlen($subject->Email)) { $nieuwsubject->naam = $subject->Naam; $nieuwsubject->adres = $subject->Adres; $nieuwsubject->postcode = $subject->Postcode; $nieuwsubject->woonplaats = $subject->Woonplaats; $nieuwsubject->telefoon = $subject->Telefoon; $nieuwsubject->email = $subject->Email; if (!$nieuwsubject->save()) throw new ServerSourceException( 'Interne fout, kon subject gegevens niet bijwerken in de database.' ); } } // zet dossier alsof het net gesynchronised is $this->CI->load->model( 'webserviceapplicatiedossier' ); if (!$this->CI->webserviceapplicatiedossier->zet( $this->_account->webservice_applicatie_id, $dossier->id, date('Y-m-d H:i:s') )) throw new ServerSourceException( 'Interne fout, kon dossier niet registreren als gesynchroniseerd.' ); // rond transactie af if (!$this->CI->db->trans_complete()) throw new ServerSourceException( 'Interne fout, transactie kon niet worden gecommit.' ); $this->_output_json( intval( $dossier->id ) ); } public function DossierBescheidenToevoegen() { $this->locallog( 'DossierBescheidenToevoegen' ); // check global variables verify_data_members( array( 'DossierId', 'TekeningStukNummer', 'Auteur', 'Omschrijving', 'DatumLaatsteWijziging', 'BestandsNaam', 'Bestand' ), $this->_data ); // check data if (!$this->_data->Bestand || !$this->_data->BestandsNaam) throw new DataSourceException( 'Onvolledige bestandsinformatie.' ); $bestand = @base64_decode( $this->_data->Bestand ); if ($bestand === false) throw new DataSourceException( 'Kon bestand niet base64-decoden.' ); // check access $this->CI->load->model( 'dossier' ); //$this->CI->load->model( 'deelplan' ); $this->CI->load->model( 'deelplanbescheiden' ); $this->CI->load->model( 'dossierbescheiden' ); $dossier = $this->CI->dossier->get( $this->_data->DossierId ); if (!$dossier) throw new DataSourceException( 'Ongeldige DossierId gespecifieerd.' ); if ($dossier->gearchiveerd || $dossier->verwijderd) throw new DataSourceException( 'Opgegeven dossier is gearchiveerd of verwijderd, kan geen bescheiden toevoegen.' ); if ($dossier->herkomst != 'koppeling') throw new DataSourceException( 'Dossier is niet via de webservice aangemaakt, kan niet bewerken via de webservice.' ); // check klant access if (!$this->_account->mag_bij_klant( $dossier->get_gebruiker()->klant_id )) throw new DataSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot klant van opgegeven dossier.' ); // start transactie if ($this->CI->db->_trans_depth != 0) throw new ServerSourceException( 'Interne fout, transactie diepte is niet 0.' ); $this->CI->db->_trans_status = true; $this->CI->db->trans_start(); // voeg bescheiden toe aan dossier $this->locallog( 'DossierBescheidenToevoegen: aanmaken van dossierbescheiden' ); if (!($dossierbescheiden = $this->CI->dossierbescheiden->add( $dossier->id ))) throw new ServerSourceException( 'Interne fout, kon bescheiden niet aan database toevoegen.' ); $dossierbescheiden->tekening_stuk_nummer = $this->_data->TekeningStukNummer; $dossierbescheiden->auteur = $this->_data->Auteur; $dossierbescheiden->omschrijving = $this->_data->Omschrijving; $dossierbescheiden->datum_laatste_wijziging = $this->_data->DatumLaatsteWijziging; $dossierbescheiden->bestandsnaam = $this->_data->BestandsNaam; $dossierbescheiden->bestand = $bestand; // base64 decoded if (!$dossierbescheiden->save()) throw new ServerSourceException( 'Interne fout, kon bescheiden gegevens niet bijwerken in de database.' ); // zet bescheiden alsof net gesynchronised is $this->locallog( 'DossierBescheidenToevoegen: aanmaken van webserviceapplicatiebescheiden' ); $this->CI->load->model( 'webserviceapplicatiebescheiden' ); if (!$this->CI->webserviceapplicatiebescheiden->zet( $this->_account->webservice_applicatie_id, $dossierbescheiden->id, date('Y-m-d H:i:s') )) throw new ServerSourceException( 'Interne fout, kon dossier niet registreren als gesynchroniseerd.' ); // Now automatically add the bescheiden to each of the 'deelplannen' of the dossier. $this->locallog( 'DossierBescheidenToevoegen: automatisch koppelen van bescheiden aan alle onderliggende deelplannen' ); // First get all of the current 'dossierbescheiden' for the dossier (this includes the one that was just added). $dossierBescheidenen = $this->CI->dossierbescheiden->get_by_dossier($dossier->id, true); $dossierBescheidenenIds = array_keys($dossierBescheidenen); // Then get all of the 'deelplannen' of the dossier. $dossierDeelplannen = $dossier->get_deelplannen(); // Now loop over the deelplannen, assigning the dossierbescheiden to each one of them. foreach($dossierDeelplannen AS $dossierDeelplan) { // Get the currently assigned documents for this deelplan $currentlyAssignedDeelplanBescheidenen = $this->CI->deelplanbescheiden->get_by_deelplan($dossierDeelplan->id); // Now use the model to assign the proper set of documents to the deelplan. $this->CI->deelplanbescheiden->set_for_deelplan($dossierDeelplan->id, $dossierBescheidenenIds, $currentlyAssignedDeelplanBescheidenen); } // rond transactie af $this->locallog( 'DossierBescheidenToevoegen: afronden van transactie' ); if (!$this->CI->db->trans_complete()) throw new ServerSourceException( 'Interne fout, transactie kon niet worden gecommit.' ); // done $this->locallog( 'DossierBescheidenToevoegen: output van id' ); $this->locallog( 'DossierBescheidenToevoegen: output van id waarde=' . $dossierbescheiden->id ); $this->_output_json( $dossierbescheiden->id ); } public function DossierBescheidenVerwijderen() { // check global variables verify_data_members( array( 'DossierId', 'DossierBescheidenId' ), $this->_data ); // check bescheiden id $this->CI->load->model( 'dossier' ); $dossier = $this->CI->dossier->get( $this->_data->DossierId ); if (!$dossier) throw new DataSourceException( 'Ongeldige DossierId gespecifieerd.' ); if ($dossier->gearchiveerd || $dossier->verwijderd) throw new DataSourceException( 'Opgegeven dossier is gearchiveerd of verwijderd, kan geen bescheiden toevoegen.' ); if ($dossier->herkomst != 'koppeling') throw new DataSourceException( 'Dossier is niet via de webservice aangemaakt, kan niet bewerken via de webservice.' ); // check klant access if (!$this->_account->mag_bij_klant( $dossier->get_gebruiker()->klant_id )) throw new DataSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot klant van opgegeven dossier.' ); // check dossier bescheiden id $this->CI->load->model( 'dossierbescheiden' ); $dossierbescheiden = $this->CI->dossierbescheiden->get( $this->_data->DossierBescheidenId ); if (!$dossierbescheiden) throw new DataSourceException( 'Ongeldige DossierBescheidenId gespecifieerd.' ); if ($dossierbescheiden->dossier_id != $dossier->id) throw new DataSourceException( 'Opgegeven dossier bescheiden hoort niet bij het opgegeven dossier.' ); // start transactie if ($this->CI->db->_trans_depth != 0) throw new ServerSourceException( 'Interne fout, transactie diepte is niet 0.' ); $this->CI->db->_trans_status = true; $this->CI->db->trans_start(); // delete! if (!$dossierbescheiden->delete()) throw new ServerSourceException( 'Interne fout, kon bescheiden niet verwijderen uit de database.' ); // rond transactie af if (!$this->CI->db->trans_complete()) throw new ServerSourceException( 'Interne fout, transactie kon niet worden gecommit.' ); $this->_output_json( $dossierbescheiden->id ); } public function DossierArchiveren() { // check dossier verify_data_members( array( 'DossierId' ), $this->_data ); $this->CI->load->model( 'dossier' ); if (!($dossier = $this->CI->dossier->get( $this->_data->DossierId ))) throw new DataSourceException( 'Ongeldige DossierId gespecifieerd.' ); if ($dossier->gearchiveerd || $dossier->verwijderd) throw new DataSourceException( 'Opgegeven dossier is reeds gearchiveerd of verwijderd.' ); if ($dossier->herkomst != 'koppeling') throw new DataSourceException( 'Dossier is niet via de webservice aangemaakt, kan niet archiveren via de webservice.' ); // archiveer! $dossier->archiveer(); // done! $this->_output_json( intval( $dossier->id ) ); } } WebserviceModule::register_module( WS_COMPONENT_ZAKEN_KOPPELING, new ZakenWebserviceModule() ); <file_sep><?php function table_sort_move( Model $model, $id, $direction /* must be either <0, or >0, never 0! */, $where='1', $sortfield='sortering' ) { $CI = get_instance(); $db = $CI->db; // find object to move up $object = $model->get( $id ); if (!$object) return false; // find current value for sortfield $curSortField = intval( $object->$sortfield ); // find next in line, either up or down if ($direction > 0) $res = $db->query( 'SELECT id FROM ' . $model->get_table() . ' WHERE ' . $sortfield . ' > ' . $curSortField . ' AND (' . $where . ') ORDER BY ' . $sortfield . ' ASC LIMIT 1' ); else if ($direction < 0) $res = $db->query( 'SELECT id FROM ' . $model->get_table() . ' WHERE ' . $sortfield . ' < ' . $curSortField . ' AND (' . $where . ') ORDER BY ' . $sortfield . ' DESC LIMIT 1' ); else // direction == 0... return false; if (!$res) throw new Exception( 'Fout bij herstructuren van sorteringswaarden.' ); // if we have no result, this item is already the lowest, or highest value if (!$res->num_rows()) return false; // fetch the other object $otherId = reset( $res->result() )->id; $res->free_result(); $otherObject = $model->get( $otherId ); if (!$otherObject) return false; // really shouldn't happen, but fail silently // switch the values $object->$sortfield = $otherObject->$sortfield; $otherObject->$sortfield = $curSortField; $object->save(); $otherObject->save(); return true; } <file_sep><?php class CI_Settings { var $settings; var $descriptions; public function CI_Settings() { $CI = get_instance(); foreach ($CI->db->get( 'settings' )->result() as $setting) { $this->settings[ $setting->key ] = $setting->value; $this->descriptions[ $setting->key ] = $setting->description; } } public function get( $key ) { return isset($this->settings[$key]) ? $this->settings[$key] : null; } public function set( $key, $value, $do_transaction=true ) { // if trans is failing anyways, why bother? $CI = get_instance(); if (!$do_transaction && !$CI->db->_trans_status) return; // prepare if (!$CI->dbex->is_prepared( 'update_setting' )) $CI->dbex->prepare( 'update_setting', 'UPDATE settings SET value = ? WHERE key = ?' ); if (!$CI->dbex->is_prepared( 'add_setting' )) $CI->dbex->prepare( 'add_setting', 'INSERT INTO settings (value, key) VALUES (?, ?)' ); $args = array( $value, $key ); // execute transaction if ($do_transaction) $CI->db->trans_start(); $stored = $CI->dbex->execute( 'add_setting', $args, TRUE )===TRUE; if (!$stored) { $CI->db->_trans_status = TRUE; $stored = $CI->dbex->execute( 'update_setting', $args, FALSE )===TRUE; if ($stored) $stored = $CI->db->affected_rows()==1; } if ($do_transaction) $CI->db->trans_complete(); // did we store? if ($stored) $this->settings[$key] = $value; return $stored; } public function all() { return array( 'settings' => $this->settings, 'descriptions' => $this->descriptions ); } }<file_sep><? require_once 'base.php'; class GrondslagResult extends BaseResult { function GrondslagResult( &$arr ) { parent::BaseResult( 'grondslag', $arr ); } public function get_klant() { $CI = get_instance(); return $CI->klant->get( $this->klant_id ); } public function get_teksten() /* list of GrondslagTekst objects */ { $CI = get_instance(); $CI->load->model( 'grondslagtekst' ); return $CI->grondslagtekst->search( array( 'grondslag_id' => $this->id ), null, false, 'AND', 'artikel' ); } } class Grondslag extends BaseModel { function Grondslag() { parent::BaseModel( 'GrondslagResult', 'bt_grondslagen' ); } public function check_access( BaseResult $object ) { // disable for now // see /deelplannen/wettelijke_grondslag/XXX return; } public function add( $grondslag, $klant_id=null ) { /* $db = $this->get_db(); $this->dbex->prepare( 'Grondslag::add', 'INSERT INTO bt_grondslagen (grondslag, klant_id, quest_document) VALUES (?, ?, ?)', $db ); $args = array( 'grondslag' => $grondslag, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, 'quest_document' => NULL ); $this->dbex->execute( 'Grondslag::add', $args, false, $db ); $args['id'] = $db->insert_id(); return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'grondslag' => $grondslag, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, 'quest_document' => NULL ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function add_conditional( $grondslag, $klant_id=null ) { $g = $this->find( $grondslag, $klant_id ); if ($g) return $g; return $this->add( $grondslag, $klant_id ); } public function find( $grondslag, $klant_id=null ) { $db = $this->get_db(); $this->dbex->prepare( 'Grondslag::find', 'SELECT * FROM bt_grondslagen WHERE grondslag = ? AND klant_id = ?', $db ); $args = array( $grondslag, $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $res = $this->dbex->execute( 'Grondslag::find', $args, false, $db ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function get_for_huidige_klant( $assoc=false ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE klant_id = ? ORDER BY grondslag' ); $res = $CI->dbex->execute( $stmt_name, array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[$row->id] = $this->getr( $row, false ); return $result; } public function get_gebruikte_grondslagen() { return $this->convert_results( $this->_CI->db->query( ' SELECT * FROM bt_grondslagen WHERE id IN ( SELECT DISTINCT(grondslag_id) FROM bt_grondslag_teksten ) ORDER BY grondslag ') ); } } <file_sep><?php require_once 'base.php'; class ArtikelvraagmapResult extends BaseResult{ public function ArtikelvraagmapResult( &$arr ){ parent::BaseResult( 'artikelvraagmap', $arr ); } }//Class end class Artikelvraagmap extends BaseModel{ public function Artikelvraagmap(){ parent::BaseModel( 'ArtikelvraagmapResult', 'artikel_vraag_mappen' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_artikel_vragen( $artikelId, $assoc=false ){ $result = array(); $vragen = $this->db ->where('artikel_id', $artikelId ) ->get( $this->_table ) ->result(); foreach( $vragen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function add( $mapchecklistId, $btRisicoId, $artikelId, $vraagId, $isActive=TRUE ){ $data = array( 'map_checklist_id' => $mapchecklistId, 'bt_riskprofiel_id' => $btRisicoId, 'artikel_id'=> $artikelId, 'vraag_id' => $vraagId, 'is_active' => $isActive, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function delete_by_artikel_vraag( $mapchecklistId, $artikelId=null, $vraagId=null ){ $result = TRUE; $result = $this->db ->where('map_checklist_id', $mapchecklistId ); if($artikelId != null) $result = $this->db ->where('artikel_id', $artikelId ); if($vraagId != null) $result = $this->db ->where('vraag_id', $vraagId ); $result = $this->db ->delete( $this->_table ) ; return $result; } //TODO: Depricated. Replace this method by get_artikel_vraag_mappingen. public function get_by_vraag( $matrixmapId, $vraagId, $assoc=false ){ $result = array(); $vragen = $this->db ->where('matrix_id', $matrixmapId ) ->where('vraag_id', $vraagId ) ->get( $this->_table ) ->result(); foreach( $vragen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_matrixmapping_vragen( $matrixId, $btRpId, $assoc=false ){ $result = array(); $vragen = $this->db ->where('matrix_id', $matrixId ) ->where('bt_riskprofiel_id', $btRpId ) ->get( $this->_table ) ->result(); foreach( $vragen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_risicoprofilen_list_map_by_matrix( $matrixId, $assoc=false ){ $result = array(); $mappen = $this->db->select($this->_table.'.id AS id,map_checklist_id,bt_riskprofiel_id,artikel_id,vraag_id,is_active,matrixmap_id AS matrix_id') ->join('matrixmap_checklisten', 'matrixmap_checklisten.id = '.$this->_table.'.map_checklist_id', 'left' ) ->where('matrixmap_id', $matrixId ) ->group_by('bt_riskprofiel_id') ->get( $this->_table ) ->result(); foreach( $mappen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_artikel_vraag_mappingen( $matrixmapId, $vraagId=NULL, $assoc=false ){ $result = array(); $list = $this->db ->where('matrix_id', $matrixmapId ); if( $vraagId != NULL ){ $list = $this->db ->where('vraag_id', $vraagId ); } $list = $this->db ->get( $this->_table ) ->result(); foreach( $list as $row ){ $row = $this->getr( $row ); ($assoc) ? $result[$row->id] = $row : $result[] = $row; } return $result; } }//Class end<file_sep>-- yes, no key on gebruiker_id / klant_id, don't want to fail on that data! CREATE TABLE IF NOT EXISTS `app_error_reports` ( `id` int(11) NOT NULL AUTO_INCREMENT, `versie` varchar(5) NOT NULL, `datum` datetime NOT NULL, `request_duur` int(11) NOT NULL, `request_url` varchar(256) NOT NULL, `request_type` varchar(4) NOT NULL, `request_body` text NOT NULL, `response_body` text NOT NULL, `response_parseable` tinyint(4) NOT NULL, `gebruiker_id` int(11) DEFAULT NULL, `klant_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; <file_sep><?php class BRIS_HttpResponse_Passport extends BRIS_HttpResponse_Abstract { public function getAnyPhone() { if( isset($this->PhoneMobile) ) { return $this->PhoneMobile; } elseif( isset($this->PhoneBusiness) ) { return $this->PhoneBusiness; } elseif( isset($this->PhoneHome) ) { return $this->PhoneHome; } else { return null; } } public function getName() { $name = trim(trim($this->FirstName . ' ' . $this->MiddleName) . ' '. $this->LastName); if( $name == '') { return $this->DisplayName; } return $name; } } <file_sep><?php define( 'BRIS_TOEZICHT_VERSION', '3.2.1' ); define( 'BRIS_TOEZICHT_RELEASE_DATE', '07-09-2015' ); <file_sep><?php /** * Code obtained from AbiSource Corporation B.V. with the consent of <NAME>. */ require_once(BASEPATH.'database/DB_result'.EXT); /** * Helper class for using/manipulating the MySQLi results. */ class CI_DB_mysqli_prep_stmt_result extends CI_DB_result { var $statement = null; var $data = array(); function __construct($statement) { $this->statement = $statement; $this->num_rows = $this->num_rows(); } /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mysqli_stmt_num_rows( $this->statement ); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mysqli_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mysqli_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // Deprecated function field_names() { return $this->list_fields(); } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mysqli_fetch_field($this->result_id)) { $F = new stdClass(); $F->name = $field->name; $F->type = $field->type; $F->default = $field->def; $F->max_length = $field->max_length; $F->primary_key = ($field->flags & MYSQLI_PRI_KEY_FLAG) ? 1 : 0; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { mysqli_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mysqli_stmt_data_seek ( $this->statement, $n ); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { $res = mysqli_stmt_fetch( $this->statement ); if ($res===TRUE) { $arr = array(); foreach ($this->data as $k => $v) $arr[$k] = $v; return $arr; } return FALSE; } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { $res = mysqli_stmt_fetch( $this->statement ); if ($res===TRUE) { $obj = new stdClass(); foreach ($this->data as $k => $v) $obj->$k = $v; return $obj; } return FALSE; } } // class CI_DB_mysqli_prep_stmt_result extends CI_DB_result /** * Helper class for using/manipulating the oci8 (Oracle) results. */ class CI_DB_oci8_prep_stmt_result extends CI_DB_result { var $data = array(); var $num_rows = 0; var $numfields = 0; var $cur_idx = 0; var $column_names = array(); //function __construct($statement) function __construct(&$statement) { //echo "+++ CI_DB_oci8_prep_stmt_result __construct<br />\n"; //int oci_fetch_all ( resource $statement , array &$output [, int $skip = 0 [, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC ]]] ) // oci_fetch_all($statement, $this->data, 0, -1, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC); //echo "+++ statement +++<br />"; //d($statement); $data_with_uppercase_column_names = array(); oci_fetch_all($statement, $data_with_uppercase_column_names, 0, -1, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC); //echo "+++ CI_DB_oci8_prep_stmt_result upper case columns data:\n"; // d($data_with_uppercase_column_names); //echo "+++ CI_DB_oci8_prep_stmt_result lower case columns data:\n"; foreach($data_with_uppercase_column_names as $data_with_uppercase_column_names_row) { $data_with_lowercase_column_names_row = array(); foreach ($data_with_uppercase_column_names_row as $column_name_upper_case => $column_data) { $column_name_lower_case = strtolower($column_name_upper_case); $data_with_lowercase_column_names_row["$column_name_lower_case"] = $column_data; } $this->data[] = $data_with_lowercase_column_names_row; } // d($this->data); $this->num_rows = oci_num_rows( $statement ); //d($this->num_rows); $this->numfields = oci_num_fields( $statement ); for ($i = 1; $i <= $this->numfields; $i++) { // $column_name = oci_field_name($statement, $i); // !!! Note: the column names are stored using uppercase letters! We probably want to change that to lowercase! $column_name = strtolower(oci_field_name($statement, $i)); // !!! Note: the column names are stored using uppercase letters! We probably want to change that to lowercase! //$column_type = oci_field_type($statement, $i); //$column_size = oci_field_size($statement, $i); $this->column_names[] = $column_name; } /* echo '+++ CI_DB_oci8_prep_stmt_result :: __construct : before freeing statement +++ <br />'; d($statement); d(is_resource($statement)); d(get_resource_type($statement)); d(is_resource($statement) && (get_resource_type($statement) == 'oci8 statement') ); * */ oci_free_statement( $statement ); /* echo '+++ CI_DB_oci8_prep_stmt_result :: __construct : after freeing statement +++ <br />'; d($statement); d(is_resource($statement)); d(get_resource_type($statement)); d(is_resource($statement) && (get_resource_type($statement) == 'oci8 statement') ); exit; * */ } /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return $this->num_rows; //return oci_num_rows( $this->statement ); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return $this->numfields; //return oci_num_fields( $this->statement ); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { return $this->column_names; } // Deprecated function field_names() { return $this->list_fields(); } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { throw new Exception('Not implemented (field_data) -- not needed?.'); } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { // No action needed in Oracle? unset($this->data); } /** * Resets the result such that it doesn't re-use previously executed statements/data. * * @return null */ function reset_result() { //echo "+--+ CI_DB_oci8_prep_stmt_result :: reset_result<br />\n"; //return oci_free_statement( $this->statement ); // No action needed in Oracle? //unset($this->data); } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { //throw new Exception('Not implemented (_data_seek) -- not needed?.'); $this->cur_idx = $n; } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { if ($this->cur_idx < $this->num_rows) { return $this->data[$this->cur_idx++]; } else { return false; } } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { if ($this->cur_idx < $this->num_rows) { return (object)$this->data[$this->cur_idx++]; } else { return false; } //return oci_fetch_object ( $this->statement ); } } // class CI_DB_oci8_prep_stmt_result extends CI_DB_result /** * Database extension class that supports prepared statements. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author Marc 'Foddex' <NAME> * @link http://www.foddex.net/ */ class CI_DBEx { var $CI; var $statements = array(); var $use_oracle = false; var $use_mysqli = false; function CI_DBEx() { $this->CI =& get_instance(); $this->CI->load->database(); // Determine which DB is used $this->use_oracle = ($this->CI->db instanceof CI_DB_oci8_driver); $this->use_mysqli = ($this->CI->db instanceof CI_DB_mysqli_driver); } function unprepare_all() { $this->statements = array(); } /** * Prepares a REPLACE INTO SQL statement with the specified name. Returns true * when the statement was successfully prepared. Returns false otherwise. * Note 1: the application already uses a lot of SQL statements that are MySQL based, they have the following syntax: * REPLACE INTO <table_name> (col_name1, col_name2, ...) VALUES (?, ?, ...) * For backwards compatibility with the normal 'prepare' method, the way to call this 'prepare_replace_into' method is kept 100% * backwards compatible with this simple MySQL syntax, hence making the MySQLi implementation straightforward, and making other implementations * specific to the syntax that is required in the other DBs. * Note 2: the $key_columns parameter is not needed for MySQL (hence, the MySQL implementation ignores it), for other DBs such as Oracle it is handy though * to indicate which columns to match on, a thing which otherwise would require trickery by checking the respective table's key columns */ function prepare_replace_into( $statement_name, $statement_sql, $db=null, $key_columns = array() ) { if ($this->use_mysqli) { // We are using MySQL, use the normal 'prepare' method without further modifications. return $this->prepare( $statement_name, $statement_sql, $db ); } else { // We are using a different DB than MySQL, use an adapted syntax, so we end up with a valid compatible statement. // As a default, assume the MySQL syntax also works for the other DB we are using, and override the syntax in case it is not compatible. $adapted_statement_sql = $statement_sql; // Oracle is incompatible with the MySQL syntax, so we need to rewrite it. if ($this->use_oracle) { //echo "=== DBEX::prepare_replace_into Oracle implementation<br />\n"; //d($statement_sql); // Replace multiple whitespaces with single ones $statement_sql = preg_replace("|\s+|", ' ', trim($statement_sql)); //d($statement_sql); //d($key_columns); // Extract the 'values' so we can use them further ahead for checking if we need to use a question mark (for a prepared parameter) // or a direct value. Note: so as to not accidentally eliminate spaces that appear as part of a string, we must make sure to // only remove the leading and trailing whitespaces of each of the 'values' parts, rather than doing a complete str_replace like is done for the columns. preg_match("|VALUES\s*\((.*)\)|smi", $statement_sql, $matches); //d($matches); $values_str = $matches[1]; //$values = explode(',',str_replace(' ', '', $values_str)); $values_with_leading_and_trailing_whitespaces = explode(',', $values_str); //d($values_with_leading_and_trailing_whitespaces); // Make sure to trim the question marks and direct values of leading and trailing whitespace, without removing whitespace that // may appear in the values themselves. $values = array(); foreach ($values_with_leading_and_trailing_whitespaces as $value_with_leading_and_trailing_whitespaces) { $values[] = trim($value_with_leading_and_trailing_whitespaces); } //d($values); // Further strip the SQL, remove the 'REPLACE INTO ' and 'VALUES...' parts. // After these two statements, the base SQL should be reduced to precisely: "<table_name> (<col_name1>, <col_name2>, ...)" $stripped_statement_sql = str_ireplace('REPLACE INTO ', '', $statement_sql); $stripped_statement_sql = trim(preg_replace("|\s*VALUES.*|smi", '', $stripped_statement_sql)); // The 'trim' should not be needed, but just in case... //d($stripped_statement_sql); // Extract the table name and column names. preg_match("|(\w+)\s\((.*)\)|", $stripped_statement_sql, $matches); // d($matches); $table_name = $matches[1]; $columns_str = $matches[2]; $columns = explode(',',str_replace(' ', '', $columns_str)); //echo "table name: *{$table_name}*<br />\n"; //echo "columns: *{$columns_str}*<br />\n"; //d($columns); // Construct the 'fields' part, including '?' parameter placeholders. // Use the same loop to construct the update and insert assignment parts too $fields_parts = array(); $update_assignment_parts = array(); $insert_assignment_parts = array(); $column_cnt = 0; foreach ($columns as $column) { //$fields_parts[] = "? {$column}"; $fields_parts[] = $values[$column_cnt++] . " {$column}"; // Note: make sure to ONLY update the non-key columns! Otherwise, an Oracle error will occur! if (!in_array($column, $key_columns)) { $update_assignment_parts[] = "{$table_name}.{$column} = val.{$column}"; } $insert_assignment_parts[] = "val.{$column}"; } $fields_str = implode(', ', $fields_parts); $update_assignments_str = implode(', ', $update_assignment_parts); $insert_assignments_str = implode(', ', $insert_assignment_parts); // Construct the 'key columns' part. $key_columns_parts = array(); foreach ($key_columns as $key_column) { $key_columns_parts[] = "{$table_name}.{$key_column} = val.{$key_column}"; } $key_columns_str = implode(' AND ', $key_columns_parts); // Now put all the pieces together, generically constructing an Oracle compatible query. $adapted_statement_sql = " MERGE INTO {$table_name} USING ( SELECT {$fields_str} FROM dual ) val ON ( {$key_columns_str} ) WHEN MATCHED THEN UPDATE SET {$update_assignments_str} WHEN NOT MATCHED THEN INSERT ({$columns_str}) VALUES ({$insert_assignments_str}) "; //echo "Final Oracle statement SQL:<br />\n"; //d($adapted_statement_sql); //echo $adapted_statement_sql . "<br />\n"; //exit; } // if ($this->use_oracle) // Now that we have rewritten the SQL statement to a compatible format, use the normal 'prepare' method without further modifications. return $this->prepare( $statement_name, $adapted_statement_sql, $db ); } } /** * Prepares an SQL statement with the specified name. Returns true * when the statement was successfully prepared. Returns false otherwise. */ public function prepare( $statement_name, $statement_sql, $db=null ) { //echo '+++ DBEX::Prepare<br />'; //'UserSessionDatabaseStorageHandler::read' //d($statement_sql); if (!$db) $db = $this->CI->db; if ($this->use_mysqli) { // Handle the preparing step the MySQLi way, using '?' parameters. $statement = mysqli_prepare( $db->conn_id, $statement_sql ); //d($statement); } else if ($this->use_oracle) { // Oracle doesn't use '?' mark style parameters. Binding also only seems to be supported by explicit names, so we pre-parse the // SQL of the statement ourselves in order to replace the question marks by generic ':p1', ':p2', ... etc. parameters. // Explode the statement into parts, using the '?' as a delimiter $statement_parts = explode('?', $statement_sql); // The 'parts' will always contain at least one entry, which is the entire statement in case no parameters are used. Therefore, start out // with only that part, and chain in parameters for each (if any) subsequent part. $statement_sql = array_shift($statement_parts); // Chain in the other parts, delimited by the generated generic parameter names. $param_cnt = 0; // Note: DON'T use the commented out while style, as it doesn't work on SQL that ends in a '?' because the final empty string is not // recognised as being precisely that and causes the while loop to terminate without processing that last empty string!!! //while ($statement_part = array_shift($statement_parts)) foreach ($statement_parts as $statement_part) { $statement_sql .= ':p'.++$param_cnt . $statement_part; } // Prepare the pre-parsed statement $statement = oci_parse($db->conn_id, $statement_sql); } if ($statement===FALSE) { if ($db->db_debug) { echo 'ERROR: ' . $db->_error_message(); echo '<pre>'; debug_print_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); echo '</pre>'; } else return FALSE; } $this->statements[ $statement_name ] = array( 'sql' => $statement_sql, 'stmt' => $statement, ); //d($this->statements); return TRUE; } /** * Prepares an SQL statement with the specified name. Returns true when the statement was successfully prepared. Returns false otherwise. * This method is basically a combination of the normal 'prepare' method and the 'bind_parameter_with_return_value' method, * it is used in particular in Oracle for having a mechanism to easily perform 'generic' insert queries, that result in an * autoincrement value being set, and to have access to that "last inserted ID" value without too much effort. */ function prepare_with_insert_id( $statement_name, $statement_sql, $db=null, &$last_insert_id, $id_column_name = 'ID' ) { // Initialise the 'last inserted ID' to 0. The value of this variable is only relevant for Oracle. MySQL doesn't need any of this. $last_insert_id = 0; // For Oracle we need to have the insert query make use of a return value to handily obtain (and have access to) the "last inserted ID". if ($this->use_oracle) { // Unconditionally chain in the 'RETURN' part to the query. For queries that already feature a return value, this method should // (probably) not be used. $statement_sql .= " return {$id_column_name} into :last_insert_id"; // Prepare the query the normal way and keep the outcome of it as the return value $prepare_result = $this->prepare($statement_name, $statement_sql, $db); // When the query has been prepared, we bind the 'return_value' parameter to the prepared result parameter (i.e. 'last_insert_id'). $bind_result = $this->bind_parameter_with_return_value($statement_name, ":last_insert_id", $last_insert_id, 10, SQLT_INT); // Return the result of the query preparation combined with the result of binding the return parameter. return ($prepare_result && $bind_result); } else { // For the non-Oracle databases we do not need the above trickery in order to easily hava access to the "last inserted ID" // (or at least in MySQL we don't), so just call the normal prepare method for those DBs. return $this->prepare($statement_name, $statement_sql, $db); } } /** * Unprepares a statement. Returns True when a statement was actually * successfully unprepared. Returns false value. */ function unprepare( $statement_name ) { if ($this->is_prepared( $statement_name )) { if ($this->use_mysqli) { return mysqli_stmt_close( $this->statements[ $statement_name ]['stmt'] ); } else if ($this->use_oracle) { return oci_free_statement( $this->statements[ $statement_name ]['stmt'] ); } } return FALSE; } /** * Allows manual binding of a prepared parameter that results in the $return_value parameter containing the DB value after execution. * Returns a boolean to indicate if the parameter binding went successfully or not. */ function bind_parameter_with_return_value($statement_name, $bind_name, &$return_value, $length, $bind_type) { if ($this->use_oracle) { $statement = &$this->statements[ $statement_name ]; return oci_bind_by_name($statement['stmt'], $bind_name, $return_value, $length, $bind_type); } else { return true; } } // Calls 'execute' with the proper debug level set and a variable amount of parameters. function execute_debug( $debug_level, $statement_name, $data_array, $may_fail=false, $db=null, $force_types = '' ) { // Simply calls 'execute' with the passed level. This method allows for quicker typing, as it's not necessary to repeat the optional parameters in the call. return $this->execute($statement_name, $data_array, $may_fail, $db, $force_types, $debug_level); } /** * Executes a prepared statement. Checks if the specified amount of elements * in the data array matches the amount of ?'s found when prepare()-ing the * statement. * Returns false when the statement name was not valid (i.e. not prepare()-d in * this session), when the query failed, or when the amount of params is invalid. * Returns a normal CI query result object otherwise. */ function execute( $statement_name, $data_array, $may_fail=false, $db=null, $force_types = '', $debug_level = 0 ) { // For scrutinously debugging Oracle queries, we make use of debugging levels. In due time (i.e. when everything is stable enough, we can remove // all debugging information. When debugging is globally enabled, a LOT of locations trigger output. If this is not desired, simply add a specific suffix // to the statement name by which it is prepared to let this method automatically apply the proper debug level to that particular statement. // Note: as of yet the debug traces are only implemented up to the point where they were needed. They can be extended as the need arises. Note also that // at present the debug level 1 doesn't do anything yet, other than marking the entry and exit moments. // Usage possibilities: // -Global debugging of ALL execute statements. Simply set te $debug_level variable to the desired value in the start of this method. // -Pass the value explicitly in this methods call. // -Call the 'execute_debug' wrapper method, with the desired level as the first parameter. // -Add a specific 'debug level' suffix to the statement name (this is not the preferred method). // // Levels: // 0: None. // 1: Critical data only. // 2: Show more information, including the flow through the various steps. // 3: Verbose informaton, show everything. if (substr($statement_name, -15) == '_debug_critical') { $debug_level = 1; } else if (substr($statement_name, -13) == '_debug_medium') { $debug_level = 2; } else if (substr($statement_name, -14) == '_debug_verbose') { $debug_level = 3; } // At this point an overriding debug level can be set, that switches ALL traces to the desired level, regardless of what way they are being called. //$debug_level = 3; if ($debug_level > 0) { echo '>>> DBex execute (entering method) <<<' . "<br />\n"; if ($debug_level > 1) { echo '+++ 1 +++' . "<br />\n"; } if ($debug_level > 2) { echo "Statement name: '{$statement_name}'<br />\n"; echo "Data array:"; d($data_array); echo "May fail?: " . ($may_fail ? 'yes' : 'no') . "<br />\n"; echo "DB connection passed?: " . (is_null($db) ? 'no' : 'yes') . "<br />\n"; echo "Force types: '{$force_types}'<br />\n"; } } global $__RequestTimer; // Create a data set that is used to hold all references to LOB columns (Oracle). $lobs = array(); if (!$db) { $db = $this->CI->db; } if ($debug_level > 1) { echo '+++ 2 +++' . "<br />\n"; } // check if we know this statement if (!$this->is_prepared( $statement_name )) { if ($debug_level > 1) { echo '+++ 3 +++' . "<br />\n"; } if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } $db->_trans_status = FALSE; return FALSE; } if ($debug_level > 1) { echo '+++ 4 +++' . "<br />\n"; } $statement = &$this->statements[ $statement_name ]; if ($debug_level > 2) { echo "Statement:<br />\n"; d($statement); } // convert into array if it's not an array if (!is_array( $data_array )) { $data_array = array( $data_array ); } // Either use the forced type string or try to properly determine it using educated guesses. The latter doesn't always work flawlessly (particularly for determining // whether data is binary or not), so allow the auto-determination to be overridden. if (!empty($force_types)) { $types = $force_types; } else { $types = ''; foreach ($data_array as $var) { if (is_null($var)) $types .= 's'; else if (is_int($var)) $types .= 'i'; else if (is_float($var)) $types .= 'd'; else if ($this->use_oracle && (strlen($var) > 4000)) // !!! Oracle LOB types! These cannot be handled as 'literal strings' if they are longer than 4000 characters. { if (ctype_print($var)) { $types .= 'c'; // If the ENTIRE string consists of printable characters, assume we are dealing with a CLOB type } else { $types .= 'b'; // In the string contains unprintable characters, assume we are dealing with a BLOB type } } else $types .= 's'; } } if ($debug_level > 2) { echo "Using types: '{$types}'<br />\n"; } // we must have references in our data array, so build them now $data = array(); foreach ($data_array as $k => &$v) $data[] = &$v; // bind params if ($types) { // Handle the binding either the Oracle way, or the MySQL way if ($this->use_mysqli) { call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $statement['stmt'], $types ), $data )); } else if ($this->use_oracle) { // For Oracle we have to handle the binding explicitly by parameter names (see the comments in the 'prepare' method). // These parameter names where generated generically in the prepare method, and this is the location where they get bound // in an equally generic way. $param_cnt = 0; foreach ($data_array as $param_value) { // Work out the name of the placeholder to bind to, as well as the datatype of it. $cur_type = $types[$param_cnt]; $param_name = ':p'.++$param_cnt; $oracle_bind_type = ($cur_type == 'i') ? SQLT_INT : SQLT_CHR; // Make a distinction here between LOB data and data that can be inserted as 'normal literal' data. In Oracle, one can safely insert up to 4000 // characters of data as a 'literal string', but if the data is longer than that, we HAVE to use the proper LOB handling way, as is done below. if ( ($cur_type == 'b') || ($cur_type == 'c') ) { // Allocate a handle to the LOB and store it in the '$lobs' set too ${"lob$param_cnt"} = OCINewDescriptor($db->conn_id, OCI_D_LOB); // Specify the proper bind type. // Note: for CLOB (= 'Character LOB') columns we must use OCI_B_CLOB, for BLOB (= 'Binary LOB'), we probably must use OCI_B_BLOB. // Using OCI_B_BLOB for a CLOB column WILL fail!!! //$oracle_bind_type = OCI_B_BLOB; //$oracle_bind_type = OCI_B_CLOB; $oracle_bind_type = ($cur_type == 'b') ? OCI_B_BLOB : OCI_B_CLOB; // The actual binding of the LOB data/handle goes slightly differently than for normal data. Note that we must first bind the LOB handle, and then // AFTER binding it, write the data to it. There are two ways to do this, the first being the mechanism used here: directly writing the data, suing the // 'WriteTemporary' method, the second being to postpone this action, and perform it by calling the 'save' method of each LOB handle, AFTER successful // execution of the statement itself! oci_bind_by_name($statement['stmt'], $param_name, ${"lob$param_cnt"}, -1, $oracle_bind_type); // 'Write' the actual data to the statement ${"lob$param_cnt"}->WriteTemporary($param_value); // Store the LOB handle in an array, so it can be properly disposed of after execution. Note: if for some reason we need to postpone the writing out // of LOB data until after the execution of the statement, we will also need this set, for having all handles handy for calling their 'save' method. $lobs[] = ${"lob$param_cnt"}; } else { // !!! NOTE !!!: The statements parameter will be bound to the actual PHP variable! For this reason, each and every bound parameter value variables // must continue to exist at the moment the oci_execute call is made, as otherwise Oracle often (though not always) returns the following error: // "ORA-01460: unimplemented or unreasonable conversion requested" // The reason: once the loop is terminated, only the very last time $param_value is filled will still exist. If we had bound directly to that 'value' // (i.e. 'variable', in reality!!), only the very last value of it is still present and the other bounds are also in one way or another referring to that // same variable, causing VERY unpredictable behaviour!!!!! // Hence, when binding the parameters we must NOT do this: oci_bind_by_name($statement['stmt'], $param_name, $param_value); // ...but we must instead do this: oci_bind_by_name($statement['stmt'], $param_name, ${"bindval$param_cnt"}); //if (strlen($param_value) >= 4000) ${"bindval$param_cnt"} = $param_value; // echo "++-- Binding param: *{$param_name}* of type: *{$cur_type}*, corresponding to Oracle type: *{$oracle_bind_type}* with value: *{$param_value}*\n"; // oci_bind_by_name($statement['stmt'], $param_name, ${"bindval$param_cnt"}); // oci_bind_by_name($statement['stmt'], $param_name, ${"bindval$param_cnt"}, -1, $oracle_bind_type); oci_bind_by_name($statement['stmt'], $param_name, ${"bindval$param_cnt"}); // oci_bind_by_name($statement['stmt'], $param_name, ${"bindval$param_cnt"}, -1); } } } } // if ($types) // execute prepared statement $query_log_string = $statement['sql'] . ', values = ' . var_export( $data_array, true ); $db->queries[] = $query_log_string; if ($__RequestTimer) { //$__RequestTimer->sub( 'dbex: ' . preg_replace( '/\s+/', ' ', $query_log_string ) ); $__RequestTimer->sub( 'dbex' ); } $start_time = microtime( true ); if ($this->use_mysqli) { $res = mysqli_stmt_execute( $statement[ 'stmt' ] ); } else if ($this->use_oracle) { // Execute the prepared statement $res = oci_execute( $statement[ 'stmt' ] ); // Check if any errors were returned. $errors = oci_error(); // Free the LOB resources, if any. Note: this must be done AFTER the oci_execute call! foreach ($lobs as $lob) { $lob->close(); $lob->free(); } // Show the errors, if any if (!empty($errors)) { echo "+++ Failed statement: <br />\n"; d($statement); echo "+++ oci_error: <br />\n"; d($errors); if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } exit; } } $end_time = microtime( true ); $db->query_times[] = $end_time - $start_time; if ($res===FALSE) { if ($db->db_debug && !$may_fail) { /* echo '<pre>'; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo '</pre>'; * */ throw new Exception( 'Database fout: ' . $db->_error_message() ); } else if ($may_fail) $db->_trans_status = FALSE; else { if ($this->use_oracle) { $errors = oci_error(); if (!empty($errors)) { echo "+-+ Failed statement: <br />\n"; d($statement); echo "+-+ oci_error: <br />\n"; d($errors); if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } exit; } } //echo "+#+# oci_error: <br />\n"; //d(oci_error()); exit; throw new Exception( "Database fout: " . $query_log_string . ': ' . $db->_error_message() ); } if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } return FALSE; } // is this a write query? if so, then don't bother // handling results or anything, just return TRUE in that case if ($db->is_write_type( $statement['sql'] ) === TRUE) { if ($debug_level > 0) { echo '<<< DBex execute (successful exit - write query) >>>' . "<br />\n"; } return TRUE; } // MySQLi specific handling for non-write queries if ($this->use_mysqli) { // fetch result id so we can handle it in the normal CI way if (!mysqli_stmt_store_result( $statement['stmt'] )) { $db->_trans_status = FALSE; if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } return FALSE; } $result_id = mysqli_stmt_result_metadata( $statement['stmt'] ); if ($result_id===FALSE) { $db->_trans_status = FALSE; if ($debug_level > 0) { echo '<<< DBex execute (unsuccessful exit) >>>' . "<br />\n"; } return FALSE; } } if ($__RequestTimer) $__RequestTimer->subfinish(); // create result object and return that! $db->load_rdriver(); if ($this->use_mysqli) { $RES = new CI_DB_mysqli_prep_stmt_result($statement['stmt']); } else if ($this->use_oracle) { $RES = new CI_DB_oci8_prep_stmt_result($statement['stmt']); } $RES->conn_id = $db->conn_id; //$RES->result_id = $result_id; // ??? !!! Not needed in Oracle? $RES->result_id = ($this->use_mysqli) ? $result_id : null; // setup associative fields for result if ($this->use_mysqli) { $params = array(); foreach ($RES->field_data() as $field) { $RES->data[ $field->name ] = ''; $params[] = &$RES->data[ $field->name ]; } if ($this->use_mysqli) { $res = call_user_func_array( 'mysqli_stmt_bind_result', array_merge( array( $statement['stmt'], ), $params )); } } if ($debug_level > 0) { echo '<<< DBex execute (successful exit - read query) >>>' . "<br />\n"; } //d($statement); //d($RES); return $RES; } /** * Returns true if a statement with the specified name was * successfully prepared, and not yet unprepared (i.e. removed). */ function is_prepared( $statement_name ) { //echo "+++ is_prepared :: statement name: {$statement_name}<br />"; // In order for a statement to be (completely) valid and usable, the statement name must have associated SQL and a VALID statement handle; if not, return false. if (isset( $this->statements[ $statement_name ] )) { // For Oracle we also have to check if the statement handle is still valid! if ($this->use_oracle) { //d($this->statements[ $statement_name ]); // Check if the statement handle is still valid; this is not always the case and when it isn't, we need to return false! // Note: we can decide to unset it too from the array of statements, a la: unset($this->statements[ $statement_name ]); $statement_handle_is_valid = (is_resource($this->statements[ $statement_name ]['stmt']) && (get_resource_type($this->statements[ $statement_name ]['stmt']) == 'oci8 statement') ); //echo "Valid statement?: "; //echo ($statement_handle_is_valid) ? 'Yes<br />' : 'No<br />'; return $statement_handle_is_valid; } else { return true; } } else { return false; } } } // class CI_DBEx <file_sep>ALTER TABLE `lease_configuraties` ADD `speciaal_veld_gebruiken` TINYINT NOT NULL DEFAULT '0', ADD `speciaal_veld_waarden` LONGTEXT NULL DEFAULT NULL ; <file_sep>ALTER TABLE `klanten` DROP `laatste_factuur_datum`; ALTER TABLE `klanten` DROP `aangevraagd_op`; ALTER TABLE `klanten` DROP `actie_code`; ALTER TABLE `klanten` DROP `uiterste_datum`; <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('klant.heeft_toezichtmomenten_licentie', 'Heeft toezichtmomentenbeheer licentie?', NOW(), 0), ('beheer.index::toezichtmomenten', 'Toezichtmomentenbeheer', NOW(), 0), ('toezichtmomenten.headers.checklistgroepen', 'Checklistgroepen', NOW(), 0), ('toezichtmomenten.headers.checklisten', 'Checklisten', NOW(), 0), ('toezichtmomenten.headers.toezichtmomenten', 'Toezichtmomenten', NOW(), 0), ('toezichtmomenten.headers.monenten', 'Toezichtmomenten', NOW(), 0), ('toezichtmomenten.headers.momenten', 'Toezichtmomenten', NOW(), 0), ('toezichtmomenten.headers.hoofdgroepen', 'Hoofdgroepen', NOW(), 0), ('nav.toezichtmomenten.hoofdgroepen', 'Hoofdgroepen', NOW(), 0), ('nav.toezichtmomenten.checklistgroepen', 'Checklistgroepen', NOW(), 0), ('nav.toezichtmomenten.checklisten', 'Checklisten', NOW(), 0), ('nav.toezichtmomenten.toezichtmomenten', 'Toezichtmomenten', NOW(), 0) ; <file_sep><? $CI = get_instance(); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); $disable_hiding_tekst = false;// X/Y co�rdinaten, BAG identificatienummer $dossier_access=='readonly' ? $reg_gegevens_bewerkbare=false : ""; if(!isset($form_access)){ $form_access=""; } ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('registratiegegevens.header'), 'group_tag' => 'dossier', 'expanded' => !$open_tab_group, 'width' => '100%', 'height' => $CI->is_Mobile ? '380px' : 'auto' ) ); ?> <!-- mode1 generic-columns --> <table border="0" cellspacing="0" cellpadding="0" class="generic-columns"><tr><td class="generic-column" style="width:50%"> <!-- left column --> <table class="generic-content rounded10 form" height="400px"> <tr> <td class="generic-content"> <table style="width:100%"> <tr> <td><h3><?=tg('registratiegegevens')?></h3></td> </tr> <tr> <td><?=tgg('dossier.dossiernaam')?> <?=verplicht_image('beschrijving', $verplichte_velden)?></td> <td><input name="beschrijving" type="text" value="<?=isset($dossier)?$dossier->beschrijving:''?>" size="40" maxlength="128" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?> /></td> <td><?=htag('dossiernaam')?></td> </tr> <tr> <td><?=tgg('dossier.identificatienummer')?> <?=verplicht_image('kenmerk', $verplichte_velden)?></td> <td><input name="kenmerk" type="text" value="<?=isset($dossier)?$dossier->kenmerk:''?>" size="40" maxlength="32" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('identificatienummer')?></td> </tr> <tr> <td><?=tgg('dossier.aanmaakdatum')?> <?=verplicht_image('aanmaak_datum', $verplichte_velden)?></td> <td> <input type="text" size="10" value="<?= date('d-m-Y', isset($dossier) ? $dossier->aanmaak_datum : time()) ?>" disabled <?=($dossier_access!='write' && $form_access!='write')?'readonly':''?>/> </td> <td><?=htag('aanmaak_datum')?></td> </tr> <? if (!empty($project_status)): ?> <tr> <td><?=tgg('dossier.bristoetsstatus')?></td> <td> <input type="text" size="20" value="<?= ucfirst($bristoets_status) ?>" disabled readonly/> </td> <td><?=htag('bristoetsstatus')?></td> </tr> <tr> <td><?=tgg('dossier.bristoezichtstatus')?></td> <td> <input type="text" size="20" value="<?= ucfirst($bristoezicht_status) ?>" disabled readonly/> </td> <td><?=htag('bristoezichtstatus')?></td> </tr> <tr> <td><?=tgg('dossier.projectstatus')?></td> <td> <input type="text" size="20" value="<?= ucfirst($project_status) ?>" disabled readonly/> </td> <td><?=htag('projectstatus')?></td> </tr> <? endif; ?> <tr> <td><h3><?=tg('plaatsbepaling')?></h3></td> </tr> <tr class="<?=$disable_hiding_tekst || $CI->tekst->has('dossier.bag_identificatienummer',true) ? '' : 'hidden'?>"> <td><?=tgg('dossier.bag_identificatienummer')?></td> <td><input name="bag_identificatie_nummer" value="<?=isset($dossier)?$dossier->bag_identificatie_nummer:''?>" type="text" size="40" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('bag_identificatie_nummer')?></td> </tr> <tr class="<?=$disable_hiding_tekst || $CI->tekst->has('dossier.xy-coordinaten',true) ? '' : 'hidden'?>"> <td><?=tgg('dossier.xy-coordinaten')?></td> <td><input name="xy_coordinaten" value="<?=isset($dossier)?$dossier->xy_coordinaten:''?>" type="text" size="40" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('xy_coordinaten')?></td> </tr> <tr> <td><?=tgg('dossier.locatie_adres')?> <?=verplicht_image('locatie_adres', $verplichte_velden)?></td> <td><input name="locatie_adres" value="<?=isset($dossier)?$dossier->locatie_adres:''?>" type="text" size="40" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('locatie')?></td> </tr> <tr> <td><?=tgg('dossier.locatie_postcode_woonplaats')?> <?=verplicht_image('locatie_postcode', $verplichte_velden)?></td> <td><input name="locatie_postcode" value="<?=isset($dossier)?$dossier->locatie_postcode:''?>" type="text" size="6" maxlength="6" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/> <input name="locatie_woonplaats" value="<?=isset($dossier)?$dossier->locatie_woonplaats:''?>" type="text" size="27" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('postcode-woonplaats')?></td> </tr> <tr> <td><?=tgg('dossier.correspondentie_adres')?></td> <td><input name="correspondentie_adres" value="<?=isset($dossier)?$dossier->correspondentie_adres:''?>" type="text" size="40" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> </tr> <tr> <td><?=tgg('dossier.correspondentie_postcode')?></td> <td><input name="correspondentie_postcode" value="<?=isset($dossier)?$dossier->correspondentie_postcode:''?>" type="text" size="6" maxlength="6" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/> <input name="correspondentie_plaats" value="<?=isset($dossier)?$dossier->correspondentie_plaats:''?>" type="text" size="27" maxlength="64" <?=($dossier_access!='write' && $form_access!='write') || !$reg_gegevens_bewerkbare ?'disabled readonly':''?>/></td> <td><?=htag('postcode-woonplaats')?></td> </tr> <tr class="<?=($disable_hiding_tekst || $CI->tekst->has('dossier.kadastraal_sectie_nummer',true))&& $reg_gegevens_bewerkbare? '' : 'hidden'?>"> <td><?=tgg('dossier.kadastraal_sectie_nummer')?> <?=verplicht_image('locatie_kadastraal', $verplichte_velden)?></td> <td><input name="locatie_kadastraal" value="<?=isset($dossier)?$dossier->locatie_kadastraal:''?>" type="text" size="8" maxlength="20" <?=($dossier_access!='write' && $form_access!='write')?' disabled readonly':''?>/> / <input name="locatie_sectie" value="<?=isset($dossier)?$dossier->locatie_sectie:''?>" type="text" size="8" maxlength="20" <?=($dossier_access!='write' && $form_access!='write')?'disabled readonly':''?>/> / <input name="locatie_nummer" value="<?=isset($dossier)?$dossier->locatie_nummer:''?>" type="text" size="8" maxlength="20" <?=($dossier_access!='write' && $form_access!='write')?'disabled readonly':''?>/></td> <td><?=htag('ksn')?></td> </tr> <tr> <td><h3><?=tg('dossierverantwoordelijke')?></h3></td> </tr> <tr> <td><?=tg('dossierverantwoordelijke')?></td> <td> <select name="gebruiker_id" <?=$dossier_access!="write" && ($form_access!="write" && !$reg_gegevens_bewerkbare) ?'disabled readonly':''?>> <? foreach ($gebruikers as $gebruiker): ?> <? if ($gebruiker->status!="geblokkeerd") :?> <option <?=$gebruiker->id==$gebruiker_id?'selected':''?> value="<?=$gebruiker->id?>"><?=htmlentities($gebruiker->to_string())?></option> <? endif;?> <? endforeach; ?> </select> </td> <td><?=htag('verantwoordelijke')?></td> </tr> <? if ($klant_id == 202 && $form_access=="write"): ?> <tr> <td><h3><?=tg('dossierfoto')?></h3></td> </tr> <tr> <td> <? if ( isset($dossier) && !is_null($dossier->get_foto()) ): ?> <?=tg('dossierfoto')?><br /><img src="data:image/png;base64,<?=(is_null($dossier->get_foto()) ? '' : base64_encode($dossier->get_foto()->bestand))?>" style="border:1px solid black;" width="75px"/> <? endif; ?> </td> <td><input type="file" name="dossierfoto" <?=$dossier_access!='write'?'disabled':''?>/><br/>U kunt vrijwel elk logo formaat gebruiken!<div id="dossierfoto"></div></td> <td><?=htag('dossierfoto')?></td> </tr> <? endif; ?> </table> </td> </tr> </table> </td><td class="generic-column" style="width:50%"> <table class="generic-content rounded10 form" height="400px"> <tr> <td class="generic-content"> <table> <tr> <td><h3><?=tgg('dossier.opmerkingen')?></h3></td> <td><?=htag('opmerkingen')?></td> </tr> <tr> <td colspan="2"><textarea style="width:100%; height: 300px;" name="opmerkingen" <?=isset($dossier_access)!='write' || !$reg_gegevens_bewerkbare?'disabled readonly':''?>><?=htmlentities(isset($dossier)?$dossier->opmerkingen:'', ENT_COMPAT, 'UTF-8')?></textarea></td> </tr> </table> </td> </tr> </table> </td></tr></table> <script type="text/javascript"> $(document).ready(function(){ $('input[name$=_datum]').datepicker({ dateFormat: "dd-mm-yy" }); }); </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <file_sep><? $is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); ?> <? if (!isset( $embedded ) || !$embedded): ?> <? load_view( 'header.php' ); ?> <? endif; ?> <? if (isset( $pages ) && is_array( $pages )): ?> <? foreach ($pages as $index => $page): ?> <div style="border:0;margin:0;padding:50px;width:<?=$page['width']?>px;height:<?=$page['height']?>px;"> <div class="Editor" style="width: <?=$page['width']?>px"> <img class="Drawing" src="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'], strtotime($document->get_timestamp('created_at')), $page['version'], '' )?>" /> </div> </div> <? endforeach; ?> <? elseif ($guids): ?> <? foreach ($guids->get_document_guids() as $guid): ?> <!-- <?=$guid?> --> <? try { $document = Document::restore_state( $guid ); } catch (Exception $e) { $document = null; } ?> <? if ($document): ?> <? foreach ($document->get_working_data() as $page): ?> <div style="border:0;margin:0;padding:50px;width:<?=$page['width']?>px;height:<?=$page['height']?>px;"> <div class="Editor" style="width: <?=$page['width']?>px; height:<?=$page['height']?>px; display: none" document_id="<?=$document->get_external_data_by_key( 'document_id' )?>" guid="<?=$guid?>" pagenumber="<?=$page['pagenumber']?>"> <? if (@$is_btz): ?> <? if ($page['numslices']): ?> <div style="border:0;margin:0;padding:0;" class="Drawing"> <? for ($i=0; $i<$page['numslices']; ++$i): ?> <img target_url="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'] . chr(65+$i), strtotime($document->get_timestamp('created_at')), $page['version'], $document->get_guid() )?>" src="/files/images/s.gif" width="100%" /> <? endfor; ?> </div> <? else: ?> <img class="Drawing" target_url="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'], strtotime($document->get_timestamp('created_at')), $page['version'], $document->get_guid() )?>" src="/files/images/s.gif" /> <? endif; ?> <? else: ?> <img class="Drawing" src="<?=sprintf( PDFANNOTATOR_PAGEIMAGE_URL, $page['pagenumber'], strtotime($document->get_timestamp('created_at')), $page['version'], $document->get_guid() )?>" /> <? endif; ?> </div> </div> <? endforeach; ?> <? endif; ?> <? endforeach; ?> <? if (@$is_btz): ?> <div style="position:fixed; left: 9999px; top: 9999px;"> <? foreach ($guids->get_document_guids() as $guid): ?> <? try { $document = Document::restore_state( $guid ); } catch (Exception $e) { continue; } ?> <img class="Overview" target_url="<?=sprintf( PDFANNOTATOR_OVERVIEW_URL, $document->get_guid() )?>" src="/files/images/s.gif" document_id="<?=$document->get_external_data_by_key( 'document_id' )?>" /> <? endforeach; ?> </div> <? endif; ?> <? else: ?> <div id="PanelUploadDocument"> <h1>U heeft nog geen document ge&uuml;pload</h1> <form method="post" action="<?=PDFANNOTATOR_UPLOAD_DOCUMENT_URL?>" enctype="multipart/form-data"> <p> Upload een PDF bestand: <input type="file" name="pdf" /> <input type="submit" value="Uploaden" /><br/> <input type="checkbox" name="low" > Lage kwaliteit (voor mobiele verbindingen) </p> </form> </div> <? endif; ?> <div id="PanelLayerInfo" class="NoSelect"></div> <div id="PanelZoom" class="NoSelect"> <div style="display: relative;"> <div id="PanelZoomList" class="NoSelect"> <div zoom="25">25%</div> <div zoom="50">50%</div> <div zoom="75">75%</div> <div zoom="100">100%</div> <div zoom="150">150%</div> <div zoom="200">200%</div> <div zoom="400">400%</div> </div> </div> <div id="PanelZoomCurrent">100%</div> </div> <div id="PanelMenuContainer" class="NoSelect"> <div id="PanelMenu" class="InlineBlock"> <!-- !-- !-- L A G E N !-- !-- --> <div class="PanelMenuHeader"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-icon-layers.png" class="PanelMenuIcon"> Lagen <div class="PanelMenuArrow"></div> </div> <div class="PanelMenuContents"> <div class="PanelMenuLayersHeader"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-delete.png" class="PanelMenuLayerDelete"> <div class="InlineBlock PanelMenuFilterNone"></div> <div class="InlineBlock PanelMenuFilterGroen"></div> <div class="InlineBlock PanelMenuFilterGeel"></div> <div class="InlineBlock PanelMenuFilterRood"></div> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-add.png" class="PanelMenuAdd"> </div> <div class="PanelMenuLayersList"> </div> <div class="PanelMenuLayersAddWindow Hidden"> <table style="width: 100%"> <tr> <td style="padding: 10px 3px; font-weight: bold;">Maak een nieuwe kaartlaag</td> </tr> <tr> <td><input type="text" placeholder="Vul een kaartlaag naam in..." style="width: 250px" class="PanelMenuLayersCustomName" /></td> </tr> <tr> <td style="padding-left: 30px;"> <input type="button" value="Aanmaken" class="PanelMenuLayersAddCustom" style="min-width: 100px; width: 100px;" /> <input type="button" value="Annuleren" class="PanelMenuLayersCancelAdd" style="min-width: 100px; width: 100px;" /> </td> </tr> <tr> <td style="padding: 10px 3px; font-weight: bold;">Baseer een kaartlaag op een vraag</td> </tr> </table> <div class="PanelMenuLayersReferenceList"> </div> </div> </div> <!-- !-- !-- K L E U R E N !-- !-- --> <div class="PanelMenuHeader"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-icon-colors.png" class="PanelMenuIcon"> Kleuren <div class="PanelMenuArrow"></div> <div class="PanelMenuCurrentSetting"> <div class="InlineBlock PanelMenuCurrentFillColor" style="width: 25px; height: 25px;"></div><div class="InlineBlock PanelMenuCurrentBorderColor PanelMenuSelectedColor" style="width: 25px; height: 25px;"></div> </div> </div> <div class="PanelMenuContents"> <table class="PanelMenuColorTable"> <tr> <td>Vul kleur</td> <td>Lijn/tekst kleur</td> </tr> <tr> <td><div class="InlineBlock PanelMenuCurrentFillColor"></div></td> <td><div class="InlineBlock PanelMenuCurrentBorderColor PanelMenuSelectedColor"></div></td> </tr> <tr> <? $colors = array( array('000000','7f7f7f','880015','ed1c24','ff7f27','fff200','22b14c','00a2e8','3f48cc','a349a4'), array('ffffff','c3c3c3','b97a57','ffaec9','ffc90e','efe4b0','b5e61d','99d9ea','7092be','c8bfe7'), ); ?> <td colspan="2"> <table> <? for ($i=0; $i<2; ++$i) { echo '<tr>'; foreach ($colors[$i] as $color) { echo '<td><div style="background-color: #' . $color . '" class="ColorChoice InlineBlock"></div></td>'; } echo '</tr>'; } ?> </table> </td> </tr> </table> </div> <!-- !-- !-- S T E M P E L S !-- !-- --> <div class="PanelMenuHeader"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-icon-images.png" class="PanelMenuIcon"> Stempels <div class="PanelMenuArrow"></div> <div class="PanelMenuCurrentSetting"> <img class="PanelMenuCurrentImage" class="Hidden" width="50" height="25"> </div> </div> <div class="PanelMenuContents PanelMenuImageLibrary" style="height: 300px; overflow-y: auto;"> <? load_view( 'image-list.php', array( 'is_btz' => $is_btz ) ); ?> </div> <!-- !-- !-- T E K E N I N G !-- !-- --> <div class="PanelMenuHeader"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-icon-background.png" class="PanelMenuIcon"> Tekening <div class="PanelMenuArrow"></div> <div class="PanelMenuCurrentSetting"> <div class="PanelMenuCurrentTransparency">100%</div> </div> </div> <div class="PanelMenuContents"> <table class="PanelMenuTransparencyTable"> <tr> <td colspan="4" style="text-align: left">Tekening transparantie:</td> </tr> <tr> <td><div style="background: transparent url(<?=PDFANNOTATOR_FILES_BASEURL?>images/regular-button-small.png) no-repeat left top; width: 43px; height: 25px; text-align: center; padding-top: 4px;" transparency="0.25">25%</div></td> <td><div style="background: transparent url(<?=PDFANNOTATOR_FILES_BASEURL?>images/regular-button-small.png) no-repeat left top; width: 43px; height: 25px; text-align: center; padding-top: 4px;" transparency="0.50">50%</div></td> <td><div style="background: transparent url(<?=PDFANNOTATOR_FILES_BASEURL?>images/regular-button-small.png) no-repeat left top; width: 43px; height: 25px; text-align: center; padding-top: 4px;" transparency="0.75">75%</div></td> <td><div style="background: transparent url(<?=PDFANNOTATOR_FILES_BASEURL?>images/regular-button-small.png) no-repeat left top; width: 43px; height: 25px; text-align: center; padding-top: 4px;" transparency="1.0">100%</div></td> </tr> </table> <table class="PanelMenuImageOptionsTable"> <tr> <td colspan="4" style="text-align: left">Tekening roteren en spiegelen:</td> </tr> <tr> <td><img title="Niet roteren." src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-rotate0.png" class="Checked"></td> <td><img title="Roteer 90 graden met de klok mee." src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-rotate90.png"></td> <td><img title="Roteer 180 graden met de klok mee." src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-rotate180.png"></td> <td><img title="Roteer 90 graden tegen de klok in." src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-rotate270.png"></td> <td><img title="Spiegel horizontaal." src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-flip-horizontal.png"></td> <td><img title="Spiegel verticaal" src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-background-flip-vertical.png"></td> </tr> </table> <table class="PanelMenuOverviewTable"> <tr> <td style="text-align: left">Tekening navigatie:</td> </tr> <tr> <td><input type="button" value="Toon overview" style="width: auto" /></td> </tr> </table> </div> <!-- !-- !-- T E K S T !-- !-- --> <div class="PanelMenuHeader LowerBorder"> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-icon-text.png" class="PanelMenuIcon"> Tekst <div class="PanelMenuArrow"></div> <div class="PanelMenuCurrentSetting"> <table width="100%" height="100%"><tr><td class="PanelMenuCurrentFont" style="vertical-align: middle;">Arial</td></tr></table> </div> </div> <div class="PanelMenuContents"> <table class="PanelMenuTextSettings"> <tr> <td style="width: 100px; padding-left: 15px;"><b>Vetgedrukt</b></td> <td><input type="checkbox" class="PanelMenuBold" name="bold" /></td> <td style="width: 50px;"></td> <td>10pt</td> <td><input type="radio" class="PanelMenuFontSize" name="fontsize" value="10pt" checked /></td> </tr> <tr> <td style="width: 100px; padding-left: 15px;"><i>Cursief</i></td> <td><input type="checkbox" class="PanelMenuItalic" name="italic" /></td> <td></td> <td>16pt</td> <td><input type="radio" class="PanelMenuFontSize" name="fontsize" value="16pt" /></td> </tr> <tr> <td style="width: 100px; padding-left: 15px;"><u>Onderstreept</u></td> <td><input type="checkbox" class="PanelMenuUnderline" name="underline" /></td> <td></td> <td>32pt</td> <td><input type="radio" class="PanelMenuFontSize" name="fontsize" value="32pt" /></td> </tr> </table> <? foreach (array( 'Arial', 'Verdana', 'Courier New', 'Tahoma' ) as $index => $font): ?> <div class="<?=$index ? '' : 'Selected'?>" style="font-family: <?=$font?>"> <div class="InlineBlock PanelMenuFontChoiceButtonLeft"></div><? ?><div class="InlineBlock PanelMenuFontChoiceButtonMid"><?=$font?></div><? ?><div class="InlineBlock PanelMenuFontChoiceButtonRight"></div> </div> <? endforeach; ?> <br/> </div> </div><!-- no space between these divs! --><div id="PanelMenuHandle" class="InlineBlock"></div> </div> <div id="PanelToolsContainer" class="NoSelect"> <div class="PanelToolsTool AlwaysOnTop PanelToolsHasSubMenu Camera"></div> <div class="PanelToolsSubMenu Hidden Camera" style="width: 112px;"><!-- width = 2 * (55+1), offset = -(width - 55), position = relative, see CSS --> <div class="PanelToolsTool InlineBlock Camera"></div><div class="PanelToolsTool InlineBlock CameraAssignment"></div> </div> <div class="PanelToolsTool AlwaysOnTop Camera Selected Hidden" toolname="Camera"></div> <div class="PanelToolsTool AlwaysOnTop CameraAssignment Selected Hidden" toolname="CameraAssignment"></div> <? if ($is_Mobile): ?> <div class="PanelToolsTool AlwaysOnTop Pan"></div> <div class="PanelToolsTool AlwaysOnTop Pan Selected Hidden" toolname="Pan"></div> <? endif; ?> <div class="PanelToolsTool AlwaysOnTop Move Selected Hidden" toolname="Move"></div> <div class="PanelToolsTool AlwaysOnTop ChangeVraag Selected Hidden" toolname="ChangeVraag"></div> <div class="PanelToolsTool AlwaysOnTop Resize Selected Hidden" toolname="Resize"></div> <div class="PanelToolsTool AlwaysOnTop Text Selected Hidden" toolname="Text"></div> <div class="PanelToolsTool AlwaysOnTop Image Selected Hidden" toolname="Image"></div> <div class="PanelToolsTool AlwaysOnTop Quad Selected Hidden" toolname="Quad"></div> <div class="PanelToolsTool AlwaysOnTop Circle Selected Hidden" toolname="Circle"></div> <div class="PanelToolsTool AlwaysOnTop SingleLine Selected Hidden" toolname="SingleLine"></div> <div class="PanelToolsTool AlwaysOnTop Measure Selected Hidden" toolname="Measure"></div> <!--div class="PanelToolsTool AlwaysOnTop DownloadAlles Selected Hidden" toolname="DownloadAlles"></div> <div class="PanelToolsTool AlwaysOnTop DownloadScherm Selected Hidden" toolname="DownloadScherm"></div--> <div class="PanelToolsTool AlwaysOnTop Delete Selected Hidden" toolname="Delete"></div> <div id="PanelToolsHandle" class="InlineBlock"></div><!-- no space between these divs --><div id="PanelTools" class="InlineBlock"> <div class="PanelToolsTool Move"></div> <div class="PanelToolsTool ChangeVraag"></div> <div class="PanelToolsTool Resize"></div> <div class="PanelToolsTool Text"></div> <div class="PanelToolsTool Image"></div> <div class="PanelToolsTool PanelToolsHasSubMenu SingleLine"></div> <div class="PanelToolsSubMenu" style="width: 168px; left: -113px;"><!-- width = 3 * (55+1), offset = -(width - 55), position = relative, see CSS --> <div class="PanelToolsTool InlineBlock Quad"></div><div class="PanelToolsTool InlineBlock Circle"></div><div class="PanelToolsTool InlineBlock SingleLine"></div> </div> <div class="PanelToolsTool Measure"></div> <!-- div class="PanelToolsTool PanelToolsHasSubMenu Download"></div> <div class="PanelToolsSubMenu" style="width: 112px; left: -57px;"> <div class="PanelToolsTool InlineBlock DownloadAlles"></div><div class="PanelToolsTool InlineBlock DownloadScherm"></div> </div--> <div class="PanelToolsTool Delete"></div> </div> </div> <? if (!isset( $embedded ) || !$embedded): ?> <? load_view( 'upload-form.php' ); ?> <? endif; ?> <? if (@$is_btz): ?> <!-- tell PDF annotator scripting that colored line images have already been loaded! --> <script type="text/javascript"> $(document).ready(function(){ var staticClass = PDFAnnotator.Line.prototype; <? foreach (array_merge( $colors[0], $colors[1] ) as $color): ?> staticClass.preloadedColors.push( staticClass.cleanupColor( '#<?=$color?>' ) ); <? endforeach; ?> }); </script> <? endif; ?> <script type="text/javascript"> /* * PDF Annotator is 2012 - 2013 (c) Copyright Imotep B.V. * Developed by FoddexSOFT (<NAME>) */ // main variables PDF annotator engine var PDFAnnotatorEngine, PDFAnnotatorGUI, PDFAnnotatorServer ,annot_selected=null ; // function to create a PDF annotator engine object function CreatePDFAnnotatorForDocument( containerDomObjects, loadAnnotations ) { if (!PDFAnnotatorEngine) PDFAnnotatorEngine = new PDFAnnotator.Engine( containerDomObjects, PDFAnnotatorServer, PDFAnnotatorGUI, 'Algemene laag', loadAnnotations ); else PDFAnnotatorEngine.reboot( containerDomObjects ); } // function that reports whether or not a specific document ID is available function HavePDFDocument( document_id ) { var editorDivs = $('[document_id=' + document_id + ']'); return editorDivs.size() > 0; } // function to select a document, can be called from parent window function SelectPDFDocument( document_id ) { // hide all current documents $('div.Editor').hide().parent().hide(); // show this document var editorDivs = $('div[document_id=' + document_id + ']'); editorDivs.show().parent().show(); CreatePDFAnnotatorForDocument({ editableContainers: editorDivs, drawings: editorDivs.find('.Drawing') }, false /* don't load annotations yet */ ); // set meta data, then load annotations PDFAnnotatorEngine.setMetaData( 'document_id', document_id ); PDFAnnotatorEngine.setMetaData( 'guid', editorDivs.attr('guid') ); PDFAnnotator.Server.prototype.instance.loadAnnotations( PDFAnnotatorEngine ); // when fully done, update layer states (met andere woorden, update groen/geel/rood/none voor layers die bij een vraag horen) PDFAnnotatorEngine.getGUI().menu.layers.updateLayersByReferences(); } // used by parent window (BTZ!) function GetPDFAnnotatorEngine() { return PDFAnnotatorEngine; } // when document is done loading, bootstrap the engine $(document).ready(function(){ var panelMenu = $('#PanelMenu') ; // create PDF annotator server communication object PDFAnnotatorServer = new PDFAnnotator.Server.PDFAnnotatorBTZ(); // create PDF annotator GUI PDFAnnotatorGUI = new PDFAnnotator.GUI({ rootContainer: $('#PanelLayerInfo').parent(), menuconfig: { mainContainer: panelMenu, /* the main DOM node that contains the menu */ headers: panelMenu.find('.PanelMenuHeader' ), /* the tabs */ handle: $('#PanelMenuHandle' ), /* the handle (i.e. the thing that when clicked toggles the menu's visibility) */ panels: { colors: { choices: panelMenu.find('.ColorChoice' ), fillselector: panelMenu.find('.PanelMenuCurrentFillColor' ), lineselector: panelMenu.find('.PanelMenuCurrentBorderColor' ), selectedClass: 'PanelMenuSelectedColor' }, imagelist: { container: panelMenu.find('.PanelMenuImageLibrary' ), currentImage: panelMenu.find('.PanelMenuCurrentImage') }, drawing: { initialTransparency: 0.5, transparencyChoices: panelMenu.find('.PanelMenuTransparencyTable div'), currentTransparency: panelMenu.find('.PanelMenuCurrentTransparency'), options: panelMenu.find('.PanelMenuImageOptionsTable img' ), checkedClass: 'Checked', showOverview: panelMenu.find('.PanelMenuOverviewTable input') }, text: { bold: panelMenu.find('.PanelMenuTextSettings [name=bold]'), italic: panelMenu.find('.PanelMenuTextSettings [name=italic]'), underline: panelMenu.find('.PanelMenuTextSettings [name=underline]'), sizes: panelMenu.find('.PanelMenuTextSettings [name=fontsize]'), fonts: panelMenu.find('.PanelMenuTextSettings').siblings( 'div' ), selectedClass: 'Selected', currentFont: panelMenu.find('.PanelMenuCurrentFont') }, layers: { list: panelMenu.find('.PanelMenuLayersList'), addLayerWindow: { window: panelMenu.find('.PanelMenuLayersAddWindow'), referencesList: panelMenu.find('.PanelMenuLayersReferenceList'), cancel: panelMenu.find('.PanelMenuLayersCancelAdd'), addCustom: panelMenu.find('.PanelMenuLayersAddCustom'), customName: panelMenu.find('.PanelMenuLayersCustomName'), subjectClass: 'PanelMenuLayersReferenceSubject', referenceClass: 'PanelMenuLayersReferenceReference' }, entryClass: 'PanelMenuLayersEntry', invisibleClass: 'PanelMenuLayerInvisible', activeClass: 'PanelMenuLayerActive', filters: { none: panelMenu.find('.PanelMenuFilterNone'), groen: panelMenu.find('.PanelMenuFilterGroen'), geel: panelMenu.find('.PanelMenuFilterGeel'), rood: panelMenu.find('.PanelMenuFilterRood') }, filterDepressdClass: 'Depressed', addLayer: panelMenu.find('.PanelMenuAdd'), removeLayer: panelMenu.find('.PanelMenuLayerDelete'), visibleImages: { visible: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-visible.png', invisible: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-invisible.png' }, filterImages: { none: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-layer-filter-none.png', groen: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-layer-filter-groen.png', geel: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-layer-filter-geel.png', rood: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/menu-layers-layer-filter-rood.png' }, contentClasses: { visibility: 'PanelMenuLayerVisibility', filter: 'PanelMenuLayerFilter', name: 'PanelMenuLayerName' }, currentLayerInfo: $('#PanelLayerInfo') } } }, toolsconfig: { mainContainer: $('#PanelTools' ), /* the main DOM node that contains the tools */ handle: $('#PanelToolsHandle' ), /* the handle (i.e. the thing that when clicked toggles the tools's visibility) */ tools: $('#PanelTools .PanelToolsTool:not(.PanelToolsHasSubMenu), .PanelToolsSubMenu .PanelToolsTool.Camera:not(.Selected), .PanelToolsTool.CameraAssignment:not(.Selected), .PanelToolsTool.AlwaysOnTop.Pan:not(.Selected)'), selectedTools: $('#PanelToolsContainer .PanelToolsTool.AlwaysOnTop:not(.Camera):not(.CameraAssignment):not(.Pan), .PanelToolsTool.AlwaysOnTop.Camera.Selected, .PanelToolsTool.AlwaysOnTop.CameraAssignment.Selected, .PanelToolsTool.AlwaysOnTop.Pan.Selected'), submenus: $('#PanelToolsContainer .PanelToolsSubMenu' ), /* the DOM nodes that contain sub menus, their "prev()"'s automatically become the triggers */ activeToolIndex: <?=$is_Mobile?4:2?>, /* start with text tool activated (it's at this index in the tools list) */ camera: { form: $('.CameraForm'), imageSrc: '<?=PDFANNOTATOR_FILES_BASEURL?>stempels/_hidden/camera.png', imageOpdrachtSrc: '<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/opdracht.png', imageSize: new PDFAnnotator.Math.IntVector2( 64, 64 ) } }, zoomconfig: { mainContainer: $('#PanelZoom'), current: $('#PanelZoomCurrent'), list: $('#PanelZoomList') } }); <? if (!$guids): ?> // single document PDF annotator situation CreatePDFAnnotatorForDocument( { editableContainers: $('div.Editor'), drawings: $('div.Editor .Drawing') }, true ); <? else: ?> // multiple document PDF annotator situation CreatePDFAnnotatorForDocument( { editableContainers: $(), drawings: $() }, true ); <? endif; ?> }) </script> <? if (!isset( $embedded ) || !$embedded): ?> <? load_view( 'footer.php' ); ?> <? endif; ?> <file_sep> DROP TABLE IF EXISTS bt_toezichtmoment_performers; CREATE TABLE bt_toezichtmoment_performers ( id int NOT NULL AUTO_INCREMENT, dlplan_chklist_id int NOT NULL, toezichtmoment_id int NOT NULL, volledige_naam varchar(100) DEFAULT NULL, email varchar(100) DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_bt_toezichtmoment_performers_deelplan_checklisten_id FOREIGN KEY (dlplan_chklist_id) REFERENCES deelplan_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_bt_toezichtmoment_performers_bt_toezichtmomenten_id FOREIGN KEY (toezichtmoment_id) REFERENCES bt_toezichtmomenten (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB; <file_sep>DELETE FROM bt_grondslagen WHERE id NOT IN (SELECT grondslag_id FROM bt_grondslag_teksten); UPDATE verantwoordingen SET grondslag = 'BB12' WHERE grondslag = 'BB2012'; <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_beheer')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('gebruikersbeheer'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <? if (get_instance()->is_Mobile) { $col_widths = array( 'volledige_naam' => 150, 'rol' => 120, ); } else { $col_widths = array( 'volledige_naam' => 200, 'rol' => 150, ); } $col_description = array( 'volledige_naam' => tgg('gebruiker.volledige_naam'), 'rol' => tgg('gebruiker.rol'), ); if (APPLICATION_LOGIN_SYSTEM == 'LocalDB') { $col_widths['status'] = 70; $col_description['status'] = tgg('gebruiker.status'); } $col_unsortable = array( 'opties' ); foreach ($checklistgroepen as $cg) { $sname = htmlentities( substr( $cg->naam, 0, 7 ), ENT_COMPAT, 'UTF-8' ); $name = htmlentities( $cg->naam, ENT_COMPAT, 'UTF-8' ); $key = 'cg' . $cg->id; $col_widths[$key] = 60; $col_description[$key] = '<span title="' . $name . '">' . $sname . '</span>'; $col_unsortable[] = $key; } $col_widths['opties'] = 150; $col_description['opties'] = tgg('algemeen.opties'); $rows = array(); foreach ($data as $i => $gebruiker) { $actief = $gebruiker->status == 'actief'; if($actief || $viewdata['mode']=="alle"){ $row = (object)array(); $row->onclick = $actief ? "location.href='" . site_url('/instellingen/gebruiker_edit/' . $gebruiker->id) . "'" : '&nbsp;'; $row->data = array(); $row->data['volledige_naam'] = $gebruiker->volledige_naam; $row->data['rol'] = $gebruiker->rol_id ? ($gebruiker->get_rol()->naam) : tgg('gebruiker.geen_rol_toegewezen'); $row->status = ucfirst( $gebruiker->status ); if (APPLICATION_LOGIN_SYSTEM == 'LocalDB') $row->data['status'] = ucfirst( $gebruiker->status ); foreach ($checklistgroepen as $cg) { $cg_id = $cg->id; $gebruiker_id = $gebruiker->id; $checked = isset( $gebruiker_checklistgroepen[$gebruiker_id] ) && in_array( $cg_id, $gebruiker_checklistgroepen[$gebruiker_id] ); $title = tgn('mag_gebruiker_toezicht_uitvoeren_voor', $gebruiker->get_status(), $cg->naam); $title = htmlentities( $title, ENT_COMPAT, 'UTF-8' ); $row->data['cg' . $cg_id] = '<input type="checkbox" gebruiker_id="' . $gebruiker_id . '" checklist_groep_id="' . $cg_id . '" onclick="eventStopPropagation(event);" ' . ($checked ? 'checked' : '') . ' title="' . $title. '" />'; } $opties = ''; if ($actief) { if ($this->login->mag_gebruikers_verwijderen()) $opties .= '<a href="' . site_url('/instellingen/gebruiker_delete/'.$gebruiker->id) . '"><img src="' . site_url('/content/png/delete') . '" /></a>'; if ($this->login->mag_gebruikers_toevoegen()) $opties .= '<a href="' . site_url('/instellingen/gebruiker_edit/'.$gebruiker->id) . '"><img src="' . site_url('/content/png/edit') . '" /></a>'; $opties .= '<a href="' . site_url('/instellingen/gebruiker_collegas/'.$gebruiker->id) . '"><img src="' . site_url('/content/png/collegas') . '" /></a>'; } else $opties .= '&nbsp;'; $row->data['opties'] = $opties; if (!$actief) foreach ($row->data as $k => &$v) $v = '<span style="color:#999">' . $v . '</span>'; $rows[] = $row; } } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'config' => array( 'mode' => $viewdata['mode'], ), 'new_button_js' => null, // no longer possible, goes through BRIS KennisID 'url' => '/instellingen/gebruikers', 'scale_field' => 'opties', 'do_paging' => false, 'table_type' =>'gebruikers', 'header' => ' <input type="radio" ' . ($viewdata['mode']=='actief' ? 'checked' : '') . ' name="filter" value="mijn" /> ' . tg('toon_actieve_gebruikers') . ' <input type="radio" ' . ($viewdata['mode']=='alle' ? 'checked' : '') . ' name="filter" value="alle" /> ' . tg('toon_alle_gebruikers') . ' ' . htag('actief_gebruiker_filter') . ' ', ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? if (APPLICATION_HAVE_ROLLENBEHEER): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Rollenbeheer', 'rightheader' => '', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/rollenbeheer') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <? endif; ?> <? if($this->gebruiker->get_logged_in_gebruiker()->get_klant()->usergroup_activate == 1 && $this->login->verify( 'beheer', 'users_groups' )):?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('users_group'), 'rightheader' => '', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/users_groups') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <? endif; ?> <? if ($this->login->mag_gebruikers_toevoegen()): ?> <br/> <input type="button" value="<?=tgn('gebruiker.toevoegen')?>" onclick="location.href='<?=site_url('/instellingen/gebruiker_toevoegen')?>';"> <? endif; ?> <script type="text/javascript"> $(document).ready(function(){ // handle dossier filter by type/state $('input[type=radio][name=filter]').click(function(){ var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'mode', this.value ); }); // handle gebruiker-checklist-groep clicks $('input[type=checkbox][gebruiker_id]').click(function(){ var gebruiker_id = $(this).attr('gebruiker_id'); var data = { gebruiker_id: gebruiker_id, checklist_groep_ids: '' }; $('input[type=checkbox][gebruiker_id=' +gebruiker_id+ ']:checked').each(function(){ var checklist_groep_id = $(this).attr( 'checklist_groep_id' ); data.checklist_groep_ids += (data.checklist_groep_ids ? ',' : '') + checklist_groep_id; }); $.ajax({ url: '/instellingen/gebruiker_checklist_groep_rechten', type: 'POST', async: true, dataTypeString: 'json', data: data, success: function( data, textStatus, jqXHR ) { if (data.match( /^OK$/ )) return; alert( '<?=tgn('fout_bij_opslaan')?>?>:\n\n' + data ); location.href = location.href; }, error: function( jqXHR, textStatus, errorThrown ) { alert( '<?=tgn('communicatie_fout_met_server_bij_opslaan_of_pagina_niet_gevonden')?>' ); location.href = location.href; } }); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>DROP TABLE IF EXISTS bt_toezichtmomenten; CREATE TABLE bt_toezichtmomenten ( id int(11) NOT NULL AUTO_INCREMENT, naam varchar(128) DEFAULT NULL, checklist_id int(11) NOT NULL, PRIMARY KEY (id), CONSTRAINT FK_bt_toezichtmomenten_bt_checklisten_id FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; DROP TABLE IF EXISTS bt_toezichtmomenten_vragen; DROP TABLE IF EXISTS bt_toezichtmomenten_hoofdgroepen; CREATE TABLE bt_toezichtmomenten_hoofdgroepen ( id int(11) NOT NULL AUTO_INCREMENT, toezichtmoment_id int(11) DEFAULT NULL, hoofdgroep_id int(11) DEFAULT NULL, PRIMARY KEY (id), UNIQUE INDEX bt_hoofdgroep_moment_index (hoofdgroep_id), CONSTRAINT FK__bt_toezichtmomenten_hoofdgroepen__toezichtmoment_id FOREIGN KEY (toezichtmoment_id) REFERENCES bt_toezichtmomenten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK__bt_toezichtmomenten_hoofdgroepen__hoofdgroep_id FOREIGN KEY (hoofdgroep_id) REFERENCES bt_hoofdgroepen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; alter table `klanten` add column heeft_toezichtmomenten_licentie enum ('nee', 'ja') NOT NULL DEFAULT 'nee'; <file_sep><?php require_once 'base.php'; function _get_doorloop_tijden_sort( $a, $b ) { $adiff = $a->laatste_datum - $a->aanmaak_datum; $bdiff = $b->laatste_datum - $b->aanmaak_datum; return $bdiff - $adiff; } class Statistiek extends BaseModel { function Statistiek() { parent::BaseModel( '', '' ); } public function check_access( BaseResult $object ) { // disabled for model } function get_gebruiker( $klant_id ) { if (!$this->_CI->dbex->is_prepared( 'get_gebruiker_statistieken' )) $this->_CI->dbex->prepare( 'get_gebruiker_statistieken', ' SELECT COUNT(*) AS aantal, g.volledige_naam, g.intern, g.status FROM gebruikers g JOIN dossiers d ON (d.gebruiker_id = g.id) JOIN deelplannen r ON (r.dossier_id = d.id) WHERE g.klant_id = ? GROUP BY g.id ORDER BY aantal DESC ' ); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_gebruiker_statistieken', $args ); $result = $res->result(); $res->free_result(); return $result; } function get_functie_frequency( $klant_id ) { if (!$this->_CI->dbex->is_prepared( 'get_functie_frequency_func' )) $this->_CI->dbex->prepare( 'get_functie_frequency_func', ' SELECT COUNT(*) AS aantal, cg.id, cg.naam FROM gebruikers g JOIN dossiers d ON (d.gebruiker_id = g.id) JOIN deelplannen r ON (r.dossier_id = d.id) JOIN deelplan_checklisten rc ON (r.id = rc.deelplan_id) JOIN bt_checklisten c ON (rc.checklist_id = c.id) JOIN bt_checklist_groepen cg ON (c.checklist_groep_id = cg.id) WHERE g.klant_id = ? GROUP BY cg.id ORDER BY aantal DESC ' ); if (!$this->_CI->dbex->is_prepared( 'get_functie_frequency_subfunc' )) $this->_CI->dbex->prepare( 'get_functie_frequency_subfunc', ' SELECT COUNT(*) AS aantal, sf.checklist_id, c.naam FROM gebruikers g JOIN dossiers d ON (d.gebruiker_id = g.id) JOIN deelplannen r ON (r.dossier_id = d.id) JOIN deelplan_checklisten sf ON (r.id = sf.deelplan_id) JOIN bt_checklisten c ON (sf.checklist_id = c.id) WHERE g.klant_id = ? GROUP BY sf.checklist_id ORDER BY aantal DESC ' ); $result = array(); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_functie_frequency_func', $args ); $result['functies'] = $res->result(); $res->free_result(); $res = $this->dbex->execute( 'get_functie_frequency_subfunc', $args ); $result['subfuncties'] = $res->result(); $res->free_result(); return $result; } function get_doorloop_tijden( $klant_id ) { $this->_CI->load->model('dossier'); if (!$this->_CI->dbex->is_prepared( 'get_snelkeuzes_statistieken' )) $this->_CI->dbex->prepare( 'get_snelkeuzes_statistieken', ' SELECT d.*, MAX(l.datum) AS laatste_datum FROM gebruikers g JOIN dossiers d ON (d.gebruiker_id = g.id) JOIN deelplannen r ON (d.id = r.dossier_id) JOIN logs l ON (l.rapport_id = d.id) WHERE g.klant_id = ? GROUP BY r.id ' ); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_snelkeuzes_statistieken', $args ); $result = array(); foreach ($res->result() as $row) { $r = $this->_CI->dossier->getr( $row ); $looptijd = $r->laatste_datum - $r->aanmaak_datum; $d = floor( $looptijd / (24*60*60) ); $looptijd -= $d * (24*60*60); $h = floor( $looptijd / (60*60) ); $looptijd -= $h * (60*60); $m = floor( $looptijd / 60 ); $r->looptijd = sprintf("%dd %02du %02dm", $d, $h, $m ); $result[] = $r; } $res->free_result(); uasort( $result, '_get_doorloop_tijden_sort' ); return $result; } function get_vraag_status( $klant_id ) { if (!$this->_CI->dbex->is_prepared( 'get_vraag_status_statistieken' )) $this->_CI->dbex->prepare( 'get_vraag_status_statistieken', ' SELECT COUNT(*) AS aantal, rv.status FROM deelplan_vragen rv JOIN deelplannen r ON (rv.deelplan_id = r.id) JOIN dossiers d ON (r.dossier_id = d.id) JOIN gebruikers g ON (d.gebruiker_id = g.id) WHERE g.klant_id = ? GROUP BY rv.status ' ); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_vraag_status_statistieken', $args ); $result = $res->result(); $res->free_result(); return $result; } function get_dossiers_uit_periode( $klant_id, $van=null, $tot=null ) { $this->_CI->load->model('dossier'); $q = sprintf( ' SELECT d.* FROM dossiers d JOIN gebruikers g ON (d.gebruiker_id = g.id) WHERE g.klant_id = ? %s %s ORDER BY d.aanmaak_datum DESC ', !$van?'':('AND aanmaak_datum >= '.$van), !$tot?'':('AND aanmaak_datum <= '.$tot) ); $this->_CI->dbex->prepare( 'get_deelplannen_uit_periode', $q ); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_deelplannen_uit_periode', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $this->_CI->dossier->getr( $row ); $res->free_result(); return $result; } function get_toetstijden( $klant_id ) { if (!$this->_CI->dbex->is_prepared( 'get_toetstijden_statistieken' )) $this->_CI->dbex->prepare( 'get_toetstijden_statistieken', ' SELECT rv.vraag_id, rv.seconden, cl.id AS checklist_id, cl.naam AS checklist_naam, h.naam AS hoofdgroep_naam, h.id AS hoofdgroep_id, c.naam AS categorie_naam, c.id AS categorie_id, v.* FROM deelplan_vragen rv JOIN deelplannen r ON (rv.deelplan_id = r.id) JOIN dossiers d ON (r.dossier_id = d.id) JOIN gebruikers g ON (d.gebruiker_id = g.id), bt_vragen v, bt_categorieen c, bt_hoofdgroepen h, bt_checklisten cl WHERE g.klant_id = ? AND rv.vraag_id = v.id AND v.categorie_id = c.id AND c.hoofdgroep_id = h.id AND h.checklist_id = cl.id ORDER BY h.sortering, c.sortering, v.sortering ' ); $args = array( $klant_id ); $res = $this->dbex->execute( 'get_toetstijden_statistieken', $args ); $result = array(); foreach ($res->result() as $row) { if (!isset( $result[ $row->vraag_id ] )) $result[ $row->vraag_id ] = array( 'max'=>0, 'min'=>999999999, 'total'=>0, 'count'=>0, 'data'=>$row ); $result[ $row->vraag_id ]['total'] += $row->seconden; $result[ $row->vraag_id ]['count']++; $result[ $row->vraag_id ]['min'] = min( $row->seconden, $result[ $row->vraag_id ]['min'] ); $result[ $row->vraag_id ]['max'] = max( $row->seconden, $result[ $row->vraag_id ]['max'] ); } foreach( $result as &$row ) $row['avg'] = round( $row['total'] / $row['count'] ); $res->free_result(); return $result; } } <file_sep><? require_once 'base.php'; class WebserviceApplicatieResult extends BaseResult { function WebserviceApplicatieResult( &$arr ) { parent::BaseResult( 'webserviceapplicatie', $arr ); } function get_dossier_informatie() { return get_instance()->webserviceapplicatiedossier->get_for_webapplicatie_id( $this->id ); } function get_deelplan_informatie() { return get_instance()->webserviceapplicatiedeelplan->get_for_webapplicatie_id( $this->id ); } function get_bescheiden_informatie() { return get_instance()->webserviceapplicatiebescheiden->get_for_webapplicatie_id( $this->id ); } } class WebserviceApplicatie extends BaseModel { function WebserviceApplicatie() { parent::BaseModel( 'WebserviceApplicatieResult', 'webservice_applicaties', true ); } function get_by_name( $name ) { $stmt_name = 'WebserviceApplicatie::get_by_name'; $CI = get_instance(); $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE naam = ?' ); $results = $this->convert_results( $CI->dbex->execute( $stmt_name, array( $name ) ) ); if (empty( $results )) return null; return reset( $results ); } } <file_sep><?php require_once '../../../application/models/base.php'; class DeelplanOpdrachtResult extends BaseResult { function DeelplanOpdrachtResult( &$arr ) { parent::BaseResult( 'deelplanopdracht', $arr ); } private function _get_data_keys() { return array( 'overzicht_afbeelding_0', 'overzicht_afbeelding_1', 'overzicht_afbeelding_2', 'overzicht_afbeelding_3', 'overzicht_afbeelding_4', 'overzicht_afbeelding_5', 'overzicht_afbeelding_6', 'overzicht_afbeelding_7', 'overzicht_afbeelding_8', 'overzicht_afbeelding_9', 'snapshot_afbeelding', ); } function load_image_data() { if (property_exists($this, 'overzicht_afbeelding_0')) return; // get data $res = $this->_CI->db->query('SELECT ' . implode(',', $this->_get_data_keys()) . ' FROM deelplan_opdrachten WHERE id = ' . intval($this->id)); if (!$res) throw new Exception('Kon opdracht informatie niet ophalen voor opdracht ' . intval($this->id)); $my_data = reset($res->result()); if (!$my_data) throw new Exception('Kon opdracht informatie niet vinden voor opdracht ' . intval($this->id)); $res->free_result(); // process data foreach ($my_data as $k => $v) $this->$k = $v; } function unload_image_data() { foreach ($this->_get_data_keys() as $k) unset($this->$k); } function get_deelplan() { $this->_CI->load->model( 'deelplan' ); return $this->_CI->deelplan->get( $this->deelplan_id ); } function get_vraag() { $this->_CI->load->model( 'vraag' ); return $this->_CI->vraag->get( $this->vraag_id ); } function get_dossier_opdrachtgever() { $this->_CI->load->model( 'gebruiker' ); return $this->_CI->gebruiker->get( $this->opdrachtgever_gebruiker_id ); } function get_dossier_subject() { $this->_CI->load->model( 'dossiersubject' ); return $this->_CI->dossiersubject->get( $this->dossier_subject_id ); } function get_dossier_bescheiden() { $this->_CI->load->model( 'dossierbescheiden' ); return $this->_CI->dossierbescheiden->get( $this->dossier_bescheiden_id ); } function get_deelplan_upload() { $this->_CI->load->model( 'deelplanupload' ); return $this->_CI->deelplanupload->get( $this->deelplan_upload_id ); } function get_deelplan_uploads() { $this->_CI->load->model( 'deelplanupload' ); return $this->_CI->deelplanupload->get_by_opdracht( $this->id ); } function get_overzicht_afbeelding_aantal() { $i = 0; while ($this->{'overzicht_afbeelding_' . $i}) ++$i; return $i; } function get_overzicht_afbeelding_url( $i ) { return site_url( '/deelplannen/opdracht_afbeelding/overzicht/' . $this->id . '/' . $i ); } function get_snapshot_afbeelding_url() { return site_url( '/deelplannen/opdracht_afbeelding/snapshot/' . $this->id ); } function get_overzicht_afbeelding_preview_url( $size ) { return site_url( '/deelplannen/opdracht_afbeelding/overzicht_preview/' . $this->id . '/' . $size ); } function get_snapshot_afbeelding_preview_url( $size ) { return site_url( '/deelplannen/opdracht_afbeelding/snapshot_preview/' . $this->id . '/' . $size ); } public function update_toezichtmoment_gereed() { $model = $this->_model; $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'categorie' ); $this->_CI->load->model( 'hoofdgroep' ); $this->_CI->load->model( $model ); $this->_CI->load->model( 'toezichtmoment' ); $this->_CI->load->model( 'deelplanchecklisttoezichtmoment' ); $this->_CI->load->model( 'projectmap' ); $this->_CI->load->model( 'deelplan' ); $deelplan = $this->_CI->deelplan->get($this->deelplan_id); $proj_vragen = $this->_CI->projectmap->get_by_deelplan( $deelplan ); foreach( $proj_vragen as $proj_vraag ){ if($proj_vraag->vraag_id == $this->vraag_id) break; } if($proj_vraag->toezichtmoment_id == NULL ){ return TRUE; } $vraag = $this->_CI->vraag->get($this->vraag_id); $categorie = $this->_CI->categorie->get($vraag->categorie_id); $hoofdgroep = $this->_CI->hoofdgroep->get($categorie->hoofdgroep_id); // $toezichtmoment = $this->_CI->toezichtmoment->get_by_hoofdgroep($hoofdgroep->id); // if($toezichtmoment->id == NULL ) // return TRUE; $is_gereed = true; $categorieen = $hoofdgroep->get_categorieen(); foreach($categorieen as $cat ) { $cat_vragen = $cat->get_vragen(); foreach($cat_vragen as $cat_vraag ) { $opdrachten = $this->_CI->$model->search(array('deelplan_id'=>$this->deelplan_id,'vraag_id'=>$cat_vraag->id,'deelplan_checklist_id'=>$this->deelplan_checklist_id)); foreach($opdrachten as $opdracht) { $is_gereed = ($opdracht->status == 'gereed'); if( !$is_gereed ) break; } if( !$is_gereed ) break; } } // $deelplanchecklisttoezichtmoment = $this->_CI->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist($this->deelplan_checklist_id,$toezichtmoment->id); $deelplanchecklisttoezichtmoment = $this->_CI->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist($this->deelplan_checklist_id, $proj_vraag->toezichtmoment_id ); if(!count($deelplanchecklisttoezichtmoment)) return TRUE; $deelplanchecklisttoezichtmoment = $deelplanchecklisttoezichtmoment[0]; $deelplanchecklisttoezichtmoment->status_gereed_uitvoerende = $is_gereed; $deelplanchecklisttoezichtmoment->save(); } function markeer_gereed() { if ($this->status == 'gereed') return; // bepaal notificatie data $this->_CI->load->model( 'notificatie' ); $deelplan = $this->get_deelplan(); $dossier = $deelplan->get_dossier(); $target_gebruiker_id = $this->opdrachtgever_gebruiker_id ? $this->opdrachtgever_gebruiker_id : $target_gebruiker_id = $dossier->gebruiker_id; $uitvoerder = isset($this->gebruiker_id) ? $this->_CI->gebruiker->get_logged_in_gebruiker()->volledige_naam : $subject = $this->get_dossier_subject()->naam; $bericht = 'Gebruiker ' . $uitvoerder. ' heeft opdracht afgerond voor ' . $dossier->kenmerk . '/' . $deelplan->naam . ($this->annotatie_tag ? ', foto locatie ' . $this->annotatie_tag : '') . ', opdracht "' . $this->opdracht_omschrijving . '"'; // markeer gereed $this->status = 'gereed'; $this->save(); $this->update_toezichtmoment_gereed(); // voeg notificatie toe $this->_CI->notificatie->add_gebruiker_specifieke_notificatie( $target_gebruiker_id, $bericht ); } public function verwerk_in_layer() { // geen annotatie tag? dan niks te doen if (!$this->annotatie_tag) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': geen annotatie tag, doe niks' ); return; } // geen foto nog geupload? dan niks doen if (!($upload = $this->get_deelplan_upload())) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': geen foto upload, doe niks' ); return; } $this->_CI->load->model( 'deelplanlayer' ); // haal deelplan layer informatie op $deelplanlayer = $this->_CI->deelplanlayer->get_layer_for_deelplan_bescheiden( $this->deelplan_id, $this->dossier_bescheiden_id ); if (!$deelplanlayer) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': kan layer data niet vinden voor deelplan/dossier ' . $this->deelplan_id . '/' . $this->dossier_bescheiden_id ); return; } // haal layer op voor onze vraag // NOTE: $layer is NIET een Layer class object (uit application/libraries/pdf-annotator/data/annotation-data.php), maar // een export daarvan, dus een gewoon stdClass PHP object zonder functies, puur data! (Dit is het formaat waarin data via // HTTP/JSON wordt uitgewisseld tussen de server en de website, en de server en de app) $layer = $deelplanlayer->geef_layer_voor_vraag( $this->vraag_id ); if (!$layer) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': kan layer niet vinden voor vraag ' . $this->vraag_id ); return; } // loop door de layer heen, kijk eerst of we een COMPOUND annotatie kunnen vinden // die als filename onze naam heeft; als dat zo is, doen we niks, want dan zijn we // al succesvol verwerkt $foto_tag = preg_replace( '/\.jpg$/i', '', $upload->filename ); foreach ($layer->pages->{'1'} as $annotation) if ($annotation->type == 'compound') if ($annotation->photoid == $foto_tag) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': foto annotatie gevonden met photoid "' . $foto_tag . '", doe niks' ); return; } // ok, we zijn nog niet verwerkt op deze layer, zoek nu naar en FOTO OPDRACHT annotatie // met als naam de tag die in deze opdracht zit $found = false; $worst_set = false; $worst_kleur = ''; $worst_status = ''; $totale_toelichting = ''; foreach ($layer->pages->{'1'} as $i => $annotation) { if ($annotation->type == 'photoassignment') { if ($annotation->photoid == $this->annotatie_tag) { $vraag = $this->get_vraag(); // re-class the annotation, make it a compound annotation instead // of a photoassignment! set the photoid to indicate our the photo // belonging to this compound annotation, and set the rest of the // values. $annotation->type = 'compound'; $annotation->photoid = $foto_tag; // link met foto (niet echt nodig, is al zelfde anders komt er uit de if hierboven niet true) $annotation->status = $this->antwoord; // code voor waardeoordeel: "w01" $annotation->filter = $vraag->get_waardeoordeel_kleur( false, $this->antwoord ); // kleur: "geel" (of "oranje"), "groen" of "rood" $annotation->waardeoordeel = $vraag->get_waardeoordeel( false, $this->antwoord ); // tekst: "Voldoet niet" $annotation->bouwdeel_ids = ''; // niet specifiek gekoppeld aan 1 bouwdeel $annotation->w = 400; // defaults uit APP! $annotation->h = 200; $annotation->textcolor = '000000'; $annotation->bgcolor = 'ffffff'; $annotation->text = $this->toelichting; // de opgegeven toelichting! $annotation->font = 'Arial'; $annotation->fontsize = 16; $annotation->bold = false; $annotation->italic = false; $annotation->underline = false; unset( $annotation->direction ); unset( $annotation->dirlength ); unset( $annotation->dircolor ); unset( $annotation->imagesrc ); unset( $annotation->imagesizew ); unset( $annotation->imagesizeh ); unset( $annotation->imageopdrachtsrc ); // found it! $found = true; } } // we moeten bepalen wat nu de slechtste status/waardeoordeel is, die retourneren we // zodat het vraag antwoord gezet kan worden. // deze check moet NA de if hierboven, omdat die if het type op compound KAN zetten, // en als ie dat doet, dan moeten we em hier meenemen! if ($annotation->type == 'compound') { if (strlen($annotation->text)) $totale_toelichting .= "[GERELATEERDE BEVINDING]\n{$annotation->text}\n\n"; // als dit de eerste compound annotatie is, dan altijd overnemen if (!$worst_set) { $worst_set = true; $worst_kleur = $annotation->filter; $worst_status = $annotation->status; } // anders, kijk of de huidige compound annotatie "slechter/erger" is, // zo ja dan die kopieren else if ($annotation->filter == 'rood' || (($annotation->filter == 'oranje' || $annotation->filter == 'geel') && $worst_kleur == 'groen')) { $worst_kleur = $annotation->filter; $worst_status = $annotation->status; } } else if ($annotation->type == 'text') { if (strlen($annotation->text)) $totale_toelichting .= "[TEKSTBALLON]\n{$annotation->text}\n\n"; } } // tenslotte, de layerdata hercoderen en bewaren, maar alleen als we iets // gevonden (en dus veranderd) hebben if (!$found) { error_log( 'verwerk_in_layer(): opdracht ' . $this->id . ': geen foto opdracht annotatie gevonden met photoid "' . $this->annotatie_tag . '", doe niks' ); return; } $deelplanlayer->hercodeer_layer_informatie(); if (!$deelplanlayer->save(0,0,0)) throw new Exception( 'Fout bij opslaan van deelplan layer informatie.' ); // ok, we're done and everything went succesfull! if (!$worst_set) // except when this is the case, but shouldn't really happen ;-) return; return array( 'nieuwe_status' => $worst_status, 'nieuwe_toelichting' => $totale_toelichting, ); } } class DeelplanOpdracht extends BaseModel { function DeelplanOpdracht() { parent::BaseModel( 'DeelplanOpdrachtResult', 'deelplan_opdrachten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); } public function get_by_deelplan_checklistgroep_checklist( $deelplan_id, $checklistgroep_id=null, $checklist_id=null ) { $q = 'SELECT do.id '. ',do.deelplan_id '. ',do.vraag_id '. ',do.dossier_subject_id '. ',do.opdracht_omschrijving '. ',do.gereed_datum, do.status '. ',do.email_verzonden '. ',do.annotatie_tag '. ',do.tag, do.antwoord '. ',do.deelplan_upload_id '. ',do.opdrachtgever_gebruiker_id '. ',do.`deelplan_checklist_id` AS `deelplan_checklist_id` '. ',(SELECT `bouwnummer` FROM `deelplan_checklisten` `dc` WHERE `dc`.`id`=`do`.`deelplan_checklist_id` LIMIT 1) AS `bouwnummer`'. 'FROM deelplan_opdrachten `do` JOIN bt_vragen v ON do.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id WHERE do.deelplan_id = ' . intval( $deelplan_id ) . ' ' . ($checklistgroep_id ? 'AND cl.checklist_groep_id = ' . intval( $checklistgroep_id ) : '') . ' ' . ($checklist_id ? ' AND cl.id = ' . intval($checklist_id) : '') . ' '; return $this->convert_results( $this->db->query( $q ) ); } public function add_zonder_foto( $deelplan_id, $data ) { $vraag_id = $data->vraag_id; $dossier_subject_id = $data->dossier_subject_id; $opdracht_omschrijving = $data->opdracht_omschrijving; $gereed_datum = date('Y-m-d', strtotime($data->gereed_datum)); $tag = $data->tag; $deelplanchecklist_id = $data->deelplanchecklist_id; // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method, passing a suffix for the prepared statement name along, in order to make the statement name unique. $gebruiker_id = $this->_CI->gebruiker->get_logged_in_gebruiker()->id; $data = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'dossier_subject_id' => $dossier_subject_id, 'opdracht_omschrijving' => $opdracht_omschrijving, 'gereed_datum' => (get_db_type() == 'oracle') ? array('format_string' => get_db_literal_for_date("?"), 'data' => $gereed_datum) : $gereed_datum, 'status' => 'nieuw', 'email_verzonden' => 0, 'opdrachtgever_gebruiker_id' => $gebruiker_id, 'tag' => $tag ? $tag : (sha1(microtime() . mt_rand())), 'deelplan_checklist_id' => $deelplanchecklist_id ); // Call the normal 'insert' method of the base record. Note that a very similar call is made in the 'add_met_foto' method down below, in order to // properly distinguish between the call made here, and that one, and hence, to not accidentally re-use the previously prepared statement (with an incorrect // number of parameters(!)) that would result by relying on the name by which the 'insert' method stores the prepared statement by name, make sure to pass a // unique 'statement name suffix' to the 'insert' method! $force_types = (get_db_type() == 'oracle') ? 'iiicssiisi' : ''; $result = $this->insert( $data, '_zonder_foto', $force_types ); return $result; } public function add_met_foto( $deelplan_id, $vraag_id, $dossier_subject_id, $opdracht_omschrijving, $gereed_datum, $dossier_bescheiden_id, $annotatie_tag, $tag=null ) { // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. $gebruiker_id = $this->_CI->gebruiker->get_logged_in_gebruiker()->id; $data = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'dossier_subject_id' => $dossier_subject_id, 'opdracht_omschrijving' => $opdracht_omschrijving, 'gereed_datum' => (get_db_type() == 'oracle') ? array('format_string' => get_db_literal_for_date("?"), 'data' => $gereed_datum) : $gereed_datum, 'status' => 'nieuw', 'email_verzonden' => 0, 'dossier_bescheiden_id' => $dossier_bescheiden_id, 'annotatie_tag' => $annotatie_tag, 'opdrachtgever_gebruiker_id' => $gebruiker_id, 'tag' => $tag ? $tag : (sha1(microtime() . mt_rand())), ); // Call the normal 'insert' method of the base record. Note that a very similar call is made in the 'add_zonder_foto' method above, in order to // properly distinguish between the call made here, and that one, and hence, to not accidentally re-use the previously prepared statement (with an incorrect // number of parameters(!)) that would result by relying on the name by which the 'insert' method stores the prepared statement by name, make sure to pass a // unique 'statement name suffix' to the 'insert' method! // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'iiicssiisis' : ''; $result = $this->insert( $data, '_met_foto', $force_types ); return $result; //return $this->insert( $data ); } public function get_deelplan_upload_image ($upload_id) { $this->_CI->load->model( 'deelplanupload' ); $deelplanupload = $this->_CI->deelplanupload->get( $upload_id ); return $deelplanupload->get_data(); } public function get_my_opdrachten( $gebruiker_id=null, $only_unfinished=true ) { if (!$gebruiker_id ) { $gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker(); if (!$gebruiker) return array(); $gebruiker_id = $gebruiker->id; } $external_user = $this->_CI->gebruiker->is_external_user(); if ($external_user) { $query = ' SELECT o.*, c.hoofdgroep_id, (SELECT `bouwnummer` FROM `deelplan_checklisten` `dc` WHERE `dc`.`id`=`o`.`deelplan_checklist_id` LIMIT 1) AS `bouwnummer` FROM deelplan_opdrachten o JOIN dossier_subjecten ds ON o.dossier_subject_id = ds.id JOIN bt_vragen v ON o.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN externe_gebruikers e ON ds.email = e.email WHERE e.id = ' . $gebruiker_id .($only_unfinished ? ' AND o.status = \'nieuw\'' : '') . ' ORDER BY o.gereed_datum '; return $this->convert_results( $this->db->query( $query ), true); } else { $query = ' SELECT o.* FROM deelplan_opdrachten o JOIN dossier_subjecten ds ON o.dossier_subject_id = ds.id WHERE ds.gebruiker_id = ' . $gebruiker_id . ' ' . ($only_unfinished ? 'AND status = \'nieuw\'' : '') . ' ORDER BY o.gereed_datum '; return $this->convert_results( $this->db->query( $query )); } } } <file_sep>-- run php index.php /cli/fillgrondslagtekstentabel<file_sep><? if(!isset($table_type)){ $table_type=""; $table_class=""; } else { $table_class=$table_type;?> <script src="/files/js/tableHeadFixer.js"></script> <script> $(document).ready(function() { $(".list2.gebruikers").tableHeadFixer({"left" : 3}); }); </script> <?php } if (!isset( $do_paging )) $do_paging = false; if (!is_array( @$viewdata )) $viewdata = array( 'sortfield' => 'foobar', 'sortorder' => 'asc', 'search' => null, ); if (!is_array( @$col_widths )) $col_widths = array( 'foobar' => 250, ); if (!is_array( @$col_description )) $col_description = array( 'foobar' => 'Missing col_description array', ); if (!is_array( @$col_unsortable )) $col_unsortable = array(); if (!isset( $config ) || !is_array( $config )) $config = array(); if (!isset( $url_template )) { $url_template = ''; foreach ($config as $key => $unused) $url_template .= '/' . $key; if ($do_paging) $url_template .= '/pagenum/pagesize/sortfield/sortorder/search'; else $url_template .= '/sortfield/sortorder/search'; } if (!isset( $url )) $url = '/missing/url/variable'; if (!isset( $scale_field )) $scale_field = reset( array_reverse( array_keys( $col_widths ) ) ); if (!isset( $header )) $header = ''; if (!isset( $disable_search )) $disable_search = false; if (!isset( $center_headers )) $center_headers = array(); ?> <? // set sort image HTML $sort_image = '<img src="'.site_url('/files/images/sort_' . $viewdata['sortorder'] . '.png').'" style="float:left" />'; // note: append to initial header! $header2 = ''; if (!$disable_search) $header2 .= ' <div style="height: auto; background-color: transparent; border: 0; padding: 0; margin: 0;"> <input type="text" value="' . htmlentities($viewdata['search'], ENT_COMPAT, 'UTF-8') . '" name="filter_text" size="20" /> <input name="search_button" type="button" value="' . tgng('form.zoeken') . '" /> <input name="reset_button" type="button" value="' . tgng('form.wissen') . '" /> </div> '; ?> <!-- begin searchable list --> <div class="searchable-list" style="padding:0;margin:0;background-color:inherit;height:auto;border:0"> <!-- header with search block --> <? if ($header || $header2): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => $header, 'rightheader' => $header2, 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <div class="searchable-list" style="padding:0;margin:0;background-color:inherit;height:auto;border:0"> <!-- main contents --> <table class="list2 <?=$table_class;?>" width="100%" cellpadding="0" cellspacing="0" border="0"> <thead<?php if(isset($header_id))echo ' id="'.$header_id.'"';?>> <tr> <td class="left" style="width: 16px">&nbsp;</td> <? foreach ($col_description as $field => $description): ?> <? if (in_array( $field, $col_unsortable )): ?> <td class="mid" style="<?=$field!=$scale_field ? 'width: ' . $col_widths[$field] . 'px;' : ''?> <?=in_array( $field, $center_headers ) ? 'text-align:center;' : ''?>"> <?=$description?> </td> <? else: ?> <td class="mid" style="cursor:pointer; <?=$field!=$scale_field ? 'width: ' . $col_widths[$field] . 'px;': ''?> <?=in_array( $field, $center_headers ) ? 'text-align:center;' : ''?>" sortfield="<?=$field?>" sortorder="<?=$viewdata['sortfield']==$field && $viewdata['sortorder']=='asc' ? 'desc' : 'asc'?>"> <?=$viewdata['sortfield']==$field ? $sort_image : ''?> <?=$description?> </td> <? endif; ?> <? endforeach; ?> <td class="right" style="width: 16px">&nbsp;</td> </tr> </thead> <tbody> <? if ($table_type!="gebruikers") :?> <? foreach ($rows as $i => $row): ?> <tr> <td class="container rounded5 <?=$i % 2 ? 'zebra' : ''?>" colspan="<?=sizeof($col_widths)+2?>" style="padding: 5px 0px; cursor: pointer;" onclick="<?=$row->onclick?>"> <table class="contents" style="width:100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td style="width: 16px"></td> <? foreach ($row->data as $field => $value): ?> <? $width = $field!=$scale_field ? $col_widths[$field] : null; ?> <td style="<?=$width ? 'width:' . $width . 'px; ' : ''?> <?=in_array( $field, $center_headers ) ? 'text-align:center;' : ''?>"> <?=$value?> </td> <? endforeach; ?> <td style="width: 12px"></td> </tr> </table> </td> </tr> <? endforeach; ?> <? else :?> <? foreach ($rows as $i => $row): ?> <tr class="container rounded5 <?=$i % 2 ? 'zebra' : ''?>" colspan="<?=sizeof($col_widths)+2?>" style="padding: 5px 0px; cursor: pointer;" onclick="<?=$row->onclick?>"> <td style="width: 16px"></td> <? foreach ($row->data as $field => $value): ?> <? $width = $field!=$scale_field ? $col_widths[$field] : null; ?> <td style="<?=$width ? 'width:' . $width . 'px; ' : 'width:16px;'?> <?=in_array( $field, $center_headers ) ? 'text-align:center;' : ''?>"> <?=$value?> </td> <? endforeach; ?> <td style="width: 16px"></td> </tr> <? endforeach; ?> <?endif;?> </tbody> </table> </div> <div class="configuration hidden"> <!-- config elements --> <? if ($do_paging): ?> <div config="pagenum" value="<?=$viewdata['pagenum']?>"></div> <div config="pagesize" value="<?=$viewdata['pagesize']?>"></div> <? endif; ?> <div config="search" value="<?=htmlentities( $viewdata['search'], ENT_QUOTES, 'UTF-8' )?>"></div> <div config="sortfield" value="<?=$viewdata['sortfield']?>"></div> <div config="sortorder" value="<?=$viewdata['sortorder']?>"></div> <? foreach ($config as $key => $value): ?> <div config="<?=$key?>" value="<?=htmlentities( $value, ENT_QUOTES, 'UTF-8' )?>"></div> <? endforeach; ?> <!-- url --> <div url="<?=$url?>" template="<?=$url_template?>"></div> </div> <? if (isset( $post_table_html )): ?> <!-- post table html --> <?=$post_table_html?> <? endif; ?> <? if ($do_paging): ?> <? // handle large lists: lists with more than 15 pages $large_list_count = 15; if ($viewdata['pages'] > $large_list_count) { // do first five for ($i=0; $i<5; ++$i) $allow_list[$i] = true; // do pages around current one for ($i=$viewdata['pagenum']-2; $i<=$viewdata['pagenum']+2; ++$i) if ($i >= 0 && $i<$viewdata['pages']) $allow_list[$i] = true; // do last five for ($i=$viewdata['pages']-6; $i < $viewdata['pages']; ++$i) $allow_list[$i] = true; } else // allow all pages for ($i=0; $i < $viewdata['pages']; ++$i) $allow_list[$i] = true; ?> <div style="height: 5px;"></div> <table width="100%"><tr><td style="text-align:left"> <? if ($viewdata['pagesize'] != 'alle'): ?> <? $brokelist = false; ?> <input type="button" <?=$viewdata['pagenum'] ? '' : 'disabled'?> value="&lt;&lt;" pagenum="0" /> <input type="button" <?=$viewdata['pagenum'] ? '' : 'disabled'?> value="&lt;" pagenum="-1" /> <? for ($i=0; $i<$viewdata['pages']; ++$i): ?> <? if (!isset( $allow_list[$i] )) { $brokelist = true; continue; } ?> <? if ($brokelist): $brokelist = false; ?>...<?endif;?> <input type="button" <?=$viewdata['pagenum']!=$i ? '' : 'disabled'?> value="<?=$i+1?>" pagenum="<?=$i?>" /> <? endfor; ?> <input type="button" <?=$viewdata['pagenum'] != $viewdata['pages'] - 1 ? '' : 'disabled'?> value="&gt;" pagenum="+1" /> <input type="button" <?=$viewdata['pagenum'] != $viewdata['pages'] - 1 ? '' : 'disabled'?> value="&gt;&gt;" pagenum="<?=$viewdata['pages']-1?>" /> <? endif; ?> </td><td style="text-align:right"> <? foreach (array( 10=>10, 25=>25, 50=>50, 100=>100, 'alle'=>tgng('form.alles') ) as $val => $desc): ?> <input type="button" <?=$val == $viewdata['pagesize'] ? 'disabled' : ''?> value="<?=$desc?>" pagesize="<?=$val?>" /> <? endforeach; ?> </td></tr></table> <? endif; ?> <? if (isset( $new_button_js ) && !is_null( $new_button_js )): ?> <!-- new block --> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => '<input style="float:right" name="new_button" type="button" value="' . tgng('form.nieuw') . '" onclick="' . $new_button_js . '" />', 'rightheader' => '', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> </div> <!-- end searchable list --> <file_sep>ALTER TABLE `bt_checklisten` ADD `standaard_checklist_status` ENUM( 'open', 'afgerond' ) NULL DEFAULT NULL, ADD `standaard_vraag_type` ENUM( 'meerkeuzevraag', 'invulvraag' ) NULL DEFAULT NULL, ADD `standaard_vraag_aanwezigheid` INT NULL , ADD `standaard_hoofdthema_id` INT NULL DEFAULT NULL , ADD `standaard_thema_id` INT NULL DEFAULT NULL , ADD `standaard_toezicht_moment` VARCHAR( 128 ) NULL , ADD `standaard_fase` VARCHAR( 128 ) NULL; ALTER TABLE `bt_checklisten` ADD INDEX ( `standaard_hoofdthema_id` ); ALTER TABLE `bt_checklisten` ADD INDEX ( `standaard_thema_id` ); ALTER TABLE `bt_checklisten` ADD FOREIGN KEY ( `standaard_hoofdthema_id` ) REFERENCES `bt_hoofdthemas` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `bt_checklisten` ADD FOREIGN KEY ( `standaard_thema_id` ) REFERENCES `bt_themas` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `bt_checklisten` ADD `standaard_waardeoordeel_tekst_00` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_00` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_01` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_01` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_02` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_02` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_03` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_03` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_04` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_04` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_10` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_10` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_11` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_11` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_12` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_12` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_13` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_13` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_14` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_14` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_20` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_20` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_21` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_21` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_22` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_22` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_23` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_23` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_tekst_24` VARCHAR(32) NULL DEFAULT NULL, ADD `standaard_waardeoordeel_kleur_24` ENUM('groen','oranje','rood') NULL DEFAULT NULL; ALTER TABLE `bt_checklisten` ADD `standaard_waardeoordeel_is_leeg_00` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_00`, ADD `standaard_waardeoordeel_is_leeg_01` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_01`, ADD `standaard_waardeoordeel_is_leeg_02` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_02`, ADD `standaard_waardeoordeel_is_leeg_03` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_03`, ADD `standaard_waardeoordeel_is_leeg_04` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_04`, ADD `standaard_waardeoordeel_is_leeg_10` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_10`, ADD `standaard_waardeoordeel_is_leeg_11` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_11`, ADD `standaard_waardeoordeel_is_leeg_12` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_12`, ADD `standaard_waardeoordeel_is_leeg_13` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_13`, ADD `standaard_waardeoordeel_is_leeg_14` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_14`, ADD `standaard_waardeoordeel_is_leeg_20` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_20`, ADD `standaard_waardeoordeel_is_leeg_21` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_21`, ADD `standaard_waardeoordeel_is_leeg_22` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_22`, ADD `standaard_waardeoordeel_is_leeg_23` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_23`, ADD `standaard_waardeoordeel_is_leeg_24` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_tekst_24`; ALTER TABLE `bt_checklisten` ADD `standaard_waardeoordeel_standaard` ENUM('00','01','02','03','04','10','11','12','13','14','20','21','22','23','24') NULL DEFAULT NULL, ADD `standaard_waardeoordeel_steekproef` ENUM('00','01','02','03','04','10','11','12','13','14','20','21','22','23','24') NULL DEFAULT NULL; CREATE TABLE `bt_checklist_grondslagen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `grondslag_tekst_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `checklist_id` (`checklist_id`), KEY `grondslag_tekst_id` (`grondslag_tekst_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `bt_checklist_grondslagen` ADD CONSTRAINT FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`grondslag_tekst_id`) REFERENCES `bt_grondslag_teksten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE `bt_checklist_richtlijnen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `richtlijn_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `richtlijn_id` (`richtlijn_id`), KEY `checklist_id` (`checklist_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `bt_checklist_richtlijnen` ADD CONSTRAINT FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`richtlijn_id`) REFERENCES `bt_richtlijnen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE `bt_checklist_aandachtspunten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `aandachtspunt` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `checklist_id` (`checklist_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `bt_checklist_aandachtspunten` ADD CONSTRAINT FOREIGN KEY ( `checklist_id` ) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep><?php class BTZAppWebserviceModule extends WebserviceModule { public function GeefGebruikerInfo() { $this->_output_json( (object)array( 'Success' => true, 'Ingelogd' => $this->CI->login->logged_in(), 'GebruikerId' => $this->CI->login->logged_in() ? $this->CI->login->get_user_id() : 0, 'VolledigeNaam' => $this->CI->login->logged_in() ? $this->CI->gebruiker->get_logged_in_gebruiker()->volledige_naam : '', ) ); } public function GeefDossiersVoorToezichthouder() { // haal gebruiker op if (!($gebruiker = $this->CI->gebruiker->get( $this->CI->login->get_user_id() ))) throw new DataSourceException( 'Niet ingelogd' ); if (!$this->_account->mag_bij_klant( $gebruiker->klant_id )) throw new DataSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot klant van opgegeven gebruiker.' ); // haal dossiers op $this->CI->load->model( 'dossier' ); $list = array_merge( $this->CI->dossier->get_by_gebruiker( intval( $gebruiker->id ), $unused_ref, null, false /* de niet gearchiveerde dossiers */ ), $this->CI->dossier->get_van_collegas( intval( $gebruiker->id ), $unused_ref, null, null, false /* de niet gearchiveerde dossiers */ ), $this->CI->dossier->get_by_gebruiker( intval( $gebruiker->id ), $unused_ref, null, true /* de WEL gearchiveerde dossiers */ ), $this->CI->dossier->get_van_collegas( intval( $gebruiker->id ), $unused_ref, null, null, true /* de WEL gearchiveerde dossiers */ ) ); $dossiers = array(); foreach ($list as $dossier) $dossiers[$dossier->id] = $dossier; $dossiers = array_values( $dossiers ); // bouw output $data = array( 'Success' => true, 'Dossiers' => array(), ); foreach ($dossiers as $dossier) { // sla verwijderde dossiers over if ($dossier->verwijderd) continue; // sla dossiers zonder deelplannen over $deelplannen = $dossier->get_deelplannen(); if (empty( $deelplannen )) continue; $dosdata = array( 'DossierId' => intval( $dossier->id ), 'Identificatienummer' => strval( $dossier->kenmerk ), 'Dossiernaam' => strval( $dossier->beschrijving ), 'LaatstBijgewerktOp' => date( 'd-m-Y', strtotime( $dossier->laatst_bijgewerkt_op ) ), 'AangemaaktOp' => date( 'd-m-Y', $dossier->aanmaak_datum ), 'Locatie' => array( 'Adres' => $dossier->locatie_adres, 'Postcode' => $dossier->locatie_postcode, 'Woonplaats' => $dossier->locatie_woonplaats, 'Kadastraal' => $dossier->locatie_kadastraal, 'Sectie' => $dossier->locatie_sectie, 'Nummer' => $dossier->locatie_nummer, 'GeoLocatie' => ($geo = $dossier->get_geo_locatie()) ? array( 'Latitude' => floatval($geo->latitude), 'Longitude' => floatval($geo->longitude) ) : null, ), 'Correspondentie' => array( 'Adres' => $dossier->correspondentie_adres, 'Postcode' => $dossier->correspondentie_postcode, 'Plaats' => $dossier->correspondentie_plaats ), 'Herkomst' => strval( $dossier->herkomst ), 'Opmerkingen' => strval( $dossier->opmerkingen ), 'BagIdentificatieNummer' => strval( $dossier->bag_identificatie_nummer ), 'XYCoordinaten' => strval( $dossier->xy_coordinaten ), 'Gearchiveerd' => $dossier->gearchiveerd ? true : false, 'VerantwoordelijkeGebruikerId' => intval( $dossier->gebruiker_id ), 'Deelplannen' => array(), ); foreach ($deelplannen as $deelplan) { $bouwdelen = array(); foreach ($deelplan->get_bouwdelen() as $bouwdeel) { $bouwdelen[] = $bouwdeel->get_array_copy(); } $dpdata = array( 'DeelplanId' => intval( $deelplan->id ), 'Identificatienummer' => strval( $deelplan->kenmerk ), 'DeelplanNaam' => strval( $deelplan->naam ), 'OloNummer' => strval( $deelplan->olo_nummer ), 'AangevraagdOp' => date( 'd-m-Y', strtotime( $deelplan->aanvraag_datum ) ), 'AangemaaktOp' => date( 'd-m-Y', strtotime( $deelplan->aangemaakt_op ) ), 'Afgemeld' => $deelplan->afgemeld ? true : false, 'Bouwdelen' => $bouwdelen, 'Scopes' => array(), ); foreach ($deelplan->get_checklistgroepen() as $checklistgroep) { if ($checklistgroep->modus != 'niet-combineerbaar') { // simpelweg het checklistgroep ID voldoet $dpdata['Scopes'][] = array( 'ChecklistGroepId' => intval( $checklistgroep->id ), 'Naam' => $checklistgroep->naam, 'GeplandeDatum' => $deelplan->get_plannings_datum( $checklistgroep->id ), 'ToezichthouderGebruikerId' => ($g = $deelplan->get_toezichthouder( $checklistgroep->id )) ? intval($g->id) : null, ); } else { // combineer checklistgroep ID en checklist ID foreach ($deelplan->get_checklisten() as $checklist) { if ($checklist->checklist_groep_id == $checklistgroep->id) { $dpdata['Scopes'][] = array( 'ChecklistGroepId' => intval( $checklistgroep->id ), 'ChecklistId' => intval( $checklist->id ), 'bouwnummer' => $checklist->bouwnummer, 'Naam' => $checklistgroep->naam . ' - ' . $checklist->naam.(($checklist->bouwnummer)!=''?' - '.$checklist->bouwnummer:''), 'GeplandeDatum' => $deelplan->get_plannings_datum( $checklistgroep->id, $checklist->id ), 'ToezichthouderGebruikerId' => ($g = $deelplan->get_toezichthouder_checklist( $checklist->id, $checklist->bouwnummer )) ? intval($g->id) : null, ); } } } } $dosdata['Deelplannen'][] = $dpdata; } $data['Dossiers'][] = $dosdata; } // output $this->_output_json( $data ); } public function GeefToezichtBescheiden() { // haal gebruiker op if (!($gebruiker = $this->CI->gebruiker->get( $this->CI->login->get_user_id() ))) throw new DataSourceException( 'Niet ingelogd' ); if (!$this->_account->mag_bij_klant( $gebruiker->klant_id )) throw new DataSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot klant van opgegeven gebruiker.' ); // get data verify_data_members( array( 'DeelplanId' ), $this->_data ); $this->CI->load->model( 'deelplan' ); if (!($deelplan = $this->CI->deelplan->get( $this->_data->DeelplanId ))) throw new DataSourceException( 'Ongeldig deelplan ID opgegeven.' ); $access = $deelplan->get_access_to_deelplan(); if ($access == 'none') throw new DataSourceException( 'Opgegeven gebruiker heeft in het geheel geen toegang tot het deelplan.' ); $this->_output_json( (object)array( 'Success' => true, 'Ingangen' => $deelplan->get_bescheiden_en_mappen_structuur()->Ingangen, ) ); } public function GeefStempels() { // get settings $include_contents = isset( $this->_data->WithContents ) && $this->_data->WithContents; // load library $this->CI->load->library( 'pdfannotatorlib' ); $this->CI->pdfannotatorlib->load_stempel_library(); $lib = StempelLibrary::instance(); // helper function $cleanup_path = function( $path, $complete ) { if ($complete) return pathinfo( $path, PATHINFO_BASENAME ); else return '/' . $path; }; // worker function $process_dir = function( StempelDirectory $dir, stdClass $output=null ) use (&$process_dir, $cleanup_path) { $myOutput = (object)array( 'Naam' => $cleanup_path( $dir->get_directory(), true ), 'Type' => 'directory', 'Ingangen' => array(), ); $output->Ingangen[] = $myOutput; foreach ($dir->get_entries() as $entry) { if ($entry instanceof StempelDirectory) $process_dir( $entry, $myOutput ); else if ($entry instanceof StempelFile) { $myOutput->Ingangen[] = (object)array( 'Naam' => $cleanup_path( $entry->get_filename(), true ), 'Src' => $cleanup_path( $entry->get_filename(), false ), 'Type' => 'stempel', 'Contents' => base64_encode( file_get_contents( $entry->get_filename() ) ), ); } } }; // go! $output = (object)array( 'Name' => '', 'Ingangen' => array(), ); $process_dir( $lib->get_directory(), $output ); // output result $sha1 = sha1( json_encode( $output->Ingangen ) ); if ($include_contents) $this->_output_json( (object)array( 'Success' => true, 'Sha1' => $sha1, 'Ingangen' => $output->Ingangen[0]->Ingangen, ) ); else $this->_output_json( (object)array( 'Success' => true, 'Sha1' => $sha1, ) ); } } WebserviceModule::register_module( WS_COMPONENT_BTZAPP_KOPPELING, new BTZAppWebserviceModule() ); <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.checklist_volgorde')?></h1> <? $this->load->view( 'checklistwizard/_volgorde', array( 'entries' => $checklisten, 'get_id' => function( $cl ) { return $cl->id; }, 'get_image' => function( $cl ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $cl ) { return $cl->naam; }, 'store_url' => '/checklistwizard/checklist_volgorde/' . $checklistgroep->id, 'return_url' => '/checklistwizard/checklisten/' . $checklistgroep->id, ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php /** Webservice class. Implement your own functions in here. * Register them, and the types they need, as shown in the example code in the constructor. */ class MVVSuiteWebservice extends AbstractWebservice { private $_CI = null; // SOAP specific members, used for constructing the content, parameters, etc. // Note: these members have nothing to do with the class we are implementing here! Instead they are used for calling the main 'soapDossier' webservice! //private $soap_wsdl = "https://www.bristoezicht.nl/soapdossier/wsdl"; private $remoteSoapWsdl = ""; private $remoteSoapLicentieNaam = "DH_mvv-suite_usr"; private $remoteSoapLicentieWachtwoord = "DH_mvv-suite_pwd"; public function __construct() { // Note: the following 'define' is VERY important, as not setting it causes the security mechanism to act up on us where we do not want it to!!! define('IS_WEBSERVICE', true); // Get the proper location of the webservice we need to call. Note: this must be specified in the application/config/config.php file! $this->remoteSoapWsdl = $CI->config->item('ws_url_wsdl_mtmi_soapdossier'); // Get a reference to the CI object $this->_CI = get_instance(); // // STEP 1: Call parent constructor, and initialize // parent::__construct(); $this->_initialize(); // Load the SOAP client helper $this->_CI->load->helper( 'soapclient' ); // Load the models we will be using $this->_CI->load->model( 'gebruiker' ); $this->_CI->load->model( 'dossier' ); // // STEP 2: Register types, starting with simple types, and working to structs and arrays // of structs and/or simple types. Remember that types must be known when used, so register // them in the proper order. // The abstract base class knows the following simple types: string, int, boolean and base64Binary. // //$this->_register_compound_type( 'MyStruct', array( 'fieldname1'=>'int', 'fieldname2'=>'string' ) ); //$this->_register_array_type( 'MyStructArray', 'MyStruct' ); // Define the 'medewerker' and 'medewerkers' compound types //$this->_register_compound_type( 'Medewerker', array( 'Naam'=>'string', 'Functie'=>'string', 'Telefoon'=>'string', 'Email'=>'string' ) ); //$this->_register_array_type( 'MedewerkersArray', 'Medewerker' ); // Define the 'subject' and 'subjecten' compound types //$this->_register_compound_type( 'Subject', array( 'Naam'=>'string', 'Rol'=>'string', 'Adres'=>'string', 'Contactpersoon'=>'string', 'Correspondentieadres'=>'string' ) ); //$this->_register_array_type( 'SubjectenArray', 'Subject' ); // Define an auxiliary type for the 'betrokkenen' $this->_register_compound_type( 'typeBetrokkene', array( 'betrokkeneId' => 'int', 'organisatie' => 'string', 'naam' => 'string', 'rol' => 'string', 'straat' => 'string', 'huisNummer' => 'string', 'huisNummerToevoeging' => 'string', 'postcode' => 'string', 'woonplaats' => 'string', 'telefoon' => 'string', 'email' => 'string', //'gebruikerId' => 'int' // !! Maybe we should make this available? ) ); $this->_register_array_type( 'arrayTypeBetrokkene', 'typeBetrokkene' ); // Define the various parts that define a compound 'plaatsbepaling' compound type. Note: at present a SINGLE 'adres' and 'perceel' is expected; should this be multi, an // array type needs to be defined for it too (just like the array types 'MedewerkersArray' and 'SubjectenArray'). $this->_register_compound_type( 'typeAdres', array( 'straat'=>'string', 'huisNummer'=>'string', 'huisNummerToevoeging' => 'string', 'postcode'=>'string', 'woonplaats'=>'string' ) ); $this->_register_compound_type( 'typePerceel', array( 'xCoordinaat'=>'float', 'yCoordinaat'=>'float' ) ); $this->_register_compound_type( 'typePlaatsBepaling', array( 'adres' => 'typeAdres', 'perceel' => 'typePerceel', 'vrijeLocatie' => 'string' ) ); // Define a compound type for passing some (partially optional?) information about the request $this->_register_compound_type( 'typeAanroepGegevens', array( 'datumEnTijdAanroep' => 'string', 'actie' => 'string', 'checksum' => 'string' ) ); // Define the 'dossierdata' compound type /* $this->_register_compound_type( 'DossierData', array( 'Dossiernummer' => 'int', 'Omschrijving' => 'string', 'Medewerkers' => 'MedewerkersArray', 'Subjecten' => 'SubjectenArray', 'DatumAanvraag' => 'string', 'DatumBeschikking' => 'string', 'DatumOnherroepelijk' => 'string', 'Bouwwerkcategorie' => 'string', 'Plaatsbepaling' => 'Plaatsbepaling' ) ); * */ $this->_register_compound_type( 'typeDossierData', array( 'dossierNummer' => 'string', 'omschrijving' => 'string', 'betrokkenen' => 'arrayTypeBetrokkene', 'datumAanvraag' => 'string', 'datumBeschikking' => 'string', 'datumOnherroepelijk' => 'string', 'bouwwerkCategorie' => 'string', 'plaatsBepaling' => 'typePlaatsBepaling' ) ); // Define the compound type that binds all RPC call parameters together. $this->_register_compound_type( 'typeVerwerkDossierParameters', array( 'dossierData' => 'typeDossierData', 'aanroepGegevens' => 'typeAanroepGegevens' ) ); // Define a resultset type for the RPC calls. $this->_register_compound_type( 'resultVerwerkDossier', array( 'success' => 'boolean', 'message' => 'string', 'dossierId' => 'int', 'dossierHash' => 'string' ) ); // // STEP 3: Register methods. All types used here must be registered in step 2, except for the // aforementioned list of simple types in step 2. // /* $this->_register_method( 'int', 'createFoo', array( 'bar' => 'int' ) ); $this->_register_method( 'int', 'createFoo2', array( 'bar1' => 'int', 'bar2' => 'string', 'bar3' => 'boolean', 'bar4' => 'base64Binary', 'bar5' => 'MyStruct', 'bar6' => 'MyStructArray' ) ); $this->_register_method( 'MyStructArray', 'fooBar', array( 'parm' => 'MyStruct' ) ); * */ // Register the only RPC call we want to make available. //$this->_register_method( 'int', 'verwerkDossier', array( 'dossierData' => 'DossierData', 'aanroepGegevens' => 'Aanroepgegevens' ) ); $this->_register_method( 'resultVerwerkDossier', 'verwerkDossier', array('parameters' => 'typeVerwerkDossierParameters') ); // // STEP 4: Finalize! // $this->_finalize(); } // The 'verwerkDossier' RPC call is the main point of entry. It expects a complete set of dossier data and it will handle/dispatch all required processing. // The second parameter (i.e. 'aanroepGegevens' is used for keeping track of data about the request itself). //public function verwerkDossier( $dossierData, $aanroepGegevens ) public function verwerkDossier( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'dossierId' => 0, 'dossierHash' => '' ); // Start by extracting the requested action. That action serves as main 'switch' for determining which method to call, etc. $requestedAction = $parameters->aanroepGegevens->actie; //d($requestedAction); // Set the client ID to that of '<NAME>' (= 131) and get the 'Nog Niet Toegewezen' user. $useKlantId = 131; $notYetAssignedUsers = $this->_CI->gebruiker->get_by_klant( $useKlantId, false, 'nog_niet_toegewezen' ); //$notYetAssignedUser = reset($notYetAssignedUsers); //d($notYetAssignedUser->id); //d($notYetAssignedUser); $notYetAssignedUser = (!empty($notYetAssignedUsers)) ? reset($notYetAssignedUsers) : null; $notYetAssignedUserId = (!is_null($notYetAssignedUser)) ? $notYetAssignedUser->id : null; // First extract some data from the parameters into variables with shorter names $dossierData = $parameters->dossierData; $dossierAdres = $dossierData->plaatsBepaling->adres; $dossierPerceel = $dossierData->plaatsBepaling->perceel; $dossierVrijeLocatie = $dossierData->plaatsBepaling->vrijeLocatie; $dossierPerceelCoordinatenStr = (!empty($dossierPerceel->xCoordinaat) && !empty($dossierPerceel->yCoordinaat)) ? $dossierPerceel->xCoordinaat . ', ' . $dossierPerceel->yCoordinaat : ''; // Since the caller in this case does not keep track of dossier IDs and hashes as we know them, we must work around this. // First, see if for the current client a dossier already exists with this kenmerk. If so, for any all calls (except for 'dossierToevoegen') // we can use the dossier ID and hash of that dossier $existingDossier = $this->_CI->dossier->get_by_kenmerk( $dossierData->dossierNummer, $useKlantId ); // Make sure to properly initialise the $existingDossier object (if any). if ($requestedAction == 'dossierToevoegen') { // If a dossier with the passed 'kenmerk' already exists, at this time we do not allow another one with the same 'kenmerk' to be created and instead we // set an error message. Instead, we could also decide to change the requested action to 'dossierBewerken'. if (!is_null($existingDossier)) { // A dossier already exists with this 'kenmerk'? -> error out $resultSet['message'] = "Er bestaat reeds een dossier met het kenmerk '" . $dossierData->dossierNummer . "'. Er wordt niet nog een dossier met hetzelfde kenmerk toegevoegd."; } // Unconditionally re-initialise the dossier to null. If an error message was set we do not proceed with the call anyway and now at least we always // know for sure that it's properly set. $existingDossier = null; } else { // If we could not retrieve a dossier, we cannot proceed with the requested operation, so we notify the caller of that, and bail out. if (is_null($existingDossier)) { // No dossier found? -> error out $resultSet['message'] = "Er bestaat (nog) geen dossier met het kenmerk '" . $dossierData->dossierNummer . "'. De gevraagde actie '{$requestedAction}' kan niet worden uitgevoerd."; } else if (is_null($existingDossier->dossier_hash) || empty($existingDossier->dossier_hash)) { // Retrieved dossier doesn't have a dossier hash? -> error out $resultSet['message'] = "Er bestaat een dossier met het kenmerk '" . $dossierData->dossierNummer . "', maar deze is niet via de koppeling aangemaakt. De gevraagde actie '{$requestedAction}' mag niet worden uitgevoerd."; } } // else of clause: if ($requestedAction != 'dossierToevoegen') // In case the above checks did not result in an error message being set, we continue, otherwise we return early. if (!empty($resultSet['message'])) { return $resultSet; } // From this point onwards we know we either are adding a dossier or are manipulating an existing one, and the valid dossier has been found too. // Handle the calls to create/manipulate the dossier as required (if instructed to do so) if ( ($requestedAction == 'dossierToevoegen') || ($requestedAction == 'dossierBewerken') ) { // Start by working out which of the main SOAP service methods needs to be used and fill the data set for that accordingly. // Specify the WS method for manipulating a dossier and also fill the fields we need for the 'add' as well as the 'edit' calls. $soapMethod = 'soapManipulateDossier'; $soapParameters_soapManipulateDossier = array(); $soapParameters_soapManipulateDossier['licentieNaam'] = $this->remoteSoapLicentieNaam; $soapParameters_soapManipulateDossier['licentieWachtwoord'] = $this->remoteSoapLicentieWachtwoord; $soapParameters_soapManipulateDossier['actie'] = 'Add'; $soapParameters_soapManipulateDossier['dossierId'] = 0; $soapParameters_soapManipulateDossier['dossierHash'] = ''; $soapParameters_soapManipulateDossier['dossierNaam'] = $dossierData->omschrijving; // 512 characters, ends up in the "beschrijving" column $soapParameters_soapManipulateDossier['identificatieNummer'] = $dossierData->dossierNummer; // 32 characters, ends up in the "kenmerk" column $soapParameters_soapManipulateDossier['gebruikerId'] = $notYetAssignedUserId; $soapParameters_soapManipulateDossier['aanmaakDatum'] = ''; $soapParameters_soapManipulateDossier['bagNummer'] = ''; $soapParameters_soapManipulateDossier['xyCoordinaten'] = $dossierPerceelCoordinatenStr; $soapParameters_soapManipulateDossier['locatieStraat'] = $dossierAdres->straat; $soapParameters_soapManipulateDossier['locatieHuisNummer'] = $dossierAdres->huisNummer; $soapParameters_soapManipulateDossier['locatieHuisNummerToevoeging'] = $dossierAdres->huisNummerToevoeging; $soapParameters_soapManipulateDossier['locatiePostcode'] = $dossierAdres->postcode; $soapParameters_soapManipulateDossier['locatieWoonplaats'] = $dossierAdres->woonplaats; $soapParameters_soapManipulateDossier['opmerkingen'] = 'Aangemaakt via de MVV-Suite koppeling'; $soapParameters_soapManipulateDossier['betrokkenen'] = $dossierData->betrokkenen; // Override the specific fields that are of importance when using an 'edit' call. // Note particularly that a look-up needs to be performed for the existing dossier ID and dossier hash, as these are not passed in the // MVV-Suite webservice! if ($requestedAction == 'dossierBewerken') { // Override some parameters for editing an existing dossier $soapParameters_soapManipulateDossier['actie'] = 'Edit'; $soapParameters_soapManipulateDossier['dossierId'] = $existingDossier->id; // Must be an existing dossier! $soapParameters_soapManipulateDossier['dossierHash'] = $existingDossier->dossier_hash; $soapParameters_soapManipulateDossier['gebruikerId'] = $existingDossier->gebruiker_id; // Make sure to NOT overwrite the existing user from the webservice. //$soapParameters_soapManipulateDossier['identificatieNummer'] = 'OJG-SOAP-FW-TS-001'; // 32 characters, ends up in the "kenmerk" column //$soapParameters_soapManipulateDossier['opmerkingen'] = 'Bewerkt via de MVV-Suite koppeling'; } // if ($requestedAction == 'dossierBewerken') } // if ( ($requestedAction == 'dossierToevoegen') || ($requestedAction == 'dossierBewerken') ) // From here on, set up the connection to our main SOAP dossier gateway and use that very extensive service for doing the actual work. // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); $wrappedSoapClient = getWrappedSoapClientHelper($this->remoteSoapWsdl."/{$randval}", $soapMethod, $debug, $silent); $parametersStr = 'soapParameters_' . $soapMethod; // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $$parametersStr); //d($wrappedSoapClient); //d($wsResult); if (empty($wsResult)) { $errorMessage = "De dossier webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet;; } } else { $errorMessage = "Foutmelding(en) bij maken connectie naar dossier webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet;; } // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar dossier webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult)) { //d($wsResult); exit; // Extract the results that we need from the main service and pass them back in the result set $resultSet['success'] = $wsResult->success; $resultSet['message'] = $wsResult->message; if (!empty($resultSet['message']) && !empty($wsResult->results->actionResultMessage)) { $resultSet['message'] .= "\n"; } $resultSet['message'] .= $wsResult->results->actionResultMessage; $resultSet['dossierId'] = $wsResult->results->dossierId; $resultSet['dossierHash'] = $wsResult->results->dossierHash; } // When all the work is done, simply return the compound resultset. return $resultSet; } } // class MVVSuiteWebservice extends AbstractWebservice <file_sep><?php class Extern extends Controller { private function _get_my_opdrachten($gebruiker_id=null, $only_unfinished=true ) { $this->load->model( 'deelplanopdracht' ); return $this->deelplanopdracht->get_my_opdrachten($gebruiker_id, $only_unfinished); } function inloggen($post_login_location = '') { $this->login->doe_inlog_pagina($post_login_location); } public function index( $initial_command=null ) { $page = 'dossiers'; $klant_id = null; $dossier_id = null; $bouwnummer_id = null; $hoofdgroep_id = null; $opdracht_id = null; $status = null; // reset the klant id to null just to be sure (no lingering klant ids wanted) $this->_assign_customer(null); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $page_options = array("options"=>array ( "regexp" =>"/^(dossiers|toezichtmomenten|opdrachten|opdracht|opslaan|afsluiten)$/", "default"=>"dossiers;") ); $page = filter_input(INPUT_POST,'page', FILTER_VALIDATE_REGEXP, $page_options); $klant_id = filter_input(INPUT_POST,'klant_id', FILTER_VALIDATE_INT); $dossier_id = filter_input(INPUT_POST,'dossier_id', FILTER_VALIDATE_INT); $bouwnummer_id = filter_input(INPUT_POST,'bouwnummer_id', FILTER_SANITIZE_STRING); $hoofdgroep_id = filter_input(INPUT_POST,'hoofdgroep_id', FILTER_VALIDATE_INT); $opdracht_id = filter_input(INPUT_POST,'opdracht_id', FILTER_VALIDATE_INT); $confirmed = filter_input(INPUT_POST,'confirmed', FILTER_VALIDATE_BOOLEAN); } switch ($page) { case 'dossiers': //Check if specific assignment was requested global $CI; foreach ($CI->uri->segments as $segment) { if (substr($segment,0,8)=='opdracht') { $opdracht_segment = array_pad(explode ("=",$segment),2,null); $opdracht_request = $opdracht_segment[1]; } } case 'toezichtmomenten': case 'opdrachten': case 'opdracht': //make sure the array's are clean. For now, only projecten, toezichtmomenten and opdrachten will be used $objecten = array(); // general array to take over the relevant array for posting //get klanten for external user $opdrachtgevers = $this->gebruiker->get_opdrachtgevers($this->login->get_user_id(), false); $my_opdrachten = $this->_get_my_opdrachten(null, false); $opdracht_ids_per_klant = array(); $num_dossier_opdrachten = 0; $num_hoofdgroep_opdrachten = 0; if ($opdrachtgevers) { foreach ($opdrachtgevers as $opdrachtgever) { $opdracht_ids_per_klant[$opdrachtgever->id]->opdrachten[] = $opdrachtgever->opdracht_id; $opdracht_ids_per_klant[$opdrachtgever->id]->klant_naam = $opdrachtgever->klant_naam; } foreach ($opdracht_ids_per_klant as $klant=>$opdracht_ids) { $klant_naam = $opdracht_ids->klant_naam; foreach ($opdracht_ids->opdrachten as $id) { // Temporarily link the external user to the klant. $this->_assign_customer($klant); $opdracht = $my_opdrachten[$id]; $deelplan = $opdracht->get_deelplan(); $dossier = $deelplan->get_dossier(); $vraag = $opdracht->get_vraag(); $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); $bouwnummer = $opdracht->bouwnummer; if ($opdracht_request == $opdracht->id) { $page = 'opdracht'; $opdracht_id = $opdracht->id; $klant_id = $klant; $dossier_id = $dossier->id; $bouwnummer_id = $bouwnummer; $hoofdgroep_id = $hoofdgroep->id; } if ($opdracht_id == $opdracht->id) { $status = $opdracht->status; } //add the assignment/task $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['opdrachten'][$opdracht->status][$opdracht->id] = $opdracht; //add the additional information if not already present //klant info if (!isset($objecten[$klant]['naam'])) $objecten[$klant]['naam']=$klant_naam; //dosier info $objecten[$klant]['dossiers'][$dossier->id]['aantal'] = !isset($objecten[$klant]['dossiers'][$dossier->id]['aantal']) ? 1 : $objecten[$klant]['dossiers'][$dossier->id]['aantal']+1; if (!isset($objecten[$klant]['dossiers'][$dossier->id]['naam'])) $objecten[$klant]['dossiers'][$dossier->id]['naam']= $dossier->get_omschrijving(); if (!isset($objecten[$klant]['dossiers'][$dossier->id]['locatie'])) $objecten[$klant]['dossiers'][$dossier->id]['locatie']= $dossier->get_locatie(); if (!isset($objecten[$klant]['dossiers'][$dossier->id]['deadline']) || ($objecten[$klant]['dossiers'][$dossier->id]['deadline'] == max( $opdracht->gereed_datum, $objecten[$klant]['dossiers'][$dossier->id]['deadline']))) $objecten[$klant]['dossiers'][$dossier->id]['deadline']= $opdracht->gereed_datum; if (isset($vraag->hercontrole_datum) && (!isset($objecten[$klant]['dossiers'][$dossier->id]['recheck']) || $objecten[$klant]['dossiers'][$dossier->id]['recheck'] > $vraag->hercontrole_datum )) $objecten[$klant]['dossiers'][$dossier->id]['recheck']= $opdracht->gereed_datum; //hoofdgroep info $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['aantal'] = !isset($objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['aantal']) ? 1 : $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['aantal'] +1; if (!isset($objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['naam'])) $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['naam']= $hoofdgroep->naam; if (!isset($objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['deadline']) || ($objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['deadline'] == max( $opdracht->gereed_datum, $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['deadline']))) $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['deadline']= $opdracht->gereed_datum; if (isset($vraag->hercontrole_datum) && (!isset($objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['recheck']) || $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['recheck'] > $vraag->hercontrole_datum )) $objecten[$klant]['dossiers'][$dossier->id]['hoofdgroepen'][$bouwnummer][$hoofdgroep->id]['recheck']= $opdracht->gereed_datum; } } } break; case 'opslaan': $result = $this->save_opdracht($opdracht_id); $objecten = array( 'id'=>$opdracht_id, 'result'=>$result ); break; case 'afsluiten': // Controleer of er nog niet-gereed gemelde opdrachten zijn $my_opdrachten = $this->_get_my_opdrachten(null, false); $unfinished_count = 0; foreach ($my_opdrachten as $opdracht) { if ($opdracht->status != 'gereed') $unfinished_count++; } if ($unfinished_count > 0 && !$confirmed) { $objecten = array( 'result' => "<form method='post'> <input type='hidden' name='page' value='afsluiten'> <input type='hidden' name='confirmed' value='true'> <input id='close' type='submit' value='afsluiten' hidden/> <p>U heeft nog $unfinished_count onafgesloten opdrachten. Klik <label class='link' for='close'>hier</label> om evengoed af te sluiten. </form>" ); } else { $objecten = array( 'result' => "<p>U bent nu uitgelogd. Klik <a href='extern/inloggen'>hier</a> om opnieuw in te loggen.</p>" ); // clear all cookies // TODO: check if "remember login" is set. foreach ($_COOKIE as $key => $value) { unset( $_COOKIE[ $key ] ); // set empty string value, and set expire time way back in the past setcookie( $key, '', time()-1800, '/' ); } } break; } // Temporarily link the external user to the klant. $this->_assign_customer($klant_id); //make sure no errors are outputted ob_clean(); $this->load->view( 'extern/index', array( 'klant' => $klant_id, 'dossier' => $dossier_id, 'hoofdgroep' => $hoofdgroep_id, 'bouwnummer' => $bouwnummer_id, 'opdracht' => $opdracht_id, 'objecten' => $objecten, 'page' => isset($page)?$page:null, 'status' => $status ) ); } public function opdracht_afbeelding( $id, $upload_id, $thumbnail = false) { $etag = sha1( 'opdracht_afbeelding-' . $upload_id ); if (@$_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header("HTTP/1.1 304 Not Modified"); exit; } $this->load->model( 'deelplanopdracht' ); if (!$opdracht = $this->deelplanopdracht->get( $id )) /* handles security */ { throw new Exception( 'Fout bij ophalen afbeelding: opgegeven ID niet geldig.' ); } $im = new Imagick(); $im->readImageBlob($this->deelplanopdracht->get_deelplan_upload_image ($upload_id)); if ($thumbnail == true) { $im->scaleImage(150, 0, false ); } else { } $png = $im->getImageBlob(); $im->destroy(); if (!$png) throw new Exception( 'Fout bij ophalen afbeelding.' ); // output $cacheTime = 365 * 86400; $cacheExpires = strtotime( '+1 year' ); header( 'Content-Type: image/png' ); header( 'Content-Length: ' . strlen($png) ); header( 'Cache-Control: max-age=' . $cacheTime . ',public' ); header( 'Pragma: public' ); header( 'Expires: ' . date( 'D, d M Y H:i:s ', $cacheExpires ) ) . ' UTC'; header( 'Last-Modified: ' . date( 'D, d M Y H:i:s ' ) ) . ' GMT'; header( 'Etag: ' . $etag ); echo $png; } public function save_opdracht($opdracht_id) { $this->load->model( 'deelplanopdracht' ); $this->load->model( 'deelplanvraaggeschiedenis' ); $errors = array(); $opdrachtgevers = $this->gebruiker->get_opdrachtgevers($this->login->get_user_id()); foreach ($opdrachtgevers as $opdrachtgever) { if ($opdrachtgever->opdracht_id == $opdracht_id) { $this->_assign_customer($opdrachtgever->id); break; } } try { // start transactie $this->db->trans_start(); try { $gereed_options = array("options"=>array ( "regexp" =>"/^(on)$/", "default"=>"off;") ); $gereed = filter_input(INPUT_POST,'gereed', FILTER_VALIDATE_REGEXP, $gereed_options); // haal data op, controleer of alles er is if (isset($_POST['waardeoordeel'])) { $waardeoordeel = $_POST['waardeoordeel']; } else { $waardeoordeel = ''; } if ($gereed == 'on') { if ($waardeoordeel) { $gereed = true; } else { $errors[] = "De opdracht kan niet gereed worden gemeld als het waarde-oordeel nog niet is ingevuld."; $gereed =false; } } else { $gereed = false; } if (isset($_POST['toelichting'])) { $toelichting = $_POST['toelichting']; } else { $toelichting = ''; } if (!($opdracht = $this->deelplanopdracht->get( $opdracht_id ))) throw new Exception( 'Ongeldige opdracht ID ' . $opdracht_id ); //$gebruiker_id = $this->gebruiker->get_logged_in_gebruiker()->id; $opdracht->antwoord = $waardeoordeel; $opdracht->toelichting = $toelichting; $opdracht->save( 0, 0, 0 ); // werk opdracht bij if ($gereed) { $opdracht->markeer_gereed(); // bekijk of we een revisie moeten toevoegen, dit is het geval wanneer er in de deelplanvraag al // iets staat ingevuld; // LET OP: deelplan_vragen heeft geen model, omdat het geen ID veld heeft! We krijgen dus een // stdClass standaard PHP object terug uit _get_deelplan_vraag ! $this->load->model( 'deelplanchecklist' ); $this->load->model( 'deelplanvraag' ); $deelplanChecklist = $this->deelplanchecklist->get( $opdracht->deelplan_checklist_id ); if ($deelplanChecklist) { if (is_null($deelplanChecklist)) { $errorMessage = 'Kan deelplan checklist niet vinden: deelplan-checklist ID ' . $opdracht->deelplan_checklist_id . ', deelplan ID ' . $opdracht->deelplan_id . ', vraag ID ' . $opdracht->vraag_id; $errors[] = $errorMessage; throw new Exception( $errorMessage ); } $bouwnummer = $deelplanChecklist->bouwnummer; $deelplanvraag = $this->deelplanvraag->get_by_deelplan_and_vraag_and_bouwnummer( $opdracht->deelplan_id, $opdracht->vraag_id, $bouwnummer ); } else { $deelplanvraag = $this->_get_deelplan_vraag( $opdracht->deelplan_id, $opdracht->vraag_id ); } if (is_null($deelplanvraag)) { $errorMessage = 'Kan deelplan vraag niet vinden: deelplan ID ' . $opdracht->deelplan_id . ', vraag ID ' . $opdracht->vraag_id . ', bouwnummer ' . $bouwnummer; $errors[] = $errorMessage; throw new Exception( $errorMessage ); } if ($deelplanvraag->status) $this->deelplanvraaggeschiedenis->add( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $deelplanvraag->status, $deelplanvraag->toelichting, $deelplanvraag->gebruiker_id, $deelplanvraag->last_updated_at ); // verwerk opdracht in z'n layer $result = $opdracht->verwerk_in_layer(); // Update waardeoordeel and toelichting $vraag = $opdracht->get_vraag(); // Loop all opdrachten and get the worst waardeoordeel if (isset( $opdracht->deelplan_checklist_id )) { $vraag_opdrachten = $this->deelplanopdracht->search( array( 'vraag_id' => $vraag->id, 'deelplan_checklist_id' => $opdracht->deelplan_checklist_id, 'status' => 'gereed')); } else { $vraag_opdrachten = $this->deelplanopdracht->search( array( 'vraag_id' => $vraag->id, 'status' => 'gereed')); } // Start with the ok status and "pull down" if a worse status is encountered $worst_kleur = 'groen'; $worst_antwoord = ''; // Check every opdracht to see if we need to lower the status of the vraag foreach ($vraag_opdrachten as $sub_opdracht) { $nieuwe_kleur = $vraag->get_waardeoordeel_kleur ( true, $opdracht->antwoord); // The current opdracht status is assigned to the vraag if: // - The current opdracht status equals the worst status and the antwoord is not yet set OR // - The current opdracht status is rood or oranje while the worst status is groen OR // - The current opdracht status is rood while the worst status is groen or oranje if ( ($nieuwe_kleur == $worst_kleur && $worst_antwoord == '') || (($nieuwe_kleur == 'rood' || $nieuwe_kleur == 'oranje') && $worst_kleur == 'groen' ) || ($nieuwe_kleur == 'rood' && ($worst_kleur == 'oranje' || $worst_kleur == 'groen') ) ) { $worst_kleur = $nieuwe_kleur; $worst_antwoord = $sub_opdracht->antwoord; } } $this->_zet_deelplan_vraag( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $worst_antwoord, "$toelichting (waardeoordeel: ".$vraag->get_waardeoordeel($waardeoordeel).")", $deelplanvraag->gebruiker_id , $bouwnummer); } // commit! if (!$this->db->trans_complete()) { $errors[] = 'Fout bij committen naar database'; throw new Exception( 'Fout bij committen naar database.' ); } // Once the above transaction has completed, we update 'status_gereed_uitvoerende'. Note: this MUST be done AFTER the transaction // is complete, as otherwise it fails! $opdracht->update_gereed_status_toezichtmoment(); //Upload images if there are any if ($_FILES['images']) { $num_errors = $this->upload($opdracht_id); if ($num_errors) { $errors[] = "Tijdens het opslaan van de afbeeldingen hebben zich $num_errors fouten voorgedaan"; } } } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); throw $e; } // done! if (sizeof($errors)) { $tekst = "<div class='error'>Let op: er zijn fouten opgetreden. De opdracht is <b>niet of niet geheel</b> opgeslagen:<br />". implode("<br />",$errors). "</div>"; return $tekst; } else { return "<span class='information'>De opdracht is succesvol opgeslagen.</span>"; } } catch (Exception $e) { if (sizeof($errors)) { $tekst = "<div class='error'>Let op: er zijn fouten opgetreden. De opdracht is <b>niet of niet geheel</b> opgeslagen:<br />". implode("<br />",$errors). "</div>"; return $tekst; } else { return "<span class='error'>Let op: er is een fout opgetreden. De opdracht is <b>niet of niet geheel</b> opgeslagen.</span>"; } } } function _assign_customer ($customer_id) { $this->gebruiker->klant_id = $customer_id; $this->session->set_userdata(array('kid'=>$customer_id)); } // !!! Must be extended with bouwnummers!!! // Change to using the get_by_deelplan_and_vraag_and_bouwnummer( $deelplan_id, $vraag_id, $bouwnummer ) method from the deelplanvraag model! private function _get_deelplan_vraag( $deelplan_id, $vraag_id ) { $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->where( 'vraag_id', $vraag_id ); if (!($res = $this->db->get( 'deelplan_vragen' ))) throw new Exception( 'Fout bij lezen van deelplan vragen database' ); $deelplanvraag = $res->row_object(); $res->free_result(); return $deelplanvraag ? $deelplanvraag : null; } private function _zet_deelplan_vraag( $deelplan_id, $vraag_id, $status, $toelichting, $gebruiker_id, $bouwnummer = '' ) { $this->db->set( 'status', $status ); $this->db->set( 'toelichting', $toelichting ); $this->db->set( 'gebruiker_id', $gebruiker_id ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->where( 'vraag_id', $vraag_id ); if ($bouwnummer) { $this->db->where( 'bouwnummer', $bouwnummer); } if (!$this->db->update( 'deelplan_vragen' )) throw new Exception( 'Fout bij bewerken van deelplan vragen database' ); } public function upload($opdracht_id) { $num_errors = 0; try { if (!isset( $_FILES['images'] )) { throw new Exception( '$_FILES["images"] is niet gezet.' ); } // laad opdracht $this->load->model( 'deelplanopdracht' ); if (!($opdracht = $this->deelplanopdracht->get( $opdracht_id ))) { throw new Exception( 'Ongeldig opdracht ID ontvangen: ' . $opdracht_id ); } $associated_user = $opdracht->opdrachtgever_gebruiker_id; $this->load->model( 'deelplanchecklist' ); $deelplanChecklist = $this->deelplanchecklist->get( $opdracht->deelplan_checklist_id ); if (!is_null($deelplanChecklist)) { $bouwnummer = $deelplanChecklist->bouwnummer; } else { $bouwnummer = null; } $file_count = count($_FILES['images']['name']); for ($file_index=0 ; $file_index < $file_count ; $file_index++) { if (!$_FILES['images']['error'][$file_index] && $_FILES['images']['tmp_name'][$file_index]) { $opdracht_id = $opdracht_id; $tmp_name = $_FILES['images']['tmp_name'][$file_index]; $name = $_FILES['images']['name'][$file_index]; if (false === ($contents = @file_get_contents( $tmp_name ))){ $num_errors++; } else { // start transactie $this->db->trans_start(); try { $this->load->model( 'deelplanupload' ); $upload = $opdracht->get_deelplan_upload(); // creeer een nieuwe deelplan upload! $filename = date('d-m-Y H.i.s') . ' #' . $opdracht->id . '_'.$file_index.'.jpg'; $upload = $this->deelplanupload->add( $opdracht->deelplan_id, $opdracht->vraag_id, $filename, $contents, $bouwnummer, $associated_user); $opdracht->deelplan_upload_id = $upload->id; $this->deelplanupload->add_opdrachtupload($opdracht->id, $upload->id); $opdracht->save(); // commit! if (!$this->db->trans_complete()) $num_errors++; } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); $num_errors++; } } } } // done! } catch (Exception $e) { $num_errors ++; } return $num_errors; } } <file_sep><? /** * Code obtained from AbiSource Corporation B.V. with the consent of <NAME>. * * NOTE: slightly altered (read: stripped) to suite our needs. The _verify function * has lost much of its capabilities. */ function initialiseer_systeem_instellingen( $login, $external=false ) { //echo "+-+ A +-+<br />"; $CI = get_instance(); $lease_configuratie = null; $lease_configuratie_id = $CI->session->_loginSystem->get_lease_configuratie_id(); //d($lease_configuratie_id); if (!$lease_configuratie_id && $external==false) { //echo "+-+ B +-+<br />"; $CI->load->model( 'gebruiker' ); $gebruiker_id = $login->get_user_id(); if ($gebruiker_id != -1) { //echo "+-+ C +-+<br />"; $gebruiker = $CI->gebruiker->get( $gebruiker_id ); if ($gebruiker) { //echo "+-+ D +-+<br />"; $CI->load->model( 'klant' ); $lease_configuratie = $gebruiker->get_klant()->get_lease_configuratie(); } } } //echo "+-+ E +-+<br />"; if (!$lease_configuratie && $lease_configuratie_id) { //echo "+-+ F +-+<br />"; $CI->load->model( 'leaseconfiguratie' ); $lease_configuratie = $CI->leaseconfiguratie->get( $lease_configuratie_id ); } //echo "+-+ G +-+<br />"; if ($lease_configuratie) { //echo "+-+ H +-+<br />"; $lease_configuratie->zet_systeem_instellingen(); } else { //echo "+-+ I +-+<br />"; $CI->load->model( 'leaseconfiguratie' ); LeaseConfiguratieResult::zet_standaard_systeem_instellingen(); } //echo "+-+ J +-+<br />"; //exit; } //d(APPLICATION_LOGIN_SYSTEM); //d(AUTH_KENNIS_ID); switch (APPLICATION_LOGIN_SYSTEM) { case AUTH_KENNIS_ID: // echo "+++ 1 +++<br />"; //exit; class CI_Login { var $CI; var $_login_uid_var = 'login_uid'; var $_force_validation = 'force_validation'; var $logged_in = false; function is_external_user() { return false; } public function get_name() { return 'KennisID'; // 100% zeker dat het deze is, niet de constante returnen... } /** * Login constructor * * Automatically loads the user state from the session data */ function CI_Login() { // echo "+-+ CI_Login::CI_Login +-+<br />"; // exit; $this->CI = get_instance(); $this->CI->load->library( 'Kennisid' ); $this->CI->load->library( 'Kmxlicensesystem' ); if (HTTP_USER_AUTHENTICATION) { //echo "+-+ 1 +-+<br />"; $this->logged_in = true; } else { //echo "+-+ 2 +-+<br />"; $force_validation = $this->CI->session->userdata($this->_force_validation); if (!is_bool( $force_validation )) { //echo "+-+ 3 +-+<br />"; $this->CI->session->set_userdata($this->_force_validation, true); $force_validation = true; } //dpb(2); //define('SKIP_TOKEN_VALIDATION', true); if (defined( 'SKIP_TOKEN_VALIDATION' ) && SKIP_TOKEN_VALIDATION) { //echo "+-+ 4 +-+<br />"; $this->logged_in = true; } else { //echo "+-+ 5 +-+<br />"; if ($force_validation) { //echo "+-+ 6 +-+<br />"; if ($this->logged_in = $this->CI->kennisid->validate_session_token()) { //echo "+-+ 7 +-+<br />"; $this->CI->session->set_userdata($this->_force_validation, false); } } else { //echo "+-+ 8 +-+<br />"; $this->logged_in = $this->get_user_id() != -1; } } } //echo "+-+ 9 +-+<br />"; //exit; initialiseer_systeem_instellingen( $this ); } /** * Returns whether or not the current user in the current session * is logged in or not. Result is either true or false. */ function logged_in() { if (IS_CLI || (defined('IS_WEBSERVICE') && IS_WEBSERVICE)) { return $this->get_user_id() != -1; } return $this->logged_in; } /** * Returns user id, or -1 when not logged in. */ function get_user_id() { if ($this->CI->session->userdata($this->_login_uid_var)===false) return -1; $uid = $this->CI->session->userdata($this->_login_uid_var); if (!is_numeric( $uid ) || $uid <= 0) return -1; return $uid; } /** * Registers the user as logged in as the given user ID. */ function login( $userid ) { if ($this->logged_in()) return false; return $this->login_as( $userid ); } /** * Login as */ function login_as( $userid ) { if (!is_numeric($userid) || $userid<0) return false; $data = array( $this->_login_uid_var => $userid ); $this->CI->session->set_userdata( $data ); $this->CI->session->set_user_recognizables(); return true; } /** Logs out the user, if he was logged in. */ function logout() { $this->CI->session->unset_userdata( array( $this->_login_uid_var => '' ) ); $this->CI->session->unset_user_recognizables(); } /** * Checks if the user may use the specified class/method. */ function verify( $class, $method ) { // get the 'security array' $security = $this->CI->config->item('security'); if ($security===false) { show_error('The config item "security" is not set. Cannot proceed.'); } // match class and method against security config $uri = $class . '/' . $method; $logged_in = $this->logged_in(); foreach ($security as $preg => $requirements) { if (preg_match( '#' . $preg . '#', $uri )) { if ($requirements==='*') return true; if ($requirements===true) return $logged_in; if ($requirements===false) return !$logged_in; if (is_int($requirements)) return $this->CI->rechten->geef_recht_modus( $requirements ) != RECHT_MODUS_GEEN; if (is_array($requirements)) { foreach ($requirements as $requirement) { if ($this->CI->rechten->geef_recht_modus( $requirement ) != RECHT_MODUS_GEEN) return true; } return false; } show_error('Ongeldige rechten gedeclareerd voor ' . $uri); } } // geen rechten! show_error('U heeft geen rechten voor de opgevraagde pagina, /' . $uri . '.<br/>Als u hier bent gekomen via een hyperlink, meld het ons dan a.u.b. zo snel mogelijk!' ); } public function doe_inlog_pagina() { // !!! OJG (17-7-2015): We used to be able to pass a return URL to KennisID but this functionality appears to no longer work correctly, as when we // explicitely click on the 'inloggen' link when a session has expired, we always end up on the same page with the same error again. // By not passing a ReturnUrl value we at least get the right KennisID log in screen and can log in again. // Possibly this needs to be fixed later, so leave both assignments here, so as to avoid the first one from being considered obsolete and hence // easily get deleted and forgotten afterwards. ;) $return_url = site_url( '/gebruikers/postlogin/{0}' ); //$return_url = ''; $this->CI->kennisid->redirect_login( $return_url ); } public function doe_uitlog_pagina() { $this->logout(); $this->CI->kennisid->reset_session_token(); session_destroy(); redirect( 'https://www.kennisid.nl/LogOff?ReturnUrl=' . rawurlencode( site_url() ) ); //redirect( 'https://system.kennisid.nl/LogOff?ReturnUrl=' . rawurlencode( site_url() ) ); //redirect( 'https://kennisidsystem2-2015.azurewebsites.net/LogOff?ReturnUrl=' . rawurlencode( site_url() ) ); } public function require_javascript() { return true; } public function get_javascript_url() { return 'https://www.kennisid.nl/Integration/Script.js?Token=' . rawurlencode($this->CI->kennisid->get_session_token()); //return 'https://system.kennisid.nl/Integration/Script.js?Token=' . rawurlencode($this->CI->kennisid->get_session_token()); //return 'https://kennisidsystem2-2015.azurewebsites.net/Integration/Script.js?Token=' . rawurlencode($this->CI->kennisid->get_session_token()); } public function have_logout() { return false; } public function mag_gebruikers_toevoegen() { return false; } public function mag_gebruikers_verwijderen() { return false; } } break; case 'LocalDB': // echo "+++ 2 +++<br />"; // exit; class CI_Login { private $CI; private $_login_uid_var = 'local_login_uid'; function is_external_user() { return false; } public function get_name() { return 'LocalDB'; // 100% zeker dat het deze is, niet de constante returnen... } function CI_Login() { $this->CI = get_instance(); initialiseer_systeem_instellingen( $this ); } /** * Returns whether or not the current user in the current session * is logged in or not. Result is either true or false. */ function logged_in() { return $this->get_user_id() != -1; } /** * Returns user id, or -1 when not logged in. */ function get_user_id() { if ($this->CI->session->userdata($this->_login_uid_var)===false) { return -1; } $uid = $this->CI->session->userdata($this->_login_uid_var); if (!is_numeric( $uid ) || $uid <= 0) { return -1; } return $uid; } /** * Registers the user as logged in as the given user ID. */ function login( $userid ) { if ($this->logged_in()) return false; return $this->login_as( $userid ); } /** * Login as */ function login_as( $userid ) { if (!is_numeric($userid) || $userid<0) return false; $data = array( $this->_login_uid_var => $userid ); $this->CI->session->set_userdata( $data ); $this->CI->session->set_user_recognizables(); return true; } /** Logs out the user, if he was logged in. */ function logout() { $this->CI->session->unset_userdata( array( $this->_login_uid_var => '' ) ); $this->CI->session->unset_user_recognizables(); } /** * Checks if the user may use the specified class/method. */ function verify( $class, $method ) { // get the 'security array' $security = $this->CI->config->item('security'); if ($security===false) { show_error('The config item "security" is not set. Cannot proceed.'); } // match class and method against security config $uri = $class . '/' . $method; $logged_in = $this->logged_in(); foreach ($security as $preg => $requirements) { if (preg_match( '#' . $preg . '#', $uri )) { if ($requirements==='*') return true; if ($requirements===true) return $logged_in; if ($requirements===false) return !$logged_in; if (is_int($requirements)) { return $this->CI->rechten->geef_recht_modus( $requirements ) != RECHT_MODUS_GEEN; } if( is_array($requirements) ) { foreach($requirements as $requirement) { if ($this->CI->rechten->geef_recht_modus( $requirement ) != RECHT_MODUS_GEEN) { // var_dump($class, $method, $security, $uri); exit; return true; } } return false; } show_error('Ongeldige rechten gedeclareerd voor ' . $uri); } } // geen rechten! show_error('U heeft geen rechten voor de opgevraagde pagina, /' . $uri . '.<br/>Als u hier bent gekomen via een hyperlink, meld het ons dan a.u.b. zo snel mogelijk!' ); } public function doe_inlog_pagina($post_login_location = '') { $lease_configuratie_id = $this->CI->session->_loginSystem->get_lease_configuratie_id(); // zie application/controllers/lease.php if ($lease_configuratie_id) { $this->CI->load->model( 'leaseconfiguratie' ); $leaseconfiguratie = $this->CI->leaseconfiguratie->get( $lease_configuratie_id ); } $errors = array(); if (isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST') { $is_found_gebruiker = false; $klant = $this->CI->klant->get_by_naam( @$_POST['klantnaam'] ); if( $klant && $lease_configuratie_id == $klant->lease_configuratie_id ) { $gebruikers = $this->CI->gebruiker->search( array( 'klant_id' => $klant->id, 'gebruikersnaam' => @$_POST['gebruikersnaam'], 'wachtwoord' => sha1( @$_POST['wachtwoord'] ) ) ); if (!empty( $gebruikers )) { $gebruiker = reset( $gebruikers ); // check of login systeem klopt! $leaseconfiguratie = $gebruiker->get_klant()->get_lease_configuratie(); if ($leaseconfiguratie && $leaseconfiguratie->login_systeem == 'normaal') { if (!$this->login( $gebruiker->id )) throw new Exception( 'Interne fout bij inloggen.' ); $this->CI->session->set_userdata( 'kid', $klant->id ); $this->CI->session->set_userdata( 'is_std_doc', $klant->standaard_documenten ); $this->CI->session->set_userdata( 'is_std_deelpl', $klant->standaard_deelplannen ); } } } if (!$this->logged_in()) { $errors[] = 'ongeldige_klant_en_gebruikersnaam_en_wachtwoord_combinatie'; } else { $this->CI->session->set_userdata( array( 'has_children_organisations'=> $leaseconfiguratie->has_children_organisations, // 'kid' => $klant->id, // 'parent_klant_id' => $klant->parent_id, 'is_std_doc' => $klant->standaard_documenten, 'is_std_deelpl' => $klant->standaard_deelplannen ) ); // After we are logged in, we check if we should return to a different location than the default post login one. If so, redirect to there. if (!empty($_POST['post_login_location'])) { // Decode the redirect location, and go there! $post_login_location_decoded = base64_decode($_POST['post_login_location']); redirect($post_login_location_decoded); } else { redirect(); } } } $label = $leaseconfiguratie ? $leaseconfiguratie->login_label : 'Inloggen'; // $label .= $klant ? ' ('.$klant->volledige_naam.')' : ''; $this->CI->load->view( 'gebruikers/inloggen', array( 'errors' => $errors, 'leaseconfiguratie' => $leaseconfiguratie, 'label' => $label, 'post_login_location' => $post_login_location ) ); } public function doe_uitlog_pagina() { $this->logout(); redirect(); } public function require_javascript() { return false; } public function get_javascript_url() { return ''; } public function have_logout() { return true; } public function mag_gebruikers_toevoegen() { return true; } public function mag_gebruikers_verwijderen() { return true; } } break; case 'LocalDBExternalUsers': // echo "+++ 3 +++<br />"; // exit; class CI_Login { private $CI; private $_login_uid_var = 'local_external_user_login_uid'; private $_is_external = true; function is_external_user() { return $this->_is_external; } public function get_name() { return 'LocalExternalDB'; } function CI_Login() { $this->CI = get_instance(); initialiseer_systeem_instellingen( $this , true); } /** * Returns whether or not the current user in the current session * is logged in or not. Result is either true or false. */ function logged_in() { return $this->get_user_id() != -1; } /** * Returns user id, or -1 when not logged in. */ function get_user_id() { $uid = $this->CI->session->userdata($this->_login_uid_var); if ($uid===false) { return -1; } if (!is_numeric( $uid ) || $uid <= 0) { return -1; } return $uid; } /** * Registers the user as logged in as the given user ID. */ function login( $userid ) { if ($this->logged_in()) { //user is already logged in, so return true. return true; } return $this->login_as( $userid ); } /** * Login as */ function login_as( $userid ) { if (!is_numeric($userid) || $userid<0) return false; $data = array( $this->_login_uid_var => $userid , $this->_is_external => true); $this->CI->session->set_userdata( $data ); $this->CI->session->set_user_recognizables(); return true; } /** Logs out the user, if he was logged in. */ function logout() { $this->CI->session->unset_userdata( array( $this->_login_uid_var => '', $this->_is_external =>'' ) ); $this->CI->session->unset_user_recognizables(); } /** * Checks if the user may use the specified class/method. */ function verify( $class, $method ) { // get the 'security array' $security = $this->CI->config->item('security'); if ($security===false) { show_error('The config item "security" is not set. Cannot proceed.'); } // match class and method against security config $uri = $class . '/' . $method; $logged_in = $this->logged_in(); foreach ($security as $preg => $requirements) { if (preg_match( '#' . $preg . '#', $uri )) { if ($requirements==='*') { return true; } if ($requirements===true) { return $logged_in; } if ($requirements===false) { return !$logged_in; } if (is_int($requirements)) { return $this->CI->rechten->geef_recht_modus( $requirements ) != RECHT_MODUS_GEEN; } if( is_array($requirements) ) { foreach($requirements as $requirement) { if ($this->CI->rechten->geef_recht_modus( $requirement ) != RECHT_MODUS_GEEN) { return true; } } return false; } show_error('Ongeldige rechten gedeclareerd voor ' . $uri); } } // geen rechten! show_error('U heeft geen rechten voor de opgevraagde pagina, /' . $uri . '.<br/>Als u hier bent gekomen via een hyperlink, meld het ons dan a.u.b. zo snel mogelijk!' ); } public function doe_inlog_pagina($post_login_location = '') { $errors = array(); if (isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST') { //TODO Validate input on password and token to prevent hacks! $email = filter_input(INPUT_POST,'email', FILTER_VALIDATE_EMAIL); $token = @$_POST['token']; $password1 = @$_POST['<PASSWORD>']; $password2 = @$_POST['<PASSWORD>']; $post_login_location_encoded = filter_input(INPUT_POST,'post_login_location', FILTER_VALIDATE_URL); if (@$_POST['pwdreset']) { if ($email) { $message = tg('email_forgottenpassword'); //If the email address is valid, set a reset token and send an email if ($this->CI->gebruiker->get_external_user ($email, '', false)) { //generate random password. When moving to PHP 7 or higher, use random_bytes instead //used the bin2hex to allow using it in url's (urlencode/decode messed it up) $random_password = bin2hex(openssl_random_pseudo_bytes(14)); //create salted hash for the password. When moving to PHP 5.5 or higher, the require_once can be removed because of the builtin password_hash function require_once(BASEPATH.'libraries/Password.php'); $pwd_hash= password_hash($random_password, PASSWORD_DEFAULT); //create the record if it does not exist already $url_query = "UPDATE `externe_gebruikers` SET `token` = '$<PASSWORD>', `status` = 'geblokkeerd' WHERE `email` = '$email';"; $this->CI->db->query($url_query); //Send the reset mail $onderwerp = "<NAME>"; $reset_url = site_url("/extern/index/token=$random_password&email=$email"); $sender = '<EMAIL>'; $recipient = $email; $x_mailer = null; $company_name= 'BRIStoezicht'; $content_type = 'text/html'; $mail_body = "<!DOCTYPE html> <html> <head> <title></title> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <style> body { font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <p class='url'>U heeft aangegeven dat u uw wachtwoord vergeten bent. Klik <a href='$reset_url'>hier</a> om uw wachtwoord opnieuw in te stellen.</p> <p>Deze email is automatisch verzonden.</p> </body> </html>"; $this->CI->load->library( 'simplemail' ); if( !$this->CI->simplemail->send( $onderwerp, $mail_body, array($email), $cc = array(), $bcc = array(), $content_type, $extra_headers = array(), $sender, $x_mailer ) ) { $message = 'Het emailbericht kon niet worden verstuurd. Neem svp contact op met de helpdesk'; } } $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'information' => $message )); return; } else { $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'error' => tg('missing_email') )); return; } exit; } // Check if password reset or new user is applicable if ($token) { // Check if the token is valid if ($this->CI->gebruiker->verify_external_user_token($email, $token)) { // Check if the two passwords matched if ($password1 == $password2 && preg_match("/^(?=.*?[A-Z])(?=(.*[a-z]))(?=(.*\W))(?!.*\s).{8,}$/",$password1)) { //Save the new password $this->CI->gebruiker->set_external_user_password($email, $password1); } else { // The passwords don't match $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'error' => "De door u ingevoerde wachtwoorden komen niet overeen of voldoen niet aan de complexiteitsregels.<br /> Het wachtwoord dient te bestaan uit: <ul> <li>8 karakters</li> <li>minimaal 1 kleine letter</li> <li>minimaal 1 hoofdletter</li> <li>minimaal 1 cijfer</li> <li>minimaal 1 leesteken te bevatten</li> </ul>", 'token_is_valid' => true, 'token' => $token )); return; } } else { $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'token_is_valid' => false, 'error' => tg('invalid_token'), 'token' => $token )); return; } } // Check the provided password $externe_user = $this->CI->gebruiker->get_external_user( $email, $password1 ); if (!isset($externe_user) || !$this->login( $externe_user->id )) { $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'error' => "De combinatie van wachtwoord / emailadres is niet correct", )); return; } else { // Check if user logs in while token was set (when password was reset but then remembered) if ($this->CI->gebruiker->get_external_user_isblocked($email)) { $this->CI->gebruiker->set_external_user_password($email, $<PASSWORD>); } // Check if the post login location is not the inlog page if (!empty($_POST['post_login_location'])) { $post_login_location_decoded = base64_decode($_POST['post_login_location']); if ($post_login_location_decoded == 'extern/inloggen') { $post_login_location_decoded = 'extern/index'; } } // After we are logged in, we check if we should return to a different location than the default post login one. // If so, redirect to there. if ($post_login_location_decoded) { // Decode the redirect location, and go there! redirect($post_login_location_decoded); } else { redirect('extern/index'); } } } $token_provided = false; foreach ($this->CI->uri->segments as $segment) { if (substr($segment,0,5)=='token') { $token_email_array = array_pad(explode ("&",$segment),2,null); $token_segment = array_pad(explode("=",$token_email_array[0]),2,null); $email_segment = array_pad(explode("=",$token_email_array[1]),2,null); $token_provided = true; } } // For now, remove all cookies before logging in. // TODO: check the appropriate 'extern' cookie and do not remove it if keep logged in is set... foreach ($_COOKIE as $key => $value) { unset( $_COOKIE[ $key ] ); // set empty string value, and set expire time back in the past setcookie( $key, '', time()-1800, '/' ); } $segments = implode ("/",$this->CI->uri->segments); //remove email and token if passed $post_login_location = preg_replace("/(\/token=.+)(?:\/|$)/U","/", $segments); //remove inloggen if passed $post_login_location = preg_replace("/((?:\/|^)extern\/inloggen\/)/i", "/extern/", $post_login_location ); $post_login_location_encoded = base64_encode($post_login_location); if ($token_provided == true) { $email = $email_segment[1]; //Check if the account has indeed not been verified yet if ($this->CI->gebruiker->get_external_user_isblocked ($email)) { $token = $token_segment[1]; if ($this->CI->gebruiker->verify_external_user_token($email, $token)) { $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'token_is_valid' => true, 'token' => urlencode($token) )); } else { $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded, 'token_is_valid' => false, 'error' => "Het opgegeven token is niet (meer) geldig.", 'token' => urlencode($token) )); } } else { //User is not blocked anymore so reload the page without token redirect($post_login_location); } } else { //no token was passed $this->CI->load->view( 'extern/login', array( 'post_login_location' => $post_login_location_encoded )); } } } break; default: die( "Login systeem foutief gedefinieerd." ); } <file_sep>ALTER TABLE `dossier_subjecten` ADD `organisatie` VARCHAR( 128 ) NOT NULL AFTER `naam` ; <file_sep><? $ver = 'v' . config_item('application_version'); ?> <!doctype html> <html> <head> <title>BRIStoezicht - Webservice Test Omgeving</title> <link rel="shortcut icon" href="<?=site_url('/files/images/favicon.png')?>" /> <!-- css --> <link rel="stylesheet" href="<?=site_url('/files/css/toezicht.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery-ui-1.8.21.custom.css')?>" type="text/css" /> <style type="text/css"> th { text-align: left; vertical-align: top; } .ok { color: #118541; } .nietok { color: #d33b32; } </style> <!-- js --> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-1.7.min.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-ui-1.8.21.custom.min.js')?>"></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/modal.popup.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/json.js')?>" ></script> <script type="text/javascript"> var scheduleHandle = null; function getRequestString() { return $('[name=Request]').val(); } function setRequest( value ) { $('[name=Request]').val( JSON.stringify( value, undefined, ' ' ) ); } function getRequest() { try { return JSON.parse( getRequestString() ); } catch (err) { return undefined; } } function isValidRequest( request ) { return request && (typeof( request ) == 'object'); } function checkRequest() { var object = getRequest(); if (!isValidRequest( object )) { $('.nietok').show(); $('.ok').hide(); return false; } else { $('.nietok').hide(); $('.ok').show(); return true; } } function updateURL() { $('[name=Url]').val( '/webservice/' + $('[name=Functie]').val() ); } function replaceInRequest( path, newval ) { var object = getRequest(); if (!isValidRequest( object )) return; var rootobject = object; var elements = (''+path).split( '.' ); for (i=0; i<elements.length - 1; ++i) { if (typeof( object[elements[i]] ) != 'object') return; object = object[elements[i]]; } object[elements[i]] = newval; setRequest( rootobject ); } function scheduleRequestCheck() { if (scheduleHandle) { clearTimeout( scheduleHandle ); scheduleHandle = null; } scheduleHandle = setTimeout( checkRequest, 400 ); } function setResponse( anyvalue ) { if (anyvalue) switch (typeof( anyvalue )) { case 'object': $('[name=Response]').val( JSON.stringify( anyvalue, undefined, ' ' ) ); break; default: { try { // attempt to parse & re-stringify (with spacing) the incoming value $('[name=Response]').val( JSON.stringify( JSON.parse( anyvalue ), undefined, ' ' ) ); } catch (err) { // if this fails (due to PHP warnings), show original value $('[name=Response]').val( anyvalue ); } break; } } else // empty value $('[name=Response]').val( '' ); } function executeRequest() { $('[name=Response]').parents('div').slideDown(); setResponse(''); $.ajax({ url: $('[name=Url]').val(), type: 'POST', data: getRequestString(), beforeSend: function(xhr){ var gebruikersnaam = $('[name=GebruikersAccount]').val(); var wachtwoord = $('[name=GebruikersPassword]').val(); var s = gebruikersnaam + ':' + wachtwoord; var a = 'Basic ' + btoa( s ); xhr.setRequestHeader('Authorization', a ); }, success: function( data ) { setResponse( data ); }, error: function( data ) { setResponse( data.responseText ); } }); } </script> </head> <body style="padding: 20px;"> <img src="<?=site_url('/files/images/bristoezicht.png')?>"> <h1>Webservice - Verzoek</h1> <table> <tr> <th style="width:170px">Webservice account:</th> <td><input type="text" name="WebserviceAccount" size="40" maxlength="64" /></td> </tr> <tr> <th>Webservice wachtwoord:</th> <td><input type="text" name="WebservicePassword" size="40" maxlength="64" /></td> </tr> <tr> <th>Functie:</th> <td> <select name="Functie"> <? foreach ($functies as $functie): ?> <option value="<?=$functie?>"><?=$functie?></option> <? endforeach; ?> </select> </td> </tr> <tr> <th>URL:</th> <td><input type="text" name="Url" size="40" maxlength="64" readonly /></td> </tr> <tr> <th style="width:170px">Gebruikersaccount:</th> <td><input type="text" name="GebruikersAccount" size="40" maxlength="64" /></td> </tr> <tr> <th>Gebruikerswachtwoord:</th> <td><input type="password" name="<PASSWORD>ersPassword" size="40" maxlength="64" /></td> </tr> <tr> <th>Verzoek:</th> <td> <textarea name="Request" style="width: 600px; height: 250px;"><?=$basisverzoek?></textarea><br/> <div style="float:right"> <img src="<?=site_url('/files/images/offline-klaar.png')?>" class="hidden ok" style="vertical-align: top"> <span class="hidden ok">JSON syntax correct</span> <img src="<?=site_url('/files/images/offline-niet-klaar.png')?>" class="hidden nietok" style="vertical-align: top"> <span class="hidden nietok">JSON syntax ongeldig</span> </div> <input type="button" class="uitvoeren" value="Verzoek uitvoeren" /> </td> </tr> </table> <div class="hidden"> <h1>Webservice - Resultaat</h1> <table> <tr> <th style="width:170px">Resultaat:</th> <td><textarea name="Response" readonly style="width: 600px; height: 250px;"></textarea></td> </tr> </table> </div> <script type="text/javascript"> // initialize by reformatting the text as output by PHP setRequest( getRequest() ); // set handlers $(document).ready(function(){ checkRequest(); updateURL(); $('[name=WebserviceAccount], [name=WebservicePassword]').blur(function(){ replaceInRequest( this.name, $(this).val() ); }); $('[name=Request]').change(function(){ checkRequest(); }); $('[name=Request]').keypress( scheduleRequestCheck ); $('[name=Functie]').change(function(){ updateURL(); }); $('input.uitvoeren').click(function(){ executeRequest(); }); }); </script> <br/> <span style="font-style:italic; color: #777;">BRIStoezicht <?=config_item('application_version')?></span> </body> </html> <file_sep>CREATE TABLE `bt_checklist_koppel_voorwaarden` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `veld` enum('aanvraagdatum','gebruiksfunctie','bouwsom','is integraal','is eenvoudig','is dakkapel','is bestaand') NOT NULL, `operator` enum('bevat','bevat niet','==','!=','>','<','>=','<=') NOT NULL, `waarde` varchar(128) NOT NULL, PRIMARY KEY (`id`), KEY `checklist_id` (`checklist_id`), CONSTRAINT `bt_checklist_koppel_voorwaarden_ibfk_1` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB;<file_sep> CREATE TABLE `sessies` ( `session_id` varchar(64) NOT NULL, `ip` varchar(15) NOT NULL, `user_agent` varchar(256) NOT NULL, `expires_timestamp` int(11) NOT NULL, `data` longtext NOT NULL, PRIMARY KEY (`session_id`,`ip`,`user_agent`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; <file_sep>ALTER TABLE `gebruikers` ADD `outlook_synchronisatie` TINYINT NOT NULL DEFAULT '1'; ALTER TABLE `deelplannen` ADD `outlook_synchronisatie` TINYINT NOT NULL DEFAULT '1'; ALTER TABLE `outlook_sync_data` ADD `start_time` TIME NOT NULL AFTER `date` , ADD `end_time` TIME NOT NULL AFTER `start_time` ; -- nieuw ALTER TABLE `deelplan_checklisten` ADD `initiele_start_tijd` TIME NULL AFTER `initiele_datum` , ADD `initiele_eind_tijd` TIME NULL AFTER `initiele_start_tijd`; ALTER TABLE `deelplan_checklist_groepen` ADD `initiele_start_tijd` TIME NULL AFTER `initiele_datum` , ADD `initiele_eind_tijd` TIME NULL AFTER `initiele_start_tijd`; ALTER TABLE `deelplan_vragen` ADD `hercontrole_start_tijd` TIME NULL AFTER `hercontrole_datum` , ADD `hercontrole_eind_tijd` TIME NULL AFTER `hercontrole_start_tijd`; ALTER TABLE `outlook_sync_data` DROP INDEX `deelplan_id_2`; ALTER TABLE `outlook_sync_data` ADD UNIQUE (`deelplan_id` ,`date` ,`start_time` ,`end_time`); <file_sep><?php class CI_Cookie { /** * Returns cookie value for given name. */ public function get( $name ) { return @ $_COOKIE[$name]; } /* * Sets value as cookie in client's browser. * NOTE: you can only use set this before the first view is loaded! */ public function set( $name, $value, $expire=null /* unix timestamp */, $path='/', /*bool*/ $secure = null, /*bool*/ $httponly = null ) { setcookie( $name, $value, $expire, $path, null, $secure, $httponly ); $_COOKIE[$name] = $value; } /* * Deletes a cookie in client's browser. */ public function del( $name ) { $this->set( $name, '', time() - 7200 ); unset( $_COOKIE[$name] ); } } <file_sep>BRISToezicht.SearchableList = { lists: [], // jQuery collection 0+ objects updateCurrentConfig: function( listDiv, variable, value, skip_reload ) { // build config var searchConfig = this.getSearchConfig( listDiv ); // update config, both locally and in DOM (might not reload right away!) searchConfig[ variable ] = value; listDiv.find( '.configuration div[config=' + variable + ']' ).attr( 'value', value ); // reload? if (!skip_reload) { var url = listDiv.find( '.configuration div[url]' ).attr( 'url' ); // goto new URL! location.href = url + this.getUrlParams( listDiv, searchConfig ); } }, getSearchConfig: function( listDiv ) { // build config var searchConfig = {}; listDiv.find( '.configuration div[config]' ).each(function(){ searchConfig[ $(this).attr('config') ] = $(this).attr('value'); }); return searchConfig; }, getUrlParams: function( listDiv, searchConfig ) { if (!searchConfig) searchConfig = this.getSearchConfig( listDiv ); var template = listDiv.find( '.configuration div[template]' ).attr( 'template' ); for (var i in searchConfig) { template = template.replace( new RegExp( i ), BRISToezicht.Tools.urlSafeStr( searchConfig[i] ) ); } return template; }, getListDiv: function( dom ) { var parents = $(dom).parents('div.searchable-list'); if (parents.size() == 0) return null; return $(parents[0]); }, initialize: function() { this.lists = $('.searchable-list'); if (!this.lists.size()) return; this.lists.each(function(){ var listDiv = $(this); // handle search button listDiv.find('input[type=button][name=search_button]').click(function(){ var search = listDiv.find('input[type=text][name=filter_text]').val(); if (!search || search.length==0) search = '~'; BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'search', search ); }); // handle reset button listDiv.find('input[type=button][name=reset_button]').click(function(){ BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'search', '~' ); }); // handle enter in search text input listDiv.find('input[type=text][name=filter_text]').keypress( function( evt ){ if (evt.keyCode == 13){ var search = listDiv.find(this).val(); if (!search || search.length==0) search = '~'; BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'search', search ); } }); // handle sort links listDiv.find('td[sortfield]').click(function(){ var field = listDiv.find(this).attr('sortfield'); var order = listDiv.find(this).attr('sortorder'); BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'sortfield', field, true ); BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'sortorder', order ); }); // handle pagesize buttons listDiv.find('input[type=button][pagesize]').click(function(){ BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'pagesize', listDiv.find(this).attr('pagesize') ); }); // handle page buttons listDiv.find('input[type=button][pagenum]').click(function(){ var searchConfig = BRISToezicht.SearchableList.getSearchConfig( listDiv ); var pagenum = $(this).attr('pagenum'); if (('' + pagenum) == '-1') BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'pagenum', searchConfig.pagenum - 1 ); else if (('' + pagenum) == '+1') BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'pagenum', searchConfig.pagenum + 1 ); else BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'pagenum', pagenum ); }); }); } }; <file_sep>INSERT INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('algemeen.opties', 'Opties', '2013-04-10 11:22:50'), ('beheer.gebruikers::communicatie_fout_met_server_bij_opslaan_of_pagina_niet_gevonden', 'Communicatie fout met server bij opslaan, of pagina niet gevonden.', '2013-04-10 11:27:42'), ('beheer.gebruikers::fout_bij_opslaan', 'Fout bij opslaan', '2013-04-10 11:28:13'), ('beheer.gebruikers::gebruikersbeheer', 'Gebruikersbeheer', '2013-04-10 11:22:33'), ('beheer.gebruikers::mag_gebruiker_toezicht_uitvoeren_voor', 'Mag gebruiker $1 toezicht uitvoeren voor $2?', '2013-04-10 11:24:25'), ('beheer.gebruikers::toon_actieve_gebruikers', 'Toon actieve gebruikers', '2013-04-10 11:26:36'), ('beheer.gebruikers::toon_alle_gebruikers', 'Toon alle gebruikers', '2013-04-10 11:26:48'), ('beheer.gebruiker_collegas::collega_info', 'Collega informatie', '2013-04-17 18:07:07'), ('beheer.index::instellingen', 'Instellingen', '2013-04-04 12:14:13'), ('beheer.index::log_info', 'Log informatie', '2013-04-04 12:14:09'), ('beheer.index::scope_sjablonen', 'Scope sjablonen', '2013-04-04 12:14:33'), ('beheer.index::scope_sjablonen_info', 'Beheer hier uw scope sjablonen.', '2013-04-04 12:16:07'), ('beheer.index::themabeheer', 'Themabeheer', '2013-04-04 12:14:24'), ('beheer.index::themabeheer_info', 'Beheer hier uw hoofd en subthema''s.', '2013-04-04 12:15:55'), ('beheer.index::verantwoordingsteksten', 'Verantwoordingsteksten', '2013-04-04 12:14:30'), ('beheer.index::verantwoordingsteksten_info', 'Beheer hier standaard verantwoordingsteksten.', '2013-04-04 12:16:03'), ('beheer.index::view.page.beheer.instellingen_tekst', 'Beheer hier verschillende instellingen voor uw account en medewerkers.', '2013-04-04 12:15:42'), ('beheer.index::view.page.beheer.log_info_tekst', 'Bekijk hier alle veranderingen die uw medewerkers in het systeem hebben gemaakt.', '2013-04-04 12:15:35'), ('beheer.index::view.page.beheer.wizard_tekst', 'Beheer hier uw checklisten!', '2013-04-04 12:15:46'), ('beheer.index::wetten_en_regelgeving', 'Wetten en regelgeving', '2013-04-04 12:14:22'), ('beheer.index::wetten_en_regelgeving_info', 'Bekijk hier wetteksten en regelgevingen die van toepassing zijn op uw checklisten.', '2013-04-04 12:15:50'), ('beheer.index::wizard', 'Checklistwizard', '2013-04-04 12:14:17'), ('BRIStoezicht', 'BRIStoezicht', '2013-04-03 13:47:25'), ('deelplan.aanvraagdatum', 'Aanvraagdatum', '2013-04-04 15:02:16'), ('deelplan.deelplan_naam', 'Deelplan naam', '2013-04-04 15:02:16'), ('deelplan.identificatienummer', 'Identificatienummer', '2013-04-04 15:02:16'), ('deelplan.olo_nummer', 'OLO nummer', '2013-04-04 15:02:16'), ('deelplannen.bekijken::bescheiden', 'Bescheiden', '2013-04-04 15:11:52'), ('deelplannen.bekijken::betrokkenen', 'Betrokkenen', '2013-04-04 15:11:52'), ('deelplannen.bekijken::deelplan_bewerken', 'Deelplan bewerken', '2013-04-04 15:11:02'), ('deelplannen.bekijken::registratiegegevens', 'Registratiegegevens', '2013-04-04 15:11:42'), ('deelplannen.bekijken::scopes', 'Scopes', '2013-04-04 15:11:52'), ('deelplannen.bekijken::themas', 'Thema''s', '2013-04-04 15:11:52'), ('deelplannen.bewerken::bescheiden', 'Bescheiden', '2013-04-04 15:09:53'), ('deelplannen.bewerken::betrokkenen', 'Betrokkenen', '2013-04-04 15:09:50'), ('deelplannen.bewerken::deelplan_verwijderen', 'Deelplan verwijderen', '2013-04-04 15:00:12'), ('deelplannen.bewerken::deelplan_werkelijk_verwijderen_u_kunt_deze_actie_niet_ongedaan_maken', 'Deelplan werkelijk verwijderen? U kunt deze actie niet ongedaan maken!', '2013-04-04 15:00:50'), ('deelplannen.bewerken::de_huidige_scopeselectie_is_gebaseerd_op', 'De huidige scopeselectie is gebaseerd op het $1 sjabloon.', '2013-04-04 15:04:26'), ('deelplannen.bewerken::er_zijn_nog_geen_bescheiden_gedefinieerd', 'Er zijn nog geen bescheiden gedefinieerd voor dit dossier. U kunt dit alsnog doen onder "Dossier bewerken".', '2013-04-04 15:09:00'), ('deelplannen.bewerken::er_zijn_nog_geen_betrokkenen_gedefinieerd', 'Er zijn nog geen betrokkenen gedefinieerd voor dit dossier. U kunt dit alsnog doen onder "Dossier bewerken".', '2013-04-04 15:08:37'), ('deelplannen.bewerken::er_zijn_nog_geen_scopes_geselecteerd', 'Er zijn nog geen scopes geselecteerd, of de geselecteerde scopes hebben geen thema''s.', '2013-04-04 15:07:49'), ('deelplannen.bewerken::gebruik_een_scope_sjabloon', 'Gebruik een scope sjabloon', '2013-04-04 15:02:55'), ('deelplannen.bewerken::naam_van_het_nieuwe_sjabloon', 'Naam van het nieuwe sjabloon...', '2013-04-04 15:05:18'), ('deelplannen.bewerken::nieuw_sjabloon_aanmaken', 'Nieuw sjabloon aanmaken', '2013-04-04 15:04:58'), ('deelplannen.bewerken::registratiegegevens', 'Registratiegegevens', '2013-04-04 15:02:16'), ('deelplannen.bewerken::selecteer_een_sjabloon', '-- selecteer een sjabloon --', '2013-04-04 15:03:18'), ('deelplannen.bewerken::sjablonen', 'Sjablonen', '2013-04-04 15:06:11'), ('deelplannen.bewerken::sjabloon_naam', 'Naam', '2013-04-04 15:05:47'), ('deelplannen.bewerken::themas', 'Thema''s', '2013-04-04 15:09:47'), ('deelplannen.bewerken::welke_scopes_wilt_u_toetsen', 'Welke scopes wilt u toetsen?', '2013-04-04 15:02:16'), ('deelplannen.checklistgroep::aandachtspunten', 'Aandachtspunten', '2013-04-04 15:37:39'), ('deelplannen.checklistgroep::alleen_lezen_modus_actief', 'alleen-lezen modus actief', '2013-04-16 10:33:33'), ('deelplannen.checklistgroep::alles', 'Alles', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::auteur', 'Auteur', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::datum', 'Datum', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::de_applicatie_is_nog_niet_klaar_voor_offline_gebruik_even_geduld_aub', 'De applicatie is nog niet klaar voor offline gebruik, even geduld a.u.b...', '2013-04-16 10:35:48'), ('deelplannen.checklistgroep::dit_bescheiden_is_niet_beschikbaar_in_de_pdf_annotator', 'Dit bescheiden is niet beschikbaar in de PDF annotator. Dit kan liggen aan een verkeerd bestandsformaat van het bescheiden, of missende functionaliteit in uw browser.', '2013-04-16 10:36:27'), ('deelplannen.checklistgroep::document_naam', 'Naam:', '2013-04-16 10:34:19'), ('deelplannen.checklistgroep::email_verstuurd', 'Email succesvol verzonden.', '2013-04-16 13:21:31'), ('deelplannen.checklistgroep::foto_naam', 'Naam:', '2013-04-16 10:34:13'), ('deelplannen.checklistgroep::geeft_aan_of_de_applicatie_klaar_is_voor_offline_werken', 'Geeft aan of de applicatie klaar is voor offline werken.', '2013-04-04 15:44:35'), ('deelplannen.checklistgroep::geeft_aan_of_er_nog_onopgeslagen_werk_aanwezig_is_in_dit_venster.', 'Geeft aan of er nog onopgeslagen werk aanwezig is in dit venster.', '2013-04-04 15:42:26'), ('deelplannen.checklistgroep::gesynchroniseerd', 'Gesynchroniseerd', '2013-04-04 15:43:06'), ('deelplannen.checklistgroep::interne_fout_bij_het_selecteren_van_het_bescheiden', 'Interne fout bij het selecteren van het bescheiden.', '2013-04-16 10:36:53'), ('deelplannen.checklistgroep::kies_een_standaard_tekst', 'Kies een standaard tekst', '2013-04-04 15:38:48'), ('deelplannen.checklistgroep::klaar_voor_offline_werken', 'Klaar voor offline werken.', '2013-04-04 15:44:51'), ('deelplannen.checklistgroep::klik_om_de_online_status_bij_te_werken', 'Klik om de online status bij te werken.', '2013-04-04 15:43:54'), ('deelplannen.checklistgroep::klik_om_filtering_op_geel_aan_uit_te_zetten', 'Klik om filtering op geel aan/uit te zetten', '2013-04-04 15:40:23'), ('deelplannen.checklistgroep::klik_om_filtering_op_groen_aan_uit_te_zetten', 'Klik om filtering op groen aan/uit te zetten', '2013-04-04 15:40:23'), ('deelplannen.checklistgroep::klik_om_filtering_op_rood_aan_uit_te_zetten', 'Klik om filtering op rood aan/uit te zetten', '2013-04-04 15:40:23'), ('deelplannen.checklistgroep::naam', 'Naam', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::niet_gesynchroniseerd', 'Niet gesynchroniseerd', '2013-04-04 15:43:06'), ('deelplannen.checklistgroep::nieuw', 'Nieuw', '2013-04-04 15:19:29'), ('deelplannen.checklistgroep::nieuwe_toelichting', 'Nieuwe toelichting', '2013-04-04 15:38:48'), ('deelplannen.checklistgroep::niveau_gemiddeld', 'Niveau 2', '2013-04-04 15:46:52'), ('deelplannen.checklistgroep::niveau_hoog', 'Niveau 3', '2013-04-04 15:46:52'), ('deelplannen.checklistgroep::niveau_laag', 'Niveau 1', '2013-04-04 15:46:52'), ('deelplannen.checklistgroep::niveau_zeer_hoog', 'Niveau 4', '2013-04-04 15:46:52'), ('deelplannen.checklistgroep::niveau_zeer_laag', 'Steekproef', '2013-04-04 15:46:52'), ('deelplannen.checklistgroep::nog_niet_klaar_voor_offline_werken', 'Nog NIET klaar voor offline werken!', '2013-04-04 15:45:08'), ('deelplannen.checklistgroep::omschrijving', 'Omschrijving', '2013-04-04 15:37:43'), ('deelplannen.checklistgroep::online', 'Online', '2013-04-04 15:44:06'), ('deelplannen.checklistgroep::open_toezichtvoortgang', 'Open toezichtvoortgang', '2013-04-04 15:45:49'), ('deelplannen.checklistgroep::plan_een_hercontrole', 'Plan een hercontrole', '2013-04-04 15:19:29'), ('deelplannen.checklistgroep::relevant', 'Relevant', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::relevante_documenten', 'Relevante documenten', '2013-04-04 15:18:51'), ('deelplannen.checklistgroep::richtlijnen', 'Richtlijnen', '2013-04-04 15:37:34'), ('deelplannen.checklistgroep::selecteer_eerst_een_bescheiden_om_te_annoteren', 'Selecteer eerst een bescheiden om te annoteren.', '2013-04-16 10:35:06'), ('deelplannen.checklistgroep::soort', 'Soort', '2013-04-04 15:32:05'), ('deelplannen.checklistgroep::specificatie', 'Specificatie', '2013-04-04 15:35:56'), ('deelplannen.checklistgroep::status_filter', 'Status filter', '2013-04-04 15:39:29'), ('deelplannen.checklistgroep::synchroniseren', 'Synchroniseren...', '2013-04-04 15:43:06'), ('deelplannen.checklistgroep::terug', 'Terug', '2013-04-04 15:41:57'), ('deelplannen.checklistgroep::terug_naar_overzicht', 'Terug naar overzicht', '2013-04-04 15:30:52'), ('deelplannen.checklistgroep::toelichting', 'Toelichting', '2013-04-04 15:18:33'), ('deelplannen.checklistgroep::volgende_vraag', 'Volgende vraag', '2013-04-04 15:47:36'), ('deelplannen.checklistgroep::vorige_vraag', 'Vorige vraag', '2013-04-04 15:47:36'), ('deelplannen.checklistgroep::wettelijke_grondslagen', 'Wettelijke grondslagen', '2013-04-04 15:37:29'), ('deelplannen.checklistgroep::x_van_y', '$1 van $2', '2013-04-04 15:29:26'), ('dossier.aanmaakdatum', 'Aanmaakdatum', '2013-04-04 13:28:39'), ('dossier.bag_identificatienummer', 'BAG identificatienummer', '2013-04-04 14:32:15'), ('dossier.datum_hercontrole', 'Datum hercontrole', '2013-04-04 13:33:58'), ('dossier.deelplan_olo_nummers', 'Deelplan OLO nummers', '2013-04-04 13:28:52'), ('dossier.dossiernaam', 'Dossiernaam', '2013-04-04 13:23:29'), ('dossier.geplande_datum', 'Geplande datum', '2013-04-04 13:28:44'), ('dossier.identificatienummer', 'Identificatienummer', '2013-04-04 13:28:36'), ('dossier.initiele_datum', 'Initiele datum', '2013-04-04 13:33:55'), ('dossier.kadastraal_sectie_nummer', 'Kadastraal / Sectie / Nummer', '2013-04-04 14:35:25'), ('dossier.locatie_adres', 'Locatie adres', '2013-04-04 13:28:47'), ('dossier.locatie_postcode_woonplaats', 'Locatie postcode / woonplaats', '2013-04-04 14:35:46'), ('dossier.matrix', 'Matrix', '2013-04-04 13:33:51'), ('dossier.opmerkingen', 'Opmerkingen', '2013-04-04 13:23:35'), ('dossier.scope', 'Scope', '2013-04-04 13:33:45'), ('dossier.status_scope', 'Status scope', '2013-04-04 13:34:05'), ('dossier.toezichthouder', 'Toezichthouder', '2013-04-04 13:33:48'), ('dossier.xy-coordinaten', 'X/Y coördinaten', '2013-04-04 14:32:15'), ('dossiers.bekijken::afgemeld', 'afgemeld', '2013-04-04 13:31:50'), ('dossiers.bekijken::bevindingen', 'Bevindingen', '2013-04-04 13:43:37'), ('dossiers.bekijken::bijlage_documenten_tekeningen', 'Bijlage: Documenten/Tekeningen', '2013-04-04 13:43:51'), ('dossiers.bekijken::bijlage_fotos', 'Bijlage: Foto''s', '2013-04-04 13:43:44'), ('dossiers.bekijken::bijlage_juridische_grondslag', 'Bijlage: Juridische grondslag', '2013-04-04 13:43:59'), ('dossiers.bekijken::deelplannen', 'Deelplannen', '2013-04-04 13:43:08'), ('dossiers.bekijken::deelplannen.header', 'Deelplannen', '2013-04-04 13:30:07'), ('dossiers.bekijken::deelplan_afmelden', 'Deelplan afmelden', '2013-04-04 13:32:25'), ('dossiers.bekijken::deelplan_bekijken', 'Deelplan bekijken', '2013-04-04 13:32:25'), ('dossiers.bekijken::deelplan_bewerken', 'Deelplan bewerken', '2013-04-04 13:32:25'), ('dossiers.bekijken::dit_dossier_werkelijk_afmelden_u_kunt_deze_actie_niet_ongedaan_maken', 'Dit dossier werkelijk afmelden? U kunt deze actie niet ongedaan maken!', '2013-04-04 13:25:59'), ('dossiers.bekijken::documenten', 'Documenten', '2013-04-04 13:43:23'), ('dossiers.bekijken::dossier.header', 'Dossier $1', '2013-04-04 13:29:45'), ('dossiers.bekijken::dossiergegevens', 'Dossiergegevens', '2013-04-04 13:43:21'), ('dossiers.bekijken::fout_bij_opslaan', 'Fout bij opslaan', '2013-04-04 13:40:24'), ('dossiers.bekijken::inleiding', 'Inleiding', '2013-04-04 13:43:18'), ('dossiers.bekijken::juridische_grondslagen', 'Juridische grondslagen', '2013-04-04 13:43:14'), ('dossiers.bekijken::laat_leeg_voor_automatische_naam', 'Laat leeg voor automatische naam', '2013-04-04 13:30:47'), ('dossiers.bekijken::maak_een_nieuw_deelplan_aan', 'Maak een nieuw deelplan aan', '2013-04-04 13:30:47'), ('dossiers.bekijken::nog_niet_ingepland', 'Nog niet ingepland', '2013-04-04 13:35:26'), ('dossiers.bekijken::nog_niet_toegewezen', 'Nog niet toegewezen', '2013-04-04 13:35:22'), ('dossiers.bekijken::open_toezicht', 'Open toezicht', '2013-04-04 13:36:22'), ('dossiers.bekijken::rapportage.header', 'Rapportage', '2013-04-04 13:36:59'), ('dossiers.bekijken::rapportageonderdelen', 'Rapportageonderdelen', '2013-04-04 13:43:04'), ('dossiers.bekijken::samenvatting', 'Samenvatting', '2013-04-04 13:43:34'), ('dossiers.bekijken::selectiemogelijkheden', 'Selectiemogelijkheden', '2013-04-04 13:42:47'), ('dossiers.bekijken::voer_een_naam_in_voor_het_nieuwe_deelplan', 'Voer een naam in voor het nieuwe deelplan.', '2013-04-04 13:39:46'), ('dossiers.bescheiden_popup::auteur', 'Auteur', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::bestand', 'Bestand', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::datum_laatste_wijziging', 'Datum laatste wijziging', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::even_geduld_aub_uw_upload_kan_even_duren', 'Even geduld a.u.b., uw upload kan even duren...', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::nog_geen_voorbeeld_beschikbaar', 'Nog geen voorbeeld beschikbaar.', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::omschrijving', 'Omschrijving', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::tekeningnummer', 'Tekeningnummer', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::versienummer', 'Versienummer', '2013-04-16 10:49:35'), ('dossiers.bescheiden_popup::zaaknummer_registratie', 'Zaaknummer registratie', '2013-04-16 10:49:35'), ('dossiers.bescheiden_toevoegen::documenten.header', 'Bescheiden', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::er_is_nog_een_upload_bezig_even_geduld_aub', 'Er is nog een upload bezig, even geduld a.u.b...', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::fout_bij_communicatie_met_server', 'Fout bij communicatie met server.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::geselecteerde_bescheiden_werkelijk_verwijderen', 'Geselecteerde bescheiden werkelijk verwijderen?', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::selecteer_eerst_de_bescheiden_die_u_wenst_te_verwijderen', 'Selecteer eerst de bescheiden die u wenst te verwijderen.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::u_kunt_een_nieuw_bescheiden_niet_verwijderen', 'U kunt een nieuw bescheiden niet verwijderen.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_toevoegen::weet_u_zeker_dat_u_dit_bescheiden_wilt_verwijderen', 'Weet u zeker dat u dit bescheiden wilt verwijderen?', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::documenten.header', 'Bescheiden', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::er_is_nog_een_upload_bezig_even_geduld_aub', 'Er is nog een upload bezig, even geduld a.u.b...', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::fout_bij_communicatie_met_server', 'Fout bij communicatie met server.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::geselecteerde_bescheiden_werkelijk_verwijderen', 'Geselecteerde bescheiden werkelijk verwijderen?', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::selecteer_eerst_de_bescheiden_die_u_wenst_te_verwijderen', 'Selecteer eerst de bescheiden die u wenst te verwijderen.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::u_kunt_een_nieuw_bescheiden_niet_verwijderen', 'U kunt een nieuw bescheiden niet verwijderen.', '2013-04-17 18:07:07'), ('dossiers.bescheiden_verwijderen_batch::weet_u_zeker_dat_u_dit_bescheiden_wilt_verwijderen', 'Weet u zeker dat u dit bescheiden wilt verwijderen?', '2013-04-17 18:07:07'), ('dossiers.bewerken::adres', 'Adres', '2013-04-04 13:48:20'), ('dossiers.bewerken::betrokkenen', 'Betrokkenen', '2013-04-04 13:48:20'), ('dossiers.bewerken::betrokkene_bekijken', 'Betrokkene bekijken', '2013-04-04 14:27:16'), ('dossiers.bewerken::betrokkene_bewerken', 'Betrokkene bewerken', '2013-04-04 13:48:20'), ('dossiers.bewerken::betrokkene_details', 'Betrokkene details', '2013-04-04 13:48:20'), ('dossiers.bewerken::betrokkene_toevoegen', 'Betrokkene toevoegen', '2013-04-04 13:48:20'), ('dossiers.bewerken::documenten.header', 'Documenten', '2013-04-04 14:29:53'), ('dossiers.bewerken::dossierverantwoordelijke', 'Dossierverantwoordelijke', '2013-04-04 14:29:53'), ('dossiers.bewerken::email', 'E-mail', '2013-04-04 13:48:20'), ('dossiers.bewerken::er_is_nog_een_upload_bezig_even_geduld_aub', 'Er is nog een upload bezig, even geduld a.u.b....', '2013-04-04 14:40:31'), ('dossiers.bewerken::fout_bij_communicatie_met_server', 'Fout bij communicatie met server', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_betrokkene_aan_het_bewerken_of_toevoegen', 'Geen betrokkene aan het bewerken of toevoegen.', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_betrokkene_geselecteerd', 'Geen betrokkene geselecteerd', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_rechten_om_betrokkenen_op_te_slaan', 'Geen rechten om betrokkenen op te slaan.', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_rechten_om_betrokkene_te_verwijderen', 'Geen rechten om betrokkene te verwijderen.', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_rechten_om_betrokkene_te_wijzigen', 'Geen rechten om betrokkene te wijzigen.', '2013-04-04 13:48:20'), ('dossiers.bewerken::geen_rechten_om_betrokkene_toe_te_voegen', 'Geen rechten om betrokkene toe te voegen.', '2013-04-04 13:48:20'), ('dossiers.bewerken::geselecteerde_bescheiden_werkelijk_verwijderen', 'Geselecteerd bescheiden werkelijk verwijderen?', '2013-04-04 14:41:23'), ('dossiers.bewerken::naam', 'Naam', '2013-04-04 13:48:20'), ('dossiers.bewerken::organisatie', 'Organisatie', '2013-04-04 13:48:20'), ('dossiers.bewerken::overzicht_betrokkenen', 'Overzicht betrokkenen', '2013-04-16 10:29:38'), ('dossiers.bewerken::plaatsbepaling', 'Plaatsbepaling', '2013-04-04 14:28:53'), ('dossiers.bewerken::postcode', 'Postcode', '2013-04-04 13:48:20'), ('dossiers.bewerken::registratiegegevens', 'Registratiegegevens', '2013-04-04 14:28:53'), ('dossiers.bewerken::registratiegegevens.header', 'Registratiegegevens', '2013-04-04 14:29:25'), ('dossiers.bewerken::rol', 'Rol', '2013-04-04 13:48:20'), ('dossiers.bewerken::selecteer_eerst_de_bescheiden_die_u_wenst_te_verwijderen', 'Selecteer eerst het bescheiden dat u wenst te verwijderen.', '2013-04-04 14:41:23'), ('dossiers.bewerken::telefoon', 'Telefoon', '2013-04-04 13:48:20'), ('dossiers.bewerken::u_kunt_een_nieuw_bescheiden_niet_verwijderen', 'U kunt een nieuw bescheiden niet verwijderen.', '2013-04-04 14:42:18'), ('dossiers.bewerken::weet_u_zeker_dat_u_deze_betrokkene_wilt_verwijderen', 'Weet u zeker dat u deze betrokkene wilt verwijderen?', '2013-04-04 13:48:20'), ('dossiers.bewerken::weet_u_zeker_dat_u_dit_bescheiden_wilt_verwijderen', 'Weet u zeker dat u dit bescheiden wilt verwijderen?', '2013-04-04 14:42:18'), ('dossiers.bewerken::woonplaats', 'Woonplaats', '2013-04-04 13:48:20'), ('dossiers.index::archiveer_geselecteerde_dossiers', 'Archiveer geselecteerde dossiers', '2013-04-04 12:45:46'), ('dossiers.index::dossier_terugzetten', 'Dossier terugzetten', '2013-04-04 12:44:32'), ('dossiers.index::dossier_verwijderen', 'Dossier verwijderen', '2013-04-04 12:44:32'), ('dossiers.index::gepland_op', 'Gepland op', '2013-04-04 12:42:50'), ('dossiers.index::herkomst', 'Herkomst', '2013-04-04 12:41:37'), ('dossiers.index::id-nummer', 'Id nummer', '2013-04-04 12:41:42'), ('dossiers.index::importeren_starten', 'Importeren starten', '2013-04-04 12:40:17'), ('dossiers.index::kaartweergave', 'Kaartweergave', '2013-04-05 12:44:55'), ('dossiers.index::locatie', 'Locatie', '2013-04-04 12:42:53'), ('dossiers.index::maak_een_nieuw_dossier_aan', 'Maak een nieuw dossier aan', '2013-04-04 12:40:00'), ('dossiers.index::projectomschrijving', 'Project omschrijving', '2013-04-04 12:41:46'), ('dossiers.index::toon_alle_dossiers', 'Toon alle dossiers', '2013-04-04 12:45:55'), ('dossiers.index::toon_gearchiveerde_dossiers', 'Toon gearchiveerde dossiers', '2013-04-04 12:46:01'), ('dossiers.index::toon_mijn_dossiers', 'Toon mijn dossiers', '2013-04-04 12:45:50'), ('dossiers.index::verantwoordelijke', 'Verantwoordelijke', '2013-04-04 12:41:52'), ('dossiers.index::weet_u_zeker_dat_u_de_geselecteerde_dossiers_wilt_archiveren', 'Weet u zeker dat u de geselecteerde dossiers wilt archiveren?', '2013-04-04 12:47:21'), ('dossiers.subject_bewerken::adres', 'Adres', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::betrokkenen', 'Betrokkenen', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::betrokkene_bekijken', 'Betrokkene bekijken', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::betrokkene_bewerken', 'Betrokkene bewerken', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::betrokkene_details', 'Betrokkene details', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::betrokkene_toevoegen', 'Betrokkene toevoegen', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::email', 'Email', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::fout_bij_communicatie_met_server', 'Fout bij communicatie met server.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_betrokkene_aan_het_bewerken_of_toevoegen', 'Geen betrokkene aan het bewerken of toevoegen.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_betrokkene_geselecteerd', 'Geen betrokkene geselecteerd.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_rechten_om_betrokkenen_op_te_slaan', 'Geenr echten om betrokkene op te slaan.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_rechten_om_betrokkene_te_verwijderen', 'Geen rechten om betrokkene te verwijderen.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_rechten_om_betrokkene_te_wijzigen', 'Geen rechten om betrokkene te wijzigen.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::geen_rechten_om_betrokkene_toe_te_voegen', 'Geen rechten om betrokkene toe te voegen.', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::naam', 'Naam', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::organisatie', 'Organisatie', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::postcode', 'Postcode', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::rol', 'Rol', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::telefoon', 'Telefoon', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::weet_u_zeker_dat_u_deze_betrokkene_wilt_verwijderen', 'Weet u zeker dat u deze betrokkene wilt verwijderen?', '2013-04-04 14:38:06'), ('dossiers.subject_bewerken::woonplaats', 'Woonplaats', '2013-04-04 14:38:06'), ('editor.gebruiker', 'Gebruiker', '2013-04-10 11:29:30'), ('form.aanmaken', 'Aanmaken', '2013-04-04 13:30:47'), ('form.alle', 'Alle', '2013-04-04 00:00:00'), ('form.alles', 'Alles', '2013-04-04 12:49:43'), ('form.alles_selecteren', 'Alles selecteren', '2013-04-04 14:39:18'), ('form.alles_wissen', 'Alles wissen', '2013-04-04 00:00:00'), ('form.annuleren', 'Annuleren', '2013-04-04 00:00:00'), ('form.deselecteer_alles', 'Deselecteer alles', '2013-04-04 15:06:50'), ('form.dossier_afmelden', 'Dossier afmelden', '2013-04-04 13:25:59'), ('form.dossier_bewerken', 'Dossier bewerken', '2013-04-04 13:23:49'), ('form.downloaden', 'Downloaden', '2013-04-04 13:44:26'), ('form.geen', 'Geen', '2013-04-04 00:00:00'), ('form.ja', 'Ja', '2013-04-04 00:00:00'), ('form.nee', 'Nee', '2013-04-04 00:00:00'), ('form.nieuw', 'Nieuw', '2013-04-04 14:35:25'), ('form.opslaan', 'Opslaan', '2013-04-04 00:00:00'), ('form.selecteer_alles', 'Selecteer alles', '2013-04-04 15:07:01'), ('form.toevoegen', 'Toevoegen', '2013-04-04 00:00:00'), ('form.verwijderen', 'Verwijderen', '2013-04-04 00:00:00'), ('form.volgende', 'Volgende', '2013-04-04 00:00:00'), ('form.vorige', 'Vorige', '2013-04-04 00:00:00'), ('form.wijzigen', 'Wijzigen', '2013-04-04 00:00:00'), ('form.wissen', 'Wissen', '2013-04-04 12:48:44'), ('form.zoeken', 'Zoeken', '2013-04-04 12:48:44'), ('gebruiker.geen_rol_toegewezen', '-- geen rol toegewezen --', '2013-04-10 11:24:00'), ('gebruiker.intern', 'Intern', '2013-04-10 11:30:28'), ('gebruiker.prijs', 'Uurtarief', '2013-04-10 11:30:37'), ('gebruiker.rol', 'Rol', '2013-04-10 11:22:39'), ('gebruiker.rol_id', 'Rol', '2013-04-10 11:30:24'), ('gebruiker.status', 'Status', '2013-04-10 11:22:42'), ('gebruiker.volledige_naam', 'Volledige naam', '2013-04-10 11:22:36'), ('gebruiker.wachtwoord', 'Wachtwoord (leeg laten om onveranderd te laten)', '2013-04-10 11:41:17'), ('gebruikers.inloggen::gebruikersnaam', 'Gebruikersnaam', '2013-04-05 16:26:47'), ('gebruikers.inloggen::ongeldige_klant_en_gebruikersnaam_en_wachtwoord_combinatie', 'Ongeldige organisatie, gebruikersnaam en wachtwoord combinatie.', '2013-04-05 16:29:27'), ('gebruikers.inloggen::organisatie', 'Organisatie', '2013-04-05 16:26:47'), ('gebruikers.inloggen::wachtwoord', 'Wachtwoord', '2013-04-05 16:26:47'), ('header.dossierbeheer', 'Dossierbeheer', '2013-04-03 13:30:11'), ('header.gebruikersbeheer', 'Gebruikersbeheer', '2013-04-03 13:30:15'), ('header.geen_rol_toegekend', 'Geen rol toegekend', '2013-04-05 16:26:47'), ('header.ingelogd_als', 'Ingelogd als $1', '2013-04-05 16:26:47'), ('header.instellingen', 'Instellingen', '2013-04-03 13:30:42'), ('header.management', 'Management', '2013-04-03 13:30:38'), ('header.matrixbeheer', 'Matrixbeheer', '2013-04-03 13:30:35'), ('header.niet_ingelogd', 'Niet ingelogd', '2013-04-05 16:50:46'), ('header.sitebeheer', 'Site beheer', '2013-04-03 13:30:47'), ('header.uitloggen', 'Uitloggen', '2013-04-05 16:26:47'), ('intro.index::cookie-waarschuwing', 'LET OP: BRIStoezicht maakt gebruik van cookies en kan zonder cookies niet werken. Als u hier niet mee akkoord gaat, logt u dan a.u.b. uit.', '2013-04-03 13:53:47'), ('intro.index::dashboard', 'Dashboard', '2013-04-03 13:44:57'), ('intro.index::gebruikersforum', 'Gebruikersforum', NULL), ('intro.index::geen-notificaties', 'Geen notificaties.', '2013-04-03 13:45:33'), ('intro.index::geplaatst_op', 'Geplaatst op $1', '2013-04-16 10:24:40'), ('intro.index::nieuwsberichten', 'Nieuwsberichten', '2013-04-03 13:42:48'), ('intro.index::notificaties', 'Notificaties', '2013-04-03 13:45:16'), ('intro.index::releasedatum', 'Releasedatum', '2013-04-03 13:47:40'), ('intro.index::versieinformatie', 'Versieinformatie', '2013-04-03 13:50:08'), ('nav.accountbeheer', 'Accountbeheer', '2013-04-04 11:55:35'), ('nav.afbeeldingbeheer', 'Afbeeldingbeheer', '2013-04-04 11:56:40'), ('nav.afgerond', 'Afgerond', '2013-04-04 11:48:09'), ('nav.bekijken', '$1', '2013-04-04 13:26:18'), ('nav.bewerken', 'Bewerken', '2013-04-04 11:49:48'), ('nav.bristoets_koppeling_checklistbeheer', 'BRIStoets koppeling checklistbeheer', '2013-04-04 11:56:52'), ('nav.checklistgroepbeheer', 'Checklistgroepbeheer', '2013-04-04 11:56:36'), ('nav.checklist_import', 'Checklist import', '2013-04-04 11:58:39'), ('nav.checklist_wizard', 'Checklist wizard', '2013-04-04 12:03:17'), ('nav.collegas_instellen', 'Collega''s instellen', '2013-04-04 12:06:47'), ('nav.deelplan_bekijken', '$1', '2013-04-04 12:02:16'), ('nav.deelplan_bewerken', '$1 bewerken', '2013-04-04 12:02:28'), ('nav.dossierbeheer', 'Dossierbeheer', '2013-04-04 11:45:52'), ('nav.dossier_bekijken', '$1', '2013-04-04 12:02:20'), ('nav.gebruikersbeheer', 'Gebruikersbeheer', '2013-04-04 12:06:39'), ('nav.gebruikerslijst', 'Gebruikerslijst', '2013-04-04 11:55:41'), ('nav.gebruiker_bewerken', 'Gebruiker bewerken', '2013-04-04 11:55:49'), ('nav.grondslag', '$1', '2013-04-04 11:52:08'), ('nav.grondslag_artikel_gebruik', '$1 $2', '2013-04-04 11:52:14'), ('nav.importeren', 'Importeren', '2013-04-04 11:47:28'), ('nav.instellingen', 'Instellingen', '2013-04-04 11:51:55'), ('nav.itp_import', 'ITP import', '2013-04-04 11:58:30'), ('nav.logobeheer', 'Logobeheer', '2013-04-04 11:56:09'), ('nav.logo_bekijken', 'Logo bekijken', '2013-04-04 11:56:28'), ('nav.logo_verwijderen', 'Logo verwijderen', '2013-04-04 11:56:22'), ('nav.log_informatie', 'Log informatie', '2013-04-04 12:09:54'), ('nav.management_info_resultaat', 'Resultaat', '2013-04-04 12:09:44'), ('nav.management_rapportage', 'Management rapportage', '2013-04-04 12:09:31'), ('nav.matrixbeheer', 'Matrixbeheer', '2013-04-04 12:07:40'), ('nav.nieuws_items', 'Nieuws items', '2013-04-04 11:58:18'), ('nav.nieuw_logo_toevoegen', 'Logo toevoegen', '2013-04-04 11:56:16'), ('nav.prioriteitstellingsmatrix_invullen', 'Prioriteitstellingsmatrix invullen', '2013-04-04 12:07:58'), ('nav.resultaten', 'Resultaten', '2013-04-04 11:58:55'), ('nav.risicoanalyse_effecten', 'Effecten', '2013-04-04 12:08:37'), ('nav.risicoanalyse_invullen', 'Invullen', '2013-04-04 12:08:57'), ('nav.rol_bewerken', 'Rol bewerken', '2013-04-04 12:07:06'), ('nav.scopesjabloon_bewerken', 'Bewerken', '2013-04-04 12:11:10'), ('nav.scope_sjablonen', 'Scope sjablonen', '2013-04-04 12:10:45'), ('nav.site_beheer', 'Site beheer', '2013-04-04 11:55:27'), ('nav.startpagina', 'Startpagina', '2013-04-04 11:42:24'), ('nav.stats_gebruiker_activiteit', 'Gebruikeractiviteit', '2013-04-04 11:57:51'), ('nav.stats_kennisid', 'KennisID statistieken', '2013-04-04 11:58:10'), ('nav.stats_pagina_statistieken', 'Pagina statistieken', '2013-04-04 11:57:07'), ('nav.stats_sessie_statistieken', 'Sessie statistieken', '2013-04-04 11:57:20'), ('nav.stats_uri_statistieken', 'URL statistieken', '2013-04-04 11:58:00'), ('nav.tekstbeheer', 'Tekst beheer', '2013-04-04 14:26:16'), ('nav.themabeheer', 'Themabeheer', '2013-04-04 12:10:22'), ('nav.verantwoordingsteksten', 'Verwantwoordingsteksten', '2013-04-04 12:10:29'), ('nav.verantwoordingstekst_bewerken', 'Verantwoordingstekst bewerken', '2013-04-04 12:10:36'), ('nav.versieinformatie', 'Versieinformatie', '2013-04-04 11:50:52'), ('nav.webservice_beheer', 'Webservice beheer', '2013-04-04 11:56:58'), ('nav.wetteksten_en_regelgeving', 'Wetteksten en regelgeving', '2013-04-04 11:52:01'), ('php.algemene_fout_bij_verzenden_email', 'Algemene fout bij het verzenden van de email. Is het email adres goed ingesteld?', '2013-04-16 13:30:00'), ('php.algemene_schijf_fout', 'Algemene schrijf fout op de server.', '2013-04-16 13:30:00'), ('php.foute_invoer', 'Foutieve invoer.', '2013-04-16 13:30:00'), ('php.geen_email_adres_ingesteld', 'Er is nog geen email adres ingesteld.', '2013-04-16 13:20:29'), ('php.geen_rechten', 'Geen rechten.', '2013-04-16 13:30:00'), ('php.nieuwe_deelplan_naam', 'Deelplan $1', '2013-04-04 00:00:00'), ('versie.development', 'DEVELOPMENT VERSIE', '2013-04-16 10:25:56'), ('versie.ip_versie_actief', 'IP BEPERKING ACTIEF', '2013-04-16 10:26:16'), ('versie.test', 'TEST VERSIE', '2013-04-16 10:25:00'), ('waardeoordeel.bouwdeel_voldoet', 'Bouwdeel voldoet', '2013-04-04 15:16:39'), ('waardeoordeel.gelijkwaardigheid', 'Gelijkwaardigheid', '2013-04-04 15:17:26'), ('waardeoordeel.in_bewerking', 'Geen waardeoordeel', '2013-04-04 15:15:19'), ('waardeoordeel.nader_onderzoek_nodig', 'Nader onderzoek nodig', '2013-04-04 15:17:15'), ('waardeoordeel.niet_gecontroleerd', 'Niet gecontroleerd', '2013-04-04 15:18:11'), ('waardeoordeel.niet_kunnen_controleren', 'Niet kunnen controleren', '2013-04-04 15:17:40'), ('waardeoordeel.nvt', 'Niet van toepassing', '2013-04-04 15:16:23'), ('waardeoordeel.voldoet', 'Voldoet', '2013-04-04 15:15:42'), ('waardeoordeel.voldoet_na_aanwijzigingen', 'Na aanwijzingen toezichthouder', '2013-04-04 15:17:54'), ('waardeoordeel.voldoet_niet', 'Voldoet niet', '2013-04-04 15:15:45'), ('waardeoordeel.voldoet_niet_niet_zwaar', 'Voldoet niet (niet zwaar)', '2013-04-04 15:16:58'); <file_sep><? /** * Code obtained from AbiSource Corporation B.V. with the consent of <NAME>. */ define( 'HTTPAUTH_DESTROY_SESSION_NOW', 'httpauth_destroy_session_data_asap' ); class CI_Session { var $__session_ip_varname = '__session_ip'; var $__session_useragent_varname = '__session_useragent_varname'; var $__session_unsafe_varname = '__unsafe'; // do not change! var $__session_preferred_db_varname = '__preferred_db'; var $_loginHelper; var $_loginSystem; /** * Constructor, checks for session sanity and clears all session data * if session is unknown. */ function CI_Session() { // setup system basics $CI = get_instance(); $CI->load->library( 'cookie' ); $CI->load->model( 'leaseconfiguratie' ); $this->_loginHelper = new MySessionHelper(); $this->_loginSystem = new MyLoginSystem(); // check if we have to destroy all session data now (HTTPAUTH thingy) if ($this->userdata( HTTPAUTH_DESTROY_SESSION_NOW )) $this->doHttpAuthLogout(); // make sure unsafe entry in session data is always present if (!isset($_SESSION[$this->__session_unsafe_varname])) $_SESSION[$this->__session_unsafe_varname] = array(); // check if the session is valid if (!isset($_SESSION[$this->__session_ip_varname]) || $_SESSION[$this->__session_ip_varname]!=$_SERVER['REMOTE_ADDR'] || !isset($_SESSION[$this->__session_useragent_varname]) || $_SESSION[$this->__session_useragent_varname]!=$_SERVER['HTTP_USER_AGENT']) { // reset all session data, except for the optional unsafe data $unsafe_backup = $_SESSION[$this->__session_unsafe_varname]; $_SESSION = array( $this->__session_unsafe_varname => $unsafe_backup ); } // detect HTTP authentication here if (isset($_SERVER['PHP_AUTH_USER'])) { define( 'HTTP_USER_AUTHENTICATION', true ); $this->doHttpAuthLogin(); } else define( 'HTTP_USER_AUTHENTICATION', false ); // check if there's a preferred db set if (isset( $_SESSION[ $this->__session_preferred_db_varname ] )) { $CI->config->set_item( 'db_preferred_hostindex', $_SESSION[ $this->__session_preferred_db_varname ] ); } } function doHttpAuthLogout() { $_SESSION = array(); } function doHttpAuthLogin() { $CI = get_instance(); $CI->session = $this; $CI->load->library( 'login' ); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); $email = @$_SERVER['PHP_AUTH_USER']; $password = @$_SERVER['PHP_AUTH_PW']; $res = $CI->db->query( 'SELECT id, klant_id, app_toegang FROM gebruikers WHERE status = \'actief\' AND email = ' . $CI->db->escape($email) . ' AND LENGTH(wachtwoord) > 0 AND wachtwoord = ' . $CI->db->escape(sha1( $password )) ); try { if (!$res->num_rows()) throw new Exception( 'Ongeldige gebruikersnaam/wachtwoord combinatie' ); else { // get info $data = $res->row_object(); if (!$data->app_toegang) throw new Exception( 'Uw account heeft (nog) geen toegang via de app' ); else { $gebruiker_id = intval( $data->id ); $klant_id = intval( $data->klant_id ); $res->free_result(); // and login if (!$CI->login->login_as( $gebruiker_id )) throw new Exception( 'Interne fout bij inloggen via HTTP authenticatie' ); $this->set_userdata( 'kid', $klant_id ); $this->set_userdata( HTTPAUTH_DESTROY_SESSION_NOW, 1 ); register_shutdown_function(function() use ($CI){ if ($CI && $CI->session) $CI->session->doHttpAuthLogout(); }); // test of login gewerkt heeft if (!$CI->login->logged_in()) throw new Exception( 'Login systeem fout bij inloggen via HTTP authenticatie (1)' ); if ($CI->login->get_user_id() != $gebruiker_id) throw new Exception( 'Login systeem fout bij inloggen via HTTP authenticatie: ' . $gebruiker_id . ' != ' . $CI->login->get_user_id() . ' (2)' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $CI->db->query( 'UPDATE gebruikers SET app_toegang_laatste_tijdstip = '.$now_func.' WHERE id = ' . intval($gebruiker_id) ); } } } catch (Exception $e) { header('HTTP/1.0 401 Unauthorized'); echo json_encode( array( 'Success' => false, 'Credentials' => 'invalid', 'Error' => $e->getMessage(), ) ); exit; } } function store_preferred_db( $index ) { $_SESSION[ $this->__session_preferred_db_varname ] = $index; } /** * Retrieves session data, if set. Returns null when not set, the * session variable's value otherwise. */ function userdata($item, $unsafe = false) { if ($unsafe) { if (isset($_SESSION[$this->__session_unsafe_varname][$item])) return $_SESSION[$this->__session_unsafe_varname][$item]; } else { if (isset($_SESSION[$item])) return $_SESSION[$item]; } return null; } /** * Sets session data. If $newdata is an array, all key/value pairs * are used to set session data. Otherwise it's treated as a key, * and $newval is set as its value. */ function set_userdata($newdata = array(), $newval = '', $unsafe = false) { if (!is_array($newdata)) { if ($unsafe) $_SESSION[$this->__session_unsafe_varname][$newdata] = $newval; else $_SESSION[$newdata] = $newval; } else { foreach ($newdata as $key => $value) if ($unsafe) $_SESSION[$this->__session_unsafe_varname][$key] = $value; else $_SESSION[$key] = $value; } } /** * Removes keys from the session data. When $newdata is an array, * all keys are used in the array to unset session variables. * Otherwise, it's treated as a normal index into the session array. */ function unset_userdata($newdata = array(), $unsafe = false) { if (!is_array($newdata)) { if ($unsafe) unset( $_SESSION[$this->__session_unsafe_varname][$newdata] ); else unset( $_SESSION[$newdata] ); } else { foreach ($newdata as $key => $val) if ($unsafe) unset( $_SESSION[$this->__session_unsafe_varname][$key] ); else unset( $_SESSION[$key] ); } } /** * Saves the current requester's IP and user agent. Should be called once * per session when the user logs in, to verify a session later on. */ function set_user_recognizables() { $_SESSION[$this->__session_ip_varname] = @$_SERVER['REMOTE_ADDR']; $_SESSION[$this->__session_useragent_varname] = @$_SERVER['HTTP_USER_AGENT']; } /** * Destroys the current user's IP and user agent from the session data, * and kills the session. Should be called once when user logs out. */ function unset_user_recognizables() { unset( $_SESSION[$this->__session_ip_varname] ); unset( $_SESSION[$this->__session_useragent_varname] ); } } // // Het doel van deze class is simpel: het leest, schrijft, verwijdert, etc. sessie informatie in database // Het wordt maar op 1 plek gebruikt: namelijk in MySessionHelper // class MySessionHandler { // ref to CI components private $_db; private $_dbex; // data private $_id; private $_ip; private $_useragent; private $_session_lifetime = 2592000; // by default 1 month after last request it will die public function /*void*/ initialize() { $CI = get_instance(); $CI->load->library( 'DBEx' ); $this->_db = $CI->db; $this->_dbex = $CI->dbex; // if we have a proxy forwarded IP, use that, otherwise use remote address $this->_ip = isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; // get useragent if we have it $this->_useragent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '(not set)'; // every now and then delete old sessions if ($_SERVER['REQUEST_METHOD'] != 'POST' && (mt_rand(0,100) == 1)) /* 1% chance to GC on GET */ { error_log( 'Running session garbage collector: ' . $_SERVER['REQUEST_URI'] . ' (' . $_SERVER['REQUEST_METHOD'] . ')' ); $this->gc( time() ); } // always auto-destroy CLI sessions when done if (IS_CLI) { $thiz = $this; register_shutdown_function(function() use ($thiz) { $thiz->destroy(); }); } } public function /*void*/ shutdown() { } public function /* bool */ open( $id ) { $this->_id = $id; return true; } public function /* bool */ close() { $this->_id = null; return true; } public function /* string */ read() { $stmt_name = 'UserSessionDatabaseStorageHandler::read'; $this->_dbex->prepare( $stmt_name, 'SELECT ip, user_agent, data, expires_timestamp FROM sessies WHERE session_id = ? AND user_agent = ? AND expires_timestamp > ?', $this->_db ); $res = $this->_dbex->execute( $stmt_name, array( $this->_id, $this->_useragent, time() ), false, $this->_db ); //d($res); // anything other than 1 row is an invalid situation if ($res->num_rows <= 0) { $res->free_result(); return ''; } // get row $row = $res->row_object(); $res->free_result(); return $row->data; } public function /* bool */ write( $data ) { if ($data == '__unsafe|a:0:{}' || $data == '__unsafe|a:0:{}force_validation|b:0;' || $data == '__unsafe|a:0:{}force_validation|b:1;') $this->destroy(); else { $this->_db->initialize(); $stmt_name = 'UserSessionDatabaseStorageHandler::write'; if (!$this->_dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO sessies (session_id, ip, user_agent, expires_timestamp, data) VALUES (?,?,?,?,?)', $this->_db, array('session_id', 'ip', 'user_agent') )) error_log( 'prepare failed' ); // The serialised 'data' is not always recognised as being character data; it sometimes contains data that is recognised as binary. Therefore, for Oracle we force the type // to 'c' (= CLOB). $force_types = (get_db_type() == 'oracle') ? 'sssic' : 'sssis'; if (!$this->_dbex->execute( $stmt_name, array( $this->_id, $this->_ip, $this->_useragent, time() + $this->_session_lifetime, $data ), false, $this->_db, $force_types )) error_log( 'execute failed' ); } return true; } public function /* bool */ destroy() { $this->_db->initialize(); $stmt_name = 'UserSessionDatabaseStorageHandler::destroy'; $this->_dbex->prepare( $stmt_name, 'DELETE FROM sessies WHERE session_id = ? AND user_agent = ?', $this->_db ); $this->_dbex->execute( $stmt_name, array( $this->_id, $this->_useragent ), false, $this->_db ); } public function /* bool */ gc( $timestamp ) { $stmt_name = 'UserSessionDatabaseStorageHandler::gc'; $this->_dbex->prepare( $stmt_name, 'DELETE FROM sessies WHERE expires_timestamp < ?', $this->_db ); $this->_dbex->execute( $stmt_name, array( $timestamp ), false, $this->_db ); } } // // Het doel van deze class is het helpen opzetten van een alternatief sessie storage system, // m.b.v. de MySessionHandler class. Dit is de plek waar de sessie gestart wordt, en nergens // anders!! // Deze class wordt uitsluitend gebruikt (geconstrueerd) vanuit de CI_Session class. // class MySessionHelper { private $_handler; private $_id; public function __construct() { // initialize session $this->_handler = new MySessionHandler; // uit application/hooks/login-system-session-handler.php $this->_handler->initialize(); if (!session_set_save_handler( array( $this, '__open' ), array( $this, '__close' ), array( $this, '__read' ), array( $this, '__write' ), array( $this, '__destroy' ), array( $this, '__gc' ) )) throw new Exception( 'CI_Session::__construct: failed to set save handlers' ); session_set_cookie_params( 0 ); session_save_path( '/' ); session_start(); } private function __reinitialize( $id ) { if ($id==$this->_id) return TRUE; if ($this->_id) { $this->_handler->close(); $this->_id = null; } if (!$this->_handler->open( $id )) return FALSE; $this->_id = $id; return TRUE; } public function __open( $save_path, $name ) { return TRUE; } public function __close() { return $this->_handler->close(); } public function __read( $id ) { if (!$this->__reinitialize( $id )) return FALSE; return $this->_handler->read(); } public function __write( $id, $sessdata ) { if (!$this->__reinitialize( $id )) return FALSE; return $this->_handler->write( $sessdata ); } public function __destroy( $id ) { if (!$this->__reinitialize( $id )) return FALSE; return $this->_handler->destroy(); } public function __gc( $time ) { return TRUE; } } // // Het doel van deze class is het initialiseren van systeem variabelen die aangeven // wat voor login systeem we gebruiken. Dit kunnen we pas doen als: // - de database geinitialiseerd is // - de session geinitialiseerd is // Deze class wordt uitsluitend gebruikt (geconstrueerd) vanuit de CI_Session class. // class MyLoginSystem { const LOGIN_SYSTEM_COOKIE_NAME = 'lc'; const KLANT_SYSTEM_COOKIE_NAME = 'kl'; // login systeem code: // // we hebben twee login systemen, namelijk kennisid en reguliere (eigen) login // zodra een gebruiker is ingelogd, is het systeem dat hij gebruikt vastgelegd, // aangezien we via z'n klant object kunnen zien wat de instellingen zijn; // // als iemand nog NIET is ingelogd, weten we niet welke klant het betreft; als // we geen andere informatie hebben, nemen we aan dat het een kennisid klant // betreft, en sturen we hem door naar kennisid; // echter, bepaalde lease klanten moeten in dat geval niet naar kennisid, maar // naar de eigen login pagina worden doorgestuurd; om dit aan te geven wordt // een klant dan naar /lease/LEASENAAM gestuurd. deze controller zorgt ervoor // dat bij de klant een cookie wordt gezet die het juiste login systeem aangeeft, // de gebruiker bij het juiste login scherm uitkomt // function get_login_system() { $CI = get_instance(); $lc_id = $this->get_lease_configuratie_id(); $url = $CI->uri->segments[1]; if (!$lc_id) { if ($url === 'extern') { return 'LocalDBExternalUsers'; } else { return 'KennisID'; } } $lc = $CI->leaseconfiguratie->get( $lc_id ); if (!$lc) return 'KennisID'; switch ($lc->login_systeem) { case 'kennisid': case 'hybride': return 'KennisID'; case 'normaal': return 'LocalDB'; case 'extern': return 'LocalDBExternalUsers'; default: throw new Exception( 'Foutief login systeem gedefinieerd in configuratie.' ); } } function get_lease_configuratie_id() { return get_instance()->cookie->get( self::LOGIN_SYSTEM_COOKIE_NAME ); } function set_lease_configuratie_id( $lc_id ) { // vanaf nu weet het loginsystem wat ie moet doen! get_instance()->cookie->set( self::LOGIN_SYSTEM_COOKIE_NAME, $lc_id, time() + (86400 * 365 * 10) /* "nu over 10 jaar", boeie :D */ ); } function set_klant_id( $kl_id ) { // vanaf nu weet het loginsystem wat ie moet doen! get_instance()->cookie->set( self::KLANT_SYSTEM_COOKIE_NAME, $kl_id, time() + (86400 * 365 * 10) /* "nu over 10 jaar", boeie :D */ ); } function get_klant_id( ) { return get_instance()->cookie->get( self::KLANT_SYSTEM_COOKIE_NAME ); } function forget_klant_id() { get_instance()->cookie->del( self::KLANT_SYSTEM_COOKIE_NAME ); } function forget_lease_configuratie_id() { get_instance()->cookie->del( self::LOGIN_SYSTEM_COOKIE_NAME ); } function __construct() { // kijk nu wat de sessie zegt over het te gebruiken login systeem $system = $this->get_login_system(); // definieer nu het te gebruiken login systeem. de code verwacht // dat deze define gezet is, en ofwel "kennisid", ofwel "localdb" als // waarde heeft // // LETOP: vooral voor de login library is deze define super belangrijk, // deze definieert de inhoud en werking van de CI_Login class op deze // define! define( 'APPLICATION_LOGIN_SYSTEM', $system ); } } <file_sep>PDFAnnotator.OverviewWindow = PDFAnnotator.HelperWindow.extend({ /* constructor */ init: function( engine, config ) { /* initialize base class */ this._super( engine, config ); /* cannot be initialized at this stage */ this.engine = engine; this.mapdata = { src: null, realw: null, // original size realh: null, r: null, // ratio of image (w/h) transformfunc: null, // function to get CSS transform mapw: null, // current display size of image inside the overview map maph: null, maxw: 318, // maximum size of map maxh: 204 }; /* do this just once: setup DOM event handling for scrolling. */ var thiz = this; this.engine.gui.rootContainer.scroll(function(){ thiz.updateScrollPosition( this ); }); /* setup window */ this.setupWindow(); }, /* override */ show: function() { this._super(); this.visuals .css( 'left', '200px' ) .css( 'top', '100px' ); }, setupWindow: function() { // override base styles this.visuals .css( 'padding', '0' ) .css( 'margin', '0' ) .css( 'background-color', 'transparent' ); // add our content to it $('<div>') .addClass( 'Rounded10' ) .css( 'background-color', '#000' ) .css( 'padding', '14px 45px' ) .css( 'width', 'auto' ) // note, these get changed by updateImage to accomodate page transform! .css( 'height', 'auto' ) .appendTo( this.visuals ); // make sure it's hidden by default this.hide(); // add handles this.addHandle( new PDFAnnotator.Handle.OverviewMove( this ) ); this.addHandle( new PDFAnnotator.Handle.OverviewHide( this ) ); }, setupImage: function( url, realw, realh, transformfunc ) { // make sure realw and realh are numbers this.mapdata.src = url; this.mapdata.realw = typeof(realw) == 'number' ? 1.0 * realw : parseFloat( realw ); this.mapdata.realh = typeof(realh) == 'number' ? 1.0 * realh : parseFloat( realh ); this.mapdata.r = realw / realh; this.mapdata.transformfunc = transformfunc this.updateImage(); }, updateImage: function() { if (!this.mapdata.src) return; // calculate proper size to display image in var maxw = this.mapdata.maxw; var maxh = this.mapdata.maxh; var w = maxw; var h = w / this.mapdata.r; if (h > maxh) { h = maxh; w = h * this.mapdata.r; } // get transform var transform = this.mapdata.transformfunc( w, h ); // set HTML to display image w = Math.round( w ); h = Math.round( h ); var img = $('<img>') // setup basics .attr( 'src', this.mapdata.src ) .attr( 'width', w ) .attr( 'height', h ) .css( 'width', w ) .css( 'height', h ) // setup transform .css( 'transform', transform.transform ) .css( '-ms-transform', transform.transform ) .css( '-moz-transform', transform.transform ) .css( '-webkit-transform', transform.transform ) .css( '-o-transform', transform.transform ) // setup transform origin .css( 'transform-origin', transform.origin ) .css( '-ms-transform-origin', transform.origin ) .css( '-webkit-transform-origin', transform.origin ) // update div size and set image inside div this.mapdata.mapw = !transform.swapwh ? w : h; this.mapdata.maph = !transform.swapwh ? h : w; this.visuals.find( 'div' ) .css( 'width', this.mapdata.mapw ) .css( 'height', this.mapdata.maph ) .html( img.outerHTML() ); // update rotation if (this.isVisible()) this.show(); // updates handle positions // update scroll position visually this.updateScrollPosition( this.engine.gui.rootContainer[0] ); }, updateScrollPosition: function( container ) { // get reference to current frame div (if present) var frame = this.visuals.find( 'div .frame' ); // get simple base params var w = container.clientWidth; var h = container.clientHeight; var sx = container.scrollLeft; var sw = Math.max( 0, container.scrollWidth - w ); var sy = container.scrollTop; var sh = Math.max( 0, container.scrollHeight - h ); var mw = this.mapdata.mapw; var mh = this.mapdata.maph; if (!sw && !sh) { frame.hide(); return; } else frame.show(); // create frame if not yet present if (!frame.size()) { var bordersize = 2; var base = this.visuals.find('div'); var outerframe = $('<div>') .addClass( 'NoSelect' ) .css( 'position', 'absolute' ) .css( 'left', parseInt( base.css( 'padding-left' ) ) - bordersize ) .css( 'top', parseInt( base.css( 'padding-top' ) ) - bordersize ) .css( 'width', base.css( 'width' ) ) .css( 'height', base.css( 'height' ) ) .appendTo( base ); frame = $('<div>') .css( 'border', bordersize + 'px solid #ed1c24' ) .css( 'background', 'url(\'/files/images/s.gif\') repeat left top' ) .css( 'width', '50px' ) .css( 'height', '50px' ) .css( 'padding', '0' ) .css( 'margin', '0' ) .css( 'position', 'absolute' ) .css( 'left', '0px' ) .css( 'top', '0px' ) .css( 'cursor', 'pointer' ) .addClass( 'frame' ) /* important, this way the frame is recognized later! */ .appendTo( outerframe ); // setup dragging frame .drag("start",function( ev, dd ){ dd.limit = outerframe.offset(); dd.limit.bottom = (dd.limit.top + outerframe.outerHeight() - $(this).outerHeight()) + 2*bordersize; dd.limit.right = (dd.limit.left + outerframe.outerWidth() - $(this).outerWidth()) + 2*bordersize; dd.limit.X = dd.limit.left; dd.limit.Y = dd.limit.top; dd.limit.left = 0; dd.limit.top = 0; dd.limit.right -= dd.limit.X; dd.limit.bottom -= dd.limit.Y; }) .drag(function( ev, dd ){ // update position of dragged object var x = Math.min( dd.limit.right, Math.max( dd.limit.left, dd.offsetX - dd.limit.X ) ); var y = Math.min( dd.limit.bottom, Math.max( dd.limit.top, dd.offsetY - dd.limit.Y ) ); $(this).css({ left: x, top: y }); // update scroll position container.scrollLeft = Math.round( (x / (mw - fw)) * sw ); container.scrollTop = Math.round( (y / (mh - fh)) * sh ); }); } // calc size of frame relative to client window and total size var fw = (w / (w + sw)) * mw; var fh = (h / (h + sh)) * mh; // calc position of frame var fx = (sx / sw) * (mw - fw); var fy = (sy / sh) * (mh - fh); // update frame frame .css( 'width', Math.round( fw ) + 'px' ) .css( 'height', Math.round( fh ) + 'px' ) .css( 'left', Math.round( fx ) + 'px' ) .css( 'top', Math.round( fy ) + 'px' ); } }); <file_sep><?php function get_export_tag( $prefix ) { return sha1( $prefix . $_SERVER['REMOTE_ADDR'] . mt_rand() . mt_rand() . time() . microtime() ); } class ExportResult { private $_filename; private $_contenttype; private $_contents; public function __construct( $filename, $contenttype, $contents ) { $this->_filename = $filename; $this->_contenttype = $contenttype; $this->_contents = $contents; } public function get_filename() { return $this->_filename; } public function get_contenttype() { return $this->_contenttype; } public function get_contents() { return $this->_contents; } public function store() { $tag = sha1( microtime() . mt_rand() ) . '-' . $this->_filename; if (!@file_put_contents( APPPATH . '/../files/cache/pdf/' . $tag, $this->_contents )) throw new Exception( 'Fout bij opslaan van resultaatgegevens.' ); return $tag; } static public function download( $tag, $exit=true ) { $contents = @file_get_contents( APPPATH . '/../files/cache/pdf/' . $tag ); if ($contents === false) throw new Exception( 'Tijdelijke download niet meer beschikbaar.' ); $filename = preg_replace( '/^[a-f0-9]\-/', '', $tag ); $CI = get_instance(); $CI->load->helper( 'user_download' ); user_download( $contents, $filename, $exit ); } } class ExportTempImage { static $images = array(); private $_tempfilename; private $_cleanupfilename; public function __construct( $contents, $format='png' ) { if (@is_file( $contents )) { $this->_tempfilename = $contents; } else { // write to temp file $this->_tempfilename = 'application/helpers/tcpdf-1.6/cache/tmpimage_' . time() . mt_rand() . '.' . $format; if (!@file_put_contents( $this->_tempfilename, $contents )) throw new Exception( 'Kon tijdelijk afbeeldingsbestand niet schrijven: ' . $this->_tempfilename ); } // make sure file gets properly cleaned up at shutdown (not dependent on CWD) $this->_cleanupfilename = realpath( $this->_tempfilename ); register_shutdown_function( array( $this, 'remove' ) ); self::$images[] = $this; } public function get_filename() { return $this->_tempfilename; } public function remove() { @unlink( $this->_cleanupfilename ); } } abstract class ExportBase { public function set_progress( $progress /* tussen 0 en 1 */, $action_description ) { // STUB: voor exporters zonder progress, zodat generate() gewoon werkt } abstract public function get_filename(); abstract public function get_content_type(); abstract public function get_contents(); public function generate() { // generate contents $this->set_progress( 0, 'Initializeren...' ); $this->_generate(); $this->set_progress( 1, 'Document afgerond...' ); // build PDF file return new ExportResult( $this->get_filename(), $this->get_content_type(), $this->get_contents() ); } abstract protected function _generate(); public function make_temp_image( $contents, $format='png' ) { // this class has an auto-cleanup function, it will not litter $im = new ExportTempImage( $contents, $format ); return $im->get_filename(); } public function hss( $str ) /* hss = html safe string */ { return htmlentities( $str, ENT_COMPAT, 'UTF-8' ); } } class ExportProgress { private $_library; public function __construct( $library ) { $this->_library = $library; } public function get_progress( $download_tag ) { $contents = @file_get_contents( $this->_get_progress_filename( $download_tag ) ); if ($contents === false) { $progress = -1; // unchanged! $action = null; } else { $status = @unserialize( $contents ); if (!is_array( $status ) || !isset( $status['progress'] ) || !isset( $status['action'] )) { $progress = -1; // unchanged! $action = null; } else { $progress = $status['progress']; $action = $status['action']; } } return array( 'progress' => $progress, 'action' => $action, ); } public function clear_progress( $download_tag ) { unlink( $this->_get_progress_filename( $download_tag ) ); } public function set_progress( $download_tag, $progress /* tussen 0 en 1 */, $action_description ) { @file_put_contents( $this->_get_progress_filename( $download_tag ), serialize( array( 'progress' => floatval( $progress ), 'action' => $action_description ) ) ); } private function _get_progress_filename( $download_tag ) { return APPPATH . '/libraries/' . $this->_library . '/progress/' . preg_replace( '/\W/', '-', $download_tag ) . '.progress'; } }<file_sep><? if (isset($errors) && is_array($errors) && sizeof($errors)>0): ?> <div class="error"> <ul> <? foreach ($errors as $message): ?> <li><?=strpos($message,' ')===false ? tg($message) : $message?></li> <? endforeach; ?> </ul> </div> <br/> <? endif; ?><file_sep>CREATE TABLE IF NOT EXISTS `deelplan_aandachtspunten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `toetser` varchar(64) NOT NULL, `datum` date NOT NULL, `tekst` text NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`) ) ENGINE=InnoDB; ALTER TABLE `deelplan_aandachtspunten` ADD CONSTRAINT `deelplan_aandachtspunten_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE IF NOT EXISTS `deelplan_vraag_aandachtspunten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `deelplan_aandachtspunt_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_aandachtspunt_id` (`deelplan_aandachtspunt_id`,`vraag_id`), KEY `vraag_id` (`vraag_id`), KEY `deelplan_id` (`deelplan_id`) ) ENGINE=InnoDB; ALTER TABLE `deelplan_vraag_aandachtspunten` ADD CONSTRAINT `deelplan_vraag_aandachtspunten_ibfk_3` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_vraag_aandachtspunten_ibfk_1` FOREIGN KEY (`deelplan_aandachtspunt_id`) REFERENCES `deelplan_aandachtspunten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_vraag_aandachtspunten_ibfk_2` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `deelplan_aandachtspunten` ADD `grondslag` VARCHAR( 64 ) NOT NULL; ALTER TABLE `deelplan_aandachtspunten` ADD `globaal` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'nee'; <file_sep><?php // By Marc "Foddex" <NAME> <<EMAIL>> define( 'LOCKFILE_SUCCESS', 1 ); // success result: the lock was obtained! define( 'LOCKFILE_ERROR_ALREADY_LOCKED', -1 ); define( 'LOCKFILE_ERROR_FAIL_TO_OBTAIN_LOCK', -2 ); define( 'LOCKFILE_ERROR_NOT_LOCKED', -3 ); define( 'LOCKFILE_ERROR_PROCESS_VANISHED', -4 ); define( 'LOCKFILE_ERROR_FAILED_TO_READ_LOCKDATA', -5 ); define( 'LOCKFILE_ERROR_INCOMPLETE_LOCKDATA', -6 ); class CI_FileLock { public function create( $name ) { return new FilelockImpl( $name ); } } class FilelockImpl { public static $lockpath; private $name; private $filename; private $i_locked = false; public function __construct( $name ) { self::$lockpath = config_item( 'filelock_path' ); $this->name = $name; $this->filename = FilelockImpl::$lockpath . preg_replace( '/\W/', '_', $name ) . '.lock'; } public function is_locked( $check_lock=true ) { if (!@file_exists( $this->filename )) return false; if (!$check_lock) return true; switch ($this->check_lock()) { case LOCKFILE_ERROR_ALREADY_LOCKED: return true; // yes, locked, and yes, checked the lock thoroughly default: $this->unlock( true /* forcibly remove lock */ ); return @file_exists( $this->filename ); } } public function check_lock() { if (!$this->is_locked( false )) return LOCKFILE_ERROR_NOT_LOCKED; $contents = @file_get_contents( $this->filename ); if ($contents === false) return LOCKFILE_ERROR_FAILED_TO_READ_LOCKDATA; $data = unserialize( $contents ); if (!is_array( $data ) || !isset( $data['mypid'] )) return LOCKFILE_ERROR_INCOMPLETE_LOCKDATA; exec( 'kill -s 0 ' . intval( $data['mypid'] ) . ' >/dev/null 2>&1', $lines, $exit_code ); if ($exit_code) return LOCKFILE_ERROR_PROCESS_VANISHED; // lock can be force removed! else return LOCKFILE_ERROR_ALREADY_LOCKED; // still locked, and process is alive and kicking } public function try_lock() { if ($this->is_locked()) return LOCKFILE_ERROR_ALREADY_LOCKED; // write tempfile $tempfile = $this->filename . '.pid.' . getmypid() . '.mtrand.' . mt_rand(); if (!@file_put_contents( $tempfile, serialize( $this->bake_data() ) )) return LOCKFILE_ERROR_FAIL_TO_OBTAIN_LOCK; // try to hard link tempfile to lockpath if (!@link( $tempfile, $this->filename )) { @unlink( $tempfile ); return LOCKFILE_ERROR_ALREADY_LOCKED; } // cleanup $this->i_locked = true; @unlink( $tempfile ); return LOCKFILE_SUCCESS; } public function lock() { do { $res = $this->try_lock(); if ($res != LOCKFILE_ERROR_ALREADY_LOCKED) break; error_log( 'locked, retrying...' ); usleep( 50000 ); // try again after 0.05 seconds } while (true); return $res; } public function unlock( $force=false ) { if ($force || $this->i_locked) { $this->i_locked = false; @unlink( $this->filename ); } } public function bake_data() { return array( 'mypid' => getmypid(), 'timestamp' => date( 'd-m-Y H:i:s' ), 'name' => $this->name, ); } }<file_sep>REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('extern.inloggen::newpasswordconfirm', 'bevestig nieuw wachtwoord', NOW(), 0); <file_sep>INSERT INTO deelplan_opdrachten_uploads (`opdracht_id`,`upload_id`) SELECT * FROM ( SELECT CAST( SUBSTR( filename, LOCATE('#', filename)+1, LOCATE('_', filename) - LOCATE('#', filename) -1 ) AS UNSIGNED ) AS opdracht_id, id AS upload_id FROM `deelplan_uploads` WHERE LOCATE ('#', filename) > 0 AND LOCATE ('_', filename) > LOCATE ('#', filename) ) t WHERE opdracht_id > 0;<file_sep><?php class Colectivematrix_Suite extends PHPUnit_Framework_TestCase{ protected function setUp(){ } //______________________________________________________________________________ _UT_ORG_CODE protected function tearDown(){ } //______________________________________________________________________________ _UT_ORG_CODE function test_get_dossier_bouwnummers(){ $this->CI = get_instance(); $this->CI->load->model( 'btbtzdossier' ); $data = array(); } //______________________________________________________________________________ _UT_ORG_CODE }// Class end <file_sep><? $this->load->view('elements/header', array('page_header'=>null)); ?> <? function verplicht_image( $veld, $verplichte_velden ) { if (isset( $verplichte_velden[$veld] )) return '<span style="color:red">*</span>'; return ''; } ?> <script type="text/javascript"> function has_value( component, description, cur_result ) { if ( (''+component.value).length == 0) { $('.group:first').trigger( 'click' ); $(component).addClass( 'inputerror' ); if (cur_result) // only focus first error! component.focus(); return false; } return true; } function on_submit_form() { var result = true; <? foreach ($verplichte_velden as $v => $desc): ?> if (!has_value( document.form.<?=$v?>, '<?=$desc?>', result )) result = false; <? endforeach; ?> return result; } $(document).ready(function(){ $('.inputerror').live('blur', function(){ $(this).removeClass( 'inputerror' ); }); }); </script> <form name="form" method="post" onsubmit="return on_submit_form();" enctype="multipart/form-data"> <? $this->load->view( 'dossiers/bewerken-registratiegegevens' ); ?> <? if ($reg_gegevens_bewerkbare): ?> <p align="right"> <input type="submit" value="<?=tgng('form.opslaan')?>" /> </p> <? endif; ?> </form> <script type="text/javascript"> $(document).ready(function(){ $('input[name$=_datum]').datepicker({ dateFormat: "dd-mm-yy" }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php class WettekstenImport { private $CI; private $grondslag_id; private $filename; public function __construct( $grondslag, $filename ) { $this->CI = get_instance(); $this->CI->load->model( 'grondslag' ); $rows = $this->CI->db->query( 'SELECT id FROM bt_grondslagen WHERE grondslag = ' . $this->CI->db->escape( $grondslag ) . ' AND klant_id = 1' )->result(); if (empty( $rows )) throw new Exception( 'Grondslag ' . $grondslag . ' onbekend' ); $this->grondslag_id = $rows[0]->id; foreach ($this->_scandir( APPPATH . '/../docs/wetteksten/' ) as $file) if (preg_match( '#/' . preg_quote($filename) . '$#', $file )) { $this->filename = $file; break; } if (!$this->filename) throw new Exception( 'Kon bestand ' . $filename . ' niet vinden' ); } public function run( $fix=false ) { $this->CI->db->query( 'SET AUTOCOMMIT=0' ); $this->CI->db->query( 'BEGIN;' ); // load $contents = iconv( "Windows-1252", "UTF-8", file_get_contents( $this->filename ) ); $lines = explode( "\n", $contents ); // parse $hoofdstukken = array(); $afdelingen = array(); $artikelen = array(); $curhoofdstuk = null; $curafdeling = null; $curartikel = null; foreach ($lines as $line) { if (preg_match( '/^\s*Hoofdstuk (\d+)\./', $line, $matches )) { $curhoofdstuk = $matches[1]; $curafdeling = null; $curartikel = null; } else if (preg_match( '/^\s*Afdeling ([0-9\.]+) /', $line, $matches )) { $curafdeling = preg_replace( '/\.$/', '', $matches[1] ); $curartikel = null; } else if (preg_match( '/^\s*Artikel ([0-9\.]+[a-z]?)/', $line, $matches )) { $curartikel = preg_replace( '/\.$/', '', $matches[1] ); } if ($curhoofdstuk) $hoofdstukken[$curhoofdstuk] .= "\n" . $line; if ($curafdeling) $afdelingen[$curafdeling] .= "\n" . $line; if ($curartikel) $artikelen[$curartikel] .= "\n" . $line; } echo "Hoofdstukken: " . sizeof($hoofdstukken) . "\n"; echo "Afdelingen: " . sizeof($afdelingen) . "\n"; echo "Artikelen: " . sizeof($artikelen) . "\n"; $this->CI->dbex->prepare( 'find', 'SELECT * FROM bt_grondslag_teksten WHERE grondslag_id = ? AND artikel = ?' ); $this->CI->dbex->prepare( 'update', 'UPDATE bt_grondslag_teksten SET tekst = ? WHERE grondslag_id = ? AND artikel = ?' ); $this->CI->dbex->prepare( 'insert', 'INSERT INTO bt_grondslag_teksten (tekst, grondslag_id, artikel) VALUES (?, ?, ?)' ); $stats = array( 'nieuwe_hoofdstukken' => 0, 'bestaande_hoofdstukken' => 0, 'nieuwe_afdelingen' => 0, 'bestaande_afdelingen' => 0, 'nieuwe_artikelen' => 0, 'bestaande_artikelen' => 0, ); foreach ($hoofdstukken as $hoofdstuk_nr => $hoofdstuk) { $res = $this->CI->dbex->execute( 'find', array( $this->grondslag_id, 'hoofdstuk ' . $hoofdstuk_nr ) ); $exists = $res->num_rows() > 0; $res->free_result(); $stats[ ($exists ? 'bestaande' : 'nieuwe') . '_hoofdstukken' ]++; $this->CI->dbex->execute( $exists ? 'update' : 'insert', array( $hoofdstuk, $this->grondslag_id, 'hoofdstuk ' . $hoofdstuk_nr ) ); } foreach ($afdelingen as $afdeling_nr => $afdeling) { $res = $this->CI->dbex->execute( 'find', array( $this->grondslag_id, 'afdeling ' . $afdeling_nr ) ); $exists = $res->num_rows() > 0; $res->free_result(); $stats[ ($exists ? 'bestaande' : 'nieuwe') . '_afdelingen' ]++; $this->CI->dbex->execute( $exists ? 'update' : 'insert', array( $afdeling, $this->grondslag_id, 'afdeling ' . $afdeling_nr ) ); } foreach ($artikelen as $artikel_nr => $artikel) { $res = $this->CI->dbex->execute( 'find', array( $this->grondslag_id, $artikel_nr ) ); $exists = $res->num_rows() > 0; $res->free_result(); $stats[ ($exists ? 'bestaande' : 'nieuwe') . '_artikelen' ]++; $this->CI->dbex->execute( $exists ? 'update' : 'insert', array( $artikel, $this->grondslag_id, $artikel_nr ) ); } foreach ($stats as $key => $val) echo sprintf( "%30s: %d\n", preg_replace( '/_/', ' ', $key ), $val ); if ($fix) { echo "COMMITTING...\n"; $this->CI->db->query( 'COMMIT;' ); } else { echo "ROLLING BACK...\n"; $this->CI->db->query( 'ROLLBACK;' ); } $this->CI->db->query( 'SET AUTOCOMMIT=1' ); } private function _scandir( $dir ) { $result = array(); foreach (scandir( $dir ) as $file) { if ($file == '.' || $file == '..') continue; if (is_file( $dir . $file )) $result[] = $dir . $file; else if (is_dir( $dir . $file . '/' )) $result = array_merge( $result, $this->_scandir( $dir . $file . '/' ) ); } return $result; } } <file_sep><?php require_once 'mappingen.php'; class Risicoprofielen extends Controller{ public function __construct(){ parent::__construct(); $this->navigation->push( 'nav.instellingen', '/instellingen' ); $this->navigation->push( 'nav.risicoprofielen', '/risicoprofielen' ); $this->navigation->set_active_tab( 'beheer' ); } public function index(){ $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); redirect( '/risicoprofielen/drsmlist'); } private function _check_post(){ if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'HTTP verzoek is geen POST.' ); } public function drsmlist(){ $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $dmms = $klant->get_mappingen(); $profielen = array(); foreach( $dmms as $dmm ){ $profielen = array_merge($profielen, $dmm->getRisicoprofielen()); } $this->load->view( 'risicoprofielen/drsmlist', array( 'list' => $profielen, ) ); } private function getVragenOpts($risicoprofiel){ $this->load->model( 'vraag' ); $opts = array(); foreach( $risicoprofiel['afdelingen'] as $i=>$afdeling){ foreach( $afdeling['artikelen'] as $i=>$artikel ){ if (!is_array($vragen = $this->vraag->get_by_artikel_map( $risicoprofiel['id'], $artikel['id'] ))) throw new Exception( 'Ongeldig artikel ID'); foreach( $vragen as $vraag ){ $opts[$vraag->vraag_map_id] = $vraag->is_active; } } } return $opts; } public function risicoprofielenmapping( $dmmId, $btRpId ){ $this->load->model( 'matrixmapping' ); if (!($dmm = $this->matrixmapping->get( $dmmId ))) throw new Exception( 'Ongeldig matrixmapping ID ' . $dmmId ); $this->load->model( 'colectivematrix' ); if (!$bt_collective_matrix = $this->colectivematrix->get( $dmm->bt_matrix_id )) throw new Exception( 'Ongeldig collective matrix ID'); $risicoprofiel = $bt_collective_matrix->getRisicoprofiel( $btRpId ); $this->load->model( 'artikelvraagmap' ); $btz_profiles = $this->artikelvraagmap->get_risicoprofilen_list_map_by_matrix( $dmmId ); foreach( $btz_profiles as $btz_profile ){ $bt_profiel = $bt_collective_matrix->getRisicoprofiel( $btz_profile->bt_riskprofiel_id ); if($btz_profile->bt_riskprofiel_id == $btRpId) break; } $this->navigation->push( 'nav.risicoprofielen.risicoprofielenmapping', '/risicoprofielen/risicoprofielenmapping', array($dmm->naam.' - '.$bt_profiel['naam']) ); $this->load->view( 'risicoprofielen/risicoprofielenmapping', array( 'bt_rp_id' => $btRpId, 'risicoprofiel' => $risicoprofiel, 'opts' => $this->getVragenOpts($risicoprofiel) ) ); }//----------------- public function show_artikel_vragen( $artikelId, $btRpId ){ $this->load->model( 'vraag' ); if (!is_array($vragen = $this->vraag->get_by_artikel_map( $btRpId, $artikelId ))) throw new Exception( 'Ongeldig artikel ID'); if(isset($_POST['opts'])){ foreach( $vragen as &$vraag ){ $vraag->prompt_bw = $vraag->is_dmm_bw != $vraag->is_drsm_bw ? 'BW!' : 'BW'; $vraag->bw_css = $vraag->is_drsm_bw ? 'bw' : ''; foreach( $_POST['opts'] as $vraag_map_id => $is_active ){ $vraag->is_active = ( $vraag->vraag_map_id == $vraag_map_id) ? $is_active : $vraag->is_active; } } } $this->load->view( 'risicoprofielen/artikelvragen', array( 'artikel_id' => $artikelId, 'vragen' => $vragen ,'is_active' => $_POST['is_active'] ) ); }//-------------------- public function save(){ try { $this->_check_post(); $this->load->model( 'artikelvraagmap' ); foreach($_POST['opts'] as $vraag_map_id=>$is_active){ $this->artikelvraagmap->save((object)array('id'=>$vraag_map_id,'is_active'=>$is_active)); } echo json_encode(array( 'success' => true )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } }//-------------------- public function set_risico_bw($vraagMapId, $artikelId, $btRpId) { $this->load->model( 'artikelvraagmap' ); $this->load->model( 'vraag' ); $this->load->model( 'toezichtmoment' ); $this->load->model( 'bijwoonmomentenmap' ); $vraag_map = $this->artikelvraagmap->get( $vraagMapId ); $vraag = $this->vraag->get( $vraag_map->vraag_id ); $category = $vraag->get_categorie(); $tmoment = $this->toezichtmoment->get_by_hoofdgroep( $category->hoofdgroep_id ); $bw = $this->bijwoonmomentenmap->get_by_toezichtmoment( $tmoment->id, $vraag_map->matrix_id ); $bw->is_drsm_bw = ($_POST['is_bw']=='true'); $bw->save(); $this->show_artikel_vragen( $artikelId, $btRpId ); }//-------------------- }// Class end<file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('kanswaarde.blootstelling.af_en_toe_wekelijks_of_incidenteel', 'Af en toe (wekelijks of incidenteel)', '2014-07-02 19:09:55', 0), ('kanswaarde.blootstelling.regelmatig_dagelijks_tijdens_de_werkuren', 'Regelmatig (dagelijks tijdens de werkuren)', '2014-07-02 19:09:55', 0), ('kanswaarde.blootstelling.soms_maandelijks_meerdere_malen_per_jaar', 'Soms (maandelijks, meerdere malen per jaar)', '2014-07-02 19:09:55', 0), ('kanswaarde.blootstelling.voortdurend', 'Voortdurend', '2014-07-02 19:09:55', 0), ('kanswaarde.blootstelling.zeer_zelden_minder_dan_eens_per_jaar', 'Zeer zelden (minder dan eens per jaar)', '2014-07-02 19:09:55', 0), ('kanswaarde.blootstelling.zelden_enkele_malen_per_jaar', 'Zelden (enkele malen per jaar)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.gemiddeld_ongewoon_maar_mogelijk', 'Gemiddeld (ongewoon maar mogelijk)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.groot_zeer_wel_mogelijk', 'Groot (zeer wel mogelijk)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.klein_mogelijke_op_langere_termijn', 'Klein (mogelijk op langere termijn)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.vrijwel_onmogelijk_wel_denkbaar', 'Vrijwel onmogelijk (wel denkbaar)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.zeer_groot_bijna_zeker', 'Zeer groot (bijna zeker)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.zeer_klein_onwaarschijnlijk', 'Zeer klein (onwaarschijnlijk)', '2014-07-02 19:09:55', 0), ('kanswaarde.waarschijnlijkheid.zeer_onwaarschijnlijk_bijna_niet_denkbaar', 'Zeer onwaarschijnlijk (bijna niet denkbaar)', '2014-07-02 19:09:55', 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('effectwaarde.aanzienlijk', 'Aanzienlijk', '2014-06-28 17:40:05', 0), ('effectwaarde.belangrijk', 'Belangrijk', '2014-06-28 17:40:05', 0), ('effectwaarde.catastrofaal', 'Catastrofaal', '2014-06-28 17:40:05', 0), ('effectwaarde.gering_hinder', 'Gering/hinder', '2014-06-28 17:40:05', 0), ('effectwaarde.ramp', 'Ramp', '2014-06-28 17:40:05', 0), ('effectwaarde.zeer ernstig', 'Zeer ernstig', '2014-06-28 17:40:05', 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.risicoanalyse_invullen::kanswaarde.blootstelling', 'Blootstelling', '2014-07-02 19:35:09', 0), ('beheer.risicoanalyse_invullen::kanswaarde.waarschijnlijkheid', 'Waarschijnlijkheid', '2014-07-02 19:35:09', 0); <file_sep>CREATE TABLE IF NOT EXISTS supervision_moments_executed ( id int(10) unsigned NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, checklist_id int(11) NOT NULL, start datetime NOT NULL, end datetime NULL, progress_start float NOT NULL, progress_end float NULL, supervisor_user_id int(11) NOT NULL, PRIMARY KEY (id), KEY supervisor_user_id (supervisor_user_id), KEY checklist_id (checklist_id), KEY deelplan_id (deelplan_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ALTER TABLE supervision_moments_executed ADD CONSTRAINT FK_super_user_id_GEBRUIKERS_id FOREIGN KEY (supervisor_user_id) REFERENCES gebruikers (id), ADD CONSTRAINT FK_checklist_id_CHECKLISTEN_id FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FK_id_DEELPLANNEN_id FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE;<file_sep>-- -- -- -- LET OP, deze migratie is wellicht al toegepast op LIVE ivm een live hackfix! -- -- -- ALTER TABLE `bt_vragen` ADD `automatische_toelichting_moment` ENUM( 'bij aanmaken', 'bij afmelden' ) NULL DEFAULT NULL , ADD `automatische_toelichting_template` TEXT NULL DEFAULT NULL , ADD `automatische_toelichting_methode` ENUM( 'overschrijven', 'aanvullen' ) NULL DEFAULT NULL ; <file_sep><? $this->load->view('elements/header', array('page_header'=>'handleiding')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'BRIStoezicht licentie probleem', 'width' => '60em' )); ?> <p> U kunt momenteel geen gebruik maken van BRIStoezicht vanwege een licentie probleem. Neem contact met ons op voor meer informatie. Meer details vindt u hieronder. </p> <? switch ($details) { case 'VerlopenTokenInReturnUrl': if (!isset($visited)) { $visited = true; redirect(site_url('/gebruikers/clearcookies')); } $message = 'Er is iets fout gegaan bij het inloggen via KennisID, u heeft een verlopen token ontvangen.'; break; case 'PassportInfoByTokenFout': case 'LicenseIdByTokenFout': $message = 'Er is iets fout gegaan bij het verifieren van uw gegevens bij KennisID.'; break; case 'claimLicenseSeatError': $message = 'Er is iets fout gegaan bij het verifieren van de status van uw licentie.'; break; case 'KMXErrorUnknownLicense': $message = 'Uw KennisID account heeft geen licentie voor BRIStoezicht.'; break; case 'KMXErrorPasswordFailure': case 'KMXErrorNoAccess': $message = 'Onjuiste combinatie van gebruikersnaam en wachtwoord.'; break; case 'KMXErrorLicenseFull': $message = 'Het maximaal aantal toegestane licentieplaatsen is al in gebruik.'; break; case 'KMXErrorLicenseDisabled': $message = 'Uw licentie is uitgeschakeld.'; break; case 'KMXErrorLicenseExpired': $message = 'Uw licentie is verlopen.'; break; case 'KMXErrorRestrictionLocation': $message = 'Uw locatie staat het gebruik van deze licentie niet toe.'; break; case 'KMXErrorRestrictionReferrer': $message = 'Herkomst staat het gebruik van deze licentie niet toe.'; break; case 'InterneRegistratieIssue': $message = 'Er is een administrieve fout ontdekt in de gebruiker/organisatie structuur.'; break; default: $message = 'Onbekende fout.'; break; } ?> <div style="margin:20px; padding:15px; border: 1px solid #999; background-color: white;"> <table style="width:auto"> <tr> <td style="width:10em"><b>Foutcode:</b></td> <td><i><?=$details?></i></td> </tr> <tr> <td><b>Details:</b></td> <td><i><?=$message?></i></td> </tr> </table> </div> <p> <b><a style="font-weight:inherit;" href="<?=site_url('/gebruikers/inloggen')?>">Klik hier</a></b> om opnieuw in te loggen. Als u wederom op deze pagina uitkomt, is het probleem (nog) niet opgelost. U kunt proberen of het probleem is verholpen door de opgeslagen cookies te verwijderen. Om dat te realiseren, <b><a style="font-weight:inherit;" href="<?=site_url('/gebruikers/clearcookies')?>">klik hier</a></b>. </p> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?> <file_sep>Geachte mevrouw/mijnheer, <?= $email_content ?> <? if( isset($email_options[EMAIL_OPT_QUESTION]) ) { ?> Deze notificatie heeft betrekking op de volgende vraag: <?= $email_options[EMAIL_OPT_QUESTION] ?> <? } ?> <? if( isset($email_options[EMAIL_OPT_QUESTION_STATUS]) ) { ?> Het gegeven waardeoordeel is: <?= $email_options[EMAIL_OPT_QUESTION_STATUS] ?> <? } ?> <? if( isset($email_options[EMAIL_OPT_SUPERVISOR]) ) { ?> Het waardeoordeel is gegeven door: <?= $email_options[EMAIL_OPT_SUPERVISOR] ?> <? } ?> <? if( isset($email_options[EMAIL_OPT_DATE]) ) { ?> Datum van invullen: <?= $email_options[EMAIL_OPT_DATE] ?> <? } ?> <? if( isset($email_options[EMAIL_OPT_DOSSIER_DATA]) ) { ?> Deze vraag betreft het volgende dossier: <?= $email_options[EMAIL_OPT_DOSSIER_DATA] ?> <? } ?> <? if( isset($email_options[EMAIL_OPT_ANWSER]) ) { ?> De volgende toelichting is ingevuld: <?= $email_options[EMAIL_OPT_ANWSER] ?> <? } ?> N.B.: Deze email is automatisch verzonden. Gelieve geen antwoord te sturen op deze email.<file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <!-- gebruikersbeheer fake --> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Gebruikersbeheer', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/gebruikers') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <!-- rollenbeheer --> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Rollenbeheer', 'expanded' => true, 'onclick' => '', 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <? $col_widths = array( 'editicon' => 32 ); $col_description = array( 'editicon' => '&nbsp;' ); if ($allow_klanten_edit) { if ($this->is_Mobile) $col_widths['klant'] = 100; else $col_widths['klant'] = 150; $col_description['klant'] = 'Klant'; } $col_widths = array_merge( $col_widths, array( 'naam' => 250, 'gemaakt_op' => 150, 'gebruiker' => 150, 'aanpasbaar' => 100, 'counts' => 150, 'verwijderen' => 100, ) ); $col_description = array_merge( $col_description, array( 'naam' => 'Rolnaam', 'gemaakt_op' => 'Gemaakt op', 'gebruiker' => 'Gemaakt door', 'aanpasbaar' => 'Aanpasbaar', 'counts' => 'Aantal gebruikers', 'verwijderen' => 'Verwijderen', ) ); if ($this->is_Mobile) { unset( $col_widths['counts'] ); unset( $col_description['counts'] ); } $rows = array(); foreach ($rollen as $i => $rol) { $rol_editbaar = ($rol->klant_id || $allow_klanten_edit); $row = (object)array(); $row->onclick = "location.href='" . site_url('/instellingen/rol_bewerken/' . $rol->id) . "'"; $row->data = array(); $row->data['editicon'] = $rol_editbaar ? '<a title="Verantwoordingstekst bekijken/bewerken" href="' . site_url('/instellingen/rol_bewerken/' . $rol->id) . '"><img src="' . site_url('/files/images/edit.png') . '" /></a>' : ''; if ($allow_klanten_edit) $row->data['klant'] = ($rol->klant_id && isset($klanten[$rol->klant_id])) ? $klanten[$rol->klant_id]->naam : '- alle -'; $row->data['naam'] = htmlentities( $rol->naam, ENT_COMPAT, 'UTF-8' ); $row->data['gemaakt_op'] = $rol->gemaakt_op; //$row->data['gebruiker'] = ($rol->gemaakt_door_gebruiker_id && isset( $gebruikers[$rol->gemaakt_door_gebruiker_id] )) ? $gebruikers[$rol->gemaakt_door_gebruiker_id]->volledige_naam : 'Ongeldige gebruiker.'; $row->data['gebruiker'] = ($rol->gemaakt_door_gebruiker_id && isset( $gebruikers[$rol->gemaakt_door_gebruiker_id] )) ? $gebruikers[$rol->gemaakt_door_gebruiker_id]->volledige_naam : 'Niet eigen gebruiker.'; $row->data['aanpasbaar'] = $rol_editbaar ? 'Ja' : 'Nee'; if (!$this->is_Mobile) { $row->data['counts'] = isset( $counts[$rol->id] ) ? $counts[$rol->id] : '-'; } $row->data['verwijderen'] = ' <a href="javascript:void(0);" onclick="eventStopPropagation(event); if (confirm(\'Rol ' . htmlentities( $rol->naam, ENT_COMPAT, 'UTF-8' ) . '&quot; werkelijk verwijderen? Deze actie kan niet ongedaan gemaakt worden!\nEventuele gebruikers met deze rol zullen geen rol en daarmee geen rechten meer hebben!\')) location.href=\'/instellingen/rol_verwijderen/' . $rol->id . '\';"> <img src="' . site_url('/files/images/delete.png') . '" /> </a> '; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'header' => '', 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, 'new_button_js' => "location.href='/instellingen/rol_nieuw';", 'url' => '/instellingen/rollenbeheer', 'scale_field' => 'verwijderen', 'do_paging' => false, ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? if($this->gebruiker->get_logged_in_gebruiker()->get_klant()->usergroup_activate == 1 && $this->login->verify( 'beheer', 'users_groups' )):?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('users_group'), 'rightheader' => '', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/users_groups') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <?endif;?> <? $this->load->view('elements/footer'); ?><file_sep><?php class VraagUpload2BescheidenConverter { public function run() { $CI = get_instance(); $CI->load->model('deelplan'); $CI->load->model('deelplanupload'); $CI->load->model('dossierbescheiden'); $CI->load->model('deelplanbescheiden'); $CI->load->model('deelplanvraagbescheiden'); $CI->db->trans_start(); try { $deelplanuploads = $CI->deelplanupload->all(); echo "Considering " . sizeof($deelplanuploads) . " uploads...\n"; foreach ($deelplanuploads as $du) if (!preg_match( '/\.jpg$/i', $du->filename )) { echo "Converting " . $du->filename . " ... \n"; $this->_convert( $du ); } if (!($CI->db->trans_complete())) throw new Exception( 'Fout bij database transactie commit.' ); } catch (Exception $e) { $CI->db->_trans_status = false; $CI->db->trans_complete(); throw $e; } } private function _convert( DeelplanUploadResult $du ) { $CI = get_instance(); // init $filename = $du->filename; $deelplan = $CI->deelplan->get( $du->deelplan_id ); $gebruiker = $CI->gebruiker->get( $du->gebruiker_id ); $vraag_id = $du->vraag_id; $contents = $du->data; // add bescheiden if (!($dossierbescheiden = $CI->dossierbescheiden->add( $deelplan->dossier_id ))) throw new Exception( 'Fout bij aanmaken dossierbescheiden.' ); // process bescheiden data $dossierbescheiden->bestandsnaam = $filename; $dossierbescheiden->bestand = $contents; $dossierbescheiden->tekening_stuk_nummer = 'bestand'; $dossierbescheiden->auteur = $gebruiker->volledige_naam; $dossierbescheiden->omschrijving = 'Upload'; $dossierbescheiden->zaaknummer_registratie = ''; $dossierbescheiden->versienummer = ''; $dossierbescheiden->datum_laatste_wijziging = date('d-m-Y H:i'); $dossierbescheiden->png_status = 'onbekend'; if (!$dossierbescheiden->save()) throw new Exception( 'Fout bij zetten bestandsdata dossierbescheiden.' ); // add deelplan - bescheiden link if (!($CI->deelplanbescheiden->add( $deelplan->id, $dossierbescheiden->id ))) throw new Exception( 'Fout bij aanmaken dossierbescheiden en deelplan link.' ); // set relevant if (!($CI->deelplanvraagbescheiden->add( $deelplan->id, $vraag_id, $dossierbescheiden->id ))) throw new Exception( 'Fout bij aanmaken dossierbescheiden en vraag link.' ); $du->delete(); } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //require_once( dirname(__FILE__) . '/functions.inc' ); class FtpClientHelper { # Global members for specifying the way directories should be handled, etc. private $directories_to_synchronise = array(); private $dirs_to_sync_auto_determine = true; private $start_directory = '.'; private $dir_style = 'freebsd'; private $hash_delimiter = '*****'; private $silent = false; # FTP credentials private $ftp_host_name = ''; private $ftp_user_name = ''; private $ftp_password = ''; # Internal members private $ftp_connection_id = null; private $ftp_use_passive_mode = false; // Some output specific members private $eol = "\n"; public function __construct( $use_host_name, $use_user_name, $use_password, $use_passive_mode = false, $silent = false ) { $this->ftp_host_name = $use_host_name; $this->ftp_user_name = $use_user_name; $this->ftp_password = $<PASSWORD>; $this->ftp_use_passive_mode = $use_passive_mode; $this->silent = $silent; # Open the desired FTP connection (if possible; throws an exeption otherwise). #$this->open_ftp_connection($this->ftp_host_name, $this->ftp_user_name, $this->ftp_password, $use_passive_mode); $this->open_ftp_connection($this->ftp_use_passive_mode); } // public function __construct( $use_host_name, $use_user_name, $use_password, $use_passive_mode = false, $silent = false ) # Used to indicate the specifics for handling the directory listings as they are returned by the FTP server. public function initialise_directory_settings($directories_to_synchronise = array(), $dirs_to_sync_auto_determine = true, $start_directory = '.', $dir_style = 'freebsd') { $this->set_directories_to_synchronise($directories_to_synchronise); $this->set_dirs_to_sync_auto_determine($dirs_to_sync_auto_determine); $this->set_start_directory($start_directory); $this->set_dir_style($dir_style); } public function set_directories_to_synchronise($directories_to_synchronise) { $this->directories_to_synchronise = $directories_to_synchronise; } public function set_dirs_to_sync_auto_determine($dirs_to_sync_auto_determine) { $this->dirs_to_sync_auto_determine = $dirs_to_sync_auto_determine; } public function set_start_directory($start_directory) { $this->start_directory = $start_directory; } public function set_dir_style($dir_style) { $this->dir_style = $dir_style; } public function set_eol($eol = "\n") { $this->eol = $eol; } # Helper function to get a time stamp with miliseconds precision public function getmicrotime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // function getmicrotime() private function open_ftp_connection($use_passive_mode = false) { # Set up basic FTP connection $this->ftp_connection_id = ftp_connect($this->ftp_host_name); # Login with the username and password $login_result = @ftp_login($this->ftp_connection_id, $this->ftp_user_name, $this->ftp_password); # If necessary, turn FTP passive mode on if ($use_passive_mode) { if (!$this->silent) { echo "Using passive mode for the connection{$this->eol}"; } ftp_pasv($this->ftp_connection_id, true); } # Check the connection if ( (!$this->ftp_connection_id) || (!$login_result) ) { throw new Exception( "Kon geen verbinding met FTP server maken! Opgegeven credentials: host: {$this->ftp_host_name}, user: {$this->ftp_user_name}" ); } else { $ftp_server_type = ftp_systype($this->ftp_connection_id); if (!$this->silent) { echo "Connected to {$this->ftp_host_name}, for user {$this->ftp_user_name}{$this->eol}"; echo "Remote system type is identified as: {$ftp_server_type}{$this->eol}"; } } # If the connection was opened successfully, return the connection ID return $this->ftp_connection_id; } // private function open_ftp_connection($ftp_host_name, $ftp_user_name, $ftp_password, $use_passive_mode = false) public function ftp_is_dir( $dir ) { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); # Test if you can change directory to $dir, suppress errors in case $dir is not a directory if ( @ftp_chdir( $this->ftp_connection_id, $dir ) ) { // If it is a directory, then change the directory back to the original directory ftp_chdir( $this->ftp_connection_id, $original_directory ); return true; } # Return false in case the ftp_chdir action was unsuccessfull. return false; } // public function ftp_is_dir( $dir ) public function ftp_list_dir_contents($dir = '') { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); echo "Current directory: {$original_directory}{$this->eol}"; # Work out which directory to use (the currently registered start directory, or one that was passed explicitly). $dir_to_list = (empty($dir)) ? $this->start_directory : $dir; # List the contents of the directory #if ( @ftp_chdir( $ftp_connection_id, $dir_to_list ) ) if ( ftp_chdir( $this->ftp_connection_id, $dir_to_list ) ) { # If it is a directory, list its contents echo "Successfully changed to directory {$dir_to_list}. Contents:{$this->eol}"; $directory_contents_raw = ftp_rawlist($this->ftp_connection_id, '.'); d($directory_contents_raw); # Change the directory back to the original directory and exit ftp_chdir( $this->ftp_connection_id, $original_directory ); return true; } else { echo "Failed to change to directory {$dir_to_list}!{$this->eol}"; return false; } } // public function ftp_list_dir_contents($dir) public function delete_files_from_directory($directory, $extension_filter = '') { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); echo "Current directory: {$original_directory}{$this->eol}"; # Work out which directory to use (the currently registered start directory, or one that was passed explicitly). $dir_to_delete_from = (empty($directory)) ? $this->start_directory : $directory; # Get the contents of the source directory, and store them in the target directory #if ( @ftp_chdir( $ftp_connection_id, $dir_to_delete_from ) ) if ( ftp_chdir( $this->ftp_connection_id, $dir_to_delete_from ) ) { # If it is a directory, list its contents echo "Successfully changed to directory {$dir_to_delete_from}. Contents:{$this->eol}"; #$directory_contents_raw = ftp_rawlist($this->ftp_connection_id, '.'); $directory_contents = ftp_nlist($this->ftp_connection_id, '.'); #d($directory_contents); # Now delete all files that we need to delete (filtered, if necessary). foreach ($directory_contents as $directory_entry) { # Skip directories if ($this->ftp_is_dir($directory_entry)) { echo "Skipping subdirectory {$directory_entry}...{$this->eol}"; continue; } # Skip files that do not have the desired extension (if a filter was specified) if (!empty($extension_filter) && ( substr(strtolower($directory_entry),(0-strlen($extension_filter))) != strtolower($extension_filter) ) ) { echo "Skipping file by extension. File extension for removal: {$extension_filter}. Filename: {$directory_entry}...{$this->eol}"; continue; } # Now, if we reached this position, we can delete the file. $remote_file_name_clean = str_replace('./', '', $directory_entry); if (ftp_delete($this->ftp_connection_id, $directory_entry)) { echo "File {$directory_entry} was successfully deleted!{$this->eol}"; } else { echo "File {$directory_entry} was NOT deleted!{$this->eol}"; } } // foreach ($directory_contents as $directory_entry) # Change the directory back to the original directory and exit ftp_chdir( $this->ftp_connection_id, $original_directory ); return true; } else { echo "Failed to change to directory {$dir_to_delete_from}!{$this->eol}"; return false; } } // public function delete_files_from_directory($directory, $extension_filter = '') public function get_files_from_directory($source_directory, $target_directory, $extension_filter = '') { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); echo "Current directory: {$original_directory}{$this->eol}"; # Work out which directory to use (the currently registered start directory, or one that was passed explicitly). $dir_to_get = (empty($source_directory)) ? $this->start_directory : $source_directory; # Check if the target directory exists and can be used. In case it cannot, we exit, returning 'false' if ( is_dir($target_directory) && is_writable($target_directory) ) { echo "Target directory {$target_directory} exists and is writable. Continuing...{$this->eol}"; } else { echo "Target directory {$target_directory} does not exist, or is not writable! Exiting...{$this->eol}"; return false; } # Get the contents of the source directory, and store them in the target directory #if ( @ftp_chdir( $ftp_connection_id, $dir_to_get ) ) if ( ftp_chdir( $this->ftp_connection_id, $dir_to_get ) ) { # If it is a directory, list its contents echo "Successfully changed to directory {$dir_to_get}. Contents:{$this->eol}"; #$directory_contents_raw = ftp_rawlist($this->ftp_connection_id, '.'); $directory_contents = ftp_nlist($this->ftp_connection_id, '.'); #d($directory_contents); # Now get all files that we need to get (filtered, if necessary) and store them in the target directory. foreach ($directory_contents as $directory_entry) { # Skip directories if ($this->ftp_is_dir($directory_entry)) { echo "Skipping subdirectory {$directory_entry}...{$this->eol}"; continue; } # Skip files that do not have the desired extension (if a filter was specified) if (!empty($extension_filter) && ( substr(strtolower($directory_entry),(0-strlen($extension_filter))) != strtolower($extension_filter) ) ) { echo "Skipping file by extension. Allowed extension: {$extension_filter}. Filename: {$directory_entry}...{$this->eol}"; continue; } # Now, if we reached this position, we can get the file. $remote_file_name_clean = str_replace('./', '', $directory_entry); if (ftp_get($this->ftp_connection_id, $target_directory.$remote_file_name_clean, $directory_entry, FTP_BINARY)) { echo "File {$directory_entry} was successfully retrieved!{$this->eol}"; } else { echo "File {$directory_entry} was NOT successfully retrieved!{$this->eol}"; } } // foreach ($directory_contents as $directory_entry) # Change the directory back to the original directory and exit ftp_chdir( $this->ftp_connection_id, $original_directory ); return true; } else { echo "Failed to change to directory {$dir_to_get}!{$this->eol}"; return false; } } // public function get_files_from_directory($source_directory, $target_directory, $extension_filter = '') public function get_file_from_directory($source_directory, $file_name, $target_directory) { //$old_silent = $this->silent; //$this->silent = false; # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); if (!$this->silent) { echo "Current directory: {$original_directory}{$this->eol}"; } # Work out which directory to use (the currently registered start directory, or one that was passed explicitly). $dir_to_get = (empty($source_directory)) ? $this->start_directory : $source_directory; # Check if the target directory exists and can be used. In case it cannot, we exit, returning 'false' if ( is_dir($target_directory) && is_writable($target_directory) ) { if (!$this->silent) { echo "Target directory {$target_directory} exists and is writable. Continuing...{$this->eol}"; } } else { if (!$this->silent) { echo "Target directory {$target_directory} does not exist, or is not writable! Exiting...{$this->eol}"; } return false; } # Get the file from the source directory, and store it in the target directory #if ( @ftp_chdir( $ftp_connection_id, $dir_to_get ) ) if ( ftp_chdir( $this->ftp_connection_id, $dir_to_get ) ) { # If it is a directory, proceed to get the file if (!$this->silent) { echo "Successfully changed to directory {$dir_to_get}.{$this->eol}"; } # Now, if we reached this position, we can get the file. Make sure that the target path contains a proper directory separator! #$remote_file_name_clean = str_replace('./', '', $directory_entry); //$file_name_dir_safe = str_replace(' ', '\ ', $file_name); //$file_name_dir_safe = str_replace('\\ ', '\ ', $file_name_dir_safe); //$target_path = $target_directory.DIRECTORY_SEPARATOR.$file_name_dir_safe; $target_path = $target_directory.DIRECTORY_SEPARATOR.$file_name; $target_path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $target_path); //d($target_path); //$target_directory.$file_name_dir_safe if (ftp_get($this->ftp_connection_id, $target_path, $file_name, FTP_BINARY)) { if (!$this->silent) { echo "File {$file_name} was successfully retrieved!{$this->eol}"; } } else { if (!$this->silent) { echo "File {$file_name} was NOT successfully retrieved!{$this->eol}"; } } # Change the directory back to the original directory and exit ftp_chdir( $this->ftp_connection_id, $original_directory ); //$this->silent = $old_silent; return true; } else { if (!$this->silent) { echo "Failed to change to directory {$dir_to_get}!{$this->eol}"; } //$this->silent = $old_silent; return false; } } // public function get_file_from_directory($source_directory, $file_name, $target_directory, $silent = true ) public function get_directory_contents_recursively($start_directory, $extension_filter = '', $recursion_depth = 0, $get_directories_only = false, $level_based_filter = array()) { $perform_timing = true; if ($perform_timing) $t1a = $this->getmicrotime(); # Check if we have to use a limit on the recursion depth $use_recursion_depth_limit = ($recursion_depth > 0); # This function can potentially run for a long time, possibly causing problems with time outs! As an attempt to circumvent this, when called from a loop, # we always force-open a new connection upon entering this function. if (!is_null($this->ftp_connection_id)) { $this->close(); } $this->open_ftp_connection($this->ftp_use_passive_mode); # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); echo "Current directory: {$original_directory}{$this->eol}"; # Initialise the set with directory names and the set with file names $directories_to_process = array($start_directory); $directories_to_synchronise = $directories_to_process; $files_to_synchronise = array(); $opened_directories_counter = 0; $opened_directories_counter_threshold = 25; # Recurse over the directories. Note that the set will be filled (and emptied) as directories are processed. while (!empty($directories_to_process)) { # Open a new connection after a specific amount of directories has been processed. This is done so as to prevent connections getting dropped. $opened_directories_counter++; if (($opened_directories_counter % $opened_directories_counter_threshold) == 0) { echo "Directory counter threshold of {$opened_directories_counter_threshold} reached. Resetting connection{$this->eol}"; $this->close(); $this->open_ftp_connection($this->ftp_use_passive_mode); } # Get the first entry of the set of directory names $dir_to_get = array_shift($directories_to_process); # Get the contents of the directory, and store them in a look-up set #if ( @ftp_chdir( $ftp_connection_id, $dir_to_get ) ) if ( ftp_chdir( $this->ftp_connection_id, $dir_to_get ) ) { # If it is a directory, list its contents echo "Successfully changed to directory {$dir_to_get}. Contents:{$this->eol}"; #$directory_contents_raw = ftp_rawlist($this->ftp_connection_id, '.'); $directory_contents = ftp_nlist($this->ftp_connection_id, '.'); # The following 'if' part was added by Echelon; it has been left in place, with some minor changes. if ($directory_contents === false) { #var_dump($directory_contents); echo "Connection lost. Reconnecting!{$this->eol}"; $this->close(); $this->open_ftp_connection($this->ftp_use_passive_mode); if ( ftp_chdir( $this->ftp_connection_id, $dir_to_get ) ) { $directory_contents = ftp_nlist($this->ftp_connection_id, '.'); #var_dump($directory_contents); if ($directory_contents === false) { die("Could not reconnect properly (dir contents){$this->eol}"); } } else { die("Could not reconnect properly (chdir){$this->eol}"); } } // if ($directory_contents === false) d($directory_contents); //! TODO: use the detailed custom error handler here for debugging purposes! # Now get all files that we need to get (filtered, if necessary) and store them in the look-up set. #$cnt = 0; foreach ($directory_contents as $directory_entry) { #if ($cnt++ > 8) continue; #if ($cnt++ > 7) continue; #if ($cnt++ > 6) continue; #if ($cnt++ > 5) continue; #if ($cnt++ > 3) continue; #if ($cnt++ > 2) continue; #if ($cnt++ > 1) continue; #if ($cnt++ > 0) continue; # Get the filesize and last-modified-timestamp. For directories the former handily returns -1, which we use as a 'cheap' directory test $directory_entry_size = ftp_size($this->ftp_connection_id, $directory_entry); $directory_entry_mdtm = ftp_mdtm($this->ftp_connection_id, $directory_entry); $current_directory_entry_is_dir = ($directory_entry_size == -1); # Get the complete entry name $remote_entry_name_clean = str_replace('./', '', $directory_entry); $current_entry_complete_path = $dir_to_get . '/' . $remote_entry_name_clean; #d($current_entry_complete_path); # Store directories to the set of directories to process #if ($this->ftp_is_dir($directory_entry)) if ($current_directory_entry_is_dir) { # If we use a limit on the recursion depth, we only add directories that are not nested too deep if ($use_recursion_depth_limit) { $dummy_entry_parts = explode('/', $current_entry_complete_path); if (sizeof($dummy_entry_parts) > $recursion_depth) { continue; } } // if ($use_recursion_depth_limit) # Apply the level based filter (if any) on the directories. Note: this will be followed on a file level too! if (!empty($level_based_filter)) { $dummy_entry_parts = explode('/', $current_entry_complete_path); $amount_of_path_parts = sizeof($dummy_entry_parts); $include_entry = true; echo "Applying level filter (on a directory). Checking parts: "; d($dummy_entry_parts); foreach($level_based_filter as $filter_level => $filter_value) { echo "Checking level filter: '{$filter_value}' at level: {$filter_level}. Result: "; /* # First filter out FILES that appear 'too low' in the directory structure (note: directories are allowed to pass, on behalf of the required presence of # them when iterating over the set of directories!). Perform a cheap test for files by simply checking for the presence of a '.' in the last entry. if ( ($filter_level >= $amount_of_path_parts) && (strpos($dummy_entry_parts[($amount_of_path_parts-1)], '.') !== false) ) { echo 'FAIL (file nested too low in hierarchy)' . $this->eol; $include_entry = false; } */ # Check if we have enough 'depth' in our path, and if the filter value occurs at the correct place. Note that files that occur 'too low' in the # hierarchy will be filtered out further ahead! if ( $include_entry && ($filter_level <= $amount_of_path_parts) && ($dummy_entry_parts[($filter_level-1)] != $filter_value) ) { echo 'FAIL' . $this->eol; $include_entry = false; } else { echo 'PASS' . $this->eol; } } // foreach($level_based_filter as $filter_level => $filter_value) # Only store the entry in case it passed all tests if (!$include_entry) { continue; } } // if (!empty($level_based_filter)) # Add the currently processed directory name to the set of directories to process and/or synchronise $directories_to_process[] = $current_entry_complete_path; $directories_to_synchronise[] = $current_entry_complete_path; continue; } // if ($current_directory_entry_is_dir) else { # Apply the level based filter (if any) on the files too, to check if they do not occur too low in the hierarchy! if (!empty($level_based_filter)) { $dummy_entry_parts = explode('/', $current_entry_complete_path); $amount_of_path_parts = sizeof($dummy_entry_parts); $include_entry = true; echo "Applying level filter (on a file). Checking parts: "; d($dummy_entry_parts); foreach($level_based_filter as $filter_level => $filter_value) { echo "Checking level filter: '{$filter_value}' at level: {$filter_level}. Result: "; # First filter out FILES that appear 'too low' in the directory structure (note: directories are allowed to pass, on behalf of the required presence of # them when iterating over the set of directories!). Perform a cheap test for files by simply checking for the presence of a '.' in the last entry. if ( ($filter_level >= $amount_of_path_parts) ) { echo 'FAIL (file nested too low in hierarchy)' . $this->eol; $include_entry = false; } else { echo 'PASS' . $this->eol; } } // foreach($level_based_filter as $filter_level => $filter_value) # Only store the entry in case it passed all tests if (!$include_entry) { echo "Skipping file because it appears too low in the hierarchy. Filename: {$directory_entry}..." . $this->eol; continue; } } // if (!empty($level_based_filter)) } // else of clause: if ($current_directory_entry_is_dir) # Skip files that do not have the desired extension (if a filter was specified) if (!empty($extension_filter) && ( substr(strtolower($directory_entry),(0-strlen($extension_filter))) != strtolower($extension_filter) ) ) { echo "Skipping file by extension. Allowed extension: {$extension_filter}. Filename: {$directory_entry}..." . $this->eol; continue; } # Store files that have to be inventarised # Now, if we reached this position, we can store the files descriptive data to the look-up set. echo "Processing file.... {$remote_entry_name_clean} ...." . $this->eol; #$files_to_synchronise[] = $current_entry_complete_path; # Use only the filename and size as seeding value. We can get the last modified timestamp too, but it is unreliable, as we do not know when the same # files are written to the remote folders by the client's own processes, causing the timestamp to be set to a new one, which in turn results in # different hashes being generated for the same file. #$hash_seed = $current_entry_complete_path . $this->hash_delimiter . $directory_entry_size . $this->hash_delimiter . $directory_entry_mdtm; $hash_seed = $current_entry_complete_path . $this->hash_delimiter . $directory_entry_size; $current_hash = sha1($hash_seed); $files_to_synchronise[$current_entry_complete_path] = array('size' => $directory_entry_size, 'time' => $directory_entry_mdtm, 'hash' => $current_hash); #d($directory_entry_size); #d($directory_entry_mdtm); } // foreach ($directory_contents as $directory_entry) # Change the directory back to the original directory and exit ftp_chdir( $this->ftp_connection_id, $original_directory ); #return true; } else { echo "Failed to change to directory {$dir_to_get}!" . $this->eol; return false; } // if ( ftp_chdir( $this->ftp_connection_id, $dir_to_get ) ) } // while .... if ($perform_timing) echo ">>>>> Time taken to process the entire directory structure recursively: " . ($this->getmicrotime()-$t1a) . " <<<<< " . $this->eol; #echo "++ -- ++ Files to synchronise: ++ -- ++" . $this->eol; #d($files_to_synchronise); #return $files_to_synchronise; return ($get_directories_only) ? $directories_to_synchronise : $files_to_synchronise; } // public function get_directory_contents_recursively($start_directory, $extension_filter = '', $recursion_depth = 0, $get_directories_only = false, $level_based_filter = array()) public function send_files($files_to_send, $target_directory = '', $create_remote_directories = false, $mode = FTP_BINARY) { $amount_of_ftp_failures = 0; # If only one file name was given, put it in an array if (!is_array($files_to_send)) { $files_to_send = array($files_to_send); } # Make sure the target directory is set correctly. Note that the current way it is used alleviates the need to change to the target directory. if (empty($target_directory)) { $target_directory = $this->start_directory; } $target_directory .= '/'; # If we need to create the remote directories (if they don't exist altready, that is), we do so here if ($create_remote_directories) { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); # Start by getting the various sub parts of the complete path $remote_path_parts = explode('/', $target_directory); # Iterate over the path parts, creating the sub directories as needed. $remote_path_partial = ''; foreach($remote_path_parts as $remote_path_part) { # Construct the name of the (complete) subdirectory path $remote_path_partial .= '/' . $remote_path_part; # Create the subdirectory if it doesn't exist yet if (!empty($remote_path_part) && !@ftp_chdir($this->ftp_connection_id, $remote_path_partial)) { #echo "Creating subdirectory {$remote_path_part} (full location: {$remote_path_partial})" . $this->eol; ftp_mkdir($this->ftp_connection_id, $remote_path_part); } # Now change to that subdirectory, for the next iteration (if any). @ftp_chdir( $this->ftp_connection_id, $remote_path_partial ); } // foreach($remote_path_parts as $remote_path_part) # Change the directory back to the original directory ftp_chdir( $this->ftp_connection_id, $original_directory ); } // if ($create_remote_directories) # Change the directory, if anything but the current directory is needed /* if (!empty($target_directory)) { # Keep track of the current directory, before changing the directory. $original_directory = ftp_pwd( $this->ftp_connection_id ); #echo "Current directory: {$original_directory}" . $this->eol; } */ # Now transfer all of the files. echo "Transferring " . sizeof($files_to_send) . " file(s)..." . $this->eol; foreach ($files_to_send as $file_to_send) { $remote_file_name_clean = basename($file_to_send); #if (ftp_get($this->ftp_connection_id, $target_directory.$remote_file_name_clean, $directory_entry, FTP_BINARY)) if (ftp_put($this->ftp_connection_id, $target_directory.$remote_file_name_clean, $file_to_send, $mode)) { echo "File {$remote_file_name_clean} was successfully sent!" . $this->eol; } else { echo "File {$remote_file_name_clean} was NOT successfully sent!" . $this->eol; $amount_of_ftp_failures++; } } // foreach ($files_to_send as $file_to_send) # Change the directory back to the original directory (if necessary) /* if (!empty($target_directory)) { ftp_chdir( $this->ftp_connection_id, $original_directory ); } */ # Only return true if ALL files were transferred successfully return (empty($amount_of_ftp_failures)) ? true : false; } // public function send_files($files_to_send, $target_directory = '', $create_remote_directories = false, $mode = FTP_BINARY) public function close() { ftp_close($this->ftp_connection_id); $this->ftp_connection_id = null; } } // FtpClientHelper <file_sep><?php class CI_Curl { public function create( $url=null ) { return new CommonCurl( $url ); } } class CommonCurl { private $_curl; private $_error_number = null; private $_error_str = null; private $_http_code = null; private $_poststr = null; public function __construct( $url=null ) { $this->_curl = curl_init(); if (!$this->_curl) throw new Exception( 'CommonCurl::__construct: failed to generate new CURL handle' ); curl_setopt( $this->_curl, CURLOPT_HEADER, false ); /* non-configurable setting */ curl_setopt( $this->_curl, CURLOPT_RETURNTRANSFER, true ); /* non-configurable setting */ curl_setopt( $this->_curl, CURLOPT_AUTOREFERER, true ); /* configurable setting */ curl_setopt( $this->_curl, CURLOPT_FOLLOWLOCATION, true ); /* non-configurable setting (for now) */ /* if ($denhaag) // ---> maak dit instelbaar via config.php, zie config_item('curl_proxy') { curl_setopt( $this->_curl, CURLOPT_PROXY, 'localhost:8080' ); } */ if (!is_null( $url )) $this->set_url( $url ); } public function __destruct() { $this->finish(); } public function execute( $throw_exception_on_error=true ) { $result = curl_exec( $this->_curl ); $this->_error_number = $result===false ? curl_errno( $this->_curl ) : null; $this->_error_str = $result===false ? curl_error( $this->_curl ) : null; $this->_http_code = curl_getinfo( $this->_curl, CURLINFO_HTTP_CODE ); $this->_url = curl_getinfo( $this->_curl, CURLINFO_EFFECTIVE_URL ); if ($throw_exception_on_error && $result===FALSE) throw new Exception( sprintf( "[HTTP %d] %d: %s", $this->_http_code, $this->_error_number, $this->_error_str ) ); return $result; } public function get_error_number() { return $this->_error_number; } public function get_error_string() { return $this->_error_str; } public function get_http_code() { return $this->_http_code; } public function get_effective_url() { return $this->_url; } public function set_incoming_cookies_file( $file, $set_as_outgoing_too=false ) /* set empty file to load nothing, but enable cookie handling */ { curl_setopt( $this->_curl, CURLOPT_COOKIEFILE, $file ); if ($set_as_outgoing_too) $this->set_outgoing_cookies_file( $file ); } public function set_outgoing_cookies_file( $file ) { curl_setopt( $this->_curl, CURLOPT_COOKIEJAR, $file ); } public function set_post( $is_post ) { curl_setopt( $this->_curl, CURLOPT_POST, $is_post ); if (!$is_post) $this->_poststr = null; } public function set_postfields( $string_or_array ) /* note, calling this automatically enables POST! */ { $this->_poststr = $string_or_array; curl_setopt( $this->_curl, CURLOPT_POSTFIELDS, $string_or_array ); } public function get_postfields() { return $this->_poststr; } public function set_auto_referer( $enable ) /* enabled by default */ { curl_setopt( $this->_curl, CURLOPT_AUTOREFERER, $enable ); } public function set_referer( $referer ) { curl_setopt( $this->_curl, CURLOPT_REFERER, $referer ); } public function set_user_agent( $useragent ) { curl_setopt( $this->_curl, CURLOPT_USERAGENT, $useragent ); } public function set_url( $url ) { curl_setopt( $this->_curl, CURLOPT_URL, $url ); } public function set_weak_ssl( $weak ) { curl_setopt( $this->_curl, CURLOPT_SSL_VERIFYHOST, $weak ? 0 : 1 ); curl_setopt( $this->_curl, CURLOPT_SSL_VERIFYPEER, $weak ? 0 : 1 ); } public function set_verbose( $verbose ) { curl_setopt( $this->_curl, CURLOPT_VERBOSE, $verbose ); } public function set_opt( $curloption, $curlvalue ) /* use at own risk */ { curl_setopt( $this->_curl, $curloption, $curlvalue ); } public function finish() { if ($this->_curl) { curl_close( $this->_curl ); $this->_curl = NULL; } } public function duplicate() { $curl = new CommonCurl(); $curl->finish(); // cleanup again $curl->_curl = curl_copy_handle( $this->_curl ); return $curl; } } <file_sep><div class="scrolldiv hidden" id="TelefoonPaginaDeelplannen"> <div class="header"> <div class="regular_button terug" style="float:left; position: relative; top: -6px;"><?=tg('terug')?></div> <span><?=tg('deelplannen.header')?></span> </div> <div class="content"> <h1><?=tg('deelplannen.welkom')?></h1> <span><?=tg('deelplannen.kies.deelplan')?></span> <ul class="list"> <? foreach ($dossiers as $dossierdata): $dossier = $dossierdata['dossier']; $deelplannen = $dossierdata['deelplannen']; ?> <? $i=0; foreach ($deelplannen as $deelplandata): $deelplan = $deelplandata['deelplan']; ?> <? if (sizeof($deelplannen) > 1) $class = !$i ? 'first' : ($i == sizeof($deelplannen)-1 ? 'last' : ''); else $class = 'first last'; ?> <li class="arrow-right <?=$class?> clickable bold" dossier_id="<?=$dossier->id?>" deelplan_id="<?=$deelplan->id?>"><?=htmlentities( $deelplan->naam, ENT_COMPAT, 'UTF-8' )?></li> <? ++$i; endforeach; ?> <? endforeach; ?> </ul> </div> </div> <script type="text/javascript"> $(document).ready(function(){ var base = $('#TelefoonPaginaDeelplannen'); base.find('.terug').click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_DOSSIERS ); }); base.find('ul.list li[deelplan_id]').click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_OPDRACHTEN, $(this).attr('deelplan_id') ); }); }); </script> <file_sep><? require_once 'base.php'; class UsergroupResult extends BaseResult { function UsergroupResult( &$arr ) { parent::BaseResult( 'usergroup', $arr ); } } class Usergroup extends BaseModel { private $_cache = array(); function usergroup(){ parent::BaseModel( 'UsergroupResult', 'users_groups'); } public function check_access( BaseResult $object ) { //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function save(array $postdata ){ if( $postdata['id'] == "" ){ return $this->insert( $postdata ); }else{ return parent::save( (object)$postdata ); } } public function upload($id ){ if(!empty($_FILES['image']['name'])){ if (preg_match( '/\.(jpe?g|JPE?G|png|PNG|gif|GIF)$/', $_FILES['image']['name'] )) { $this->load->helper( 'file' ); $thumbnail = NULL; $data=file_get_contents( $_FILES['image']['tmp_name'] ); if (class_exists( 'Imagick' ) ) { try { $img = new Imagick(); $img->readImageBlob($data); $img = $this->_create_thumbnail($img); $img->setImageDepth( 24 ); $img->setImageFormat( 'jpeg' ); $thumbnail = $img->getImageBlob(); $img->destroy(); } catch (Exception $e) { $thumbnail = NULL; } } if (!file_exists(DIR_DISTRIBUTEUR_UPLOAD)) { mkdir(DIR_DISTRIBUTEUR_UPLOAD, 0777); } CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file(DIR_DISTRIBUTEUR_UPLOAD , $id, $data); CI_Utils::store_file(DIR_DISTRIBUTEUR_UPLOAD.'/'.DIR_THUMBNAIL, $id, $thumbnail); } } } private function _create_thumbnail( Imagick $im ) { $imW = $im->getImageWidth(); $imH = $im->getImageHeight(); $imR = (float)$imW / (float)$imH; $logoW = 220; $logoH = 200; $logoR = (float)$logoW / (float)$logoH; if ($imW != $logoW || $imH != $logoH) { // is the relation between height and width like we want it to be? if ($imR==$logoR) { // woohoo, easy scale! $im->resizeImage( $logoW, $logoH, imagick::FILTER_BOX, 0 ); } else { // what to scale? if ($imR < $logoR) { // scale by height $im->resizeImage( null, $logoH, imagick::FILTER_BOX, 0 ); $x = ($logoW - $im->getImageWidth()) / 2; $y = 0; } else { // scale by width $im->resizeImage( $logoW, null, imagick::FILTER_BOX, 0 ); $x = 0; $y = ($logoH - $im->getImageHeight()) / 2; } $whiteCol = new ImagickPixel( "rgb(255,255,255)" ); $im2 = new Imagick(); $im2->newImage( $logoW, $logoH, $whiteCol, 'png' ); $im2->setImageDepth( $im->getImageDepth() ); $im2->compositeImage( $im, imagick::COMPOSITE_DEFAULT, $x, $y ); $whiteCol->destroy(); $im->destroy(); $im = $im2; } } return $im; } private function get_search_subquery( $search ) { $conn = get_instance()->db; $query = ' AND ('; $query .= 'users_groups.garage_naam LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.straat LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.toevoeging LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.woonplaats LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.land LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.contactpersoon_technisch LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ' OR users_groups.contactpersoon_functioneel LIKE \'%'. $conn->escape_str( $search ).'%\')'; return $query; } private function filter_group($groups_id){ $groups_id=implode(',', $groups_id); $conn = get_instance()->db; $query = ' AND '; $query .= 'id IN ('.$groups_id.') '; return $query; } public function get_list($search=null, $klant_id, $groups_id=null){ if($klant_id){ $query="select * from users_groups WHERE klant_id=$klant_id"; if($groups_id) $query .= $this->filter_group( $groups_id ); if( $search ) $query .= $this->get_search_subquery( $search ); $res = $this->db->query( $query ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $size = $res->num_rows(); $res->free_result(); if (isset($result)) return $result; } } function get_user_group_by_id( $id ){ if($id){ $sql = "select * from users_groups WHERE id = ?"; $stmt_name = 'distributeurs::by_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $id ) ))) throw new Exception( 'Pbm model exeption by method get_task_by_id' ); $result = $res->result(); if(isset($result[0]))return $this->getr($result[0]); } } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer') ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Themabeheer', 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> <form method="post"> <table style="border-spacing: 5px; width:auto"> <thead> <tr> <? if (!$bewerk): ?> <th align="right">Nummer</th> <? endif; ?> <th align="left">Thema</th> <? if (!$bewerk): ?> <th align="left">Bron</th> <? endif; ?> <th align="right">Nummer</th> <th align="left">Subthema</th> </tr> </thead> <tbody> <? foreach ($themas as $thema): ?> <? $hoofdthema = @$hoofdthemas[$thema->hoofdthema_id]; ?> <? if (!$bewerk): ?> <tr> <td align="right"><?=$hoofdthema ? $hoofdthema->nummer : '-' ?></td> <td><?=$hoofdthema ? $hoofdthema->naam : '-' ?></td> <td><?=$hoofdthema ? $hoofdthema->bron : '-' ?></td> <td align="right"><?=$thema->nummer?></td> <td><?=$thema->thema?></td> </tr> <? else: ?> <tr> <td> <select name="hoofdthema[<?=$thema->id?>]"> <? foreach ($hoofdthemas as $hoofdthema): ?> <option <?=$thema->hoofdthema_id==$hoofdthema->id?'selected':''?> value="<?=$hoofdthema->id?>"><?=$hoofdthema->nummer?>. <?=$hoofdthema->naam?></option> <? endforeach; ?> </select> </td> <? if (!$bewerk): ?> <td><?=$hoofdthema->bron?></td> <? endif; ?> <td align="right"><?=$thema->nummer?></td> <td><?=$thema->thema?></td> </tr> <? endif; ?> <? endforeach; ?> <tr> <? if (!$bewerk): ?> <td align="right"> <input type="button" value="Bewerken" onclick="location.href='<?=site_url('/instellingen/themabeheer/bewerken')?>';" /> </td> <? else: ?> <td> <input type="submit" value="Opslaan" /> <input type="button" value="Annuleren" onclick="if (confirm('Wijzigingen annuleren?')) location.href='<?=site_url('/instellingen/themabeheer')?>';" /> </td> <? endif; ?> </td> </tr> </tbody> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? if ($bewerk): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Thema toevoegen', 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> <form method="post" action="<?=site_url( '/instellingen/hoofdthema_toevoegen' )?>"> <table style="border-spacing: 5px;"> <tr> <th style="width:150px" align="left">Nummer</th> <td><input type="text" name="nummer" size="8" value="<?=$next_hoofdthema_nummer?>" /></td> </tr> <tr> <th style="width:150px" align="left">Naam</th> <td><input type="text" name="naam" size="40" /></td> </tr> <tr> <th style="width:150px" align="left">Bron</th> <td><input type="text" name="bron" size="16" value="Eigen" /></td> </tr> <tr> <th></th> <td><input type="submit" value="Toevoegen" /></td> </tr> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Subthema toevoegen', 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> <form method="post" action="<?=site_url( '/instellingen/thema_toevoegen' )?>"> <table style="border-spacing: 5px;"> <tr> <th style="width:150px" align="left">Nummer</th> <td><input type="text" name="nummer" size="8" value="" /></td> </tr> <tr> <th style="width:150px" align="left">Naam</th> <td><input type="text" name="naam" size="40" /></td> </tr> <tr> <th style="width:150px" align="left">Thema</th> <td> <select name="hoofdthema_id"> <? foreach ($hoofdthemas as $hoofdthema): ?> <option value="<?=$hoofdthema->id?>"><?=$hoofdthema->nummer?>. <?=$hoofdthema->naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <th></th> <td><input type="submit" value="Toevoegen" /></td> </tr> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE bt_richtlijnen ADD COLUMN multi_upload_richtlijnen INT DEFAULT 0 AFTER uploaded_at; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.index::richtlijn_multi_upload', 'Richtlijn multi upload', NOW(), 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.richtlijn_multi_upload::standart_documenten.header', 'Richtlijn multi upload', NOW(), 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.richtlijn_multi_upload::geselecteerde_bescheiden_werkelijk_verwijderen', 'Geselecteerd bescheiden werkelijk verwijderen?', NOW(), 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.richtlijn_multi_upload::upload_file_limit', ' Er is een fout ontstaan tijdens het uploaden van uw documenten. Het is niet mogelijk om meer dan 20 documenten tegelijk te uploaden. ', NOW(), 0); <file_sep> <? $CI = get_instance(); ?> <? if (true || $CI->is_Mobile): ?> <script type="text/javascript"> var defaultMainPanelSize = { width: parseInt( $('#nlaf_MainPanel').css( 'width' ) ), height: parseInt( $('#nlaf_MainPanel').css( 'height' ) ) }; var resizeDesign = function() { // probeer grootte van de window te bepalen var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; } // als dat niet gelukt is, dan nu niks doen! if (myWidth<=0 || myHeight<=0) { return; } // clamp de grootte, niet kleiner maken dan onze standaard grootte if (myWidth < defaultMainPanelSize.width) myWidth = defaultMainPanelSize.width; if (myHeight < defaultMainPanelSize.height) { myHeight = defaultMainPanelSize.height; myWidth -= 20; // compenseer voor scrollbalk } // maar wat er ook gebeurt, nooit kleiner dan onze minima toestaan if (myWidth < 1024 || myHeight < 600) { return; } // bereken hoeveel pixels we extra hebben nu var extraWidth = myWidth - defaultMainPanelSize.width; var extraHeight = myHeight - defaultMainPanelSize.height; // resize de main container $('#nlaf_MainPanel').css( 'width', myWidth + 'px' ).css( 'height', myHeight + 'px' ); // resize de tab list, als daar ruimte voor is var tablistWidth = parseInt( $('#nlaf_TabList').css( 'width' ) ); if (extraWidth > 0) { var extraTabListWidth = extraWidth < 50 ? extraWidth : 50; tablistWidth += extraTabListWidth; $('#nlaf_TabList').css( 'width', tablistWidth + 'px' ); $('#nlaf_PrioPanel').css( 'width', tablistWidth + 'px' ); } // resize de tab contents container $('#nlaf_TabContents').css( 'width', (myWidth - tablistWidth) + 'px' ); $('#nlaf_ViewImage').css( 'width', myWidth + 'px' ); $('#nlaf_PDFAnnotator').css( 'width', myWidth + 'px' ); }; $(document).ready(function(){ resizeDesign(); }); </script> <? endif; ?> </body> </html> <file_sep><?php require_once 'PHPUnit/Autoload.php'; require_once 'ut_utils.php'; require_once 'suites/Colectivematrix_Suite.php'; class Ut extends Controller{ private $suites; public function __construct() { // error_reporting(E_ALL); parent::__construct(); if (!config_item( 'is_ut_defined' )) redirect(); $this->suites = new PHPUnit_Framework_TestSuite( 'Package' ); $this->suites->addTestSuite( 'Colectivematrix_Suite' ); } public function exec(){ PHPUnit_TextUI_TestRunner::run( $this->suites ); } }// Class end <file_sep><?php define( 'REQUEST_RESTORE_COOKIE', 'bristoezicht-request-restore-tag' ); define( 'REQUEST_RESTORE_PATH', dirname(__FILE__) . '/requestrestore/' ); define( 'REQUEST_RESTORE_REDIRECT', '/rr' ); class RequestRestore { private function __is_app_request() { // NOTE: we can never know when we're being called, so use the isset() method // in stead of relying on defines from the Session library! return isset( $_SERVER['PHP_AUTH_USER'] ); } public function has_request_to_restore() { // if this is an APP request, do not restore request! // NOTE: we can never know when we're being called, so use the isset() method // in stead of relying on defines from the Session library! if ($this->__is_app_request()) return false; // no cookie? then nothing to do if (!isset( $_COOKIE[ REQUEST_RESTORE_COOKIE ] )) return false; // empty cookie? then nothing to do if (!$_COOKIE[ REQUEST_RESTORE_COOKIE ]) { $this->_reset(); return false; } // yes! valid and still alive and kicking! return true; } public function store_request() { // if this is an APP request, do not store request! if ($this->__is_app_request()) return; //remove tokens from url $request_uri = $result = preg_replace("/\/token=.+\//i", "/", $_SERVER['REQUEST_URI']); $data = array( 'request_uri' => $request_uri, 'request_method' => $_SERVER['REQUEST_METHOD'], 'get' => $_GET, 'post' => $_POST, 'request' => $_REQUEST, 'files' => $this->_files_to_data( $_FILES ), 'ip' => $_SERVER['REMOTE_ADDR'], ); $tag = sha1( $_SERVER['REMOTE_ADDR'] . microtime(false) . mt_rand() ); $filename = $this->_build_filename( $tag ); if (@file_put_contents( $filename, serialize( $data ) )) setcookie( REQUEST_RESTORE_COOKIE, $tag, time() + 86400*7 /* store for 7 days */, '/' ); else $this->_reset(); } public function restore_request() { if (!$this->has_request_to_restore()) return false; // tag doesn't exist anymore? then nothing todo $tag = $_COOKIE[ REQUEST_RESTORE_COOKIE ]; $filename = $this->_build_filename( $tag ); if (!is_file( $filename ) || (false === ($contents = @file_get_contents( $filename )))) { $this->_reset(); return false; } // we have data in memory, clean up on disk, and the cookie on the client $this->_reset(); unlink( $filename ); // see if data is valid $data = unserialize( $contents ); if (!is_array( $data )) return false; // restore request $_SERVER['REQUEST_URI'] = $data['request_uri']; $_SERVER['REQUEST_METHOD'] = $data['request_method']; $_GET = $data['get']; $_POST = $data['post']; $_REQUEST = $data['request']; $_FILES = $this->_data_to_files( $data['files'] ); // quick winner: GET's never do anything, so if this is a GET, redirect instantly if ($_SERVER['REQUEST_METHOD'] == 'GET') { header('Location: ' . $_SERVER['REQUEST_URI'], true, 302 ); exit; } return true; } public function get_uri_to_restore() { $return_value = ''; if (!$this->has_request_to_restore()) return false; // tag doesn't exist anymore? then nothing todo $tag = $_COOKIE[ REQUEST_RESTORE_COOKIE ]; $filename = $this->_build_filename( $tag ); if (!is_file( $filename ) || (false === ($contents = @file_get_contents( $filename )))) { $this->_reset(); return false; } // Get the data $data = unserialize( $contents ); if (!is_array( $data )) return false; // If we reached this point, simply return the URI part of the request. This is used in a bypass for the telephone interface, without having a full BTZ license. $return_value = (empty($data['request_uri'])) ? false : $data['request_uri']; return $return_value; } private function _files_to_data( array $files ) { foreach ($files as $i => $file) if (isset( $file['tmp_name'] )) $files[$i]['tmp_data'] = @file_get_contents( $file['tmp_name'] ); return $files; } private function _data_to_files( array $files ) { $tmpfiles = array(); foreach ($files as $i => $file) if (isset( $file['tmp_data'] )) { @file_put_contents( $file['tmp_name'], $file['tmp_data'] ); $tmpfiles[] = $file['tmp_name']; } // clean up (fail silently) our newly created temp files register_shutdown_function(function() use ($tmpfiles) { foreach ($tmpfiles as $tmpfile) @unlink( $tmpfile ); }); return $files; } private function _build_filename( $tag ) { return REQUEST_RESTORE_PATH . '/' . $tag . '.request'; } public function _reset() { // clear cookie in this request unset( $_COOKIE[ REQUEST_RESTORE_COOKIE ] ); // set empty string value, and set expire time way back in the past setcookie( REQUEST_RESTORE_COOKIE, '', strtotime( '01-01-2000 00:00:00' ), '/' ); } } <file_sep><? $CI = get_instance(); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); if(isset($klant_id)) $klant = $this->klant->get($klant_id); ?> <? $group_header = array( 'header' => tg('betrokkenen'), 'group_tag' => 'dossier', 'expanded' => $open_tab_group=='betrokkenen', 'width' => '100%', 'height' => $CI->is_Mobile ? '380px' : 'auto', 'defunct' => false, 'rightheader' => null ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', $group_header ); ?> <table style="width: 100%; border-spacing: 5px;"> <tr> <td style="width: 50%" valign="top"> <? $this->load->view( 'elements/laf-blocks/generic-rounded-block-begin', array( 'width' => '100%', 'style' => 'height: 500px', 'header' => tg('overzicht_betrokkenen') ) ); ?> <br/> <? $col_widths = array( 'organisatie' => 120, 'rol' => 120, 'naam' => 190, 'telefoon' => 80, ); $col_description = array( 'organisatie' => tg('organisatie'), 'rol' => tg('rol'), 'naam' => tg('naam'), 'telefoon' => tg('telefoon'), ); $col_unsortable = array( 'rol', 'naam', 'organisatie', 'telefoon' ); $rows = array(); foreach ($subjecten as $i => $subject) { $all_data_html = '<div style="display:none" '; $all_data_html .= 'subject_organisatie_type="' . $subject->organisatie_type . '" '; foreach ($subject->get_array_copy() as $k => $v) { $all_data_html .= 'subject_' . $k . '="' . htmlentities($v, ENT_COMPAT, 'UTF-8') . '" '; } $all_data_html .= '></div>'; $row = (object)array(); $row->onclick = 'selectBetrokkene(' . $subject->id . ');'; $row->data = array(); $row->data['organisatie'] = htmlentities( $subject->organisatie, ENT_COMPAT, 'UTF-8' ) . $all_data_html; $row->data['rol'] = htmlentities( $subject->rol ? $subject->rol : 'Betrokkene', ENT_COMPAT, 'UTF-8' ); $row->data['naam'] = htmlentities( $subject->naam, ENT_COMPAT, 'UTF-8' ); $row->data['telefoon'] = htmlentities( $subject->telefoon, ENT_COMPAT, 'UTF-8' ); // The below piece of code showed only users of type 'andere organisatie' as normal weight and the rest as bold. This resulted in a strange // looking list of names and for that reason everyone is now shown in normal weight. /* if ($subject->gebruiker_id) foreach ($row->data as $k => $v) $row->data[$k] = '<span style="font-weight:bold">' . $v . '</span>'; * */ $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'header' => null, 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => 'nieuweBetrokkene();', 'url' => null, 'scale_field' => 'naam', 'do_paging' => false, 'disable_search' => true, ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-rounded-block-end' ); ?> </td> <td style="width: 50%" valign="top" class="betrokkene-editor"> <? $this->load->view( 'elements/laf-blocks/generic-rounded-block-begin', array( 'width' => '100%', 'style' => 'height: 500px', 'header' => tg('betrokkene_details') ) ); ?> <br/> <input type="hidden" name="subject_id" value="" /> <table id="user_fields" style="width:100%"> <tr> <td></td> <td> <select name="subject_organisatie_type" onchange="updateElementenPerOrganisatieType(this.value, true);"> <option value="<?= SUBJECT_INTERN_ORG ?>"><?=tgn('interne.organisatie')?></option> <option value="<?= SUBJECT_EXTERN_ORG ?>"><?=tgn('andere.organisatie')?></option> <? !$klant->lease_configuratie_id ? print "<option value='".SUBJECT_KID_ORG."'>".tgn('ext-kid.organisatie')."</option>" : "";?> </select> </td> </tr> <tr> <td><?=tg('organisatie')?></td> <td><input id="subject_organisatie" name="subject_organisatie" type="text" size="40" maxlength="128" readonly /></td> </tr> <tr> <td><?=tg('naam')?></td> <td> <input id="subject_naam" name="subject_naam" type="text" size="40" maxlength="128" readonly /> <select name="subject_gebruiker_id" class="hidden" onchange="selectGebruiker(this.value)"> <? foreach ($gebruikers as $gebruiker): if ($gebruiker->status != 'actief' || $gebruiker->speciale_functie != 'geen') continue; ?> <option value="<?=$gebruiker->id?>" subject_naam="<?=htmlentities( $gebruiker->volledige_naam, ENT_COMPAT, 'UTF-8' )?>" subject_organisatie="<?=htmlentities( $gebruiker->get_klant()->naam, ENT_COMPAT, 'UTF-8' )?>" subject_email="<?=htmlentities( $gebruiker->email, ENT_COMPAT, 'UTF-8' )?>" subject_rol="<?=htmlentities( ($r = $gebruiker->get_rol()) ? $r->naam : '', ENT_COMPAT, 'UTF-8' )?>" > <?=htmlentities( $gebruiker->volledige_naam, ENT_COMPAT, 'UTF-8' )?> </option> <? endforeach; ?> </select> </td> </tr> <tr> <td><?=tg('rol')?></td> <td><input name="subject_rol" type="text" size="40" maxlength="40" readonly /></td> </tr> <tr> <td><?=tg('adres')?>:</td> <td><input name="subject_adres" type="text" size="40" maxlength="128" readonly /></td> </tr> <tr> <td><?=tg('postcode')?> / <?=tg('woonplaats')?>:</td> <td><input name="subject_postcode" type="text" size="6" maxlength="7" readonly /> <input name="subject_woonplaats" type="text" size="27" maxlength="128" readonly /></td> </tr> <tr> <td><?=tg('telefoon')?>:</td> <td><input name="subject_telefoon" type="text" size="20" maxlength="40" readonly /></td> </tr> <tr> <td><?=tg('mobiel')?>:</td> <td><input name="subject_mobiel" type="text" size="20" maxlength="40" readonly /></td> </tr> <tr> <td><?=tg('email')?>:</td> <td> <input style="margin-right: 10px" id="subject_email" name="subject_email" type="text" size="40" maxlength="128" readonly onkeypress="if(event.which === 13) { opslaanBetrokkene(); $.Event(event).preventDefault(); }" /> <div id="email_kid_help" style="display: none"><?=htag('email_kid', 'bewerken', 'dossiers')?></div> </td> </tr> </table> <br/> <table width="100%"> <tr> <td style="text-align: center" width="33%" align="center"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '90px', 'text' => tgng('form.verwijderen'), 'blank' => false, 'url' => 'javascript:verwijderBetrokkene();', 'class' => 'redbutton' ) ); ?> </td> <td style="text-align: center" width="33%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '90px', 'text' => tgng('form.wijzigen'), 'blank' => false, 'url' => 'javascript:bewerkBetrokkene();', 'class' => 'graybutton' ) ); ?> </td> <td style="text-align: center" width="33%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '90px', 'text' => tgng('form.opslaan'), 'blank' => false, 'url' => 'javascript:opslaanBetrokkene(0);', 'class' => 'greenbutton' ) ); ?> </td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-rounded-block-end' ); ?> </td> </tr> </table> <script type="text/javascript"> function jd(objToShow) { var debug = false; //var debug = true; if (debug) { window.console && console.log(objToShow); } } function getOrganisatieType() { jd('--- function getOrganisatieType ---'); return $('[name=subject_organisatie_type]').val(); } function updateElementenPerOrganisatieType( value, clear ) { jd('--- function updateElementenPerOrganisatieType ---'); var inputElements = $('input[name^=subject]'); var gebruikerSelect = $('select[name=subject_gebruiker_id]'); var gebruikerInput = $('input[name=subject_naam]'); //console.log(inputElements); //jd(inputElements); //console.log(gebruikerSelect); //console.log(gebruikerInput); if(clear) { inputElements.val(''); } //console.log(value); //console.log('clear: ' + clear); jd('+++ clear +++'); jd(clear); jd('+++ value +++'); jd(value); // First trap the situation where we need to open the message boxes for trying to add a new KennisID user. //if (value == 'kid') if( (value == 'kid') && ((clear !== undefined) && clear) ) { var fullMessage = 'Een externe opdrachtnemer die u wilt toevoegen dient te beschikken over een KennisID.<br />' + 'Indien een externe opdrachtnemer nog geen KennisID heeft, neemt u dan contact op met BRIS via <EMAIL> of 015-3030530.<br /><br />' + 'Wilt u verder gaan met het toevoegen van een externe opdrachtnemer?'; showMessageBox({ message: fullMessage, type: 'warning', buttons: ['ok', 'cancel'], height: 150, width: 600, onClose: function( res ) { jd('Messagebox gesloten'); jd(res); // We only explicitly trap the 'OK' scenario here, by opening the second message box that has the input field for the KennisID. if (res == 'ok') { showKennisIdInput(); } } }); // Return early, so the rest doesn't get executed. return true; } //if( value == 'intern' ) if( (value == 'intern') || (value == 'kid') ) { // Note: because of the (later added) code above, the below "if" part should never match and we // should always end up in the "else" part. Leave it as it is for now and if there is a need/desire later // to remove the "if" construction, do so at that time. if( (value == 'kid') && ((clear !== undefined) && clear) ) { $('#email_kid_help').css('display', 'inline'); inputElements.removeClass('disabled'); $('#user_fields').find('> tbody > tr:not(:first,:last)').hide(); } else { $('#email_kid_help').hide(); $('#user_fields').find('> tbody > tr').show(); //inputElements.addClass( 'disabled' ); //if( (value == 'intern') && ((clear !== undefined) && clear) ) if( (value == 'intern') ) { gebruikerSelect.show(); gebruikerInput.hide(); //selectGebruiker($('select[name=subject_gebruiker_id]').val()); } else { gebruikerSelect.hide(); gebruikerInput.show(); } //selectGebruiker($('select[name=subject_gebruiker_id]').val()); } } else if(value == 'ander') { jd('*** ander ***'); $('#email_kid_help').hide(); $('#user_fields').find('> tbody > tr').show(); inputElements.removeClass( 'disabled' ); gebruikerSelect.hide(); gebruikerInput.show(); } /* else { // ext-kid $('#email_kid_help').css('display', 'inline'); inputElements.removeClass('disabled'); $('#user_fields').find('> tbody > tr:not(:first,:last)').hide(); } */ setBetrokkeneEditable(true); if (value == 'intern') { selectGebruiker($('select[name=subject_gebruiker_id]').val()); } } function showKennisIdInput() { jd('--- function showKennisIdInput ---'); var fullMessage = 'Voer het e-mail adres in om gegevens uit KennisID op te halen. <br /><br /><input id="kid_email" name="kid_email" type="text" size="50" value="">'; showMessageBox({ message: fullMessage, type: 'warning', buttons: ['ok', 'cancel'], height: 150, width: 600, onClose: function( res ) { jd('Messagebox gesloten'); jd(res); // We only explicitly trap the 'OK' scenario here, by opening the second message box that has the input field for the KennisID. if (res == 'ok') { var kid_email = $('#kid_email'); var subject_email = $('#subject_email'); jd('KennisID email'); jd(kid_email.val()); jd('KennisID email form field before'); jd(subject_email.val()); subject_email.val(kid_email.val()); jd('KennisID email form field after'); jd(subject_email.val()); //subject_email.removeClass('disabled'); opslaanBetrokkene(kid_email.val()); } } }); // Done. Return. return true; } function selectGebruiker( id ) { jd('--- function selectGebruiker ---'); // find proper option var gebruikerSelect = $('select[name=subject_gebruiker_id]')[0]; for (var i=0; i<gebruikerSelect.options.length; ++i) if (gebruikerSelect.options[i].value == id) break; if (i == gebruikerSelect.options.length) return; //jd('selectGebruiker::gebruikerSelect.options:'); //jd(gebruikerSelect.options); $('input[name^=subject_]').each(function(){ var val = $(gebruikerSelect.options[i]).attr( $(this).attr('name') ); //jd('selectGebruiker::val: ' + val); if (val !== undefined) $(this).val( val ); }); } function setBetrokkeneCaption( caption ) { jd('--- function setBetrokkeneCaption ---'); $('.betrokkene-editor h3').text( caption ); } function getSelectedBetrokkeneId() { jd('--- function getSelectedBetrokkeneId ---'); var id = $('input[name=subject_id]').val(); if (!id.length) return 0; return parseInt( id ); } function isEditingBetrokkene() { jd('--- function isEditingBetrokkene ---'); return $('select[name=subject_organisatie_type]').attr( 'readonly' ) ? false : true; } function magBetrokkenenEditen() { jd('--- function magBetrokkenenEditen ---'); // slechts een helper, server checkt dit ook return <?=($dossier_access == 'write')?'true':'false'?> } function selectBetrokkene( subject_id, editable ) { jd('--- function selectBetrokkene ---'); var data = $('[subject_id=' + subject_id + ']'); $('input[name^=subject_], select[name^=subject_]').each(function(){ $(this).val( data.attr( $(this).attr('name') ) ); }); updateElementenPerOrganisatieType( data.attr( 'subject_organisatie_type' ) || getOrganisatieType() ); setBetrokkeneEditable( editable ); setBetrokkeneCaption( '<?=tgn('betrokkene_bekijken')?>' ); } function setBetrokkeneEditable( editable ) { jd('--- function setBetrokkeneEditable ---'); jd('+++ editable +++'); jd(editable); var elements = $('input[name^=subject_]:not(.disabled), select[name^=subject_]:not(.disabled)'); //var elements = $('input[name^=subject_], select[name^=subject_]'); //jd(elements); if (editable) { elements.removeAttr( 'disabled' ); elements.removeAttr( 'readonly' ); //elements.prop('disabled', false); //elements.prop('readonly', false); } else { elements.attr( 'disabled', 'disabled' ); elements.attr( 'readonly', 'readonly' ); //elements.prop('disabled', true); //elements.prop('readonly', true); } elements = $('input[name^=subject_].disabled, select[name^=subject_].disabled'); elements.attr( 'disabled', 'disabled' ); elements.attr( 'readonly', 'readonly' ); //elements.prop('disabled', true); //elements.prop('readonly', true); // For KennisID users we make sure the following fields cannot be edited: organisatie, naam, email var organisatieType = getOrganisatieType(); if( (organisatieType == 'kid') ) { jd('+++ KID: disable specific fields +++'); $('#subject_organisatie').addClass( 'disabled' ).attr( 'disabled', 'disabled' ).attr( 'readonly', 'readonly' ); $('#subject_naam').addClass( 'disabled' ).attr( 'disabled', 'disabled' ).attr( 'readonly', 'readonly' ); $('#subject_email').addClass( 'disabled' ).attr( 'disabled', 'disabled' ).attr( 'readonly', 'readonly' ); } return editable; } function bewerkBetrokkene() { jd('--- function bewerkBetrokkene ---'); var selectedBetrokkeneId = getSelectedBetrokkeneId(); //if (!getSelectedBetrokkeneId()) { if (!selectedBetrokkeneId) { alert('<?=tgn('geen_betrokkene_geselecteerd')?>'); return; } if (!magBetrokkenenEditen()) { alert('<?=tgn('geen_rechten_om_betrokkene_te_wijzigen')?>'); return; } setBetrokkeneEditable( true ); var organisatieSelect = $('select[name=subject_organisatie_type]'); organisatieSelect.hide(); setBetrokkeneCaption( '<?=tgn('betrokkene_bewerken')?>' ); } function verwijderBetrokkene() { jd('--- function verwijderBetrokkene ---'); if (!getSelectedBetrokkeneId()) { alert('<?=tgn('geen_betrokkene_geselecteerd')?>'); return; } if (!magBetrokkenenEditen()) { alert('<?=tgn('geen_rechten_om_betrokkene_te_verwijderen')?>'); return; } if (confirm( '<?=tgn('weet_u_zeker_dat_u_deze_betrokkene_wilt_verwijderen')?>' )) { $.ajax({ url: '/dossiers/subject_verwijderen/<?=$dossier->id?>/' + getSelectedBetrokkeneId(), type: 'POST', success: function( data ) { //jd(data); herlaadBetrokkenenHTML( data ); }, error: function() { alert( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } } function nieuweBetrokkene() { jd('--- function nieuweBetrokkene ---'); if (!magBetrokkenenEditen()) { alert('<?=tgn('geen_rechten_om_betrokkene_toe_te_voegen')?>'); return; } selectBetrokkene( 0, true ); setBetrokkeneCaption( '<?=tgn('betrokkene_toevoegen')?>' ); selectGebruiker( $('select[name=subject_gebruiker_id] option:first').val() ); var organisatieSelect = $('select[name=subject_organisatie_type]'); organisatieSelect.show(); } function opslaanBetrokkene(emailForSelectSubject) { jd('--- function opslaanBetrokkene ---'); // Check if we need to select the respective user after the POST call. var selectSubjectByEmail = false; if (typeof emailForSelectSubject === "undefined" || emailForSelectSubject === null || emailForSelectSubject == '') { emailForSelectSubject = ''; } else { selectSubjectByEmail = true; } jd('+++ emailForSelectSubject +++'); jd(emailForSelectSubject); jd('+++ selectSubjectByEmail +++'); jd(selectSubjectByEmail); if (!magBetrokkenenEditen()) { alert('<?=tgn('geen_rechten_om_betrokkenen_op_te_slaan')?>' ); return; } if (!isEditingBetrokkene()) { alert('<?=tgn('geen_betrokkene_aan_het_bewerken_of_toevoegen')?>' ); return; } var data = {}; $('input[name^=subject_], select[name^=subject_]').each(function(){ data[ $(this).attr('name') ] = $(this).val(); }); if (data.subject_organisatie_type == 'ander') delete data.subject_gebruiker_id; $.ajax({ url: '/dossiers/subject_bewerken/<?=$dossier->id?>', type: 'POST', data: data, success: function(data) { try { var response = jQuery.parseJSON(data); alert(response.msg); } catch(e) { // OJG ??? Why in the exception handler?! herlaadBetrokkenenHTML(data); } // herlaadBetrokkenenHTML(data); // If we need to select the user we just processed, do so here if (selectSubjectByEmail) { jd('+++ Selecting subject by email +++'); jd('+++ email for look-up +++'); jd(emailForSelectSubject); // Get the list with existing 'subjects' and search for the one where the email value matches that of the passed value. // Note that we cannot simply use the .attr method oneach element of the listOfExistingSubjects set. Therefore we have to use a slightly // more complex approach by iterating over all attributes of all subjects in the set. var listOfExistingSubjects = $('.list2').find('.contents').find('tr > td > div'); jd('+++ Processing existing subjects +++'); $.each( listOfExistingSubjects, function( idx, existingSubject ) { var selectedSubjectFound = false; var selectedSubjectId = 0; $(existingSubject.attributes).each(function() { // Extract the subject email and check if it matches the passed value. Also extract the subject ID, which we need in // case we found the subject. All other attributes can be disregarded for now. if ( (this.nodeName == 'subject_email') && (this.nodeValue == emailForSelectSubject) ) { selectedSubjectFound = true; } else if (this.nodeName == 'subject_id') { selectedSubjectId = this.nodeValue; } }); // If the subject was found, we select it. if (selectedSubjectFound) { jd('+++ Betrokkene gevonden! +++'); jd('+++ Subject ID: ' + selectedSubjectId + ' +++'); selectBetrokkene( selectedSubjectId, true ); } }); } }, error: function() { alert('<?=tgn('fout_bij_communicatie_met_server')?>'); } }); } function herlaadBetrokkenenHTML( html ) { jd('--- function herlaadBetrokkenenHTML ---'); var base = $('.betrokkenen-container'); base.html( html ); BRISToezicht.Group.visibleGroup['dossier'] = base.find('.group'); } setBetrokkeneEditable( false ); </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end', $group_header ); ?><file_sep>BRISToezicht.Toets.Status = { waardeImage: { 1: '/files/images/nlaf/waardeoordeel-rood.png', 10: '/files/images/nlaf/waardeoordeel-geel.png', 100: '/files/images/nlaf/waardeoordeel-geel.png', 1000: '/files/images/nlaf/waardeoordeel-groen.png' }, waardeKleur: { 1: 'rood', 10: 'geel', 100: 'geel', 1000: 'groen' } }; <file_sep><? require_once 'base.php'; class PbmRiskResult extends BaseResult { function PbmRiskResult( $arr ){ foreach ($arr as $k => $v) $this->$k = $v; } //------------------------------------------------------------------------------ }// Class end class Pbm_risk extends BaseModel { private $_cache = array(); function Pbm_risk(){ parent::BaseModel( 'PbmRiskResult', 'cust_rep_data_155_pbm_sub_taak' ); } //------------------------------------------------------------------------------ function get_risks( $task_id ){ $sql = 'SELECT * FROM cust_rep_data_155_pbm_sub_taak WHERE taak_id = ?'; $stmt_name = 'pbm_risk::all'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $task_id ) ))) throw new Exception( 'Pbm_risk model exeption by method get_risks' ); $result = array(); foreach( $res->result() as $row ){ unset( $row->taak_id ); $row->w = round( $row->wxbxe_w, 2 ); $row->b = round( $row->wxbxe_b, 2 ); $row->e = round( $row->wxbxe_e, 2 ); $row->r = round( $row->wxbxe_w * $row->wxbxe_b * $row->wxbxe_e, 2 ); $row->w = str_replace( ".",",", $row->w ); $row->b = str_replace( ".",",", $row->b ); $row->e = str_replace( ".",",", $row->e ); $row->r = str_replace( ".",",", $row->r ); $result[] = $this->getr( $row ); } return $result; } //------------------------------------------------------------------------------ function get_risk_by_id( $id ){ //$sql = "SELECT * FROM cust_rep_data_155_pbm_sub_taak WHERE id = ? LIMIT 1"; $sql = "SELECT * FROM cust_rep_data_155_pbm_sub_taak WHERE id = ?"; $stmt_name = 'pbm_risk::by_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $id ) ))) throw new Exception( 'Pbm_risk model exeption by method get_risk_by_id' ); $result = $res->result(); $result = $this->getr( $result[0] ); $w = round( $result->wxbxe_w, 2); $b = round( $result->wxbxe_b, 2); $e = round( $result->wxbxe_e, 2); $r = round( $result->wxbxe_w * $result->wxbxe_b * $result->wxbxe_e, 2); $result->w = str_replace( ".",",", $w ); $result->b = str_replace( ".",",", $b ); $result->e = str_replace( ".",",", $e ); $result->r = str_replace( ".",",", $r ); return $result; } //------------------------------------------------------------------------------ public function save( PbmResult $task, array $postdata ){ $postdata['taak_id'] = (int)$task->id; if( $postdata['id'] == '' ){ unset($postdata['id']); return $this->insert( $postdata ); }else{ return parent::save( (object)$postdata, true, null, false ); } } //------------------------------------------------------------------------------ }// Class end <file_sep>ALTER TABLE `webservice_applicatie_bescheiden` ADD PRIMARY KEY ( `id` ) ; ALTER TABLE `webservice_applicatie_bescheiden` CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT ; ALTER TABLE `webservice_applicatie_dossiers` ADD PRIMARY KEY ( `id` ) ; ALTER TABLE `webservice_applicatie_dossiers` CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT ; <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_layers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `dossier_bescheiden_id` int(11) NOT NULL, `layer_data` longtext NOT NULL, `pagetransform_data` LONGTEXT NOT NULL, `laatst_bijgewerkt_op` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `deelplan_id_2` (`deelplan_id`,`dossier_bescheiden_id`), KEY `dossier_bescheiden_id` (`dossier_bescheiden_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `deelplan_layers` ADD CONSTRAINT `deelplan_layers_ibfk_2` FOREIGN KEY (`dossier_bescheiden_id`) REFERENCES `dossier_bescheiden` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_layers_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <!-- gebruikersbeheer fake --> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Gebruikersbeheer', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/gebruikers') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <!-- rollenbeheer --> <? if (APPLICATION_HAVE_ROLLENBEHEER): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Rollenbeheer', 'expanded' => false, 'onclick' => 'location.href=\'' . site_url('/instellingen/rollenbeheer') . '\';', 'width' => '100%', 'height' => null, 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => null ) ); ?> <? endif;?> <!-- rollenbeheer --> <? if($this->gebruiker->get_logged_in_gebruiker()->get_klant()->usergroup_activate == 1):?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('users_group'), 'expanded' => true, 'onclick' => '', 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('gebruikersbeheer'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => null, 'width' => '100%' )); ?> <input type="button" value="<?=tgn('maak_een_nieuw_nieuw_distributeur')?>" onclick="location.href='<?=site_url('/beheer/show_user_group_form')?>'"/> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <?=htag('nieuw_dossier')?> <? $col_widths = array( 'editicon' => 32 ); $col_description = array( 'editicon' => '&nbsp;' ); $col_widths = array_merge( $col_widths, array( 'garage_naam' => 250, 'straat' => 150, 'huisnummer' => 150, 'toevoeging' => 150, 'postcode' => 150, 'woonplaats' => 150, 'land' => 150, 'kvk_nummer' => 150, 'btw_nummer' => 150, 'contactpersoon_technisch' => 150, 'contactpersoon_functioneel' => 150, ) ); $col_description = array_merge( $col_description, array( 'garage_naam' => 'Garage naam', 'straat' => 'Straat', 'huisnummer' => 'Huisnummer', 'toevoeging' => 'Toevoeging', 'postcode' => 'Postcode', 'woonplaats' => 'Woonplaats', 'land' => 'Land', 'kvk_nummer' => 'KVK nummer', 'btw_nummer' => 'BTW nummer', 'contactpersoon_technisch' => 'Contactpersoon technisch', 'contactpersoon_functioneel' => 'Contactpersoon functioneel', ) ); if ($this->is_Mobile) { unset( $col_widths['counts'] ); unset( $col_description['counts'] ); } $rows = array(); foreach ($data as $value){ $row = (object)array(); $row->onclick = "location.href='" . site_url('/beheer/show_user_group_form/' . $value->id) . "'"; $row->data = array(); $row->data['garage_naam'] = htmlentities( $value->garage_naam, ENT_COMPAT, 'UTF-8' ); $row->data['straat']=$value->straat; $row->data['huisnummer']=$value->huisnummer; $row->data['toevoeging']=$value->toevoeging; $row->data['postcode']=$value->postcode; $row->data['woonplaats']=$value->woonplaats; $row->data['land']=$value->land; $row->data['kvk_nummer']=$value->kvk_nummer; $row->data['btw_nummer']=$value->btw_nummer; $row->data['contactpersoon_technisch']=$value->contactpersoon_technisch; $row->data['contactpersoon_functioneel']=$value->contactpersoon_functioneel; $row->data['verwijderen'] = ' <a href="javascript:void(0);" onclick="eventStopPropagation(event); if (confirm(\'User group ' . htmlentities( $value->garage_naam, ENT_COMPAT, 'UTF-8' ) . '&quot; werkelijk verwijderen? Deze actie kan niet ongedaan gemaakt worden!\nEventuele gebruikers met deze rol zullen geen rol en daarmee geen rechten meer hebben!\')) location.href=\'/instellingen/delete_user_group/' . $value->id . '\';"> <img src="' . site_url('/files/images/delete.png') . '" /> </a> '; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'header' => '', 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, //'new_button_js' => "location.href='/instellingen/distributeur';", 'url' => '/instellingen/users_groups', 'scale_field' => 'verwijderen', 'do_paging' => true, 'viewdata' =>$viewdata, ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <?endif;?> <? $this->load->view('elements/footer'); ?><file_sep> REPLACE INTO `teksten` (`string`,`tekst`,`timestamp`,`lease_configuratie_id`) VALUES ('dossiers.bewerken::rapportage-organisatiekenmerken.header','Organisatiekenmerken (betaversie)',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::bedrijf','Bedrijf',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::bezoekadres','Bezoekadres',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::postadres','Postadres',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::telefoon','Telefoon',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::contactpersoon','Contactpersoon',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::preventiemedewerker','Preventiemedewerker',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::branche','Branche',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::bedrijfsactiviteiten','Bedrijfsactiviteiten',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::productieproces','Productieproces',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::bedrijfslocatie','Bedrijfslocatie',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::projectlocatie','Projectlocatie',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::productie_en','Productie- en transportmiddelen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::personen_werkzaam','Personen werkzaam',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::leeftijd','Leeftijd',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::less_18_jaar','< 18 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::18_20_jaar','18 - 20 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::21_30_jaar','21 - 30 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::31_40_jaar','31 - 40 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::41_50_jaar','41 - 50 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::51_60_jaar','51 - 60 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::61_65_jaar','61 - 65 jaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::aantal_fte','Aantal fte',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::bijzondere_groepen','Bijzondere groepen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::minder_validen','Minder validen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::zwangeren','Zwangeren',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::jeugdigen','Jeugdigen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::allochtonen','Allochtonen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::thuiswerkers','Thuiswerkers',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::inleenkrachten','Inleenkrachten',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::oproepkrachten','Oproepkrachten',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::wwb_ers','WWB-ers',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::werktijden_en_overwerk','Werktijden (en overwerk)',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::functies_voor','In het bedrijf komen de volgende functies voor',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ziekteverzuimcijfers','Ziekteverzuimcijfers afgelopen kalenderjaar',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::verzuimpercentage','Verzuimpercentage:',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::meldingsfrequentie','Meldingsfrequentie:',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::verzuimduur','Verzuimduur:',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::wao_wia_toetreding_1','WAO/WIA-toetreding',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::wao_wia_toetreding_2','Afgelopen 3 jaar maanden is (zijn)',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::wao_wia_toetreding_3','werknemer(s) de WIA ingegaan.',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ongevallencijfers_1','Ongevallencijfers en genomen maatregelen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ongevallencijfers_2','Uit informatie van de organisatie blijkt dat zich',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ongevallencijfers_3','ongeval(len) heeft (hebben) voorgedaan de afgelopen 3 jaar.',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::geconstateerde_beroepsziekten','Geconstateerde beroepsziekten',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ziekteverzuimbegeleiding_1','Ziekteverzuimbegeleiding',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::ziekteverzuimbegeleiding_2','Wordt uitgevoerd door:',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::gezondheidskundig_onderzoek_1','Periodiek ArbeidsGezond-heidskundig Onderzoek',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::gezondheidskundig_onderzoek_2','Heeft',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::gezondheidskundig_onderzoek_3','plaatsgevonden',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::successfully_saved','Succesvol opgeslagen',NOW(),0) ,('dossiers.rapportage_organisatiekenmerken::error_not_saved','Er is een fout opgetreden. De gegevens zijn niet succesvol opgeslagen.',NOW(),0) ; DROP TABLE IF EXISTS `custom_report_data_155_organisatie_kenmerken`; CREATE TABLE custom_report_data_155_organisatie_kenmerken ( id int(11) NOT NULL AUTO_INCREMENT, dossier_id int(11) NOT NULL, bedrijf varchar(255) DEFAULT NULL, bezoekadres varchar(255) DEFAULT NULL, postadres varchar(255) DEFAULT NULL, telefoon varchar(255) DEFAULT NULL, contactpersoon varchar(255) DEFAULT NULL, preventiemedewerker varchar(255) DEFAULT NULL, branche varchar(255) DEFAULT NULL, bedrijfsactiviteiten varchar(255) DEFAULT NULL, productieproces varchar(255) DEFAULT NULL, bedrijfslocatie varchar(255) DEFAULT NULL, projectlocatie varchar(255) DEFAULT NULL, productie_en varchar(255) DEFAULT NULL, personen_werkzaam varchar(255) DEFAULT NULL, jaar_less_18 varchar(255) DEFAULT NULL, jaar_18_20 varchar(255) DEFAULT NULL, jaar_21_30 varchar(255) DEFAULT NULL, jaar_31_40 varchar(255) DEFAULT NULL, jaar_41_50 varchar(255) DEFAULT NULL, jaar_51_60 varchar(255) DEFAULT NULL, jaar_61_65 varchar(255) DEFAULT NULL, aantal_fte varchar(255) DEFAULT NULL, minder_validen varchar(255) DEFAULT NULL, zwangeren varchar(255) DEFAULT NULL, jeugdigen varchar(255) DEFAULT NULL, allochtonen varchar(255) DEFAULT NULL, thuiswerkers varchar(255) DEFAULT NULL, inleenkrachten varchar(255) DEFAULT NULL, oproepkrachten varchar(255) DEFAULT NULL, wwb_ers varchar(255) DEFAULT NULL, werktijden_en_overwerk varchar(255) DEFAULT NULL, functies_voor varchar(255) DEFAULT NULL, verzuimpercentage varchar(255) DEFAULT NULL, meldingsfrequentie varchar(255) DEFAULT NULL, verzuimduur varchar(255) DEFAULT NULL, wao_wia_toetreding varchar(255) DEFAULT NULL, ongevallencijfers varchar(255) DEFAULT NULL, geconstateerde_beroepsziekten varchar(255) DEFAULT NULL, ziekteverzuimbegeleiding varchar(255) DEFAULT NULL, gezondheidskundig_onderzoek varchar(255) DEFAULT NULL, PRIMARY KEY (id), UNIQUE INDEX UK_custom_report_data_155_organisatie_kenmerken_dossier_id (dossier_id), CONSTRAINT FK_custom_report_data_155_organisatie_kenmerken_dossiers_id FOREIGN KEY (dossier_id) REFERENCES dossiers (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; <file_sep><?php class CI_PrioriteitStelling { private $db; private $dbex; private $cache = array(); public function __construct() { $CI = get_instance(); $this->db = $CI->db; $this->dbex = $CI->dbex; $CI->load->model( 'checklist' ); } // loads all available prioriteitstellingen at once, for overview pages public function lookup_all($matrix_id=NULL) { $klant_id = get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id; $db_order_by_null_clause = get_db_order_by_null_clause(); $sub_where = $matrix_id ? " and ps.matrix_id=".$matrix_id :''; $res = $this->db->query( ' SELECT ps.*, c.id AS existing_checklist_id FROM bt_prioriteitstellingen ps RIGHT JOIN bt_checklisten c ON (ps.checklist_id = c.id AND ps.klant_id = ' . $klant_id . ') JOIN bt_checklist_groepen cg ON c.checklist_groep_id = cg.id WHERE cg.klant_id = ' . $klant_id .$sub_where. ' ORDER BY ps.checklist_id ' . $db_order_by_null_clause ); foreach ($res->result() as $row) { $matrix_id = $row->matrix_id; if ($matrix_id) { // not yet any data for this matrix? then load it now if (!isset( $this->cache[ $matrix_id ] )) $this->cache[ $matrix_id ] = array(); // if this checklist ID already has a loaded prioriteitstelling, skip this row if (isset( $this->cache[ $matrix_id ][ $row->existing_checklist_id ] )) continue; // either load prioriteitstelling, or set to null if ($row->checklist_id) $this->cache[ $matrix_id ][ $row->existing_checklist_id ] = new PrioriteitStelling( $row->id, $row->checklist_id, $row->gemaakt_op, $row->matrix_id ); else $this->cache[ $matrix_id ][ $row->existing_checklist_id ] = null; } else { // we've come to the list of existing checklist's that don't have any prioriteitstelling at all foreach ($this->cache as $matrix_id => $prioriteitstellingen) $this->cache[$matrix_id][ $row->existing_checklist_id ] = null; } } $res->free_result(); // now make sure that all checklist ID's are available in all matrix arrays, // so that we won't accidentally make any new ones automatically where such is // not required foreach ($this->cache as $matrix_id => $prioriteitstellingen) foreach ($prioriteitstellingen as $checklist_id => $unused) foreach ($this->cache as $matrix_id2 => $prioriteitstellingen2) if ($matrix_id != $matrix_id2) if (!isset( $this->cache[$matrix_id2][$checklist_id] )) $this->cache[$matrix_id2][$checklist_id] = null; } // finds or creates new prioriteitstelling for checklist public function lookup_or_create( $matrix_id, $checklist_id, $create_if_not_exists=true ) { if (!$checklist_id) return NULL; $matrix_id = intval( $matrix_id ); $checklist_id = intval( $checklist_id ); if (!array_key_exists( $matrix_id, $this->cache )) $this->cache[$matrix_id] = array(); if (!array_key_exists( $checklist_id, $this->cache[$matrix_id] ) || $create_if_not_exists) { $this->cache[$matrix_id][ $checklist_id ] = $this->_lookup( $matrix_id, $checklist_id ); if (!$this->cache[$matrix_id][ $checklist_id ]) { if (!$create_if_not_exists) { return null; } $this->cache[$matrix_id][ $checklist_id ] = $this->_create( $matrix_id, $checklist_id ); } } return $this->cache[$matrix_id][ $checklist_id ]; } // finds risicoanalyse for checklist, returns null when not in database public function lookup( $matrix_id, $checklist_id ) { if (!$checklist_id) return NULL; $matrix_id = intval( $matrix_id ); $checklist_id = intval( $checklist_id ); if (!array_key_exists( $matrix_id, $this->cache )) $this->cache[$matrix_id] = array(); if (!array_key_exists( $checklist_id, $this->cache[$matrix_id] )) { $this->cache[$matrix_id][ $checklist_id ] = $this->_lookup( $checklist_id ); } return $this->cache[$matrix_id][ $checklist_id ]; } // lookup, returns null when non-existent // NOTE: does NOT read from or write to $this->cache private function _lookup( $matrix_id, $checklist_id ) { // // NOTE: niet eisen dat klant_id gelijk is aan de klant_id van de ingelogde gebruiker, anders kan je nooit // matrices van een andere aanbieder gebruiken! // $stmt = 'PrioriteitStelling::_lookup'; $this->dbex->prepare( $stmt, 'SELECT * FROM bt_prioriteitstellingen WHERE checklist_id = ? AND matrix_id = ?', $this->db ); $res = $this->dbex->execute( $stmt, array( $checklist_id, $matrix_id ), false, $this->db ); if ($res->num_rows() == 0) { $res->free_result(); return null; } else { $rows = $res->result(); $data = reset( $rows ); $res->free_result(); return new PrioriteitStelling( $data->id, $data->checklist_id, $data->gemaakt_op, $data->matrix_id ); } } // creates new prioriteitstelling in db, throws exception on failure. // NOTE: does NOT read from or write to $this->cache private function _create( $matrix_id, $checklist_id ) { // The SOAP code that generates reports (i.e. the 'soapDossier' service, in the 'soapGetDeelplanResults' method) comes across this point without being // logged in. At that time it is not possible to successfully determine the proper 'klant_id'. // Make sure to properly detect and trap this situation, and to use an overridden klant_id! if ( defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_klant_id'])) { $use_klant_id = $_POST['overridden_klant_id']; } else { $use_klant_id = get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id; } // The below query is now "Oracle-safe" // create in database $stmt = 'PrioriteitStelling::_create1'; //$this->dbex->prepare( $stmt, 'INSERT INTO bt_prioriteitstellingen (checklist_id, klant_id, matrix_id) VALUES (?, ?, ?)', $this->db ); $this->dbex->prepare_with_insert_id( $stmt, 'INSERT INTO bt_prioriteitstellingen (checklist_id, klant_id, matrix_id) VALUES (?, ?, ?)', $this->db, $last_insert_id ); $res = $this->dbex->execute( $stmt, array( $checklist_id, $use_klant_id, $matrix_id ), false, $this->db ); if (!$res) throw new Exception( 'Fout bij aanmaken prioriteitstelling in de database.' ); $risicoanalyse_id = (get_db_type() == 'oracle') ? $last_insert_id : $this->db->insert_id(); // lookup regularly $ps = $this->_lookup( $matrix_id, $checklist_id ); if (!$ps) throw new Exception( 'Fout bij ophalen nieuw aangemaakte prioriteitstelling.' ); return $ps; } public function delete( $matrix_id, $checklist_id ) { $stmt = 'PrioriteitStelling::delete'; $this->dbex->prepare( $stmt, 'DELETE FROM bt_prioriteitstellingen WHERE checklist_id = ? AND klant_id = ? AND matrix_id = ?', $this->db ); $res = $this->dbex->execute( $stmt, array( $checklist_id, get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, $matrix_id ), false, $this->db ); if (!$res) throw new Exception( 'Fout bij verwijderen prioriteitstelling uit de database.' ); unset( $this->cache[$matrix_id][$checklist_id] ); } public function get_db() { return $this->db; } public function store_override( $deelplan_id, $hoofdgroep_id, $new_prio ) { $stmt_name = 'Prioriteitstelling::store_override'; //if (!$this->dbex->prepare( $stmt_name, 'REPLACE INTO deelplan_prioriteit_overrides (deelplan_id, hoofdgroep_id, prioriteit) VALUES (?, ?, ?)' )) //if (!$this->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO deelplan_prioriteit_overrides (deelplan_id, hoofdgroep_id, prioriteit) VALUES (?, ?, ?)', null, array('id', 'deelplan_id', 'hoofdgroep_id') )) if (!$this->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO deelplan_prioriteit_overrides (deelplan_id, hoofdgroep_id, prioriteit) VALUES (?, ?, ?)', null, array('deelplan_id', 'hoofdgroep_id') )) throw new Exception( 'Database fout bij voorbereiden prepared statement.' ); if (!($res = $this->dbex->execute( $stmt_name, array( $deelplan_id, $hoofdgroep_id, $new_prio ) ) )) throw new Exception( 'Database fout bij uitvoeren prepared statement.' ); } } class PrioriteitStelling { private $id; private $checklist_id; private $checklist = null; private $gemaakt_op; private $matrix_id; private $waarden = null; // becomes array after first get_ call private $waarden_dirty = array(); static private $overrides_per_deelplan = array(); public function __construct( $id, $checklist_id, $gemaakt_op, $matrix_id ) { $this->id = $id; $this->checklist_id = $checklist_id; $this->gemaakt_op = $gemaakt_op; $this->matrix_id = $matrix_id; } public function get_gemaakt_op() { return $this->gemaakt_op; } public function get_checklist_id() { return $this->checklist_id; } public function get_matrix_id() { return $this->matrix_id; } public function get_checklist() { if (is_null( $this->checklist )) $this->checklist = get_instance()->checklist->get( $this->checklist_id ); return $this->checklist; } function get_waarden() { if (!is_array( $this->waarden )) $this->get_waarde( null, null ); // loads cache return $this->waarden; } function get_gemiddelde_waarde( $hoofdgroep_id, $deelplan_id=null ) { $hg = get_instance()->hoofdgroep->get( $hoofdgroep_id ); if (!$hg) return; $prios = array( 'zeer_laag' => 0, 'laag' => 1, 'gemiddeld' => 2, 'hoog' => 3, 'zeer_hoog' => 4 ); $aantal_vragen = 0; $gemiddelde_prio = 0; foreach ($hg->get_hoofdthemas() as $hoofdthema) { $waarde = $this->get_waarde( $hoofdgroep_id, $hoofdthema['hoofdthema']->id, $deelplan_id ); if (!$waarde) $waarde = 'zeer_hoog'; $aantal_vragen += $hoofdthema['aantal_vragen']; $gemiddelde_prio += $hoofdthema['aantal_vragen'] * $prios[$waarde]; } if (!$aantal_vragen) return false; $gemprio = $aantal_vragen ? round( $gemiddelde_prio / $aantal_vragen ) : 0; $prios = array_flip( $prios ); return $prios[$gemprio]; } function get_waarde( $hoofdgroep_id, $hoofdthema_id, $deelplan_id=null ) { $dbex = get_instance()->dbex; if (!is_array( $this->waarden )) { $this->waarden = array(); $stmt = 'PrioriteitStelling::get_waarde1'; $db = get_instance()->prioriteitstelling->get_db(); $dbex->prepare( $stmt, 'SELECT hoofdgroep_id, hoofdthema_id, waarde FROM bt_prioriteitstelling_waarden WHERE prioriteitstelling_id = ?', $db ); $res = $dbex->execute( $stmt, array( $this->id ), false, $db ); foreach ($res->result() as $row) { if (!isset( $this->waarden[ $row->hoofdgroep_id ] )) $this->waarden[ $row->hoofdgroep_id ] = array(); $this->waarden[ $row->hoofdgroep_id ][ $row->hoofdthema_id ] = $row->waarde; } $res->free_result(); } if ($deelplan_id) { // load overrides for given deelplan if not yet loaded if (!isset( self::$overrides_per_deelplan[ $deelplan_id ] )) { self::$overrides_per_deelplan[ $deelplan_id ] = array(); $stmt = 'PrioriteitStelling::get_waarde2'; $db = get_instance()->db; $dbex->prepare( $stmt, 'SELECT hoofdgroep_id, prioriteit FROM deelplan_prioriteit_overrides WHERE deelplan_id = ?', $db ); $res = $dbex->execute( $stmt, array( $deelplan_id ), false, $db ); foreach ($res->result() as $row) { self::$overrides_per_deelplan[ $deelplan_id ][ $row->hoofdgroep_id ] = $row->prioriteit; } $res->free_result(); } // check override! if (isset( self::$overrides_per_deelplan[ $deelplan_id ][ $hoofdgroep_id ] )) return self::$overrides_per_deelplan[ $deelplan_id ][ $hoofdgroep_id ]; } if (isset( $this->waarden[ $hoofdgroep_id ] )) if (isset( $this->waarden[ $hoofdgroep_id ][ $hoofdthema_id ] )) return $this->waarden[ $hoofdgroep_id ][ $hoofdthema_id ]; return ''; } public function set_waarde( $hoofdgroep_id, $hoofdthema_id, $waarde ) { if (!isset( $this->waarden[ $hoofdgroep_id ] ) || !isset( $this->waarden[ $hoofdgroep_id ][ $hoofdthema_id ] ) || $this->waarden[ $hoofdgroep_id ][ $hoofdthema_id ] != $waarde) { // store in list that keeps track of changes to DB if (!isset( $this->waarden_dirty[ $hoofdgroep_id ] )) $this->waarden_dirty[ $hoofdgroep_id ] = array(); $this->waarden_dirty[ $hoofdgroep_id ][ $hoofdthema_id ] = $waarde; // store locally if (!isset( $this->waarden[ $hoofdgroep_id ] )) $this->waarden[ $hoofdgroep_id ] = array(); $this->waarden[ $hoofdgroep_id ][ $hoofdthema_id ] = $waarde; } } function update_db( $db ) { if (!empty( $this->waarden_dirty )) { $db = get_instance()->prioriteitstelling->get_db(); $dbex = get_instance()->dbex; $stmt = 'PrioriteitStelling::update_db_waarden'; //$dbex->prepare( $stmt, 'REPLACE INTO bt_prioriteitstelling_waarden (waarde, prioriteitstelling_id, hoofdgroep_id, hoofdthema_id) VALUES (?, ?, ?, ?)', $db ); $dbex->prepare_replace_into( $stmt, 'REPLACE INTO bt_prioriteitstelling_waarden (waarde, prioriteitstelling_id, hoofdgroep_id, hoofdthema_id) VALUES (?, ?, ?, ?)', $db, array('id', 'prioriteitstelling_id', 'hoofdgroep_id', 'hoofdthema_id') ); foreach ($this->waarden_dirty as $hoofdgroep_id => $waarden) foreach ($waarden as $hoofdthema_id => $waarde ) if (!$dbex->execute( $stmt, array( $waarde, $this->id, $hoofdgroep_id, $hoofdthema_id ), false, $db )) throw new Exception( 'Fout bij opslaan van waarden van prioriteitstelling in database.' ); $this->waarden_dirty = array(); } } } <file_sep>ALTER TABLE `bt_checklist_groepen` CHANGE `integreerbare_checklisten` `modus` VARCHAR( 32 ) NOT NULL DEFAULT 'combineerbaar'; UPDATE bt_checklist_groepen SET modus = 'combineerbaar' WHERE modus = '1'; UPDATE bt_checklist_groepen SET modus = 'niet-combineerbaar' WHERE modus = '0'; ALTER TABLE `bt_checklist_groepen` CHANGE `modus` `modus` ENUM( 'combineerbaar', 'niet-combineerbaar', 'combineerbaar-op-checklist' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'combineerbaar'; <file_sep>DELETE FROM `teksten` WHERE NOT 1=1 OR `string` LIKE '%rapportage-pago_pmo.header%' OR `string` LIKE '%rapportage_pago_pmo%' OR `string` LIKE '%show_pago_pmo_form%'; REPLACE INTO `teksten` (`string`,`tekst`,`timestamp`,`lease_configuratie_id`) VALUES ('dossiers.bewerken::rapportage-pago_pmo.header','PAGO/PMO (betaversie)',NOW(),0) ,('dossiers.rapportage_pago_pmo::functie','Functie',NOW(),0) ,('dossiers.rapportage_pago_pmo::n_medewerkers','Aantal medewerkers',NOW(),0) ,('dossiers.rapportage_pago_pmo::beeldschermwerk','beeldschermwerk',NOW(),0) ,('dossiers.rapportage_pago_pmo::biologische_agentia','biologische agentia',NOW(),0) ,('dossiers.rapportage_pago_pmo::gevaarlijke_stoffen','gevaarlijke stoffen',NOW(),0) ,('dossiers.rapportage_pago_pmo::schadelijk_geluid','schadelijk geluid',NOW(),0) ,('dossiers.rapportage_pago_pmo::fysieke_belasting','fysieke belasting',NOW(),0) ,('dossiers.rapportage_pago_pmo::werkdruk_belasting','Werkdruk en mentale belasting',NOW(),0) ,('dossiers.rapportage_pago_pmo::onderwerp','Onderwerp',NOW(),0) ,('dossiers.rapportage_pago_pmo::no_items_found','Er zijn nog geen gegevens ingevoerd.',NOW(),0) ,('dossiers.show_pago_pmo_form::functie','Functie',NOW(),0) ,('dossiers.show_pago_pmo_form::n_medewerkers','Aantal medewerkers',NOW(),0) ,('dossiers.show_pago_pmo_form::beeldschermwerk','beeldschermwerk',NOW(),0) ,('dossiers.show_pago_pmo_form::biologische_agentia','biologische agentia',NOW(),0) ,('dossiers.show_pago_pmo_form::gevaarlijke_stoffen','gevaarlijke stoffen',NOW(),0) ,('dossiers.show_pago_pmo_form::schadelijk_geluid','schadelijk geluid',NOW(),0) ,('dossiers.show_pago_pmo_form::fysieke_belasting','fysieke belasting',NOW(),0) ,('dossiers.show_pago_pmo_form::werkdruk_belasting','Werkdruk en mentale belasting',NOW(),0) ,('dossiers.show_pago_pmo_form::onderwerp','Onderwerp',NOW(),0) ,('dossiers.show_pago_pmo_form::successfully_saved','Succesvol opgeslagen',NOW(),0) ,('dossiers.show_pago_pmo_form::error_not_saved','Er is een fout opgetreden. De gegevens zijn niet succesvol opgeslagen.',NOW(),0) ; DROP TABLE IF EXISTS `custom_report_data_155_pago_pmo`; CREATE TABLE `custom_report_data_155_pago_pmo` ( id int(11) NOT NULL AUTO_INCREMENT, dossier_id int(11) NOT NULL, functie varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, n_medewerkers int(11) DEFAULT 1, beeldschermwerk varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, biologische_agentia varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, gevaarlijke_stoffen varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, schadelijk_geluid varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, fysieke_belasting varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, werkdruk_belasting varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_custom_report_data_155_pago_pmo_dossiers_id FOREIGN KEY (dossier_id) REFERENCES dossiers (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'Pago/Pomo table'; <file_sep><?php class DossierExportStandaard extends DossierExportPDFBase { const FONTNAME = 'dejavusans'; const FONTSIZE = 9; const FONTHEADERSIZE = 12; private $deelplannen = array(); private $deelplan_vragen = array(); private $deelplan_prioriteiten = array(); private $deelplan_bescheiden = array(); private $deelplan_vraag_bescheiden = array(); private $deelplan_toelichtinggeschiedenis = array(); private $deelplan_uploads = array(); private $deelplan_hoofdgroepstatussen = array(); // alleen voor bevindingen, niet voor samenvatting! private $deelplan_vraag_subjecten = array(); private $deelplan_aandachtspunten = array(); private $checklistgroep_grondslagen = array(); private $checklistgroep_richtlijnen = array(); private $waardeoordelen = array(); private $betrokkenen = null; private $item_number = 0; private $item_count = 0; public function get_tcpdf_classname() { return 'DossierStandaardTCPDF'; } /******************************************************************************** * * * MAIN FUNCTIONS * * * ********************************************************************************/ protected function _generate() { // init models $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'deelplanchecklistgroep' ); $this->_CI->load->model( 'deelplanthema' ); $this->_CI->load->model( 'hoofdthema' ); $this->_CI->load->model( 'thema' ); $this->_CI->load->model( 'matrix' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'deelplanbescheiden' ); $this->_CI->load->model( 'deelplanvraagbescheiden' ); $this->_CI->load->model( 'deelplanvraaggeschiedenis' ); $this->_CI->load->model( 'deelplanupload' ); $this->_CI->load->model( 'dossierbescheiden' ); $this->_CI->load->model( 'deelplansubjectvraag' ); $this->_CI->load->model( 'grondslagtekst' ); $this->_CI->load->library( 'prioriteitstelling' ); $this->_CI->load->library( 'quest' ); $this->_CI->load->library( 'pdfannotatorlib' ); // make sure our own custom TCPDF object knows what klant we're dealing with, // and get a reference to ourself, for page headers with logo's and stuff :) $this->_tcpdf->set_references( $this ); // init data we need (multiple) times during document generation $this->_init_data(); $this->_init_status_filter(); $this->_init_betrokkene_filter(); // initialize progress $this->_init_progress(); // set creator, author, etc. $this->_initialize_meta_data(); // generate content $this->_generate_front_page(); $this->_generate_disclaimer_page(); $this->_generate_inleiding_pages(); $this->_tcpdf->AddPage(); $this->_generate_dossier_gegevens(); $this->_generate_documenten_lijst(); $this->_generate_deelplannen_lijst(); $this->_tcpdf->EndPage(); $this->_generate_samenvatting(); $this->_generate_bevindingen(); $bijlage_nr = 1; $this->_generate_foto_bijlage( $bijlage_nr ); $this->_generate_documenten_bijlage( $bijlage_nr ); $this->_generate_juridische_grondslag_bijlage( $bijlage_nr ); // generate TOC $this->_generate_toc(); } private function _init_data() { $dos = $this->get_dossier(); $this->toon_aandachtspunten = array_key_exists( 'aandachtspunten', $this->get_filter( 'onderdeel' )); foreach ($dos->get_deelplannen() as $j => $deelplan) { // Note: the commented out part was used for allowing multiple deelplan selections using checkboxes. This is currently no longer supported and // instead a single deelplan is chosen, using a radio button. The old code is left here, commented out, in case we need to support multiple // deelplan selections too again. The code has been made backwards compatible. //if (!@array_key_exists( $deelplan->id, $this->get_filter( 'deelplan' ))) // continue; $selected_deelplan = $this->get_filter( 'deelplan' ); $include_deelplan = ( (is_array($selected_deelplan) && array_key_exists( $deelplan->id, $selected_deelplan)) || (!is_array($selected_deelplan) && ( $deelplan->id == $selected_deelplan)) ); if (!$include_deelplan) continue; $this->deelplannen[] = $deelplan; $this->deelplan_vragen[$deelplan->id] = array(); $this->deelplan_prioriteiten[$deelplan->id] = array(); $this->deelplan_bescheiden[$deelplan->id] = $this->_CI->deelplanbescheiden->get_by_deelplan( $deelplan->id ); $this->deelplan_vraag_bescheiden[$deelplan->id] = $this->_CI->deelplanvraagbescheiden->get_by_deelplan( $deelplan->id ); $this->deelplan_toelichtinggeschiedenis[$deelplan->id] = $this->_CI->deelplanvraaggeschiedenis->get_by_deelplan( $deelplan->id ); $this->deelplan_uploads[$deelplan->id] = $this->_CI->deelplanupload->find_by_deelplan( $deelplan->id, true /* assoc by vraag id */ ); $this->deelplan_vraag_subjecten[$deelplan->id] = $this->_CI->deelplansubjectvraag->get_by_deelplan( $deelplan->id ); foreach ($deelplan->get_checklisten() as $i => $checklist) { $this->deelplan_vragen[$deelplan->id][$checklist->checklist_id] = $this->_CI->deelplan->filter_vragen( $deelplan->id, $deelplan->get_checklist_vragen( $checklist->checklist_id ), $prioriteiten ); $this->deelplan_prioriteiten[$deelplan->id][$checklist->checklist_id] = @$prioriteiten[$checklist->checklist_id]; if ($this->toon_aandachtspunten) { if (!isset( $this->deelplan_aandachtspunten[$deelplan->id] )) $this->deelplan_aandachtspunten[$deelplan->id] = array(); $this->deelplan_aandachtspunten[$deelplan->id][$checklist->checklist_id] = $deelplan->get_aandachtspunten( $checklist->checklist_groep_id, $checklist->id ); } $cg_id = $checklist->checklist_groep_id; if (!isset( $this->checklistgroep_grondslagen[$cg_id] )) $this->checklistgroep_grondslagen[$cg_id] = $deelplan->get_grondslagen( $cg_id ); $volgende_vraag_nummer = 1; $this->deelplan_hoofdgroepstatussen[$deelplan->id][$checklist->checklist_id] = array(); foreach ($this->deelplan_vragen[$deelplan->id][$checklist->checklist_id] as $vraag) { $vraag->rapportage_vraag_nummer = $volgende_vraag_nummer++; $hid = $vraag->hoofdgroep_id; $waarde = $this->_status_to_waarde( $vraag ); if (!isset( $this->deelplan_hoofdgroepstatussen[$deelplan->id][$checklist->checklist_id][$hid] ) || $waarde < $this->deelplan_hoofdgroepstatussen[$deelplan->id][$checklist->checklist_id][$hid]['waarde']) { $this->deelplan_hoofdgroepstatussen[$deelplan->id][$checklist->checklist_id][$hid] = array( 'waarde' => $waarde, ); } } } } } private function _init_betrokkene_filter() { $doe_filter = $this->get_filter( 'betrokkenen-filter' ) && $this->get_filter( 'betrokkenen-filter' )=='on'; if (!$doe_filter) { $this->betrokkenen = null; // geeft aan: niet filteren op betrokkenen } else { $this->betrokkenen = array(); $betrokkenen_ids = $this->get_filter( 'subjecten' ); if (is_array( $betrokkenen_ids ) && sizeof($betrokkenen_ids) > 0) { foreach ($this->get_dossier()->get_subjecten() as $subject) { if (isset( $betrokkenen_ids[$subject->id] ) && $betrokkenen_ids[$subject->id]=='on') $this->betrokkenen[ $subject->id ] = $subject; } } } } private function _init_status_filter() { // meerkeuze instellingen ophalen $this->waardeoordelen = $this->get_filter( 'waardeoordeel' ); // invulvraag instellingen ophalen $this->waardeoordeel_invulvragen = $this->get_filter( 'waardeoordeel_invulvragen' ); } private function _init_progress() { foreach (array( 'inleiding', 'dossiergegevens', 'documenten', 'deelplannen', 'samenvatting', 'bevindingen', 'bijlage-fotos', 'bijlage-documenten-tekeningen', 'bijlage-juridische-grondslag', 'show-revisions' ) as $onderdeel) if (@array_key_exists( $onderdeel, $this->get_filter( 'onderdeel' ))) $this->item_count++; if (array_key_exists( 'bijlage-juridische-grondslag', $this->get_filter( 'onderdeel' ))) { $grondslagen = $this->get_filter( 'grondslag' ); if (is_array( $grondslagen )) $this->item_count += sizeof( $grondslagen ); } } private function _initialize_meta_data() { $this->_tcpdf->SetCreator('BRIStoezicht'); $this->_tcpdf->SetAuthor('BRIStoezicht'); $this->_tcpdf->SetTitle('Bevindingenrapportage ' . $this->get_dossier()->get_omschrijving()); $this->_tcpdf->SetSubject($this->get_dossier()->get_kenmerk()); $this->_tcpdf->SetKeywords('BRIStoezicht'); // some defaults $this->_tcpdf->SetImageScale(PDF_IMAGE_SCALE_RATIO); $this->_tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $this->_tcpdf->SetFontSubsetting( false ); } private function _generate_front_page() { $this->_tcpdf->SetPrintHeader(false); $this->_tcpdf->SetPrintFooter(false); $this->_tcpdf->AddPage(); // BRIStoezicht logo at top right $logofile = APPPATH . '/../files/images/bristoezicht.png'; $this->_tcpdf->Image( $logofile, 156, 3, 50, null, 'PNG', 'https://bristoezicht.nl', 'T', true ); // Rapportage tekst $this->_tcpdf->SetFont( self::FONTNAME, 'B', 32 ); $this->_tcpdf->SetXY( 0, 100 ); $this->_tcpdf->WriteHTML( '<span style="text-align:center">Rapportage</span>' ); // Klant logo $klant = $this->get_klant(); if ($klant->logo) { $imgfilename = $this->make_temp_image( $klant->logo ); $this->_tcpdf->WriteHTML( '<span style="text-align:center"><img src="' . $imgfilename . '" width="400" /></span>' ); } // maak lijst van olo nummers van alle deelplannen $olo_nummers = array(); foreach ($this->deelplannen as $deelplan) { $o = trim( $deelplan->olo_nummer ); if ($o && !in_array( $o, $olo_nummers )) $olo_nummers[] = $o; } // Info on frontpage left bottom $betrokkenen = ''; if (is_array( $this->betrokkenen )) { $betrokkenen .= 'Betrokkenen: '; $e = 0; foreach ($this->betrokkenen as $subject) $betrokkenen .= ($e++?', ':'') . htmlentities( $subject->naam . ($subject->organisatie ? ' (' . $subject->organisatie . ')' : ''), ENT_COMPAT, 'UTF-8' ); } $dossier = $this->get_dossier(); $this->_tcpdf->SetY( 230 ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'ID: ' . $dossier->get_kenmerk() . '<br/>' . 'OLO: ' . implode( ', ', $olo_nummers ) . '<br/>' . 'Dossiernaam: ' . $dossier->beschrijving . '<br/>' . 'Locatie: ' . $dossier->get_locatie() . '<br/>' . 'Aanmaakdatum: ' . date( 'd-m-Y', $dossier->aanmaak_datum ) . '<br/>' . 'Dossierverantwoordelijke: ' . $dossier->get_gebruiker()->get_status() . '<br/>' . $betrokkenen ); $this->_tcpdf->EndPage(); } private function _generate_disclaimer_page() { // output page headers and page footers from now on $this->_tcpdf->SetPrintHeader(true); $this->_tcpdf->SetPrintFooter(true); $this->_tcpdf->SetMargins(10, 30, 10); $this->_tcpdf->SetAutoPageBreak( TRUE, PDF_MARGIN_BOTTOM ); // add new page! $this->_tcpdf->AddPage(); // add text! $this->_tcpdf->WriteHTML( '<b>Disclaimer</b><br/>' . '<span style="text-align:justify">Deze rapportage is automatisch gegenereerd door BRIStoezicht. '. 'BRIStoezicht ondersteunt en bevordert professioneel toezicht. '. 'Het systeem treedt in geen geval in de plaats van de deskundigheid van een toezichthouder. '. 'BRIStoezicht is met de grootste zorg samengesteld. '. 'BRIS bv aanvaardt echter geen enkele aansprakelijkheid voor schade die het gevolg is van onjuistheid of onvolledigheid (in de meest ruime zin des woords) van deze applicatie en de gegenereerde rapportages.</span>', true, false, true ); // end page! $this->_tcpdf->EndPage(); } private function _generate_inleiding_pages() { if (!@array_key_exists( 'inleiding', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Inleiding...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Inleiding' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Deze rapportage geeft de bevindingen van toezicht weer. '. 'Het toezicht heeft betrekking op de fysieke leefomgeving. De bevindingen zijn gebaseerd op de documenten en '. 'tekeningen die zijn weergegeven onder dossiergegevens. De diepgang van het toezicht en de momenten '. 'waarop toezicht heeft plaatsgevonden is vastgelegd in het beleid. Dat beleid is vertaald in een prioriteitenmatrix. '. 'De prioriteitenmatrix kent maximaal vijf prioriteitenniveaus:</span>', true, false, true ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<table border="1" cellspacing="0" cellpadding="3">' . '<tr><td style="background-color:#05CBFC; text-align: center; width: 50px;">S.</td><td style="background-color:#05CBFC; text-align: left; width: 300px;">Steekproef</td></tr>' . '<tr><td style="background-color:#309A6A; text-align: center; width: 50px;">1.</td><td style="background-color:#309A6A; text-align: left; width: 300px;">Visuele controle</td></tr>' . '<tr><td style="background-color:#FEFF99; text-align: center; width: 50px;">2.</td><td style="background-color:#FEFF99; text-align: left; width: 300px;">Beoordeling van hoofdlijnen</td></tr>' . '<tr><td style="background-color:#F5A000; text-align: center; width: 50px;">3.</td><td style="background-color:#F5A000; text-align: left; width: 300px;">Beoordeling hoofdlijnen en kenmerkende details</td></tr>' . '<tr><td style="background-color:#FE0002; text-align: center; width: 50px;">4.</td><td style="background-color:#FE0002; text-align: left; width: 300px;">Algehele controle van alle onderdelen</td></tr>' . '</table>', true, false, true ); $this->_tcpdf->Ln(); $this->_tcpdf->SetFont( self::FONTNAME, 'U', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'Steekproef' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Controle vindt steekproefsgewijs plaats. Waarbij een onderdeel 1 op de 10 keer wordt meegenomen.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->SetFont( self::FONTNAME, 'U', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'Niveau 1 Visuele controle' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Een vluchtige beoordeling op het oog op basis van kennis en ervaring zonder projectspecifieke tekeningen of details te raadplegen en of hulpmiddelen (bijvoorbeeld meetlat) te gebruiken.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->SetFont( self::FONTNAME, 'U', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'Niveau 2 Beperkte controle' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Beoordeling op hoofdlijnen, op het oog en met eenvoudige hulpmiddelen worden elementaire controles uitgevoerd. Er worden alleen algemene projectspecifieke tekeningen geraadpleegd. Bij twijfel vindt raadpleging van detailtekeningen plaats.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->SetFont( self::FONTNAME, 'U', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'Niveau 3 Representatieve controle' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Beoordeling op hoofdlijnen en kenmerkende details, op het oog en met eenvoudige hulpmiddelen worden elementaire controles uitgevoerd. Daarnaast worden enkele kritische detailleringen in detail beoordeeld. Er worden algemene projectspecifieke tekeningen geraadpleegd en detailtekeningen van kritische detailleringen.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->SetFont( self::FONTNAME, 'U', self::FONTSIZE ); $this->_tcpdf->WriteHTML( 'Niveau 4 Integrale controle' ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Beoordeling van alle onderdelen op detailniveau. Op het oog en met de benodigde hulpmiddelen worden controles tot op detailniveau uitgevoerd. Alle projectspecifieke tekeningen, detail-tekeningen, berekeningen, rapporten en certificaten worden geraadpleegd.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Omdat er ook binnen een bepaald bouwwerkcluster verschillen zijn tussen de omvang van de bouwprojecten (oppervlakte, aantal bouwlagen, etc.), is de mate van toezicht in de praktijk niet altijd hetzelfde. Het aantal controles zoals in de matrix opgenomen is dan ook een gemiddelde per bouwwerkcluster.</span>' ); $this->_tcpdf->Ln(); /* $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Voor ieder van de gecontroleerde aspecten is een waardeoordeel gegeven. Hieronder is de betekenis van die waardeoordelen omschreven.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<table border="1" cellspacing="0" cellpadding="3">' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-voldoet.png" /></td>'. '<td style="width:275px;">Voldoet</td>'. '<td style="width:325px;">Het gecontroleerde aspect voldoet.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-bouwdeel_voldoet.png" /></td>'. '<td style="width:275px;">Bouwdeel voldoet</td>'. '<td style="width:325px;">Een bouwdeel voldoet aan het gecontroleerde aspect maar nog niet alle bouwdelen voldoen, of nog niet alle bouwdelen zijn gecontroleerd.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-gelijkwaardig.png" /></td>'. '<td style="width:275px;">Gelijkwaardigheid</td>'. '<td style="width:325px;">Het beoogde doel van een controleaspect is op een andere wijze dan oorspronkelijk beoogd gerealiseerd.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-voldoet_na_aanwijzingen.png" /></td>'. '<td style="width:275px;">Voldoet na aanwijzingen van toezichthouder</td>'. '<td style="width:325px;">Het gecontroleerde aspect voldoet nadat de aanwijzingen van een toezichthouder zijn opgevolgd.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-voldoet_niet.png" /></td>'. '<td style="width:275px;">Voldoet niet (zwaarwegend)</td>'. '<td style="width:325px;">Een gecontroleerd aspect voldoet niet en heeft grote gevolgen. In de regel leidt dit tot een hercontrole.</td>'. '</tr>' . '</table>', true, false, true ); $this->_tcpdf->EndPage(); $this->_tcpdf->AddPage(); $this->_tcpdf->WriteHTML( '<table border="1" cellspacing="0" cellpadding="3">' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-voldoet_niet_niet_zwaar.png" /></td>'. '<td style="width:275px;">Voldoet niet (niet zwaarwegend)</td>'. '<td style="width:325px;">Een gecontroleerd aspect voldoet niet maar heeft beperkte gevolgen.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-nvt.png" /></td>'. '<td style="width:275px;">Niet van toepassing</td>'. '<td style="width:325px;">Een controleaspect is op het specifieke plan niet van toepassing.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-nader_onderzoek_nodig.png" /></td>'. '<td style="width:275px;">Nader onderzoek nodig</td>'. '<td style="width:325px;">Een controleaspect kan niet beoordeeld worden zonder dat er nader onderzoek plaatsvindt.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-niet_gecontroleerd.png" /></td>'. '<td style="width:275px;">Niet gecontroleerd</td>'. '<td style="width:325px;">Een controleaspect is niet beoordeeld of kon niet meer beoordeeld worden.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-niet_gecontroleerd_ivm_steekproef.png" /></td>'. '<td style="width:275px;">Niet gecontroleerd i.v.m. steekproef</td>'. '<td style="width:325px;">Een controleaspect is niet beoordeeld omdat deze slechts steekproefsgewijs wordt beoordeeld.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-niet_kunnen_controleren.png" /></td>'. '<td style="width:275px;">Niet kunnen controleren</td>'. '<td style="width:325px;">Een controleaspect kon niet worden beoordeeld.</td>'. '</tr>' . '<tr>'. '<td style="width:50px; text-align:center"><img src="files/images/status-in_bewerking.png" /></td>'. '<td style="width:275px;">Nog geen waardeoordeel</td>'. '<td style="width:325px;">Het is nog niet bekend of een bepaald controleaspect al dan niet voldoet of er is nog niet naar dat controleaspect gekeken.</td>'. '</tr>' . '</table>', true, false, true ); $this->_tcpdf->Ln(); */ $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Het toezicht dat is uitgevoerd met een checklist van het integraal Toezichtprotocol (iTP) is uitgevoerd overeenkomstig de uitgangspunten van de beoordelingsrichtlijn BRL 5006.</span>' ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Toezicht dat is uitgevoerd met &eacute;&eacute;n van de overige checklists, of een eigen checklist is niet per definitie uitgevoerd overeenkomstig de uitgangspunten van de beoordelingsrichtlijn BRL 5006.</span>' ); $this->_tcpdf->EndPage(); } private function _generate_dossier_gegevens() { if (!@array_key_exists( 'dossiergegevens', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Dossiergegevens...' ); $this->_output_header1( 'Dossiergegevens' ); $dos = $this->get_dossier(); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<table cellspacing="0" cellpadding="0">' . '<tr>' . '<td width="200px">Dossiernaam</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $dos->beschrijving ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Identificiatienummer</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $dos->kenmerk ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Aanmaakdatum</td>' . '<td width="25px">:</td>' . '<td width="300px">' . date( 'd-m-Y', $dos->aanmaak_datum ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Locatieadres</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $dos->locatie_adres ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Postcode en woonplaats</td>' . '<td width="25px">:</td>' . '<td width="300px">' . ($dos->locatie_postcode ? $this->hss( $dos->locatie_postcode ) . ' ' : '') . strtoupper( $this->hss( $dos->locatie_woonplaats ) ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Kadastraal / Sectie / Nummer</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $dos->locatie_kadastraal ) . ' / ' . $this->hss( $dos->locatie_sectie ) . ' / ' . $this->hss( $dos->locatie_nummer ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Opmerkingen</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $dos->opmerkingen ) . '</td>' . '</tr>' . '</table>', true, false, true ); } private function _generate_documenten_lijst() { if (!@array_key_exists( 'documenten', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Documenten...' ); $this->_output_header1( 'Documenten', false ); $this->_output_bescheiden_table( $this->get_dossier()->get_bescheiden() ); } private function _generate_deelplannen_lijst() { if (!@array_key_exists( 'deelplannen', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Deelplannen...' ); $this->_output_header1( 'Deelplannen', false ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Een locatie in de fysieke leefomgeving kan in een dossier worden opgenomen. Onder dat dossier kunnen meerdere deelplannen worden opgenomen. '. 'Ieder deelplan kan op zichzelf meerdere aspecten van de fysieke leefomgeving behelsen. '. 'Bijvoorbeeld de realisatiefase (bouwen) en de gebruiksfase (milieu). '. 'Deelplannen kunnen ook toegepast worden bij grote of complexe bouwplaatsen of inrichtingen. '. 'Zo kan ieder bouwblok of ieder onderdeel uit een inrichting in een &quot;eigen&quot; deelplan opgenomen zijn.</span>', true, false, true ); $this->_tcpdf->Ln(); $dos = $this->get_dossier(); $bescheiden = $dos->get_bescheiden(); foreach ($this->deelplannen as $deelplan) { // hoofdkop voor dit deelplan $this->_output_header2( $deelplan->naam, false ); // lijst van betrokkenen bij dit deelplan $this->_output_subheader( $this->hss( 'Betrokkenen ' . $deelplan->naam ) ); foreach ($deelplan->get_subjecten() as $i => $subject) { if ($i) $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td width="200px">Rol</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->rol ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Naam</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Adres</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->adres ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Postcode en woonplaats</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->postcode . ' ' . $subject->woonplaats ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Telefoon</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->telefoon ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">E-mail</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->email ) . '</td>' . '</tr>' . '</table>' , true, false, true ); } $this->_tcpdf->Ln(); // lijst van bescheiden bij dit deelplan $this->_output_subheader( $this->hss( 'Documenten ' . $deelplan->naam ) ); $this->_tcpdf->Ln(); $this->_output_bescheiden_table( $bescheiden ); $this->_tcpdf->Ln(); // lijst van checklists bij dit deelplan $this->_output_subheader( $this->hss( 'Checklisten ' . $deelplan->naam ) ); $this->_tcpdf->Ln(); $deelplanchecklistgroepen = $this->_CI->deelplanchecklistgroep->get_by_deelplan( $deelplan->id ); $deelplan_themas = $this->_CI->deelplanthema->get_by_deelplan( $deelplan->id ); foreach ($deelplan->get_checklisten() as $i => $checklist) { // get_checklisten() yields irregular data $checklist = $this->_CI->checklist->get( $checklist->checklist_id ); $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); // get toezichthouder data $toezichthouder = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->gebruiker->get( $deelplanchecklistgroepen[$checklistgroep->id]->toezicht_gebruiker_id ) : null; // get matrix data $matrix = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->matrix->get( $deelplanchecklistgroepen[$checklistgroep->id]->matrix_id ) : null; // get thema data $checklist_themas = array(); // lijst van alle GESELECTEERDE thema's, met als key hoofdthema id foreach ($this->_CI->thema->get_by_checklist( $checklist->id ) as $thema) // thema geselecteerd voor checklist? if (isset( $deelplan_themas[ $thema->id ] )) { if (!isset( $checklist_themas[$thema->hoofdthema_id] )) $checklist_themas[$thema->hoofdthema_id] = array(); $checklist_themas[$thema->hoofdthema_id][] = $thema; } $checklist_hoofdthemas = array(); // lijst van ALLE hoofdthema's foreach ($this->_CI->hoofdthema->get_by_checklist( $checklist->id, true ) as $hoofdthema) $checklist_hoofdthemas[ $hoofdthema->id ] = $hoofdthema; // build table $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td width="200px">Hoofdgroep / gebouwfase</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $checklist->get_checklistgroep()->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Categorie / activiteiten</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $checklist->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Toezichthouder</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $toezichthouder ? $toezichthouder->volledige_naam : '(niet bekend)' ) . '</td>' . '</tr>'; if (empty( $checklist_themas )) { $html .= '<tr>' . '<td width="200px">Thema\'s</td>' . '<td width="25px">:</td>' . '<td width="420px"></td>' . '</tr>'; } else { $eerste = true; foreach ($checklist_themas as $hoofdthema_id => $themas) { $seen_themas = array(); foreach ($themas as $thema) { if (in_array( $thema->thema, $seen_themas )) continue; $seen_themas[] = $thema->thema; } $html .= '<tr>' . '<td width="200px">' . ($eerste ? 'Thema\'s' : '') . '</td>' . '<td width="25px">' . ($eerste ? ':' : '') . '</td>' . '<td width="120px"><b>' . $this->hss( $checklist_hoofdthemas[$hoofdthema_id]->naam ) . '</b></td>' . '<td width="300px">' . implode( ', ', $seen_themas ) . '</td>' . '</tr>'; $eerste = false; } } $html .= '</table>'; // output table $this->_output_subheader( $this->hss( 'Checklist ' . ($i + 1) ) ); $this->_tcpdf->WriteHTML( $html, true, false, true ); $this->_tcpdf->Ln(); // haal hercontrole data op $hercontrole_data = $deelplan->get_hercontrole_data_voor_checklist( $checklist->id ); foreach ($hercontrole_data as $i => $datum) $hercontrole_data[$i] = date( 'd-m-Y', strtotime( $datum ) ); // build toezichtmomenten table $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td style="width:120px; font-weight: bold">Bezoeknummer</td>' . '<td style="width:110px; font-weight: bold">Datum</td>' . '<td style="width:150px; font-weight: bold">Toezichthouder</td>' . '<td style="width:140px; font-weight: bold">Geplande datum hercontrole</td>' . '<td style="width:100px; font-weight: bold">Voortgang</td>' . '</tr>'; $voortgang = $matrix ? $deelplan->get_progress_by_checklist( $matrix->id, $checklist->id ) : 0; $datums = $deelplan->get_toezichtmomenten_by_checklist( $checklist->id ); $j = 0; foreach ($datums as $datum => $gebruikers) { $last = $j++ == sizeof($datums) - 1; $gebruikerstr = ''; foreach ($gebruikers as $gebruiker_id) $gebruikerstr .= ($gebruikerstr ? ', ' : '') . (($g = $this->_CI->gebruiker->get( $gebruiker_id )) ? $g->volledige_naam : '(onbekende toezichthouder)'); $html .= '<tr>' . '<td style="font-style:italic">' . $j . '.</td>' . '<td style="font-style:italic">' . date( 'd-m-Y', strtotime( $datum ) ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $gebruikerstr ) . '</td>' . '<td style="font-style:italic">' . (($last && !empty( $hercontrole_data )) ? implode( ', ', $hercontrole_data ) : '-') . '</td>' . '<td style="font-style:italic">' . ($last ? round( 100 * $voortgang ) . '%' : '-') . '</td>' . '</tr>'; } $html .= '</table>'; // output table $this->_output_subheader( $this->hss( 'Toezichtmomenten' ) ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( $html, true, false, true ); $this->_tcpdf->Ln(); } } } private function _generate_samenvatting() { if (!@array_key_exists( 'samenvatting', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Samenvatting...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Samenvatting' ); $dos = $this->get_dossier(); foreach ($this->deelplannen as $j => $deelplan) { // hoofdkop voor dit deelplan if ($j) { $this->_tcpdf->EndPage(); $this->_tcpdf->StartPage(); } $this->_output_header2( $deelplan->naam, false ); foreach ($deelplan->get_checklisten() as $i => $checklist) { if ($i) { $this->_tcpdf->EndPage(); $this->_tcpdf->StartPage(); } // get_checklisten() yields irregular data $checklist = $this->_CI->checklist->get( $checklist->checklist_id ); $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); $this->_output_subheader( $this->hss( 'Checklist ' . ($i + 1) . ': ' . $checklist->naam ) ); $this->_tcpdf->Ln(); // pak alle vragen die actief zijn voor deze checklist in dit deelplan $vragen = $this->deelplan_vragen[ $deelplan->id ][$checklist->id]; // maak onderverdeling in vragen naar hoofdgroep $hoofdgroep_vragen = array(); foreach ($vragen as $vraag) { // voeg vraag toe $hoofdgroep_id = $vraag->hoofdgroep_id; if (!isset( $hoofdgroep_vragen[ $hoofdgroep_id ] )) $hoofdgroep_vragen[ $hoofdgroep_id ] = array( 'naam' => $vraag->hoofdgroep_naam, 'vragen' => array(), 'status' => 4, ); $hoofdgroep_vragen[ $hoofdgroep_id ]['vragen'][] = $vraag; // update hoofdgroep status $vraag_status = $this->_status_to_samenvatting_waarde( $vraag ); if ($hoofdgroep_vragen[ $hoofdgroep_id ]['status'] > $vraag_status) $hoofdgroep_vragen[ $hoofdgroep_id ]['status'] = $vraag_status; } // beslis nu wat te doen gebaseerd op het aantal verschillende hoofdgroepen if (sizeof($hoofdgroep_vragen) < 40) { $this->_tcpdf->WriteHTML( 'Onderstaande samenvatting is gegroepeerd <b>op onderwerp</b> binnen de checklist.' ); $this->_tcpdf->Ln(); $data = array_values( $hoofdgroep_vragen ); // convert from associative to indexed } else { $this->_tcpdf->WriteHTML( 'Onderstaande samenvatting is gegroepeerd <b>op hoofdthema</b> binnen de checklist.' ); $this->_tcpdf->Ln(); // get thema's en hoofdthema's, associative op ID $themas = $this->_CI->thema->get_by_checklist( $checklist->id, true ); $hoofdthemas = array(); foreach ($this->_CI->hoofdthema->get_by_checklist( $checklist->id ) as $hoofdthema) $hoofdthemas[$hoofdthema->id] = $hoofdthema; // maak onderverdeling in vragen naar hoofdthema $hoofdthema_vragen = array(); foreach ($vragen as $vraag) { // voeg vraag toe $hoofdthema_id = $vraag->thema_id ? $themas[ $vraag->thema_id ]->hoofdthema_id : NULL; $hoofdthema_naam = $hoofdthema_id ? $hoofdthemas[$hoofdthema_id]->naam : 'Algemeen'; if (!isset( $hoofdthema_vragen[ $hoofdthema_naam ] )) $hoofdthema_vragen[ $hoofdthema_naam ] = array( 'naam' => $hoofdthema_naam, 'vragen' => array(), 'status' => 4, ); $hoofdthema_vragen[ $hoofdthema_naam ]['vragen'][] = $vraag; // update hoofdthema status $vraag_status = $this->_status_to_samenvatting_waarde( $vraag ); if ($hoofdthema_vragen[ $hoofdthema_naam ]['status'] > $vraag_status) $hoofdthema_vragen[ $hoofdthema_naam ]['status'] = $vraag_status; } $data = array_values( $hoofdthema_vragen ); // convert from associative to indexed } // display table $i = 0; $tablecount = 0; while ($i < sizeof($data)) { if ($tablecount && (($tablecount % 3) == 0)) { $this->_tcpdf->FlushColumnVerticalTexts(); $this->_tcpdf->EndPage(); $this->_tcpdf->StartPage(); } ++$tablecount; $max_cols_per_table = 13; $cellwidth = 40; $cellheight = 160; @define( 'PIX_TO_UNITS', 3.5714 ); $html = '<table cellspacing="0" cellpadding="2" border="1"><tr><td width="150px" height="' . $cellheight . 'px"></td>'; $start = $i; $html_rows = array( '<td>Handhaven</td>', '<td>Aandacht</td>', '<td>Niet van toepassing</td>', '<td>Geen handhaving</td>', ); while ($i < sizeof($data) && $i - $start < $max_cols_per_table) { $naam = $data[$i]['naam']; $status = $data[$i]['status']; $params = $this->_tcpdf->serializeTCPDFtagParameters( array( $naam, $cellwidth / PIX_TO_UNITS, ($cellheight-3) / PIX_TO_UNITS, 3 / PIX_TO_UNITS ) ); $html .= '<td width="' . $cellwidth . 'px" align="center"><tcpdf method="AddColumnVerticalText" params="' . $params . '" /></td>'; for ($k=0; $k<=3; ++$k) { $html_rows[$k] .= '<td align="center" valign="center">'; if ($status == $k) { switch ($status) { case 0: $src = 'files/images/status-voldoet_niet.png'; break; case 1: $src = 'files/images/status-nader_onderzoek_nodig.png'; break; case 2: $src = 'files/images/status-voldoet.png'; break; case 3: $src = 'files/images/status-voldoet.png'; break; } $html_rows[$k] .= '<img src="' . $src . '" />'; } $html_rows[$k] .= '</td>'; } ++$i; } $html .= '</tr>'; foreach ($html_rows as $html_row) $html .= '<tr>' . $html_row . '</tr>'; $html .= '</table>'; $this->_tcpdf->WriteHTML( $html, true, false, true ); } } } $this->_tcpdf->FlushColumnVerticalTexts(); $this->_tcpdf->EndPage(); } private function _vraag_weergeven( $deelplan_id, $vraag ) { // check status filter $status = $this->_status_to_description( $vraag ); if ($vraag->get_wizard_veld_recursief( 'vraag_type' ) == 'invulvraag') { if (!$this->waardeoordeel_invulvragen) { //die( 'Neem vraag niet op, want het is een invulvraag en die tonen we niet' ); return false; } } else { if (!isset( $this->waardeoordelen[$status] )) { //die( 'Neem vraag niet op, want ' . $status . ' wordt niet getoond' ); return false; } } // check betrokkene filter if (is_array( $this->betrokkenen )) { $found = false; if (isset( $this->deelplan_vraag_subjecten[ $deelplan_id ] )) if (isset( $this->deelplan_vraag_subjecten[ $deelplan_id ][ $vraag->id ] )) { foreach ($this->deelplan_vraag_subjecten[ $deelplan_id ][ $vraag->id ] as $subject) if (isset( $this->betrokkenen[ $subject->dossier_subject_id ] )) { $found = true; break; } } if (!$found) return false; } // done! mag getoond worden! return true; } private function _generate_bevindingen() { if (!@array_key_exists( 'bevindingen', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Bevindingen...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Bevindingen' ); $dos = $this->get_dossier(); foreach ($this->deelplannen as $j => $deelplan) { // hoofdkop voor dit deelplan if ($j) { $this->_tcpdf->EndPage(); $this->_tcpdf->StartPage(); } $this->_output_header2( $deelplan->naam, false ); foreach ($deelplan->get_checklisten() as $i => $checklist) { if ($i) { $this->_tcpdf->EndPage(); $this->_tcpdf->StartPage(); } // get_checklisten() yields irregular data $checklist = $this->_CI->checklist->get( $checklist->checklist_id ); $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); $this->_output_subheader( $this->hss( 'Checklist ' . ($i + 1) . ': ' . $checklist->naam ) ); $this->_tcpdf->Ln(); // page is 650px wide $vragen = $this->deelplan_vragen[$deelplan->id][$checklist->id]; $current_hoofdgroep_id = null; foreach ($vragen as $vraag) { // kijk of de status(=waardeoordeel) van deze vraag getoond mag worden if (!$this->_vraag_weergeven( $deelplan->id, $vraag )) continue; // nieuwe hoofdgroep? dan mini tabel neergooien if ($current_hoofdgroep_id != $vraag->hoofdgroep_id) { // set new hoofdgroep $current_hoofdgroep_id = $vraag->hoofdgroep_id; // get prio for this hoofdgroep $prio = null; if ($this->deelplan_prioriteiten[$deelplan->id][$checklist->id]) $prio = $this->deelplan_prioriteiten[$deelplan->id][$checklist->id]->get_waarde( $current_hoofdgroep_id, $vraag->hoofdthema_id, $deelplan->id ); if (!$prio) $prio = 'zeer_hoog'; switch ($prio) { case 'zeer_laag': $prio_niveau = 'S'; break; case 'laag': $prio_niveau = '1'; break; case 'gemiddeld': $prio_niveau = '2'; break; case 'hoog': $prio_niveau = '3'; break; case 'zeer_hoog': $prio_niveau = '4'; break; default: $prio_niveau = '?'; break; } // output status $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTSIZE ); $waarde = $this->deelplan_hoofdgroepstatussen[$deelplan->id][$checklist->id][$current_hoofdgroep_id]['waarde']; switch ($waarde) { case 0: $this->_tcpdf->Cell( 0, 0, 'Handhaven', 0, 1 ); break; case 1: $this->_tcpdf->Cell( 0, 0, 'Nader onderzoek', 0, 1 ); break; case 2: $this->_tcpdf->Cell( 0, 0, 'In bewerking', 0, 1 ); break; case 3: $this->_tcpdf->Cell( 0, 0, 'Geen handhaving nodig', 0, 1 ); break; default: $this->_tcpdf->Cell( 0, 0, 'Onbekend (' . $status . ')', 0, 1 ); break; } $this->_tcpdf->Ln(); // output table $this->_tcpdf->WriteHTML( '<table cellpadding="0" cellspacing="0" border="0">' . '<tr>' . '<td width="20px"></td>'. '<td width="630px">' . $this->hss( $vraag->hoofdgroep_naam ) . ' (niveau ' . $prio_niveau . ')</td>' . '</tr>' . '</table>', true, false, true ); } // maak grondslagen tekst $grondslagen = array(); if (isset( $this->checklistgroep_grondslagen[ $checklistgroep->id ][ $vraag->id ] )) foreach ($this->checklistgroep_grondslagen[ $checklistgroep->id ][ $vraag->id ] as $grondslag) $grondslagen[] = $grondslag->grondslag . ' ' . $grondslag->artikel; // is er een aandachtspunt? $aandachtspunt_html = ''; if ($this->toon_aandachtspunten) { $lijst = @$this->deelplan_aandachtspunten[$deelplan->id][$vraag->checklist_id]; $full_text = ''; if (is_array( $lijst )) foreach ($lijst as $ap) { switch ($ap->soort) { case 'altijd': if (@$ap->checklist_groep_id && @$ap->checklist_groep_id != $checklistgroep->id) continue(2);; if (@$ap->checklist_id && @$ap->checklist_id != $vraag->checklist_id) continue(2);; if (@$ap->hoofdgroep_id && @$ap->hoofdgroep_id != $vraag->hoofdgroep_id) continue(2);; if (@$ap->vraag_id && @$ap->vraag_id != $vraag->id) continue(2);; break; case 'voorwaardelijk': $gebruik = false; switch ($vraag->gebruik_ndchtspntn) { case 'cg': $gebruik = (@$ap->checklist_groep_id == $checklistgroep->id); break; case 'cl': $gebruik = (@$ap->checklist_id == $vraag->checklist_id); break; case 'h': $gebruik = (@$ap->hoofdgroep_id == $vraag->hoofdgroep_id); break; case 'v': $gebruik = (@$ap->vraag_id == $vraag->id); break; } if (!$gebruik) continue(2);; break; default: throw new Exception( 'Ongeldig aandachtspuntsoort: ' . $ap->soort ); } // als we hier uitkomen, moeten we dit aandachtspunt voor deze vraag opnemen! $full_text .= '<b>' . $this->hss( $ap->titel ) . '</b> - ' . $this->hss( $ap->aandachtspunt ) . '<br/>'; } if (!strlen( $full_text )) $full_text = '<i>geen</i>'; $aandachtspunt_html .= '<tr>' . '<td width="60px"></td>' . '<td width="120px">Aandachtspunten:</td>' . '<td width="470px">' . $full_text . '</td>' . '</tr>'; } // zijn er bescheiden gekoppeld aan deze vraag? $bescheiden_html = ''; if (isset( $this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] )) { foreach ($this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] as $q => $vraagbescheiden) { $bescheiden_html .= '<tr>' . '<td width="60px"></td>' . '<td width="120px">' . ($q ? '' : 'Documenten:') . '</td>' . '<td width="470px">' . $this->hss( $vraagbescheiden->bestandsnaam . ($vraagbescheiden->auteur ? ', door ' . $vraagbescheiden->auteur : '') . ($vraagbescheiden->datum_laatste_wijziging ? ', van ' . $vraagbescheiden->datum_laatste_wijziging : '') ) . '</td>' . '</tr>'; } } // is er toelichtingsgeschiedenis? $toelichting_html = ''; if (isset( $this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id] )) { // 'intro' $toelichting_html .= // legel regel '<tr>' . '<td width="650px" colspan="3"></td>' . '</tr>' . // intro '<tr>' . '<td width="60px"></td>' . '<td width="590px" colspan="2"><u>Historie verantwoording</u></td>' . '</tr>'; // geschiedenis foreach ($this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id] as $q => $tg) { // lege regel? if ($q) $toelichting_html .= '<tr>' . '<td width="650px" colspan="3"></td>' . '</tr>'; // toelichting! $toelichting_html .= '<tr>' . '<td width="60px"></td>' . '<td width="120px">Beoordeling:</td>' . '<td width="470px">' . $this->_status_to_description( $tg->get_vraag(), $tg->status ) . ' [' . date('d-m-Y', strtotime( $tg->datum ) ) . ']</td>' . '</tr>' . '<tr>' . '<td width="60px"></td>' . '<td width="120px">Verantwoording:</td>' . '<td width="470px">' . $this->hss( $tg->toelichting ) . '</td>' . '</tr>'; } } // zijn er uploads? $fotosvideos_html = ''; if (isset( $this->deelplan_uploads[$deelplan->id][$vraag->id] )) { foreach ($this->deelplan_uploads[$deelplan->id][$vraag->id] as $q => $upload) { $fotosvideos_html .= '<tr>' . '<td width="60px"></td>' . '<td width="120px">' . ($fotosvideos_html ? '' : 'Foto\'s / video\'s:') . '</td>' . '<td width="470px">' . $this->hss( $upload->filename . ', door ' . $upload->get_auteur() . ', van ' . date('d-m-Y', strtotime($upload->uploaded_at)) ) . '</td>' . '</tr>'; } } // output vraag! $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<table cellpadding="0" cellspacing="0" border="0">' . '<tr>' . '<td width="40px"></td>'. '<td width="40px">' . $vraag->rapportage_vraag_nummer . '.</td>' . '<td width="560px">' . $this->hss( $vraag->tekst ) . '</td>' . '</tr>' . '</table>' . '<table cellpadding="0" cellspacing="0" border="0">' . '<tr>' . '<td width="60px"></td>' . '<td width="120px">Beoordeling:</td>' . '<td width="470px">' . $this->_status_to_description( $vraag ) . '</td>' . '</tr>' . $aandachtspunt_html . '<tr>' . '<td width="60px"></td>' . '<td width="120px">Verantwoording:</td>' . '<td width="470px">' . $this->hss( $vraag->toelichting ) . '</td>' . '</tr>' . '<tr>' . '<td width="60px"></td>' . '<td width="120px">Grondslagen:</td>' . '<td width="470px">' . implode( ', ', $grondslagen ) . '</td>' . '</tr>' . $bescheiden_html . $fotosvideos_html . $toelichting_html . '</table>', true, false, true ); } } } $this->_tcpdf->EndPage(); } private function _generate_foto_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-fotos', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Foto\'s...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Foto\'s' ); $this->_output_uploads_list( 'foto/video', 2, 325, 240 ); $bijlage_nr++; } private function _generate_documenten_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-documenten-tekeningen', $this->get_filter( 'onderdeel' ))) return; // doe documenten en tekeningen in PNG formaat (nu we het nieuwe annotaties systeem hebben zijn die er ws niet meer ;-)) $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Documenten / Tekeningen...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Documenten / Tekeningen' ); $this->_output_bescheiden_list( '/\.(png|jpe?g)$/', 1, 650, 720 ); $bijlage_nr++; // doe annotaties $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Annotaties...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Annotaties' ); $this->_output_annotatie_list( 1, 650, 720 ); $bijlage_nr++; } private function _generate_juridische_grondslag_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-juridische-grondslag', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Juridische grondslag...' ); $this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Juridische grondslag' ); // fetch distinct list of articles $data = array(); foreach ($this->checklistgroep_grondslagen as $cg_id => $vraag_grondslagen) foreach ($vraag_grondslagen as $vraag_id => $grondslagen) foreach ($grondslagen as $grondslag) { if (!isset( $data[$grondslag->grondslag] )) $data[$grondslag->grondslag] = array(); // new way $gt = $this->_CI->grondslagtekst->get( $grondslag->grondslag_tekst_id ); if ($gt) { $data[$grondslag->grondslag][$grondslag->artikel] = $gt->get_artikel_tekst(); } // old way if (!$data[$grondslag->grondslag][$grondslag->artikel] || ($grondslag->tekst && !isset( $data[$grondslag->grondslag][$grondslag->artikel] ))) $data[$grondslag->grondslag][$grondslag->artikel] = $grondslag->tekst; } // sort by grondslag (in key) ksort( $data ); foreach ($data as $grondslag => $artikelen) { if (!@array_key_exists( $grondslag, $this->get_filter( 'grondslag' ))) continue; $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Juridische grondslag: ' . $grondslag . '...' ); $this->_output_header2( $grondslag ); ksort( $artikelen ); foreach ($artikelen as $artikel => $tekst) { $this->_tcpdf->SetFont( self::FONTNAME, 'BU', self::FONTSIZE-2 ); $this->_tcpdf->WriteHTML( $this->hss( $artikel ), true, false, true ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE-2 ); $lines = explode( "\n", trim( $tekst ) ); foreach ($lines as $k => $line) $this->_tcpdf->MultiCell( 0, 0, trim($line), 0, 'L' ); $this->_tcpdf->Ln(); } } $this->_tcpdf->EndPage(); $bijlage_nr++; } private function _generate_toc() { $this->_tcpdf->addTOCPage(); // write the TOC title $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTHEADERSIZE ); $this->_tcpdf->MultiCell(0, 0, 'Inhoudsopgave', 0, 'C', 0, 1, '', '', true, 0); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->Ln(); // add TOC $this->_tcpdf->addTOC( 3, self::FONTNAME, '.', 'Inhoudsopgave', 'B', array(0,0,0)); // end of TOC page $this->_tcpdf->endTOCPage(); } /******************************************************************************** * * * HELPER FUNCTIONS * * * ********************************************************************************/ private function _output_header1( $text, $top_of_page=true ) { $this->_output_header( $text, 0, $top_of_page, self::FONTHEADERSIZE ); } private function _output_header2( $text, $top_of_page=true ) { $this->_output_header( $text, 1, $top_of_page, self::FONTHEADERSIZE-1 ); } private function _output_header3( $text, $top_of_page=true ) { $this->_output_header( $text, 2, $top_of_page, self::FONTHEADERSIZE-2 ); } private function _output_subheader( $text ) { // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTSIZE+1 ); $this->_tcpdf->SetTextColor( 0, 0, 0 ); $this->_tcpdf->WriteHTML( $this->hss( $text ), true, false, true ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); } private function _output_header( $text, $level, $top_of_page, $fontsize ) { // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', $fontsize ); $this->_tcpdf->SetTextColor( 0, 204, 171 ); // #00ccab $this->_tcpdf->WriteHTML( $this->hss( $text ), true, false, true ); $this->_tcpdf->Bookmark( $text, $level, $top_of_page ? 0 : -1 ); // reset color to black $this->_tcpdf->SetTextColor( 0, 0, 0 ); // additional empty line $this->_tcpdf->Ln(); } private function _output_bescheiden_table( array $bescheiden ) { $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td style="width:100px; font-weight: bold">Tekening / Stuknummer</td>' . '<td style="width:130px; font-weight: bold">Auteur</td>' . '<td style="width:150px; font-weight: bold">Omschrijving</td>' . '<td style="width:100px; font-weight: bold">Datum laatste wijziging</td>' . '<td style="width:140px; font-weight: bold">Bestandsnaam</td>' . '</tr>' ; foreach ($bescheiden as $bescheid) { $html .= '<tr>' . '<td style="font-style:italic">' . $this->hss( $bescheid->tekening_stuk_nummer ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->auteur ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->omschrijving ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->datum_laatste_wijziging ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->bestandsnaam ) . '</td>' . '</tr>'; } $html .= '</table>'; $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( $html, true, false, true ); } private function _output_uploads_list( $datatype, $foto_per_row, $max_width, $max_height ) { foreach ($this->deelplannen as $j => $deelplan) { $first = true; foreach ($deelplan->get_checklisten() as $i => $checklist) { // get list of foto/video uploads $upload_list = array(); $vragen = $this->deelplan_vragen[$deelplan->id][$checklist->id]; foreach ($vragen as $vraag) if (isset( $this->deelplan_uploads[$deelplan->id][$vraag->id] )) if ($this->_vraag_weergeven( $deelplan->id, $vraag )) foreach ($this->deelplan_uploads[$deelplan->id][$vraag->id] as $q => $upload) if ($upload->datatype == $datatype) $upload_list[] = array( $vraag, $upload ); // something todo? if (!empty( $upload_list )) { // if available, then show deelplan header if ($first) { $this->_output_header2( $deelplan->naam, false ); $first = false; } // show checklist header $this->_output_subheader( $this->hss( 'Checklist ' . ($i + 1) . ': ' . $checklist->naam ) ); $this->_tcpdf->Ln(); // show uploads $images_html = '<table cellspacing="0" cellpadding="3" border="0">'; foreach ($upload_list as $q => $upload) { // handle table rows if (!($q % $foto_per_row)) { if ($q) $images_html .= '</tr>'; $images_html .= '<tr>'; } $uploaddata = $upload[1]->get_data(); $this->_process_raw_image_data( /* raw image data */ $uploaddata, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow jpg conversion */ TRUE ); // add $images_html .= '<td width="' . $max_width . '">' . '<img src="' . $tempfilename . '" width="' . round($impixwidth-10 /* margin */) . '" height="' . round($impixheight-10 /* margin */) . '" />' . '<br/><b>Vraag ' . $upload[0]->rapportage_vraag_nummer . ':</b> ' . $this->hss( $upload[1]->filename ) . '</td>'; } $images_html .= '</tr></table>'; // output HTML $this->_tcpdf->WriteHTML( $images_html, true, false, true ); } } } } private function _process_raw_image_data( $imagecontents, $max_width, $max_height, &$impixwidth, &$impixheight, &$tempfilename, $allow_convert_to_jpg ) { // calc correct width/height to display image in $imwidth = 640; // default! $imheight = 480; try { $im = new Imagick(); if ($im->readImageBlob( $imagecontents )) { $imwidth = $im->getImageWidth(); $imheight = $im->getImageHeight(); if (!$imwidth || !$imheight) { error_log( 'Failed to determine image dims: ' . $imwidth . 'x' . $imheight ); $imwidth = 640; // default! $imheight = 480; } } $impixwidth = round( $max_width ); $impixheight = round( ($max_width / $imwidth) * $imheight ); if ($impixheight > $max_height) { $impixheight = round( $max_height ); $impixwidth = round( ($max_height / $imheight) * $imwidth ); } // resize image to be of the a small size: twice at what it will be displayed at, so we still have some detail! if ($allow_convert_to_jpg) { $im->resizeImage( 2*$impixwidth, 2*$impixheight, imagick::FILTER_BOX, 0 ); $im->setImageFormat( 'jpeg' ); $im->setImageCompression( Imagick::COMPRESSION_JPEG ); $im->setImageCompressionQuality( 80 ); unset($imagecontents); $imagecontents = $im->getImageBlob(); } } catch (ImagickException $e) { // fail silently, use default error_log( 'ImagickException: ' . $e->getMessage() ); $impixwidth = $imwidth; $impixheight = $imheight; } if ($im) @$im->destroy(); unset($im); // make tempfile from image contents $tempfilename = $this->make_temp_image( $imagecontents, 'jpg' ); unset($imagecontents); } private function _output_bescheiden_list( $regexp_match, $foto_per_row, $max_width, $max_height ) { foreach ($this->deelplannen as $j => $deelplan) { if (!isset( $this->deelplan_bescheiden[$deelplan->id] )) continue; $numfiles = 0; $images_html = '<table cellspacing="0" cellpadding="3" border="0">'; foreach ($this->deelplan_bescheiden[$deelplan->id] as $deelplanbescheiden) { // is er genoeg data in het bescheiden? $dossierbescheiden = $deelplanbescheiden->get_dossier_bescheiden(); if (!$dossierbescheiden->bestandsnaam || !preg_match( $regexp_match, $dossierbescheiden->bestandsnaam )) continue; // is het bescheiden uberhaupt in gebruik door een vraag die momenteel getoond moet/mag worden $gebruik_bescheiden = false; foreach ($deelplan->get_checklisten() as $checklist) { foreach ($this->deelplan_vragen[$deelplan->id][$checklist->id] as $vraag) { // kijk of de status(=waardeoordeel) van deze vraag getoond mag worden if (!$this->_vraag_weergeven( $deelplan->id, $vraag )) continue; if (isset( $this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] )) { foreach ($this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] as $vraagbescheiden) { if ($deelplanbescheiden->dossier_bescheiden_id == $vraagbescheiden->dossier_bescheiden_id) { $gebruik_bescheiden = true; break(3); } } } } } if (!$gebruik_bescheiden) continue; // if available, then show deelplan header if (!$numfiles) $this->_output_header2( $deelplan->naam, false ); ++$numfiles; // handle table rows if (!($numfiles % $foto_per_row)) { if ($numfiles) $images_html .= '</tr>'; $images_html .= '<tr>'; } $dossierbescheiden->laad_inhoud(); $this->_process_raw_image_data( /* raw image data */ $dossierbescheiden->bestand, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow JPG conversion */ FALSE ); $dossierbescheiden->geef_inhoud_vrij(); // add $images_html .= '<td width="' . $max_width . '">' . '<img src="' . $tempfilename . '" width="' . round($impixwidth-10 /* margin */) . '" height="' . round($impixheight-10 /* margin */) . '" />' . '<br/><b>' . $this->hss( $dossierbescheiden->bestandsnaam ) . '</b> ' . '</td>'; } $images_html .= '</tr></table>'; if ($numfiles) // output HTML $this->_tcpdf->WriteHTML( $images_html, true, false, true ); } } private function _output_annotatie_list( $foto_per_row, $max_width, $max_height ) { foreach ($this->deelplannen as $j => $deelplan) { if (!isset( $this->deelplan_bescheiden[$deelplan->id] )) continue; $numfiles = 0; $images_html = '<table cellspacing="0" cellpadding="3" border="0">'; foreach ($this->deelplan_bescheiden[$deelplan->id] as $deelplanbescheiden) { // is er genoeg data in het bescheiden? $dossierbescheiden = $deelplanbescheiden->get_dossier_bescheiden(); // get layerdata $layerdata = $this->_CI->deelplanlayer->get_layer_for_deelplan_bescheiden( $deelplan->id, $dossierbescheiden->id ); if (!$layerdata) continue; // get vragen for which there is layer data $vraag_ids = $this->_CI->pdfannotatorlib->get_vraag_ids_in_layer_data( $layerdata->layer_data ); foreach ($vraag_ids as $vraag_id) { if (!$vraag = $this->_CI->vraag->get( $vraag_id )) continue; // if available, then show deelplan header if (!$numfiles) $this->_output_header2( $deelplan->naam, false ); ++$numfiles; // process pages in PDF annotator $numpages = $this->_CI->pdfannotatorlib->bescheiden_num_pages( $dossierbescheiden->id ); for ($i = 1; $i <= $numpages; ++$i) { // handle table rows if (!($numfiles % $foto_per_row)) { if ($numfiles) $images_html .= '</tr>'; $images_html .= '<tr>'; } // get png $png = $this->_CI->pdfannotatorlib->bescheiden_naar_png( $deelplan->id, $dossierbescheiden->id, $vraag_id, $i ); // process image for rapportage $this->_process_raw_image_data( /* raw image data */ $png, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow JPG conversion */ FALSE ); // add $images_html .= '<td width="' . $max_width . '">' . '<img src="' . $tempfilename . '" width="' . round($impixwidth-10 /* margin */) . '" height="' . round($impixheight-10 /* margin */) . '" />' . '<br/><b>' . $this->hss( $vraag->tekst ) . '</b> ' . '</td>'; } } } $images_html .= '</tr></table>'; if ($numfiles) // output HTML $this->_tcpdf->WriteHTML( $images_html, true, false, true ); } } private function _status_to_samenvatting_waarde( $vraag ) { // hoofdgroep status: ("magic constants" worden gebruikt voor gemakkelijk vergelijk) // 0 - handhaven // 1 - aandacht // 2 - niet van toepassing // 3 - niet handhaven // 4 - geen enkele vraag nog beantwoord // update thema status switch ($vraag->get_waardeoordeel_kleur( true )) { case 'rood': return 0; case 'groen': return 2; case 'oranje': return 1; default: case 'in_bewerking': return 4; } } private function _status_to_waarde( $vraag ) { switch ($vraag->get_waardeoordeel_kleur( true )) { case 'groen': return 3; case 'oranje': return 1; case 'rood': return 0; default: case 'in_bewerking': return 2; } } private function _status_to_description( $vraag, $alt_status=null ) { return $vraag->get_waardeoordeel( true, $alt_status ); } private function _set_progress( $action_description ) { $this->set_progress( min( 1, $this->item_number / $this->item_count ), $action_description ); $this->item_number++; } public function get_deelplannen() { return $this->deelplannen; } } class DossierStandaardTCPDF extends TCPDF { const FONTNAME = DossierExportStandaard::FONTNAME; const FONTSIZE = DossierExportStandaard::FONTSIZE; private $_export; private $_vertical_texts = array(); public function set_references( DossierExportBase $export ) { $this->_export = $export; } public function Header() { $this->SetFont( self::FONTNAME, '', self::FONTSIZE ); $klant = $this->_export->get_klant(); if ($klant->logo_klein) { $imgfilename = $this->_export->make_temp_image( $klant->logo_klein ); $this->Image( $imgfilename, 5, 5, null, null, null, null, 'B', true ); } $this->SetY( 15 ); $this->Cell( 0, 7, $klant->naam, '', 2, 'R', false ); $this->SetPageMark(); } public function Footer() { $this->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->SetY( -15 ); $this->Cell( 0, 7, 'Pagina '.$this->getAliasNumPage().' van '.$this->getAliasNbPages(), '', 2, 'C', false ); $this->SetY( -15 ); $this->Cell( 0, 7, 'ID: ' . $this->_export->get_dossier()->get_kenmerk(), '', 2, 'R', false ); } public function AddColumnVerticalText( $text, $width, $height, $margin ) { $this->_vertical_texts[] = array( 'page' => $this->GetPage(), 'x' => $this->GetX(), 'y' => $this->GetY(), 'text' => $text, 'height' => $height, 'width' => $width, 'margin' => $margin, ); } public function FlushColumnVerticalTexts() { $curPage = $this->getPage(); foreach ($this->_vertical_texts as $text) { $this->setPage( $text['page'] ); // get data $w = $text['width']; $h = $text['height']; $m = $text['margin']; $x = $text['x']; $y = $text['y'] + $h + $m/2; $n = $text['text']; // split texts to multiple rows $rows = $this->_split_text_to_rows( $n, $h, $w ); // yep, w/h are reversed! $origx = $x; foreach ($rows as $row) { // transforme Rotate $this->StartTransform(); // Rotate 90 degrees counter-clockwise $this->Rotate(90, $x, $y ); $this->Text( $x, $y, $row ); // Stop Transformation $this->StopTransform(); // update x $x += 3; // UGH!!! VERY FREAKING UGLY!! if ($x > ($origx + $w - 3)) // UGH!!! VERY FREAKING UGLY!! break; } } $this->setPage( $curPage ); $this->_vertical_texts = array(); } private function _split_text_to_rows( $text, $maxw, $maxh ) { $rows = array(); while (strlen($text) > 0) { // see how far we can go in the current string $i = 0; while ($i < strlen($text) && $this->getStringWidth( substr( $text, 0, $i + 1) ) < $maxw) ++$i; if (!$i) // not even a single char fits? bail! break; // determine nicest breaking point in string if ($i < strlen($text) && $text[$i] != ' ') { $j = strrpos( substr( $text, 0, $i ), ' ' ); if ($j!==false && $j > 0 && $j < $i) $i = $j; } // add text $rows[] = substr( $text, 0, $i ); // now prepare for next iteration $text = ltrim( substr( $text, $i ) ); } return $rows; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_standart_documenten_beheer')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('standart_documenten.header'), 'expanded' => true, 'width' => '100%', 'group_tag' => 'document','height' => 'auto', 'defunct' => true ) ); ?> <table width="100%" class="defaultActions"> <tr> <td colspan="5"> <h3><?=tg('standaart_documenten')?></h3> </td> </tr> <tr> <? $columns = 4; $index = 0; ?> <? foreach ($bescheiden as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div class="draggable" style="padding:0;margin:0;height:auto;border:0"> <div style="display: inline-block; overflow:hidden; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; width: 190px; cursor: pointer;" onclick="openDocumentenPopup( <?=$b->id?> );" title="<?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?>"> <b><?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?></b> </div> </div> </td> <? ++$index; ?> <? endforeach;?> <tr> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => FALSE, 'width' => '120px', 'text' => tgng('form.nieuw'), 'blank' => false, 'url' => 'javascript:nieuwDocumenten(0);', 'class' => 'greenbutton' ) ); ?> </td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?> <script> function showError( msg ) { showMessageBox({message: msg, buttons: ['ok'], type: 'error'}); } function nieuwDocumenten() { openDocumentenPopup( 0 ); } function getDocumentBase() { return $('.Document-container'); } function getDocumentParent() { return $('.Document-container'); } function herlaadDocumentHTML( html ) { var base = getDocumentBase(); base.html( html ); BRISToezicht.Group.visibleGroup['document'] = base.find('.group'); location.reload(); } var uploadBezig = false; function openDocumentenPopup( id ) { selectedDocumentId = id; var uploadBezig = false; modalPopup({ url: '<?=site_url('/beheer/standart_document_popup/')?>/' + id, width: 900, height: 500, onClose: function() { if (uploadBezig) { showError( '<?=tgn('er_is_nog_een_upload_bezig_even_geduld_aub')?>' ); return false; } } }); } function isDocumentEditbaar() { return getPopup().find( 'input' ).attr( 'disabled' ) ? false : true; } function opslaanDocument() { if (!isDocumentEditbaar()) { closePopup(); return; } if (selectedDocumentId) url = '<?=site_url('/beheer/standart_documents/')?>/' + selectedDocumentId + '/' + currentDocumentMapId; else url = '<?=site_url('/beheer/create_document/');?>'; uploadBezig = true; getPopup().find( 'input, textarea, select' ).attr( 'readonly', 'readonly' ); $('.buttonbar').hide(); $('.pleasewaitbar').slideDown(); var form = getPopup().find('form'); form.attr( 'action', url ); BRISToezicht.Upload.start( form[0], function( data ){ // restore state getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); uploadBezig = false; $('.buttonbar').slideDown(); $('.pleasewaitbar').hide(); if (data.match( /^FOUT:\s*(.*?)$/ )) showError( RegExp.$1 ); else { closePopup(); location.href = location.href; //setTimeout(herlaadDocumentHTML( data ), 1000); } }); } function deleteDocumentByIds( ids ) { $.ajax({ url: '<?=site_url('/beheer/document_delete/')?>/' + ids, type: 'POST', data: { ids: JSON.stringify( ids ) }, dataType: 'html', success: function( data ) { herlaadDocumentHTML( data ); }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } function verwijderDocument() { if (!selectedDocumentId) { showError( '<?=tgn('u_kunt_een_nieuw_Document_niet_verwijderen')?>' ); return; } showMessageBox({ message: '<?=tgn('weet_u_zeker_dat_u_dit_Document_wilt_verwijderen')?>', onClose: function( res ) { if (res == 'ok') { setTimeout( function() { // call close popup to close popup underneath us, but do it 1 ms later // because otherwise getPopup (which closePopup uses) will close // our message box, in stead of the popup that called us ;-) closePopup(); }, 1 ); deleteDocumentByIds(selectedDocumentId); } } }); } function deleteDocumentAllDocuments( ids ) { $.ajax({ url: '<?=site_url('/beheer/documents_all_delete/')?>/' + ids, type: 'POST', data: { ids: JSON.stringify( ids ) }, dataType: 'html', success: function( data ) { herlaadDocumentHTML( data ); }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } function verwijderAllesDocument() { if (!selectedDocumentId) { showError( '<?=tgn('u_kunt_een_nieuw_Document_niet_verwijderen')?>' ); return; } showMessageBox({ message: '<?=tgn('weet_u_zeker_dat_u_dit_Document_wilt_verwijderen')?>', onClose: function( res ) { if (res == 'ok') { setTimeout( function() { // call close popup to close popup underneath us, but do it 1 ms later // because otherwise getPopup (which closePopup uses) will close // our message box, in stead of the popup that called us ;-) closePopup(); }, 1 ); deleteDocumentAllDocuments(selectedDocumentId); } } }); } </script><file_sep><?php /** Load tokens */ require_once(dirname(__FILE__).'/security-tokens.php'); /** Security configuration. * * The array keys in the $security array are regexp strings, that will be matched * in the given order against the currently requested URL. * * The value can either be: * - true to indicate the user must be logged in to be allowed access to the page * - false to indicate the user must NOT be logged in to be allowed access to the page * - '*' to indicate the user may ALWAYS visit the page * - a single RECHT_TYPE_xxx constant, indicating that the given "recht" has to be available to the user * - an array of RECHT_TYPE_xxx constants, indicating that any of the given "rechten" has to be available to the user */ $security['gebruikers/.*?$'] = '*'; $security['intro/index'] = true; // nieuws pagina is alleen voor ingelogde mensen $security['intro/notificatie_bekeken'] = true; $security['root/index'] = '*'; // dit is de default pagina, en handelt zelf wel/niet-ingelogd-zijn af $security['root/fetch_integration'] = '*'; $security['root/online_check'] = '*'; $security['root/session_check'] = true; $security['root/versie'] = '*'; $security['root/apptoegang'] = true; $security['content/.*$'] = '*'; $security['progress/index'] = '*'; $security['pdfannotator/line.*?'] = '*'; $security['pdfannotator'] = true; // moet je voor ingelogd zijn $security['lease/.*'] = '*'; // iedereen mag er bij $security['deviceinfo/.*'] = '*'; // iedereen mag er bij $security['tablet.*?'] = true; $security['telefoon.*?'] = array(RECHT_TYPE_PHONE_INTERFACE, RECHT_TYPE_GEBRUIKERS_BEHEREN); $security['extern/inloggen'] = '*'; // iedereen moet kunnen inloggen $security['extern/.*'] = true; // moet je voor ingelogd zijn $security['mvvsuite.*'] = '*'; // je hoeft niet ingelogd te zijn om bij de MVV suite SOAP service te mogen ;) $security['soapwoningborg.*'] = '*'; // je hoeft niet ingelogd te zijn om bij de SOAP dossier service te mogen ;) $security['soapdossier.*'] = '*'; // je hoeft niet ingelogd te zijn om bij de SOAP dossier service te mogen ;) $security['apperrorreports.*'] = '*'; // /** Deelplannen controller */ $security['dossiers/bekijken'] = RECHT_TYPE_DOSSIER_LEZEN; $security['dossiers/rapportage.*?'] = RECHT_TYPE_DOSSIER_LEZEN; $security['dossiers/dossieroverzicht_genereren'] = '*'; // iedereen mag er bij $security['dossiers/bewerken'] = array( RECHT_TYPE_DOSSIER_LEZEN, RECHT_TYPE_DOSSIER_SCHRIJVEN ); $security['dossiers/bescheiden_bewerken'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/bescheiden_map_toevoegen'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/bescheiden_lijst'] = array( RECHT_TYPE_DOSSIER_LEZEN, RECHT_TYPE_DOSSIER_SCHRIJVEN ); $security['dossiers/bescheiden_verwijderen_batch'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/bescheiden_downloaden'] = RECHT_TYPE_DOSSIER_LEZEN; $security['dossiers/bescheiden_popup'] = array( RECHT_TYPE_DOSSIER_SCHRIJVEN, RECHT_TYPE_DOSSIER_LEZEN ); $security['dossiers/bescheiden_verplaatsen'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/archiveren.*?'] = RECHT_TYPE_DOSSIER_AFMELDEN; $security['dossiers/verwijderen.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; // --regel access verder zelf $security['dossiers/terugzetten.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; // --regel access verder zelf $security['dossiers/subject_bewerken'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/subject_verwijderen'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/bescheiden_toevoegen'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/deelplan_toevoegen'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/nieuw'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/index'] = RECHT_TYPE_DOSSIER_LEZEN; $security['dossiers/importeren.*?'] = RECHT_TYPE_DOSSIERS_IMPORTEREN; $security['dossiers/export_progress'] = '*'; $security['dossiers/export.*?'] = RECHT_TYPE_DEELPLAN_AFDRUKKEN; $security['dossiers/save_organisatiekenmerken.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/show_pago_pmo_form.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/save_pago_pmo.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/show_pbm_form.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/save_pbm.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/show_pago_pbm_sub_taak_form.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/save_pbm_sub_task.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/pago_save_edit_sub_task_form.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/show_pbm_risk_form.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; $security['dossiers/save_documenten'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['dossiers/project_specifieke_mapping.*?'] = RECHT_TYPE_DOSSIER_SCHRIJVEN; /** Deelplannen controller */ $security['deelplannen/checklistgroep'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/show_photo'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/wetteksten'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/verantwoordingen'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/toezichtgegevens'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/store_toezichthouder'] = RECHT_TYPE_TOEWIJZEN_TOEZICHTHOUDERS; $security['deelplannen/store_matrix'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/store_planningdatum'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/verhoog_hoofdgroep_prioriteit'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/voeg_bescheiden_toe_aan_vraag'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/verantwoording_kiezen'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/verhoog_hoofdgroep_prioriteit'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/voeg_bescheiden_toe_aan_vraag'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/verwijder_bescheiden_van_vraag'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/download_richtlijn'] = RECHT_TYPE_TOEZICHTBEVINDING_LEZEN; $security['deelplannen/deelplanupload_download'] = RECHT_TYPE_TOEZICHTBEVINDING_LEZEN; $security['deelplannen/deelplanupload.*?'] = RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN; $security['deelplannen/wettelijke_grondslag'] = RECHT_TYPE_TOEZICHTBEVINDING_LEZEN; $security['deelplannen/bewerken'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/mappingmatrix'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/bescheiden_lijst'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/bekijken'] = RECHT_TYPE_DEELPLAN_LEZEN; $security['deelplannen/opdrachtenoverzicht'] = array( RECHT_TYPE_DEELPLAN_LEZEN, RECHT_TYPE_DEELPLAN_SCHRIJVEN ); $security['deelplannen/verwijderen'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/afmelden'] = RECHT_TYPE_DEELPLAN_SCHRIJVEN; $security['deelplannen/sjabloon_opslaan'] = RECHT_TYPE_OVERIG_BEHEER; $security['deelplannen/verzend_email.*?'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $security['deelplannen/opdracht_afbeelding'] = RECHT_TYPE_PHONE_INTERFACE; $security['deelplannen/project_specifieke_mapping'] = RECHT_TYPE_MAPPINGEN; $security['deelplannen/setintegraalstatus'] = RECHT_TYPE_MAPPINGEN; $security['deelplannen/change_status_akkoord'] = RECHT_TYPE_MAPPINGEN; /** PDF view controller */ $security['pdfview/(bescheiden|vraagupload)'] = array( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, RECHT_TYPE_DOSSIER_LEZEN ); /** Beheer controller */ $security['beheer/scopesjablonen'] = RECHT_TYPE_SITEBEHEER; $security['beheer/gebruiker.*$'] = RECHT_TYPE_GEBRUIKERS_BEHEREN; $security['beheer/rol.*$'] = RECHT_TYPE_GEBRUIKERS_BEHEREN; $security['beheer/matrix.*$'] = RECHT_TYPE_MATRICES_BEWERKEN; $security['beheer/risicoanalyse.*$'] = RECHT_TYPE_MATRICES_BEWERKEN; $security['beheer/prioriteit.*$'] = RECHT_TYPE_MATRICES_BEWERKEN; $security['beheer/users_groups.*$'] = RECHT_TYPE_GRP_ADMINISTRATOR; $security['beheer/naar_risicoanalyse'] = RECHT_TYPE_MATRICES_BEWERKEN; $security['beheer/managementinfo.*$'] = RECHT_TYPE_MANAGEMENT_INFO_BEKIJKEN; $security['beheer/.*$'] = RECHT_TYPE_OVERIG_BEHEER; $security['beheer/distributeur.*$'] = RECHT_TYPE_MATRICES_BEWERKEN; /** Wetten en regelgeving controller */ $security['wettenregelgeving/.*$'] = RECHT_TYPE_OVERIG_BEHEER; /** Checklistwizard controller */ $security['checklistwizard/.*$'] = RECHT_TYPE_CHECKLIST_WIZARD; /** Toezichtmoment controller */ $security['toezichtmomenten/.*$'] = RECHT_TYPE_TOEZICHTMOMENTEN; /** Toezichtmoment controller */ $security['mappingen/.*$'] = RECHT_TYPE_MAPPINGEN; $security['risicoprofielen/.*$'] = RECHT_TYPE_MAPPINGEN; /** Admin controller */ $security['admin/index.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_NIEUWS_BEHEREN, RECHT_TYPE_BACKLOG_BEHEREN, RECHT_TYPE_PARENT_KLANT_ADMIN ); $security['admin/nieuws.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_NIEUWS_BEHEREN ); $security['admin/parentadmin.*$'] = array( RECHT_TYPE_PARENT_KLANT_ADMIN ); $security['admin/account_beheer.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_PARENT_KLANT_ADMIN ); $security['admin/checklistgroep_beheer.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_PARENT_KLANT_ADMIN ); $security['admin/backlog.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_BACKLOG_BEHEREN ); $security['admin/.*?inline_edit.*$'] = array( RECHT_TYPE_INLINE_EDIT_BESCHIKBAAR ); $security['admin/account_list_users.*'] = array( RECHT_TYPE_ADD_USER_OWN_COMPANY, RECHT_TYPE_SITEBEHEER); $security['admin/account_gebruiker_toevoegen.*'] = array( RECHT_TYPE_ADD_USER_OWN_COMPANY, RECHT_TYPE_SITEBEHEER); $security['admin/account_user_edit.*'] = array( RECHT_TYPE_ADD_USER_OWN_COMPANY, RECHT_TYPE_SITEBEHEER); $security['admin/login_als.*'] = array( RECHT_TYPE_ADD_USER_OWN_COMPANY, RECHT_TYPE_SITEBEHEER); $security['admin/.*$'] = array( RECHT_TYPE_SITEBEHEER, RECHT_TYPE_PARENT_KLANT_ADMIN ); /** Webservice controller */ $security['webservice/.*$'] = '*'; // handles security on its own Leni0Semi4Brya3 /** Finally, assign to $config array, so that we're available by calling * config_item('security'). */ $config['security'] = $security; <file_sep><?php class Progress extends Controller { public function __construct() { define( 'SKIP_SESSION', true ); parent::__construct(); } public function index( $library, $download_tag ) { $this->load->helper('export'); $p = new ExportProgress( $library ); $progress = $p->get_progress( $download_tag ); if ($progress['progress'] == 1) $p->clear_progress( $download_tag ); header( 'Content-Type: text/json' ); echo json_encode( $progress ); } } <file_sep><? require_once 'base.php'; class GeolocatieResult extends BaseResult { function GeolocatieResult( &$arr ) { parent::BaseResult( 'geolocatie', $arr ); } } class Geolocatie extends BaseModel { function Geolocatie() { parent::BaseModel( 'GeolocatieResult', 'geo_locaties', true ); } public function check_access( BaseResult $object ) { // disable } } <file_sep><? require_once 'base.php'; class NieuwsResult extends BaseResult { function NieuwsResult( &$arr ) { parent::BaseResult( 'nieuws', $arr ); } function is_zichtbaar() { return $this->zichtbaar!='nee'; } } class Nieuws extends BaseModel { function Nieuws() { parent::BaseModel( 'NieuwsResult', 'nieuws', true ); } public function check_access( BaseResult $object ) { // disable } function add( $titel, $tekst, $lease_configuratie_id=null ) { /* if (!$this->dbex->is_prepared( 'add_nieuws' )) $this->dbex->prepare( 'add_nieuws', 'INSERT INTO nieuws (datum, zichtbaar, titel, tekst, lease_configuratie_id) VALUES (?, \'nee\', ?, ?, ?)' ); $args = array( 'datum' => time(), 'titel' => $titel, 'tekst' => $tekst, 'lease_configuratie_id' => $lease_configuratie_id ? $lease_configuratie_id : null, ); $this->dbex->execute( 'add_nieuws', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'datum' => time(), 'zichtbaar' => 'nee', 'titel' => $titel, 'tekst' => $tekst, 'lease_configuratie_id' => $lease_configuratie_id ? $lease_configuratie_id : null, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'issci' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } function get_alle_zichtbare_nieuwsitems( $leaseconfiguratie=null ) { $this->db->from( 'nieuws' ); $this->db->where( 'zichtbaar', 'ja' ); if ($leaseconfiguratie && $leaseconfiguratie->eigen_nieuws_berichten == 'ja') $this->db->where( 'lease_configuratie_id', $leaseconfiguratie->id ); else $this->db->where( 'lease_configuratie_id is null' ); $this->db->orderby( 'datum', 'desc' ); return $this->convert_results( $this->db->get() ); } function get_alle_nieuwsitems( $leaseconfiguratie=null ) { $this->db->from( 'nieuws' ); if ($leaseconfiguratie && $leaseconfiguratie->eigen_nieuws_berichten == 'ja') $this->db->where( 'lease_configuratie_id', $leaseconfiguratie->id ); else $this->db->where( 'lease_configuratie_id is null' ); $this->db->orderby( 'datum', 'desc' ); return $this->convert_results( $this->db->get() ); } } <file_sep><?php define( 'OUTLOOK_CRLF', "\r\n" ); class OutlookTools { static public function convert_to_gmt0( $datetime ) { $z = date( 'Z' ); // timezone offset in seconds, for e.g. Amsterdam which is +02:00 GMT, this is 7200, so to get 00:00 GMT, subtract 7200 from the timestamp! return date( 'Y-m-d H:i:s', strtotime($datetime) - $z ); } static public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } static public function wrap( $contents, $maxlen ) { // not using wordwrap(), it cuts lines where it doesn't really need to..? :X $result = array(); foreach (preg_split( "/\r?\n/", $contents ) as $line) { while (true) { if (strlen($line) <= $maxlen) { $result[] = $line; break; } else { $last_space = strrpos( substr( $line, 0, $maxlen ), ' ' ); if ($last_space === false) // no space in first $maxlen characters!! { $result[] = $line; break; } else { if ($last_space == 0) $line = substr( $line, $last_space + 1 ); // yes, cut space else { $result[] = substr( $line, 0, $last_space ); $line = ' ' . substr( $line, $last_space + 1 ); // yes, do not cut space, keep it at start of next line! } } } } } return implode( OUTLOOK_CRLF, $result ); } } class OutlookSynchronizer { private $CI; private $curCat; private $lastCat; public function __construct() { $this->CI = get_instance(); $this->CI->load->model( 'deelplan' ); $this->CI->load->model( 'dossier' ); $this->CI->load->model( 'vraag' ); $this->CI->load->library( 'simplemail' ); $this->curCat = new OutlookCatalogue(); $this->lastCat = new OutlookCatalogue(); } public function run( $options ) { OutlookTools::log( 'Outlook synchronizer running' ); // parse options $option_parts = explode( ',', $options ); $dry_run = !in_array( 'real', $option_parts ); $verbose = in_array( 'verbose', $option_parts ); $send_mail = !in_array( 'nosend', $option_parts ); $store = !in_array( 'nostore', $option_parts ); // initialize $this->_load_current_hercontrole_datums(); $this->_load_last_synchronisation_data(); // compare, take action $compare = $this->curCat->compare( $this->lastCat ); foreach ($compare->get_new_entries() as $entry) OutlookTools::log( '... new appointment for ' . $entry->get_recipient_email() . ' @ ' . $entry->get_date_and_time() . ' / ' . $entry->get_deelplan_id() ); foreach ($compare->get_updated_entries() as $entry) OutlookTools::log( '... updating appointment for ' . $entry['new']->get_recipient_email() . ' @ ' . $entry['new']->get_date_and_time() . ' / ' . $entry['new']->get_deelplan_id() ); foreach ($compare->get_deleted_entries() as $entry) OutlookTools::log( '... delete appointment for ' . $entry->get_recipient_email() . ' @ ' . $entry->get_date_and_time() . ' / ' . $entry->get_deelplan_id() ); // do work if not dry run if (!$dry_run) { $this->_send_messages( $compare, $verbose, $send_mail ); if ($store) $this->_store_new_synchronisation_data( $compare ); else OutlookTools::log( 'Nostore specified, not storing new state.' ); } else OutlookTools::log( 'Dry run, not handling messages.' ); } private function _load_current_hercontrole_datums() { // laadt initiele data $res = $this->CI->db->query(' SELECT d.id AS deelplan_id, g.email, g.volledige_naam, IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_datum,dcg.initiele_datum) AS initiele_datum, IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_start_tijd,dcg.initiele_start_tijd) AS initiele_start_tijd, IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_eind_tijd,dcg.initiele_eind_tijd) AS initiele_eind_tijd FROM deelplannen d LEFT JOIN deelplan_checklisten dcl ON d.id = dcl.deelplan_id LEFT JOIN bt_checklisten cl ON dcl.checklist_id = cl.id LEFT JOIN deelplan_checklist_groepen dcg ON d.id = dcg.deelplan_id LEFT JOIN bt_checklist_groepen cg ON dcg.checklist_groep_id = cg.id JOIN gebruikers g ON IF(cg.modus=\'niet-combineerbaar\',dcl.toezicht_gebruiker_id,dcg.toezicht_gebruiker_id) = g.id JOIN klanten k ON g.klant_id = k.id WHERE IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_datum,dcg.initiele_datum) IS NOT NULL AND IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_start_tijd,dcg.initiele_start_tijd) IS NOT NULL AND IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_eind_tijd,dcg.initiele_eind_tijd) IS NOT NULL AND d.afgemeld = 0 AND g.email IS NOT NULL AND d.outlook_synchronisatie = 1 AND g.outlook_synchronisatie = 1 AND k.outlook_synchronisatie = 1 GROUP BY d.id, IF(cg.modus=\'niet-combineerbaar\',dcl.initiele_datum,dcg.initiele_datum) '); foreach ($res->result() as $row) $entry = $this->curCat->get( $row->deelplan_id )->get( $row->initiele_datum . '|' . $row->initiele_start_tijd . '|' . $row->initiele_eind_tijd, null, null, 0, $row->email, $row->volledige_naam ); $res->free_result(); // laadt hercontrole data $res = $this->CI->db->query(' SELECT dv.vraag_id, dv.hercontrole_datum, dv.hercontrole_start_tijd, dv.hercontrole_eind_tijd, dv.deelplan_id, g.email, g.volledige_naam FROM deelplan_vragen dv JOIN deelplannen d ON dv.deelplan_id = d.id JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id -- een van de onderste twee zal matchen, vandaar de IFNULL() constructie -- bij het joinen op gebruikers! let wel: in principe ivm oude data -- kunnen ze ook ALLEBEI matchen, in welk geval dcl dan voorgaat boven dcg -- let op: in principe kan het ook zo zijn dat GEEN van tweeen matcht, -- dan is een cg of cl nog nooit toegekend aan een toezichthouder, deze -- vallen dan buiten deze query maar dat is ok: dan hebben we toch niemand -- om te emailen! LEFT JOIN deelplan_checklisten dcl ON cl.id = dcl.checklist_id AND d.id = dcl.deelplan_id LEFT JOIN deelplan_checklist_groepen dcg ON cg.id = dcg.checklist_groep_id AND d.id = dcg.deelplan_id JOIN gebruikers g ON IF(cg.modus=\'niet-combineerbaar\',dcl.toezicht_gebruiker_id,dcg.toezicht_gebruiker_id) = g.id JOIN klanten k ON g.klant_id = k.id WHERE dv.hercontrole_datum IS NOT NULL AND dv.hercontrole_start_tijd IS NOT NULL AND dv.hercontrole_eind_tijd IS NOT NULL AND d.afgemeld = 0 AND g.email IS NOT NULL AND d.outlook_synchronisatie = 1 AND g.outlook_synchronisatie = 1 AND k.outlook_synchronisatie = 1 '); foreach ($res->result() as $row) $entry = $this->curCat->get( $row->deelplan_id )->get( $row->hercontrole_datum . '|' . $row->hercontrole_start_tijd . '|' . $row->hercontrole_eind_tijd, null, null, 0, $row->email, $row->volledige_naam )->add_vraag_id( $row->vraag_id ); $res->free_result(); } private function _load_last_synchronisation_data() { $res = $this->CI->db->query(' SELECT osd.* FROM outlook_sync_data osd JOIN deelplannen de ON osd.deelplan_id = de.id JOIN dossiers do ON de.dossier_id = do.id JOIN gebruikers g ON do.gebruiker_id = g.id JOIN klanten k ON g.klant_id = k.id WHERE g.outlook_synchronisatie = 1 AND k.outlook_synchronisatie = 1 '); foreach ($res->result() as $row) { $entry = $this->lastCat->get( $row->deelplan_id )->get( $row->entry_date . '|' . $row->start_time . '|' . $row->end_time, $row->entry_uid, $row->id, $row->sequence, $row->recipient_email, $row->recipient_name ); if ($row->vraagids) $entry->add_vraag_ids( explode( ',', $row->vraagids ) ); } } private function _send_messages( OutlookCatalogueCompare $compare, $verbose, $send_mail ) { // werk administratie bij foreach ($compare->get_deleted_entries() as $entry) $entry->set_sequence( $entry->get_sequence() + 1 ); foreach ($compare->get_updated_entries() as $entry) { $entry['new']->set_sequence( $entry['old']->get_sequence() + 1 ); $entry['new']->set_database_id( $entry['old']->get_database_id() ); } // doe daadwerkelijke versturen! foreach ($compare->get_new_entries() as $i => $entry) { OutlookTools::log( 'Processing new ' . $i ); $entry->email_send_new_or_update( $verbose, $send_mail ); } foreach ($compare->get_deleted_entries() as $i => $entry) { OutlookTools::log( 'Processing delete ' . $i ); $entry->email_send_delete( $verbose, $send_mail ); } foreach ($compare->get_updated_entries() as $i => $entry) { OutlookTools::log( 'Processing update ' . $i ); if ($entry['old']->get_recipient_email() != $entry['new']->get_recipient_email()) { $entry['old']->email_send_delete( $verbose, $send_mail ); $entry['new']->set_sequence( 0 ); $entry['new']->email_send_new_or_update( $verbose, $send_mail ); } else { $entry['new']->email_send_new_or_update( $verbose, $send_mail ); } } } private function _store_new_synchronisation_data( OutlookCatalogueCompare $compare ) { foreach ($compare->get_new_entries() as $entry) $entry->database_store(); foreach ($compare->get_deleted_entries() as $entry) $entry->database_delete(); foreach ($compare->get_updated_entries() as $entry) $entry['new']->database_store(); } } class OutlookCatalogue { private $_deelplannen = array(); public function get( $deelplan_id ) { if (!isset( $this->_deelplannen[ $deelplan_id ] )) $this->_deelplannen[ $deelplan_id ] = new OutlookDeelplan( $deelplan_id ); return $this->_deelplannen[ $deelplan_id ]; } public function compare( OutlookCatalogue $from ) { $compare = new OutlookCatalogueCompare( $from, $this ); $compare->run(); return $compare; } public function deelplan_ids() { return array_keys( $this->_deelplannen ); } public function have( $deelplan_id ) { return isset( $this->_deelplannen[$deelplan_id] ); } public function all_entries() { $entries = array(); foreach ($this->_deelplannen as $od) $entries = array_merge( $entries, $od->get_entries() ); return $entries; } } class OutlookDeelplan { private $_deelplan_id; private $_entries = array(); public function __construct( $deelplan_id ) { $this->_deelplan_id = $deelplan_id; } public function get_deelplan_id() { return $this->_deelplan_id; } public function get( $date_and_time, $uid=null, $database_id=null, $sequence=0, $recipient_email=null, $recipient_name=null ) { // make sure date is in same format if (!preg_match( '/^\d{4}-\d{2}-\d{2}\|\d{2}:\d{2}(:\d{2})?\|\d{2}:\d{2}(:\d{2})?$/', $date_and_time )) throw new Exception( 'Datum en tijd niet in verwacht formaat: ' . $date_and_time ); // make sure it exists if (!isset( $this->_entries[ $date_and_time ] )) { $uid = sha1( $this->_deelplan_id . '::' . $date_and_time ); $this->_entries[ $date_and_time ] = new OutlookCalendarEntry( $this->_deelplan_id, $uid, $date_and_time, array(), $database_id, $sequence, $recipient_email, $recipient_name ); } // verify with input if given // NOTE: this never fails (at least, never seen it fail), it's here to check preconditions if ($uid) if ($this->_entries[ $date_and_time ]->get_uid() != $uid) throw new Exception( 'UID mismatch on entry ' . $this->_deelplan_id . '::' . $date_and_time . ', have ' . $uid . ' and ' . $this->_entries[ $date_and_time ]->get_uid() ); if ($database_id) if ($this->_entries[ $date_and_time ]->get_database_id() != $database_id) throw new Exception( 'Database ID mismatch on entry ' . $this->_deelplan_id . '::' . $date_and_time . ', have ' . $database_id . ' and ' . $this->_entries[ $date_and_time ]->get_database_id() ); if ($sequence) if ($this->_entries[ $date_and_time ]->get_sequence() != $sequence) throw new Exception( 'Sequence mismatch on entry ' . $this->_deelplan_id . '::' . $date_and_time . ', have ' . $sequence . ' and ' . $this->_entries[ $date_and_time ]->get_sequence() ); if ($recipient_email) if ($this->_entries[ $date_and_time ]->get_recipient_email() != $recipient_email) throw new Exception( 'Recipient email mismatch on entry ' . $this->_deelplan_id . '::' . $date_and_time . ', have ' . $recipient_email . ' and ' . $this->_entries[ $date_and_time ]->get_recipient_email() ); if ($recipient_name) if ($this->_entries[ $date_and_time ]->get_recipient_name() != $recipient_name) throw new Exception( 'Recipient name mismatch on entry ' . $this->_deelplan_id . '::' . $date_and_time . ', have ' . $recipient_name . ' and ' . $this->_entries[ $date_and_time ]->get_recipient_name() ); return $this->_entries[ $date_and_time ]; } public function dates() { return array_keys( $this->_entries ); } public function have( $date ) { return isset( $this->_entries[$date] ); } public function get_entries() { return array_values( $this->_entries ); } } class OutlookCalendarEntry { private $_deelplan_id; private $_uid; private $_date_and_time; private $_start_time; private $_end_time; private $_vraag_ids = array(); private $_database_id; private $_sequence; private $_recipient_email; private $_recipient_name; public function __construct( $deelplan_id, $uid, $date_and_time, array $vraag_ids, $database_id=null, $sequence=0, $recipient_email=null, $recipient_name=null ) { $this->_deelplan_id = $deelplan_id; $this->_uid = $uid; $this->_date_and_time = $date_and_time; $this->_vraag_ids = $vraag_ids; $this->_database_id = $database_id; $this->_sequence = $sequence; $this->_recipient_email = $recipient_email; $this->_recipient_name = $recipient_name; } public function add_vraag_id( $vraag_id ) { if (!in_array( $vraag_id, $this->_vraag_ids )) $this->_vraag_ids[] = $vraag_id; } public function add_vraag_ids( array $vraag_ids ) { foreach ($vraag_ids as $vraag_id) if (!in_array( $vraag_id, $this->_vraag_ids )) $this->_vraag_ids[] = $vraag_id; } public function set_database_id( $database_id ) { $this->_database_id = $database_id; } public function set_sequence( $sequence ) { $this->_sequence = $sequence; } public function get_deelplan_id() { return $this->_deelplan_id; } public function get_uid() { return $this->_uid; } public function get_date_and_time() // format: Y-m-d|H:i|H:i (date|starttime|endtime) { return $this->_date_and_time; } public function get_date() { $date_parts = explode( '|', $this->_date_and_time ); return $date_parts[0]; } public function get_start_time() { $date_parts = explode( '|', $this->_date_and_time ); return $date_parts[1]; } public function get_end_time() { $date_parts = explode( '|', $this->_date_and_time ); return $date_parts[2]; } public function get_vraag_ids() { return $this->_vraag_ids; } public function get_database_id() { return $this->_database_id; } public function get_sequence() { return $this->_sequence; } public function get_recipient_email() { return $this->_recipient_email; } public function get_recipient_name() { return $this->_recipient_name; } /** DATABASE ACTIONS */ public function database_store() { $now = date( 'Y-m-d H:i:s' ); $db = get_instance()->db; if ($this->_database_id) $db->query( ' UPDATE outlook_sync_data SET vraagids = ' . $db->escape(implode(',', $this->_vraag_ids)) . ', recipient_email = ' . $db->escape( $this->_recipient_email ) . ', recipient_name = ' . $db->escape( $this->_recipient_name ) . ', sequence = ' . intval( $this->_sequence ) . ', last_updated_at = ' . $db->escape( $now ) . ' WHERE id = ' . intval( $this->_database_id ) . ' '); else $db->query( ' INSERT INTO outlook_sync_data (deelplan_id, entry_uid, entry_date, start_time, end_time, vraagids, sequence, recipient_email, recipient_name, created_at, last_updated_at) VALUES( ' . intval($this->_deelplan_id) . ', ' . $db->escape($this->_uid) . ', ' . $db->escape($this->get_date()) . ', ' . $db->escape($this->get_start_time()) . ', ' . $db->escape($this->get_end_time()) . ', ' . $db->escape(implode(',', $this->_vraag_ids)) . ', ' . intval($this->_sequence) . ', ' . $db->escape( $this->_recipient_email ) . ', ' . $db->escape( $this->_recipient_name ) . ', ' . $db->escape( $now ) . ', ' . $db->escape( $now ) . ' ) '); } public function database_delete() { if (!$this->_database_id) throw new Exception( 'Kan geen calendar entry verwijderen zonder database ID: ' . var_export( $this, true ) ); $db = get_instance()->db; $db->query( 'DELETE FROM outlook_sync_data WHERE id = ' . intval( $this->_database_id) ); } /** EMAIL ACTIONS */ public function email_send_new_or_update( $verbose, $send_mail ) { try { $data = $this->_get_email_data(); } catch (Exception $e) { echo "Er is een fout opgetreden tijdens het ophalen van de data. Exception melding: " . $e->getMessage() . ". Verzending wordt overgeslagen.\n"; return; } $plain = $this->_load_template( 'new-or-update.plain', $data, false ); $vcal = $this->_load_template( 'new-or-update.vcal', $data, true ); if ($verbose) OutlookTools::log( 'VCAL message starts on next line:' . "\n" . $vcal ); if ($send_mail) $this->_send_email( $data['recipient_email'], $data['samenvatting'], $plain, $vcal ); else OutlookTools::log( 'Nosend specified, not really sending mail.' ); } public function email_send_delete( $verbose, $send_mail ) { try { $data = $this->_get_email_data(); } catch (Exception $e) { echo "Er is een fout opgetreden tijdens het ophalen van de data. Exception melding: " . $e->getMessage() . ". Verzending wordt overgeslagen.\n"; return; } $plain = $this->_load_template( 'delete.plain', $data, false ); $vcal = $this->_load_template( 'delete.vcal', $data, true ); if ($verbose) OutlookTools::log( 'VCAL message starts on next line:' . "\n" . $vcal ); if ($send_mail) $this->_send_email( $data['recipient_email'], $data['samenvatting'], $plain, $vcal ); else OutlookTools::log( 'Nosend specified, not really sending mail.' ); } private function _send_email( $recipient_email, $subject, $plain, $vcal ) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-'; $boundary = ''; for ($i=0;$i<48;++$i) $boundary .= $chars[mt_rand(0, strlen($chars) - 1)]; $content_type = 'multipart/alternative; boundary="=_' . $boundary . '"'; $fullbody = 'This is a multi-part message in MIME format. Your mail reader does not understand MIME message format.' . OUTLOOK_CRLF . '--=_' . $boundary . OUTLOOK_CRLF . $plain . OUTLOOK_CRLF . '--=_' . $boundary . OUTLOOK_CRLF . $vcal . OUTLOOK_CRLF . '--=_' . $boundary . '--' . OUTLOOK_CRLF ; OutlookTools::log( 'Emailing ' . $recipient_email ); get_instance()->simplemail->send( /* subject */ $subject, /* text */ $fullbody, /* recipients */ array( $recipient_email ), /* CC */ array(), /* BCC */ array(), /* content type */ $content_type ); } private function _load_template( $filename, array $data, $wrap ) { // controleer of template bestaat $fullfilename = APPPATH . 'controllers/cli/outlook/' . $filename; if (!is_file( $fullfilename )) throw new Exception( 'Kan calendar template niet laden: ' . $fullfilename ); // maak variabelen beschikbaar lokaal foreach ($data as $k => $v) $$k = $v; // laad inhoud ob_start(); require( $fullfilename ); $contents = ob_get_clean(); // word wrap return $wrap ? OutlookTools::wrap( $contents, 78 ) : $contents; } private function _get_email_data() { $CI = get_instance(); // haal data op if (!($deelplan = $CI->deelplan->get( $this->_deelplan_id ))) throw new Exception( 'Deelplan "' . $this->_deelplan_id . '" ongeldig' ); if (!($dossier = $deelplan->get_dossier())) throw new Exception( 'Kan dossier voor deelplan "' . $this->_deelplan_id . '" niet ophalen' ); $vragen = array(); foreach ($this->_vraag_ids as $vraag_id) if (!($vraag = $CI->vraag->get( $vraag_id ))) throw new Exception( 'Vraag "' . $vraag_id . '" ongeldig' ); else $vragen[] = $vraag; $event_start_at = date( 'Y-m-d', strtotime( $this->get_date() ) ) . ' ' . date( 'H:i:s', strtotime( $this->get_start_time() ) ); $event_end_at = date( 'Y-m-d', strtotime( $this->get_date() ) ) . ' ' . date( 'H:i:s', strtotime( $this->get_end_time() ) ); // bouw beschrijving $beschrijving = ''; $beschrijving .= date('l d F Y H:i', strtotime( $event_start_at )) . '-' . date('H:i', strtotime( $event_end_at )) . ' (GMT' . date('P') . ')' . OUTLOOK_CRLF; $beschrijving .= OUTLOOK_CRLF; $beschrijving .= 'Opmerking: in de GMT-offset hierboven is geen rekening gehouden met correcties voor de zomertijd.' . OUTLOOK_CRLF; $beschrijving .= OUTLOOK_CRLF; $beschrijving .= '*~*~*~*~*~*~*~*~*~*' . OUTLOOK_CRLF; $beschrijving .= OUTLOOK_CRLF; foreach ($vragen as $vraag) { $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); $beschrijving .= OUTLOOK_CRLF . 'Checklist: ' . $checklist->naam . OUTLOOK_CRLF . 'Onderwerp: ' . $hoofdgroep->naam . OUTLOOK_CRLF . 'Vraag: ' . $vraag->tekst . OUTLOOK_CRLF; } // geef resultaat terug return array( 'btz_versie' => BRIS_TOEZICHT_VERSION, 'recipient_naam' => $this->_recipient_name, 'recipient_email' => $this->_recipient_email, 'organizer_naam' => config_item('mail_sender'), 'organizer_email' => 'BRIStoezicht', 'created_at_unix' => strtotime( OutlookTools::convert_to_gmt0( date( 'Y-m-d H:i:s', time() ) ) ), // Outlook uses NOW as timestamp for this in both create & update messages...? 'updated_at_unix' => strtotime( OutlookTools::convert_to_gmt0( date( 'Y-m-d H:i:s', time() ) ) ), 'event_start_at_unix' => strtotime( OutlookTools::convert_to_gmt0( $event_start_at ) ), 'event_end_at_unix' => strtotime( OutlookTools::convert_to_gmt0( $event_end_at ) ), 'samenvatting' => 'Toezicht voor dossier ' . $dossier->get_kenmerk() . ', deelplan ' . $deelplan->naam, 'locatie' => $dossier->get_locatie(), 'beschrijving' => $beschrijving, 'uid' => $this->_uid, 'sequence' => $this->_sequence, ); } } class OutlookCatalogueCompare { private $_from; private $_to; private $_new_entries = array(); private $_deleted_entries = array(); private $_updated_entries = array(); public function __construct( OutlookCatalogue $from, OutlookCatalogue $to ) { $this->_from = $from; $this->_to = $to; } public function run() { // check for deleted deelplannen foreach ($this->_from->deelplan_ids() as $deelplan_id) if (!$this->_to->have( $deelplan_id )) $this->_deleted_entries = array_merge( $this->_deleted_entries, $this->_from->get( $deelplan_id )->get_entries() ); // check for new deelplannen foreach ($this->_to->deelplan_ids() as $deelplan_id) if (!$this->_from->have( $deelplan_id )) $this->_new_entries = array_merge( $this->_new_entries, $this->_to->get( $deelplan_id )->get_entries() ); // per shared deelplan, do deleted/new/updated check per date foreach ($this->_from->deelplan_ids() as $deelplan_id) { if ($this->_to->have( $deelplan_id )) { $fromDP = $this->_from->get( $deelplan_id ); $toDP = $this->_to->get( $deelplan_id ); // check for deleted dates foreach ($fromDP->dates() as $date) if (!$toDP->have( $date )) $this->_deleted_entries[] = $fromDP->get( $date ); // check for new dates foreach ($toDP->dates() as $date) if (!$fromDP->have( $date )) $this->_new_entries[] = $toDP->get( $date ); // per shared date, check for vraag_id changes foreach ($fromDP->dates() as $date) if ($toDP->have( $date )) { $fromEntry = $fromDP->get( $date ); $toEntry = $toDP->get( $date ); if ($fromEntry->get_vraag_ids() != $toEntry->get_vraag_ids()) $this->_updated_entries[] = array( 'old' => $fromEntry, 'new' => $toEntry ); } } } } public function get_new_entries() { return $this->_new_entries; } public function get_deleted_entries() { return $this->_deleted_entries; } public function get_updated_entries() { return $this->_updated_entries; } } <file_sep>-- houd bij wanneer dossiers voor het laatst zijn bijgewerkt ALTER TABLE dossiers ADD laatst_bijgewerkt_op TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER id; UPDATE dossiers SET laatst_bijgewerkt_op = NOW(); -- creeer en vul applicaties tabel CREATE TABLE IF NOT EXISTS webservice_applicaties ( id int(11) NOT NULL AUTO_INCREMENT, naam varchar(64) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB; INSERT INTO `webservice_applicaties` (`id` ,`naam`) VALUES (1, 'SSO' ); ALTER TABLE `webservice_applicaties` ADD UNIQUE (`naam`); -- pas webservice accounts aan ALTER TABLE webservice_accounts ADD webservice_applicatie_id INT NOT NULL AFTER id, ADD INDEX ( webservice_applicatie_id ) ; UPDATE webservice_accounts SET webservice_applicatie_id = 1; ALTER TABLE `webservice_accounts` ADD FOREIGN KEY ( `webservice_applicatie_id` ) REFERENCES `webservice_applicaties` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; -- creeer tabel voor bijhouden wanneer welke applicatie voor het laatst data bijgewerkt heeft gekregen CREATE TABLE IF NOT EXISTS `webservice_applicatie_dossiers` ( `id` int(11) NOT NULL, `webservice_applicatie_id` int(11) NOT NULL, `dossier_id` int(11) NOT NULL, `laatst_bijgewerkt_op` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY `webservice_applicatie_id` (`webservice_applicatie_id`), KEY `dossier_id` (`dossier_id`) ) ENGINE=InnoDB; ALTER TABLE `webservice_applicatie_dossiers` ADD CONSTRAINT `webservice_applicatie_dossiers_ibfk_2` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `webservice_applicatie_dossiers_ibfk_1` FOREIGN KEY (`webservice_applicatie_id`) REFERENCES `webservice_applicaties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><?php class AppErrorReports extends Controller { public function index() { $this->load->model( 'apperrorreport' ); // get request duur $data = array(); $start = strtotime(@$_POST['request_start']); $end = strtotime(@$_POST['request_end']); $data['request_duur'] = $end - $start; // get request data $fields = array('versie', 'datum', 'request_url', 'request_type', 'request_body', 'response_body', 'response_parseable', 'gebruiker_id', 'klant_id'); foreach ($fields as $field) if (isset( $_POST[$field] )) { $data[$field] = strval( $_POST[$field] ); if (preg_match( '/_body$/', $field )) { $decoded = @base64_decode( $data[$field] ); if ($decoded !== false) $data[$field] = $decoded; } } $this->apperrorreport->insert( $data ); echo "OK"; } } <file_sep>CREATE TABLE IF NOT EXISTS `externe_gebruikers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(128) NOT NULL, `naam` varchar(128) NOT NULL, `wachtwoord` varchar(255) NULL, `token` varchar(255) NULL, `status` enum('actief','geblokkeerd') NOT NULL DEFAULT 'geblokkeerd', PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; <file_sep><?php class Gebruikers extends Controller { function Gebruikers() { parent::Controller(); } function _add_sessie_stat( $gebruiker_id ) { if (!$this->dbex->is_prepared( 'sessie_stats_update' )) $this->dbex->prepare( 'sessie_stats_update', 'UPDATE stats_sessies SET aantal = aantal + 1, laatste_inlog = ? WHERE gebruiker_id = ?' ); if (!$this->dbex->is_prepared( 'sessie_stats_insert' )) $this->dbex->prepare( 'sessie_stats_insert', 'INSERT INTO stats_sessies (laatste_inlog, aantal, gebruiker_id) VALUES (?, 1, ?)' ); $args = array( time(), $gebruiker_id ); $res = $this->dbex->execute( 'sessie_stats_update', $args ); if ($this->db->affected_rows()==0) $this->dbex->execute( 'sessie_stats_insert', $args ); } function inloggen($post_login_location = '') { $this->login->doe_inlog_pagina($post_login_location); } function clearcookies () { // Logout first $this->kennisid->logout(); // Remove cookies. Specificially usefull if token is expired foreach ($_COOKIE as $key => $value) { unset( $_COOKIE[ $key ] ); // set empty string value, and set expire time back in the past setcookie( $key, '', time()-1800, '/' ); } redirect (site_url('/gebruikers/inloggen')); } function postlogin( $token ) { $debug_postlogin = false; //$debug_postlogin = true; if ($debug_postlogin) { echo "+++ gebruikers::postlogin +++<br />"; d($token); } if (APPLICATION_LOGIN_SYSTEM != "KennisID") { throw new Exception( "Foutief geconfigureerd login systeem." ); } $this->load->model( 'rol' ); // validate token if (!$this->kennisid->validate_token( $token ) ) { if ($debug_postlogin) die("+++ 1 +++<br />"); redirect( '/gebruikers/licentie_probleem/VerlopenTokenInReturnUrl' ); } //d($this->kennisid->set_session_token( $token )); // first, set session token, so that if (true !== ($result = $this->kennisid->set_session_token( $token ))) { if ($debug_postlogin) { echo "+++ 2 +++<br />"; d($result); die("+++ 2 +++<br />"); } redirect( '/gebruikers/licentie_probleem/' . $result ); } if ($debug_postlogin) echo "+++ 3 +++<br />"; //exit; // resolve user data locally $user_unique_id = $this->kennisid->get_user_unique_id(); $user_fullname = $this->kennisid->get_user_fullname(); $user_email = $this->kennisid->get_user_email(); $organisation_unique_id = $this->kennisid->get_organisation_unique_id(); $organisation_fullname = $this->kennisid->get_organisation_fullname(); if ($debug_postlogin) { d($user_unique_id); d($user_fullname); d($user_email); d($organisation_unique_id); d($organisation_fullname); } // resolve user & klant $create_nieuwe_klanten_en_gebruikers = config_item( 'kennisid_maak_klanten' ); $klant = $this->klant->get_by_kennisid_unique_id( $organisation_unique_id ); if ($debug_postlogin) d($klant->id); //exit; if (!$klant) { if ($debug_postlogin) echo "+++ 4 +++<br />"; if ($create_nieuwe_klanten_en_gebruikers) { if ($debug_postlogin) echo "+++ 5 +++<br />"; $klant = $this->_create_klant( $organisation_fullname, $organisation_unique_id ); if (!$klant) { if ($debug_postlogin) echo "+++ 6 +++<br />"; throw new Exception( 'Fout bij het automatisch aanmaken van interne klant gegevens.' ); } else { if ($debug_postlogin) echo "+++ 7 +++<br />"; $this->load->library( 'simplemail' ); $this->simplemail->send( '[BTZ] Nieuwe klant: ' . $klant->naam, "Er is zojuist een nieuwe klant, " . $klant->naam . ", aangemaakt in BRIStoezicht.", array( '<EMAIL>' ), array( '<EMAIL>' ) ); } } else { if ($debug_postlogin) echo "+++ 8 +++<br />"; redirect( '/gebruikers/licentie_probleem/NoKlantWithGivenUniqueIdYet: ' . $organisation_unique_id ); } } if ($debug_postlogin) echo "+++ 9 +++<br />"; $leaseconfiguratie = $klant->get_lease_configuratie(); if ($leaseconfiguratie && $leaseconfiguratie->login_systeem != 'kennisid') { if ($debug_postlogin) echo "+++ 10 +++<br />"; redirect( '/gebruikers/licentie_probleem/LoginSystemIssue' ); } $user = $this->gebruiker->get_by_kennisid_unique_id( $user_unique_id ); if ($debug_postlogin) echo "+++ 11 +++<br />"; if (!$user) { if ($debug_postlogin) echo "+++ 12 +++<br />"; if ($create_nieuwe_klanten_en_gebruikers) { if ($debug_postlogin) echo "+++ 13 +++<br />"; $user = $this->_create_user( $klant, $user_fullname, $user_unique_id ); if (!$user) { if ($debug_postlogin) echo "+++ 14 +++<br />"; throw new Exception( 'Fout bij het automatisch aanmaken van interne gebruiker gegevens.' ); } } else { if ($debug_postlogin) echo "+++ 15 +++<br />"; redirect( '/gebruikers/licentie_probleem/NoUserWithGivenUniqueIdYet: ' . $user_unique_id ); } } if ($debug_postlogin) echo "+++ 16 +++<br />"; // check if we need to update email, but only if database is empty (to allow manual overiddes in the database) if (!$user->email) { if ($debug_postlogin) echo "+++ 17 +++<br />"; $user->email = $user_email; $user->save(); } // make sure user.klant_id == klant.id if ($user->klant_id != $klant->id) { if ($debug_postlogin) echo "+++ 18 +++<br />"; redirect( '/gebruikers/licentie_probleem/InterneRegistratieIssue' ); } if ($debug_postlogin) echo "+++ 19 +++<br />"; $this->login->login( $user->id ); if ($debug_postlogin) echo "+++ 20 +++<br />"; // done, redirect to main page! $this->session->set_userdata( 'kid', $klant->id ); if ($debug_postlogin) { echo "+++ 21 +++<br />"; //d($user); d($this->session); exit; } //exit; redirect(); } private function _create_klant( $klantnaam, $klant_kennisid ) { return $this->klant->add( $klantnaam, $klant_kennisid ); } private function _create_user( KlantResult $klant, $volledige_naam, $user_kennisid ) { // bepaal rol $gebruikers = $klant->get_gebruikers( true ); if (sizeof( $gebruikers ) == 0) $rol = $this->rol->get_beheer_default(); else $rol = $this->rol->get_toezichthouder_default(); // maak nieuwe gebruiker $user = $this->gebruiker->add( $klant->id, $volledige_naam, $rol->id, $user_kennisid ); if ($user) { // maak deze gebruiker collega van elke andere gebruiker // maar alleen als dit geen lease klant is, of als de lease config stelt dat // we WEL automatisch collega's willen zijn $leaseconfiguratie = $klant->get_lease_configuratie(); if (!$leaseconfiguratie || $leaseconfiguratie->automatisch_collega_zijn == 'ja') { foreach ($gebruikers as $gebruiker) { $gebruiker->add_collega( $user->id ); $user->add_collega( $gebruiker->id ); } } } // done return $user; } function licentie_probleem( $details=null ) { $this->load->view( 'gebruikers/licentie_probleem', array( 'details' => rawurldecode( $details ), ) ); } function uitloggen() { $this->login->doe_uitlog_pagina(); } } <file_sep><?php class Content extends Controller { function Content() { define( 'SKIP_SESSION', true ); parent::Controller(); } function _init( $content_type, $max_age, $filename=null, $cache_control=true ) { header( 'Content-Type: ' . $content_type ); if ($cache_control) { header( 'Pragma: public' ); header( 'Cache-Control: max-age='.$max_age.', public' ); header( 'Expires: ' . date( "D, d M Y H:i:s", time() + $max_age ) . ' GMT' ); } if (!is_null($filename)) header('Content-Disposition: attachment; filename="'.$filename.'"'); } function prototype() { $this->_init( 'application/x-javascript', 24*60*60, null, false ); $this->_output_cache_headers( sha1( 'prototype') ); $this->load->view('content/prototype-1.6.1.js'); } function css() { $this->_init( 'text/css', 24*60*60, null, false ); $this->_output_cache_headers( sha1( 'css' ) ); $this->load->view('content/css'); } function png( $image='' ) { $this->_output_cache_headers( sha1($image) ); $this->_init( 'image/png', 24*60*60 ); if (preg_match( '/[a-zA-Z0-9_]+/', $image )!==FALSE) $this->load->view('content/'.$image.'.png'); } function jpg( $image='' ) { $this->_output_cache_headers( sha1($image) ); $this->_init( 'image/jpg', 24*60*60 ); if (preg_match( '/[a-zA-Z0-9_]+/', $image )!==FALSE) $this->load->view('content/'.$image.'.jpg'); } function images( $image_id='' ) { $this->load->model( 'image' ); if (!($image = $this->image->get( intval($image_id) ))) { header( 'HTTP/1.1 404 File Not Found' ); exit; } $this->_output_cache_headers( sha1($image->id) ); $this->_init( 'image/png', 30*24*60*60 ); echo $image->data; } function logo( $klant_id=null, $klein=1 ) { $this->_init( 'image/png', 24*60*60 ); $klant = $this->klant->get( $klant_id ); if ($klant==null) $this->load->view('content/leeg.png'); else if ($klein && $klant->logo_klein) echo $klant->logo_klein; else if (!$klein && $klant->logo) echo $klant->logo; else $this->load->view('content/leeg.png'); } private function _output_cache_headers( $etag=null) { $cacheTime = 365 * 86400; $cacheExpires = strtotime( '+1 year' ); header( 'Cache-Control: max-age=' . $cacheTime . ',public' ); header( 'Pragma: public' ); header( 'Expires: ' . date( 'D, d M Y H:i:s ', $cacheExpires ) ) . ' UTC'; header( 'Last-Modified: ' . date( 'D, d M Y H:i:s ' ) ) . ' GMT'; if ($etag) { header( 'Etag: ' . $etag ); // check etag if (@$_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header("HTTP/1.1 304 Not Modified"); exit; } } } function verttext( $text='(geen tekst)', $fontsize=8, $textcolor='000000', $bgcolor='FFFFFF', $height=null, $width=null ) { $this->_output_cache_headers( sha1($text) ); $text = rawurldecode( rawurldecode( rawurldecode( $text ) ) ); // determine image size $fontfile = realpath( APPPATH.'fonts/verdana.ttf' ); $tekstwidth = imagettfbbox( $fontsize, 0, $fontfile, $text ); $w = is_null($height) ? (abs( $tekstwidth[2] - $tekstwidth[0] ) + 12) : $height; $h = is_null($width) ? (abs( $tekstwidth[5] - $tekstwidth[1] ) + 5) : $width; $im = imagecreatetruecolor( $w, $h ); // colors $tc = imagecolorallocate( $im, hexdec(substr($textcolor,0,2)), hexdec(substr($textcolor,2,2)), hexdec(substr($textcolor,4,2)) ); $bc = imagecolorallocate( $im, hexdec(substr($bgcolor,0,2)), hexdec(substr($bgcolor,2,2)), hexdec(substr($bgcolor,4,2)) ); // fill bg and write text imagefilledrectangle( $im, 0, 0, $w, $h, $bc ); imagettftext( $im, $fontsize, 0, 0, $h-5, $tc, $fontfile, $text ); $im2 = imagerotate( $im, 90, $bc ); // output! header("Content-type: image/png"); imagepng($im2); imagedestroy($im2); imagedestroy($im); } } <file_sep><?php /** Webservice class. Implement your own functions in here. * Register them, and the types they need, as shown in the example code in the constructor. */ class WoningborgWebservice extends AbstractWebservice { private $_CI = null; // SOAP specific members, used for constructing the content, parameters, etc. // Note: these members have nothing to do with the class we are implementing here! Instead they are used for calling the main 'soapDossier' webservice! //private $soap_wsdl = "https://www.bristoezicht.nl/soapdossier/wsdl"; //private $remoteBtzSoapWsdl = "https://acceptatie.mtmi.imotepbv.nl/soapdossier/wsdl"; //private $remoteBtzSoapWsdl = "http://btz.localhost/soapdossier/wsdl"; private $remoteBtzSoapWsdl = ""; private $remoteBtzSoapLicentieNaam = "WB_woningborg_usr"; private $remoteBtzSoapLicentieWachtwoord = "<PASSWORD>org_pwd"; //private $remoteBtSoapWsdl = "https://ota.bristoets.nl/soapdossier?wsdl"; //private $remoteBtSoapWsdl = "http://bt.localhost/soapdossier?wsdl"; private $remoteBtSoapWsdl = ""; private $remoteBtSoapLicentieNaam = "WB_woningborg_usr"; private $remoteBtSoapLicentieWachtwoord = "<PASSWORD>"; // Specify specific private members for this class here private $btzWoningborgKlant = null; private $btWoningborgKlant = null; public function __construct() { // At least during the development phase, set the error_reportuing level such that we can see what is going on if something fails! error_reporting(E_ALL); // Note: the following 'define' is VERY important, as not setting it causes the security mechanism to act up on us where we do not want it to!!! define('IS_WEBSERVICE', true); // Get a reference to the CI object $this->_CI = get_instance(); // // STEP 1: Call parent constructor, and initialize // parent::__construct(); $this->_initialize(); // Initialise the proper URIs of the BT and BTZ Soapdossier webservices from the config.php file //$this->remoteBtzSoapWsdl = "https://acceptatie.mtmi.imotepbv.nl/soapdossier/wsdl"; //$this->remoteBtSoapWsdl = "https://ota.bristoets.nl/soapdossier?wsdl"; $this->remoteBtzSoapWsdl = $this->_CI->config->item('ws_url_wsdl_mtmi_soapdossier'); $this->remoteBtSoapWsdl = $this->_CI->config->item('ws_url_wsdl_bt_soapdossier'); // Load the SOAP client helper $this->_CI->load->helper( 'soapclient' ); // Load the models we will be using $this->_CI->load->model( 'webserviceaccount' ); $this->_CI->load->model( 'klant' ); $this->_CI->load->model( 'gebruiker' ); $this->_CI->load->model( 'dossier' ); //$this->_CI->load->model( 'deelplan' ); $this->_CI->load->model( 'btbtzdossier' ); $this->_CI->load->model( 'deelplanchecklisttoezichtmoment' ); // Get the BTZ Woningborg 'klant' object $this->btzWoningborgKlant = $this->_CI->klant->get_by_naam('<NAME>'); // !!! TODO: Get the BT Woningborg 'klant' object $this->btWoningborgKlant = new stdClass(); $this->btWoningborgKlant->id = '275'; $this->btWoningborgKlant->naam = 'Woningborg NV'; // // STEP 2: Register types, starting with simple types, and working to structs and arrays // of structs and/or simple types. Remember that types must be known when used, so register // them in the proper order. // The abstract base class knows the following simple types: string, int, boolean and base64Binary. // //$this->_register_compound_type( 'MyStruct', array( 'fieldname1'=>'int', 'fieldname2'=>'string' ) ); //$this->_register_array_type( 'MyStructArray', 'MyStruct' ); /***** AUXILIARY TYPES (BEGIN) *****/ // Define an auxiliary type for the 'gebruikers' $this->_register_compound_type( 'typeGebruiker', array( 'gebruikerId' => 'int', 'volledigeNaam' => 'string', 'email' => 'string' ) ); $this->_register_array_type( 'arrayTypeGebruiker', 'typeGebruiker' ); // Define an auxiliary type for the 'betrokkenen' $this->_register_compound_type( 'typeBetrokkene', array( 'betrokkeneId' => 'int', 'organisatie' => 'string', 'naam' => 'string', 'rol' => 'string', 'straat' => 'string', 'huisNummer' => 'string', 'huisNummerToevoeging' => 'string', 'postcode' => 'string', 'woonplaats' => 'string', 'telefoon' => 'string', 'email' => 'string', //'gebruikerId' => 'int' // !! Maybe we should make this available? ) ); $this->_register_array_type( 'arrayTypeBetrokkene', 'typeBetrokkene' ); // Define an auxiliary type for the 'document' $this->_register_compound_type( 'typeDocument', array( 'documentId' => 'int', 'omschrijving' => 'string', 'zaakNummerRegistratie' => 'string', 'tekeningNummer' => 'string', 'versieNummer' => 'string', 'datumLaatsteWijziging' => 'string', 'auteur' => 'string', 'bestandsNaam' => 'string', 'bestand' => 'base64Binary' ) ); //$this->_register_array_type( 'arrayTypeDocument', 'typeDocument' ); // Define an auxiliary type for the 'toezichtmoment' $this->_register_compound_type( 'typeToezichtmoment', array( 'toezichtmomentId' => 'int', 'naam' => 'string', 'nummer' => 'string', 'subNummer' => 'string', 'emailUitvoerende' => 'string', 'voornaamUitvoerende' => 'string', 'achternaamUitvoerende' => 'string', 'geslachtUitvoerende' => 'string', 'mobieleNummerUitvoerende' => 'string', 'datumBegin' => 'string', // Date format 'datumEinde' => 'string', // Date format 'statusAkkoordWoningborg' => 'string', 'statusGereedUitvoerende' => 'string', 'toezichthouderWoningborg' => 'typeGebruiker', 'bijwoonmoment' => 'string', // ??? What do we provide here? A date perhaps?!? or a boolean?! 'datumHercontrole' => 'string', // Date format 'sorteerVolgorde' => 'int' ) ); $this->_register_array_type( 'arrayTypeToezichtmoment', 'typeToezichtmoment' ); // Define an auxiliary type for the 'rapport' $this->_register_compound_type( 'typeRapport', array( 'rapportFormaat' => 'string', // 'PDF' of 'DOCX' 'rapport' => 'base64Binary' ) ); /***** AUXILIARY TYPES (END) *****/ /***** RETURN TYPES (BEGIN) *****/ // Define a return type for the result of getting 'gebruikers' data $this->_register_compound_type( 'typeGebruikersResult', array( 'toetsGebruikers' => 'arrayTypeGebruiker', 'toezichtGebruikers' => 'arrayTypeGebruiker' ) ); $this->_register_compound_type( 'resultSoapGetGebruikers', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeGebruikersResult' ) ); // Define a return type for the result of getting a 'project status' $this->_register_compound_type( 'typeProjectStatus', array( 'projectId' => 'int', 'status' => 'string', 'datumTijdLaatsteWijziging' => 'string' ) ); $this->_register_array_type( 'arrayTypeProjectStatus', 'typeProjectStatus' ); $this->_register_compound_type( 'typeProjectStatusResult', array( 'projectStatussen' => 'arrayTypeProjectStatus' ) ); $this->_register_compound_type( 'resultSoapGetProjectStatus', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeProjectStatusResult' ) ); // Define a return type for the result of getting 'toezichtmomenten' of a project $this->_register_compound_type( 'typeProjectToezichtmomentenResult', array( 'toezichtmomenten' => 'arrayTypeToezichtmoment' ) ); $this->_register_compound_type( 'resultSoapGetProjectToezichtmomenten', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeProjectToezichtmomentenResult' ) ); // Define a return type for the 'rapportage' result data // 'projectId' => 'int', $this->_register_compound_type( 'typeProjectRapportageResult', array( 'toetsRapport' => 'typeRapport', 'toezichtRapport' => 'typeRapport' ) ); $this->_register_compound_type( 'resultSoapGetProjectRapportage', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeProjectRapportageResult' ) ); // Define a return type for the result of manipulating a 'project' $this->_register_compound_type( 'typeAssignedBetrokkene', array( 'assignedBetrokkeneId' => 'int', 'naam' => 'string', 'email' => 'string' ) ); $this->_register_array_type( 'arrayTypeAssignedBetrokkene', 'typeAssignedBetrokkene' ); $this->_register_compound_type( 'typeSoapManipulateProjectResult', array( 'projectId' => 'int', 'projectHash' => 'string', 'actionResultMessage' => 'string', 'assignedBetrokkenen' => 'arrayTypeAssignedBetrokkene' ) ); $this->_register_compound_type( 'resultSoapManipulateProject', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeSoapManipulateProjectResult' ) ); // Define a return type for the result of manipulating a 'document' $this->_register_compound_type( 'typeSoapManipulateDocumentResult', array( 'documentId' => 'int', 'actionResultMessage' => 'string' ) ); $this->_register_compound_type( 'resultSoapManipulateDocument', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeSoapManipulateDocumentResult' ) ); // Define a return type for the result of manipulating a 'toezichtmoment' $this->_register_compound_type( 'typeSoapManipulateToezichtmomentResult', array( 'toezichtmomentId' => 'int', 'actionResultMessage' => 'string' ) ); $this->_register_compound_type( 'resultSoapManipulateToezichtmoment', array( 'success' => 'boolean', 'message' => 'string', 'errorCode' => 'int', 'results' => 'typeSoapManipulateToezichtmomentResult' ) ); /***** RETURN TYPES (END) *****/ /***** INPUT PARAMETERS TYPES (BEGIN) *****/ // Define the 'parameters' type for the 'soapGetGebruikers' method $this->_register_compound_type( 'parametersSoapGetGebruikers', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'filter' => 'string', // If empty, no filtering occurs. If set to 'toets' or 'toezicht', it will only get the users of these respective contexts. ) ); // Define the 'parameters' type for the 'soapGetProjectStatus' method $this->_register_compound_type( 'parametersSoapGetProjectStatus', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'projectHash' => 'string', 'projectId' => 'int' ) ); // Define the 'parameters' type for the 'soapGetProjectToezichtmomenten' method $this->_register_compound_type( 'parametersSoapGetProjectToezichtmomenten', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'projectHash' => 'string', 'projectId' => 'int' ) ); // Define the 'parameters' type for the 'soapGetProjectRapportage' method $this->_register_compound_type( 'parametersSoapGetProjectRapportage', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'projectHash' => 'string', 'projectId' => 'int', 'formaat' => 'string', // DOCX of PDF 'filter' => 'string' // If empty, no filtering occurs. If set to 'toets' or 'toezicht', it will only get the users of these respective contexts. ) ); // Define the 'parameters' type for the 'soapManipulateProject' method $this->_register_compound_type( 'parametersSoapManipulateProject', array( // Common: 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'filter' => 'string', // If empty, no filtering occurs. If set to 'toets' or 'toezicht', it will only get the users of these respective contexts. 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'projectHash' => 'string', // Applicable to: Edit, Delete, Check 'projectId' => 'int', // Applicable to: Add, Edit, Delete, Check 'projectNaam' => 'string', // Applicable to: Add, Edit, Check 'identificatieNummer' => 'string', // Applicable to: Add, Edit, Check 'aanmaakDatum' => 'string', // Applicable to: Add, Edit 'bagNummer' => 'string', // Applicable to: Add, Edit 'xyCoordinaten' => 'string', // Applicable to: Add, Edit 'locatieStraat' => 'string', // Applicable to: Add, Edit 'locatieHuisNummer' => 'string', // Applicable to: Add, Edit 'locatieHuisNummerToevoeging' => 'string', // Applicable to: Add, Edit 'locatiePostcode' => 'string', // Applicable to: Add, Edit 'locatieWoonplaats' => 'string', // Applicable to: Add, Edit 'opmerkingen' => 'string', // Applicable to: Add, Edit // BRIStoezicht specific 'toezichtProjectVerantwoordelijkeId' => 'int', // Applicable to: Add, Edit 'toezichtBetrokkenen' => 'arrayTypeBetrokkene', // Applicable to: Add, Edit // BRIStoets specific 'toetsProjectVerantwoordelijkeId' => 'int', // Applicable to: Add, Edit 'toetsDatum' => 'string' // Applicable to: Add, Edit ) ); // Define the 'parameters' type for the 'soapManipulateDocument' method $this->_register_compound_type( 'parametersSoapManipulateDocument', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'projectHash' => 'string', // Applicable to: Add, Edit, Delete, Check 'projectId' => 'int', // Applicable to: Add, Edit, Delete, Check 'document' => 'typeDocument' // Applicable to: Add, Edit, Delete, Check - could be changed to 'arrayTypeDocument' for multiple documents ) ); // Define the 'parameters' type for the 'soapManipulateToezichtmoment' method $this->_register_compound_type( 'parametersSoapManipulateToezichtmoment', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'projectHash' => 'string', // Applicable to: Add, Edit, Delete, Check 'projectId' => 'int', // Applicable to: Add, Edit, Delete, Check 'toezichtmoment' => 'typeToezichtmoment' // Applicable to: Add, Edit, Delete, Check - could be changed to 'arrayTypeDocument' for multiple documents ) ); /***** INPUT PARAMETERS TYPES (END) *****/ // // STEP 3: Register methods. All types used here must be registered in step 2, except for the // aforementioned list of simple types in step 2. // /* $this->_register_method( 'int', 'createFoo', array( 'bar' => 'int' ) ); $this->_register_method( 'int', 'createFoo2', array( 'bar1' => 'int', 'bar2' => 'string', 'bar3' => 'boolean', 'bar4' => 'base64Binary', 'bar5' => 'MyStruct', 'bar6' => 'MyStructArray' ) ); $this->_register_method( 'MyStructArray', 'fooBar', array( 'parm' => 'MyStruct' ) ); * */ // Register the RPC calls we want to make available. // "MANIPULATE" methods $this->_register_method( 'resultSoapManipulateProject', 'soapManipulateProject', array( 'parameters' => 'parametersSoapManipulateProject' ) ); $this->_register_method( 'resultSoapManipulateDocument', 'soapManipulateDocument', array( 'parameters' => 'parametersSoapManipulateDocument' ) ); $this->_register_method( 'resultSoapManipulateToezichtmoment', 'soapManipulateToezichtmoment', array( 'parameters' => 'parametersSoapManipulateToezichtmoment' ) ); // "GET" methods $this->_register_method( 'resultSoapGetGebruikers', 'soapGetGebruikers', array( 'parameters' => 'parametersSoapGetGebruikers' ) ); $this->_register_method( 'resultSoapGetProjectStatus', 'soapGetProjectStatus', array( 'parameters' => 'parametersSoapGetProjectStatus' ) ); $this->_register_method( 'resultSoapGetProjectToezichtmomenten', 'soapGetProjectToezichtmomenten', array( 'parameters' => 'parametersSoapGetProjectToezichtmomenten' ) ); $this->_register_method( 'resultSoapGetProjectRapportage', 'soapGetProjectRapportage', array( 'parameters' => 'parametersSoapGetProjectRapportage' ) ); // // STEP 4: Finalize! // $this->_finalize(); } /************************* HELPER METHODS (BEGIN) *************************/ // Helper method for checking the validity of the passed license name and password. private function checkCredentials($licenseName, $licensePassword) { // Try to retrieve the user record with the passed credentials $userAccount = $this->_CI->webserviceaccount->find_by_username_and_password($licenseName, $licensePassword); // If no user was found return 'false'. if (is_null($userAccount)) { return false; } // If the user credentials do not match those of the correct webservice, or if the webservice is not active, return 'false'. $wsApplication = $userAccount->get_applicatie(); // If the result was 'null' it means the user credentials provided no match, hence, a result that is not null means the user was found. return ( ($wsApplication->actief == 1) && ($wsApplication->naam == 'Woningborg') ); } // private function checkCredentials($licenseName, $licensePassword) // Helper method for checking several of the 'common' parameters and other required data, etc. // This method will typically be called in the beginning of an RPC method, to take care of common checks before doing the actual RPC method work. // Note that this method uses a 'fall-through' mechanism, meaning that it returns early in case a situation is encountered that should result in // an error being returned, rather than performing ALL checks then. private function checkCommonParametersAndData($checksToPerform = array(), &$resultSet = array()) { // Initialise the resultset if it was empty. Note that this ONLY initialises the members that can be set in this method! Hence, it is NOT a // full resultset as the RPC methods should return it !!! if (empty($resultSet)) { $resultSet = array( 'errorCode' => -1, // No error code determined yet 'message' => '' // No message determined yet ); } // Perform a 'license check', if instructed to do so. if (array_key_exists('licenseCheck', $checksToPerform)) { //echo "checkCommonParametersAndData::licenseCheck<br />"; // Extract the value(s) to check $licenseName = (!empty($checksToPerform['licenseCheck']['licenseName'])) ? $checksToPerform['licenseCheck']['licenseName'] : ''; $licensePassword = (!empty($checksToPerform['licenseCheck']['licensePassword'])) ? $checksToPerform['licenseCheck']['licensePassword'] : ''; // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($licenseName, $licensePassword)) { // Store the error message to the result set and return early $resultSet['errorCode'] = 1; // Ongeldige licentie opgegeven $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } } // if (in_array('licenseCheck', $checksToPerform)) // Perform an 'action check', if instructed to do so. if (array_key_exists('actionCheck', $checksToPerform)) { // Extract the value(s) to check $actionValue = (!empty($checksToPerform['actionCheck'])) ? $checksToPerform['actionCheck'] : ''; $actionAllowedValues = (!empty($checksToPerform['actionAllowedValues'])) ? $checksToPerform['actionAllowedValues'] : array(); // Check if the specified action value is allowed. If not, inform the caller of this. if ( empty($actionValue) || !in_array($actionValue, $actionAllowedValues) ) { // Store the error message to the result set and return early $resultSet['errorCode'] = 2; // Ongeldige actiewaarde opgegeven. $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "Ongeldige actie '{$actionValue}' opgegeven. Geldige waarden: " . implode(', ', $actionAllowedValues); return $resultSet; } } // if (in_array('actionCheck', $checksToPerform)) // Perform a 'filter check', if instructed to do so. if (array_key_exists('filterCheck', $checksToPerform)) { // Extract the value(s) to check $filterValue = (!empty($checksToPerform['filterCheck'])) ? $checksToPerform['filterCheck'] : ''; // Check if the specified filter value is valid. If not, inform the caller of this. if ( !empty($filterValue) && ($filterValue != 'toezicht') && ($filterValue != 'toets') ) { // Store the error message to the result set and return early $resultSet['errorCode'] = 3; // Ongeldige filterwaarde opgegeven. $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "Ongeldige filterwaarde '{$filterValue}' opgegeven. Geldige waarden: <leeg>, 'toets', 'toezicht'"; return $resultSet; } } // if (in_array('filterCheck', $checksToPerform)) // Perform a 'BTZ Woningborg client record exists', if instructed to do so. if (array_key_exists('btzWoningborgRecordExistsCheck', $checksToPerform) && $checksToPerform['btzWoningborgRecordExistsCheck']) { if (is_null($this->btzWoningborgKlant)) { // Store the error message to the result set and return early $resultSet['errorCode'] = 4; // BTZ Klantrecord niet correct opgehaald $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "Interne fout: Woningborg klantrecord kon niet opgehaald worden uit BRIStoezicht"; return $resultSet; } } // if (in_array('btzWoningborgRecordExistsCheck', $checksToPerform) && $checksToPerform['btzWoningborgRecordExistsCheck']) // Perform a 'BT Woningborg client record exists', if instructed to do so. if (array_key_exists('btWoningborgRecordExistsCheck', $checksToPerform) && $checksToPerform['btWoningborgRecordExistsCheck']) { if (is_null($this->btWoningborgKlant)) { // Store the error message to the result set and return early $resultSet['errorCode'] = 5; // BT Klantrecord niet correct opgehaald $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "Interne fout: Woningborg klantrecord kon niet opgehaald worden uit BRIStoets"; return $resultSet; } } // if (in_array('btWoningborgRecordExistsCheck', $checksToPerform) && $checksToPerform['btWoningborgRecordExistsCheck']) // If we reached this point, we simply return the resultset unaltered. As the resultset was passed by reference, this is not really necessary, // but it is done nonetheless so the function ALWAYS has precisely one return value. return $resultSet; } // private function checkCommonParametersAndData($checksToPerform = array(), &$resultSet = array()) // Helper method for retrieving the dossier and performing the security checks on it. private function getExistingDossier($dossierId, $dossierHash, &$resultSet) { // Initialise the dossier to null $existingDossier = null; // Try to obtain the dossier, error out on exceptions. try { // Use the model to (try to) retrieve the dossier. $existingDossier = $this->_CI->dossier->get( $dossierId ); } catch (exception $e) { // If the call failed, register the unsuccessful outcome and return early // Set the error message and code in the result set. $errorCode = 8; // Interne fout: BRIStoezicht dossier kon niet opgehaald worden. $errorMessage = "Het BRIStoezicht dossier met ID '{$dossierId}' is NIET succesvol opgehaald. Reden: " . $e->getMessage(); $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); // Perform an early return, making sure to return null return null; } // Check if a (valid) dossier has been retrieved, and if so, if the passed credentials match, so we allow edits. if (is_null($existingDossier)) { // If no dossier could be found for the passed ID, return early // Set the error message and code in the result set. $errorCode = 9; // Interne fout: BRIStoezicht dossier bestaat niet. $errorMessage = "Het BRIStoezicht dossier met ID '{$dossierId}' bestaat niet."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } else { // Check the dossierHash against the passed value $dossierHashValid = ( (strlen($dossierHash) == 40) && (strlen($existingDossier->dossier_hash) == 40) && ($dossierHash == $existingDossier->dossier_hash) ); // Only allow further processing if the dossier came in through the webservice, AND if it passes the check on the dossier hash. if ( !$dossierHashValid || ($existingDossier->herkomst != 'koppeling') ) { // Reset the retrieved dossier to null, to signal that we do not have access over it $existingDossier = null; // Set the error message and code in the result set. $errorCode = 10; // Interne fout: BRIStoezicht dossier mag niet via de koppeling bewerkt worden. $errorMessage = "Het BRIStoezicht dossier met ID '{$dossierId}' mag niet via de koppeling bewerkt worden."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } else { // Returning the dossier hash for other actions than 'Add' is not really necessary, but it can be used by the caller as a double check. // Make sure to only set the dossier hash in case it was predefined in the result set. if (array_key_exists('results', $resultSet) && array_key_exists('dossierHash', $resultSet['results'])) { $resultSet['results']['dossierHash'] = strval($existingDossier->dossier_hash); } } } // Return the retrieved dossier, if any, and if the passed credentials allow access to it. If not, make sure to return null. return $existingDossier; } // private function getExistingDossier($dossierId, $dossierHash, &$resultSet) // Helper method for retrieving the BT-BTZ dossier mapping record and performing error handling on it. private function getExistingBtBtzDossier($btzDossierId, $btzDossierHash, &$resultSet) { // Initialise the BT-BTZ dossier to null $existingBtBtzDossier = null; // Try to obtain the dossier, error out on exceptions. try { // Use the model to (try to) retrieve the dossier. $existingBtBtzDossier = $this->_CI->btbtzdossier->get_one_by_btz_dossier_id_and_hash( $btzDossierId, $btzDossierHash ); if (is_null($existingBtBtzDossier)) { throw new Exception ("Geen mapping record gevonden voor de opgegeven 'ID' en 'hash' waarden"); } } catch (exception $e) { // If the call failed, register the unsuccessful outcome and return early $errorCode = 11; // Interne fout: mapping tussen BRIStoezicht en BRIStoets dossiers kon niet opgehaald worden. $errorMessage = "De mapping tussen de BRIStoets en BRIStoezicht dossiers met project ID '{$btzDossierId}' en project hash '{$btzDossierHash}' is NIET succesvol opgehaald. Reden: " . $e->getMessage(); $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); // Perform an early return, making sure to return null return null; } // Return the retrieved mapping record, if any, and if the passed credentials allow access to it. If not, make sure to return null. return $existingBtBtzDossier; } // private function getExistingDossier($dossierId, $dossierHash, &$resultSet) // Helper function for generically setting an error code and message in a result set. private function setErrorCodeAndMessage($errorCode, $errorMessage, &$resultSet) { $resultSet['success'] = false; $resultSet['errorCode'] = $errorCode; if (!empty($resultSet['message'])) { $resultSet['message'] .= "\n"; } $resultSet['message'] .= $errorMessage; if (array_key_exists('actionResultMessage', $resultSet['results'])) { if (!empty($resultSet['results']['actionResultMessage'])) { $resultSet['results']['actionResultMessage'] .= "\n"; } $resultSet['results']['actionResultMessage'] .= $errorMessage; } // Return the result set too, in case the caller expects it as a return value. return $resultSet; } // private function setErrorCodeAndMessage($errorCode, $errorMessage, &$resultSet) // Gets a BTZ gebruiker record of a 'Woningborg' user. If no valid 'gebruiker' could be established for 'Woningborg', get the 'nog_niet_toegewezen' user. // Also verify that the user actually belongs to Woningborg. If everything fails, error out. private function getBtzGebruiker($gebruikerId, &$resultSet) { $btzGebruiker = null; // First we check if the proper 'client' record exists for 'Woningborg'. If not, error out early. // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'btzWoningborgRecordExistsCheck' => true ); //d($checksToPerform); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If at this point an errorCode has been set, the 'Woningborg client record' was not properly obtained so we cannot continue. If so, error out here. if ($resultSet['errorCode'] > 0) { // Force return 'null'. Note that the error message is retrievable in the resultSet that was passed by reference. return null; } // If we reached this point and no errorCode has been set, the 'Woningborg client record' exists so we can continue. // Try to get the user record. $btzGebruiker = $this->_CI->gebruiker->get($gebruikerId); // Verify the retrieved record (if any). $gebruikerRecordValid = true; if (is_null($btzGebruiker)) { $gebruikerRecordValid = false; $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "BRIStoezicht gebruiker met ID '{$gebruikerId}' bestaat niet."; } // Check if the retrieved 'gebruiker' record (if any) belongs to 'Woningborg'. if ($gebruikerRecordValid) { if ($btzGebruiker->klant_id != $this->btzWoningborgKlant->id) { $gebruikerRecordValid = false; $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "BRIStoezicht gebruiker met ID '{$gebruikerId}' behoort niet toe aan Woningborg."; } } // If at this point the '$gebruikerRecordValid' boolean is still true, we are done. If not, try to determine if a 'nog_niet_toegewezen' user can be determined // for 'Woningborg'. If so, use that user instead. if (!$gebruikerRecordValid) { // Get 'all Woningborg gebruikers with name or login like "<PASSWORD>"' (this really ought to return a maximum of 1 gebruiker, if any at all). // If any was/were found, simply use the first of them. $woningborgGebruikers = $this->_CI->gebruiker->get_by_klant($this->btzWoningborgKlant->id, false, 'nog_niet_toegewezen'); $btzGebruiker = (!empty($woningborgGebruikers)) ? reset($woningborgGebruikers) : null; if (!is_null($btzGebruiker)) { $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "BRIStoezicht 'nog niet toegewezen' gebruiker wordt gebruikt."; } else { // At this point no valid user could be determined, not even a 'fallback' 'nog_niet_toegewezen' user, so error out. $resultSet['errorCode'] = 6; // BTZ Klantrecord niet correct opgehaald $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . "BRIStoezicht 'nog niet toegewezen' gebruiker niet gevonden. Kan geen geldige BRIStoezicht gebruiker bepalen."; return null; } } // Returns null or a valid gebruiker return $btzGebruiker; } // private function getBtzGebruiker($gebruikerId, &$resultSet) // Gets a BT gebruiker record of a 'Woningborg' user. If no valid 'gebruiker' could be established for 'Woningborg', get the 'nog_niet_toegewezen' user. // Also verify that the user actually belongs to Woningborg. If everything fails, error out. private function getBtGebruiker($gebruikerId, &$resultSet) { $btGebruiker = null; // First we check if the proper 'client' record exists for 'Woningborg'. If not, error out early. // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'btWoningborgRecordExistsCheck' => true ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If at this point an errorCode has been set, the 'Woningborg client record' was not properly obtained so we cannot continue. If so, error out here. if ($resultSet['errorCode'] > 0) { // Force return 'null'. Note that the error message is retrievable in the resultSet that was passed by reference. return null; } // !!! TODO: implement the rest.... // Returns null or a valid gebruiker return $btGebruiker; } // private function getBtGebruiker($gebruikerId, &$resultSet) // Helper method for generically performing a SOAP call to the BTZ general SoapDossier webservice. private function performBTZSoapDossierCall($methodName, $methodParameters) { // Initialise a generic result set $resultSet = array( 'success' => false, 'message' => 'BTZ SoapDossier webservice is nog niet aangeroepen', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'wsResult' => array() ); // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); $wrappedSoapClient = getWrappedSoapClientHelper($this->remoteBtzSoapWsdl."/{$randval}", $methodName, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $methodParameters); //d($wrappedSoapClient); //d($wsResult); if (empty($wsResult)) { $errorMessage = "De BTZ SoapDossier webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } } else { $errorMessage = "Foutmelding(en) bij maken connectie naar BTZ SoapDossier webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar BTZ SoapDossier webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult)) { // Extract the results that we need from the main service and pass them back in the result set $resultSet['success'] = $wsResult->success; $resultSet['message'] = $wsResult->message; $resultSet['errorCode'] = $wsResult->errorCode; $resultSet['wsResult'] = $wsResult; } // When all the work is done, simply return the compound resultset. return $resultSet; } // private function performBTZSoapDossierCall($methodName, $methodParameters) // !!! TODO: build the actual BT webservice // Helper method for generically performing a SOAP call to the BT general SoapDossier webservice. private function performBTSoapDossierCall($methodName, $methodParameters) { // Initialise a generic result set $resultSet = array( 'success' => false, 'message' => 'BT SoapDossier webservice is nog niet aangeroepen', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'wsResult' => array() ); // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); //$wrappedSoapClient = getWrappedSoapClientHelper($this->remoteBtSoapWsdl."/{$randval}", $methodName, $debug, $silent); $wrappedSoapClient = getWrappedSoapClientHelper($this->remoteBtSoapWsdl."&{$randval}", $methodName, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $methodParameters); //d($wrappedSoapClient); //d($wsResult); if (empty($wsResult)) { $errorMessage = "De BT SoapDossier webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } } else { $errorMessage = "Foutmelding(en) bij maken connectie naar BT SoapDossier webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar BT SoapDossier webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } $resultSet['message'] = $errorMessage; // Return early, so no attempt is made to proceed (which would fail anyway). return $resultSet; } // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult)) { // Extract the results that we need from the main service and pass them back in the result set $resultSet['success'] = $wsResult->success; $resultSet['message'] = $wsResult->message; $resultSet['errorCode'] = $wsResult->errorCode; $resultSet['wsResult'] = $wsResult; } // When all the work is done, simply return the compound resultset. return $resultSet; } // private function performBTSoapDossierCall($methodName, $methodParameters) /************************* HELPER METHODS (END) *************************/ /************************* RPC CALLS IMPLEMENTATIONS *************************/ /************************* RPC CALLS "GET" (BEGIN) *************************/ // The 'soapGetGebruikers' RPC call is used for getting a list of available Woningborg users in BT and/or BTZ. public function soapGetGebruikers( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'toetsGebruikers' => array( array( 'gebruikerId' => -1, 'volledigeNaam' => '', 'email' => '' ) ), 'toezichtGebruikers' => array( array( 'gebruikerId' => -1, 'volledigeNaam' => '', 'email' => '' ) ) ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toezicht') ); $performBtSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toets') ); // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $parameters->licentieWachtwoord), 'filterCheck' => $parameters->filter, 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, 'btWoningborgRecordExistsCheck' => $performBtSoapCall, ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we can perform the SOAP call(s) to the underlying 'common SOAP layer(s)'. // Variables to keep track of what to retrieve $btzSoapCallSuccessfullyPerformed = $btSoapCallSuccessfullyPerformed = false; $rpcCallMessages = array(''); $rpcCallErrorCode = -1; // If requested to do so, get the BTZ gebruikers if ( $performBtzSoapCall ) { // Specify the WS method for manipulating a dossier and also fill the fields we need for the 'add' as well as the 'edit' calls. $btzMethodName = 'soapGetGebruikers'; $btzMethodParameters = array(); $btzMethodParameters['licentieNaam'] = $this->remoteBtzSoapLicentieNaam; $btzMethodParameters['licentieWachtwoord'] = $this->remoteBtzSoapLicentieWachtwoord; $btzMethodParameters['klantId'] = $this->btzWoningborgKlant->id; // Generically call the right BTZ SoapDossier service $btzSoapCallResultSet = $this->performBTZSoapDossierCall($btzMethodName, $btzMethodParameters); //d($btzSoapCallResultSet); //d($btzSoapCallResultSet['success']); //d($btzSoapCallResultSet['message']); //d($btzSoapCallResultSet['wsResult']); //d($btzSoapCallResultSet['wsResult']->results); // If the BTZ users were retrieved successfully, return the retrieved data. if ($btzSoapCallResultSet['success']) { // The BTZ users were retrieved successfully, proceed to pass them to the caller in the result set $btzSoapCallSuccessfullyPerformed = true; $rpcCallMessages []= "De BRIStoezicht gebruikers zijn succesvol opgehaald."; if (sizeof($btzSoapCallResultSet['wsResult']->results) > 0) { //$resultSet['results']['toezichtGebruikers'] = $btzSoapCallResultSet['wsResult']['results']; $resultSet['results']['toezichtGebruikers'] = array(); foreach ($btzSoapCallResultSet['wsResult']->results as $resultObj) { $resultToReturn = array( 'gebruikerId' => $resultObj->gebruikerId, 'volledigeNaam' => $resultObj->volledigeNaam, 'email' => $resultObj->email ); $resultSet['results']['toezichtGebruikers'][] = $resultToReturn; } } // if (sizeof($btzSoapCallResultSet['wsResult']->results) > 0) } // if ($btzSoapCallResultSet['success']) else { // The BTZ users were retrieved successfully, proceed to pass them to the caller in the result set $btzSoapCallSuccessfullyPerformed = false; $rpcCallMessages []= "De BRIStoezicht gebruikers zijn niet succesvol opgehaald."; } } // if ( $performBtzSoapCall ) // If requested to do so, get the BT gebruikers if ( $performBtSoapCall ) { // Specify the WS method for getting the BT gebruikers. $btMethodName = 'soapGetGebruikers'; $btMethodParameters = array(); $btMethodParameters['licentieNaam'] = $this->remoteBtSoapLicentieNaam; $btMethodParameters['licentieWachtwoord'] = $this->remoteBtSoapLicentieWachtwoord; $btMethodParameters['klantId'] = $this->btWoningborgKlant->id; // Generically call the right BTZ SoapDossier service $btSoapCallResultSet = $this->performBTSoapDossierCall($btMethodName, $btMethodParameters); //d($btSoapCallResultSet); //exit; //d($btzSoapCallResultSet['success']); //d($btzSoapCallResultSet['message']); //d($btzSoapCallResultSet['wsResult']); //d($btzSoapCallResultSet['wsResult']->results); // If the BT users were retrieved successfully, return the retrieved data. if ($btSoapCallResultSet['success']) { // The BT users were retrieved successfully, proceed to pass them to the caller in the result set $btSoapCallSuccessfullyPerformed = true; $rpcCallMessages []= "De BRIStoets gebruikers zijn succesvol opgehaald."; //$resultSet['results']['toetsGebruikers'] = $btSoapCallResultSet['wsResult']['results']; if (sizeof($btSoapCallResultSet['wsResult']->results) > 0) { //$resultSet['results']['toetsGebruikers'] = $btSoapCallResultSet['wsResult']['results']; $resultSet['results']['toetsGebruikers'] = array(); //foreach ($btSoapCallResultSet['wsResult']->results as $resultObj) foreach ($btSoapCallResultSet['wsResult']->results->gebruikers as $resultObj) { $resultToReturn = array( 'gebruikerId' => $resultObj->gebruikerId, 'volledigeNaam' => $resultObj->volledigeNaam, 'email' => $resultObj->email ); $resultSet['results']['toetsGebruikers'][] = $resultToReturn; } } } else { // The BTZ users were retrieved successfully, proceed to pass them to the caller in the result set $btSoapCallSuccessfullyPerformed = false; $rpcCallMessages []= "De BRIStoets gebruikers zijn niet succesvol opgehaald."; //$resultSet['errorCode'] = 210; // Fout tijdens de betreffende “manipulate” actie in BRIStoets $rpcCallMessages []= "BRIStoets errorcode: " . $btSoapCallResultSet['errorCode'] . " '" . $btSoapCallResultSet['message'] . "'"; } } // if ( $performBtSoapCall ) // Now that we have made the calls to retrieve the users we needed to retrieve, set the general messages that were determined as the calls were made. $resultSet['message'] = implode("\n", $rpcCallMessages); // Proceed to calculate the proper return code if ($performBtzSoapCall && $performBtSoapCall) // Scenario: both BTZ and BT were requested to be called { // Use a 'fall-through' mechanism to determine the proper error code. if ($btzSoapCallSuccessfullyPerformed && $btSoapCallSuccessfullyPerformed) { // Both calls were successfully made $rpcCallErrorCode = 0; } else if ($btzSoapCallSuccessfullyPerformed) { // Only the BTZ call was successfully made - the BT call failed. $rpcCallErrorCode = 104; } else if ($btSoapCallSuccessfullyPerformed) { // Only the BT call was successfully made - the BTZ call failed. $rpcCallErrorCode = 103; } else { // Neither the BT nor BTZ call was successfully made $rpcCallErrorCode = 105; } } else if ($performBtzSoapCall) // Scenario: Only BTZ was requested to be called { // Use a 'fall-through' mechanism to determine the proper error code. if ($btzSoapCallSuccessfullyPerformed) { // BTZ call was successfully made $rpcCallErrorCode = 0; } else { // BTZ call was not successfully made $rpcCallErrorCode = 103; } } else if ($performBtSoapCall) // Scenario: Only BT was requested to be called { // Use a 'fall-through' mechanism to determine the proper error code. if ($btSoapCallSuccessfullyPerformed) { // BT call was successfully made $rpcCallErrorCode = 0; } else { // BT call was not successfully made $rpcCallErrorCode = 104; } } // Set the determined error code in the result set $resultSet['errorCode'] = $rpcCallErrorCode; // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } else { // Set the proper 'success' state in the resultset. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapGetGebruikers( $parameters ) // The 'soapGetProjectStatus' RPC call is used for getting the status of the project. public function soapGetProjectStatus( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'projectStatussen' => array( array( 'projectId' => -1, 'status' => '', 'datumTijdLaatsteWijziging' => '' ) ) ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = $performBtSoapCall = true; // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $parameters-><PASSWORD>), 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we can do the actual work. Determine whether we need to get the status of one project or of multiple // projects. $dossierId = (empty($parameters->projectId) || ($parameters->projectId <= 0)) ? null : $parameters->projectId; $woningborgActiveDossiers = $this->_CI->btbtzdossier->get_active_by_klant( $this->btzWoningborgKlant->id, $dossierId ); // If our request returned dossiers, return them to the caller if (!empty($woningborgActiveDossiers)) { // Scenario where for ALL not-archived projects the status needs to be returned. $resultSet['results']['projectStatussen'] = array(); foreach ($woningborgActiveDossiers as $woningborgActiveDossier) { $projectStatusResult = array( 'projectId' => $woningborgActiveDossier->btz_dossier_id, 'status' => $woningborgActiveDossier->project_status, 'datumTijdLaatsteWijziging' => $woningborgActiveDossier->bijgewerkt_op ); $resultSet['results']['projectStatussen'][] = $projectStatusResult; } } $resultSet['success'] = true; $resultSet['message'] = 'De projectstatus aanroep is succesvol uitgevoerd'; $resultSet['errorCode'] = 0; // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapGetProjectStatus( $parameters ) // The 'soapGetProjectToezichtmomenten' RPC call is used for getting the toezichtmomenten that have been defined for a project. public function soapGetProjectToezichtmomenten( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'toezichtmomenten' => array( array( 'toezichtmomentId' => -1, 'naam' => '', 'nummer' => '', 'subNummer' => '', 'emailUitvoerende' => '', 'voornaamUitvoerende' => '', 'achternaamUitvoerende' => '', 'geslachtUitvoerende' => '', 'mobieleNummerUitvoerende' => '', 'datumBegin' => '', // Date format 'datumEinde' => '', // Date format 'statusAkkoordWoningborg' => '', 'statusGereedUitvoerende' => '', 'toezichthouderWoningborg' => array( 'gebruikerId' => -1, 'volledigeNaam' => '', 'email' => '' ), 'bijwoonmoment' => '', // ??? What do we provide here? A date perhaps?!? or a boolean?! 'datumHercontrole' => '', // Date format 'sorteerVolgorde' => 0 ) ) ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = true; // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $parameters->licentie<PASSWORD>), 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we have satisfied our common checks and we can proceed. // Get the dossier and the BT-BTZ mapping record using the passed parameters (if valid). $btzDossierID = $btzDossierHash = null; $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; $btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); $btBtzDossier = $this->getExistingBtBtzDossier($btzDossierID, $btzDossierHash, $resultSet); // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // Get the various toezichtmomenten (i.e. deelplan_checklist_toezichtmomenten) $dossierDeelplannen = $btzDossier->get_deelplannen(); // Return an error if no deelplannen were retrieved for this dossier if (empty($dossierDeelplannen)) { // Set the error message and code in the result set. $errorCode = 601; // BRIStoezicht dossier heeft geen deelplannen. $errorMessage = "BRIStoezicht dossier heeft geen deelplannen."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we have deelplannen, so iterate over them and get the deelplan_checklist_toezichtmomenten // of them. $deelplannenChecklisten = $deelplannenChecklistenToezichtmomenten = array(); foreach ($dossierDeelplannen as $dossierDeelplan) { // Get the checklisten for the currently processed deelplan and add them to the set that keeps track of them $deelplanChecklisten = $dossierDeelplan->get_deelplan_checklisten(); $deelplannenChecklisten = array_merge($deelplannenChecklisten, $deelplanChecklisten); // Now get the deelplan-checklist-toezichtmomenten for each of the deelplan-checklisten foreach ($deelplanChecklisten as $deelplanChecklist) { $deelplanChecklistenToezichtmomenten = $deelplanChecklist->get_deelplan_checklist_toezichtmomenten(); $deelplannenChecklistenToezichtmomenten = array_merge($deelplannenChecklistenToezichtmomenten, $deelplanChecklistenToezichtmomenten); } // foreach ($deelplanChecklisten as $deelplanChecklist) } // foreach ($dossierDeelplannen as $dossierDeelplan) // Return an error if no checklisten were retrieved for this dossier. Note that at present the $deelplannenChecklisten // variable is only used for performing this check. if (empty($deelplannenChecklisten)) { // Set the error message and code in the result set. $errorCode = 602; // BRIStoezicht dossier heeft geen checklisten. $errorMessage = "BRIStoezicht dossier heeft geen checklisten."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point at least one deelplan-checklist combination exists, so the data is assumed to be valid. // Now return any and all retrieved toezichtmomenten. Note that at this time we do NOT throw an error if no // deelplan-checklist-toezichtmomenten have been defined! $resultSet['results']['toezichtmomenten'] = array(); $tzmCounter = 0; foreach ($deelplannenChecklistenToezichtmomenten as $deelplannenChecklistenToezichtmoment) { // Prepare the retrieved data such that the webservice always has valid data. $dpctNaam = (is_null($deelplannenChecklistenToezichtmoment->naam)) ? '' : $deelplannenChecklistenToezichtmoment->naam; $dpctNummer = (is_null($deelplannenChecklistenToezichtmoment->nummer)) ? '' : $deelplannenChecklistenToezichtmoment->nummer; $dpctSubNummer = (is_null($deelplannenChecklistenToezichtmoment->sub_nummer)) ? '' : $deelplannenChecklistenToezichtmoment->sub_nummer; $dpctEmailUitvoerende = (is_null($deelplannenChecklistenToezichtmoment->email_uitvoerende)) ? '' : $deelplannenChecklistenToezichtmoment->email_uitvoerende; $dpctVoornaamUitvoerende = (is_null($deelplannenChecklistenToezichtmoment->voornaam_uitvoerende)) ? '' : $deelplannenChecklistenToezichtmoment->voornaam_uitvoerende; $dpctAchternaamUitvoerende = (is_null($deelplannenChecklistenToezichtmoment->achternaam_uitvoerende)) ? '' : $deelplannenChecklistenToezichtmoment->achternaam_uitvoerende; $dpctGeslachtUitvoerende = (is_null($deelplannenChecklistenToezichtmoment->geslacht_uitvoerende)) ? '' : $deelplannenChecklistenToezichtmoment->geslacht_uitvoerende; $dpctMobieleNummerUitvoerende = (is_null($deelplannenChecklistenToezichtmoment->mobiele_nummer_uitvoerende)) ? '' : $deelplannenChecklistenToezichtmoment->mobiele_nummer_uitvoerende; $dpctDatumBegin = (is_null($deelplannenChecklistenToezichtmoment->datum_begin)) ? '' : date("d-m-Y",strtotime($deelplannenChecklistenToezichtmoment->datum_begin)); $dpctDatumEinde = (is_null($deelplannenChecklistenToezichtmoment->datum_einde)) ? '' : date("d-m-Y",strtotime($deelplannenChecklistenToezichtmoment->datum_einde)); $dpctDatumHercontrole = (is_null($deelplannenChecklistenToezichtmoment->datum_hercontrole)) ? '' : date("d-m-Y",strtotime($deelplannenChecklistenToezichtmoment->datum_hercontrole)); $dpctToezichtHouderWoningborgGebruikerId = (is_null($deelplannenChecklistenToezichtmoment->toezichthouder_woningborg_gebruiker_id)) ? -1 : $deelplannenChecklistenToezichtmoment->toezichthouder_woningborg_gebruiker_id; $tzmCounter++; // Make sure that the caller always gets a useful description in the 'naam' field, so they always know which toezichtmoment // belongs to what hoofdgroep etc. $toezichtMomentIdentifier = ''; $deelplanChecklistBouwNummer = $deelplannenChecklistenToezichtmoment->get_deelplan_checklist()->bouwnummer; $btToezichtmomentNaam = $deelplannenChecklistenToezichtmoment->get_toezichtmoment()->naam; if (!is_null($deelplanChecklistBouwNummer) && !empty($deelplanChecklistBouwNummer)) { $toezichtMomentIdentifier .= "Bouwnummer: '{$deelplanChecklistBouwNummer}'"; } if (!is_null($btToezichtmomentNaam) && !empty($btToezichtmomentNaam)) { if (!empty($toezichtMomentIdentifier)) { $toezichtMomentIdentifier .= ' - '; } $toezichtMomentIdentifier .= "Toezichtmoment: '{$btToezichtmomentNaam}'"; } // Only override the 'naam' field if it was empty. if (empty($dpctNaam)) { $dpctNaam = $toezichtMomentIdentifier; } // Get the data of the 'Woningborg toezichthouder' (if any). $toezichtHouderWoningborgGebruiker = $this->_CI->gebruiker->get($dpctToezichtHouderWoningborgGebruikerId); $dpctToezichtHouderWoningborgGebruikerVolledigeNaam = (is_null($toezichtHouderWoningborgGebruiker)) ? '' : $toezichtHouderWoningborgGebruiker->volledige_naam; $dpctToezichtHouderWoningborgGebruikerEmail = (is_null($toezichtHouderWoningborgGebruiker)) ? '' : $toezichtHouderWoningborgGebruiker->email; // If a user was retrieved, check that the user really belongs to Woningborg! // If not, unset it, so we never return users that do not belong to Woningborg! if (!is_null($toezichtHouderWoningborgGebruiker) && ($toezichtHouderWoningborgGebruiker->klant_id != $this->btzWoningborgKlant->id)) { // Invalidate the toezichthouder data. $toezichtHouderWoningborgGebruiker = null; $dpctToezichtHouderWoningborgGebruikerVolledigeNaam = "Gebruiker met ID {$dpctToezichtHouderWoningborgGebruikerId} is geen geldige Woningborg gebruiker!"; $dpctToezichtHouderWoningborgGebruikerEmail = ''; // Correct the DB record too //$deelplannenChecklistenToezichtmoment->toezichthouder_woningborg_gebruiker_id = null; //$deelplannenChecklistenToezichtmoment-save(); } // if (!is_null($toezichtHouderWoningborgGebruiker) && ($toezichtHouderWoningborgGebruiker->klant_id != $this->btzWoningborgKlant->id)) // Now construct the return data in the expected format $toezichtmomentResult = array( 'toezichtmomentId' => $deelplannenChecklistenToezichtmoment->id, 'naam' => $dpctNaam, 'nummer' => $dpctNummer, 'subNummer' => $dpctSubNummer, 'emailUitvoerende' => $dpctEmailUitvoerende, 'voornaamUitvoerende' => $dpctVoornaamUitvoerende, 'achternaamUitvoerende' => $dpctAchternaamUitvoerende, 'geslachtUitvoerende' => $dpctGeslachtUitvoerende, 'mobieleNummerUitvoerende' => $dpctMobieleNummerUitvoerende, 'datumBegin' => $dpctDatumBegin, // Date format! 'datumEinde' => $dpctDatumEinde, // '01-01-1970', // Date format! 'statusAkkoordWoningborg' => $deelplannenChecklistenToezichtmoment->status_akkoord_woningborg, 'statusGereedUitvoerende' => $deelplannenChecklistenToezichtmoment->status_gereed_uitvoerende, 'toezichthouderWoningborg' => array( 'gebruikerId' => $dpctToezichtHouderWoningborgGebruikerId, 'volledigeNaam' => $dpctToezichtHouderWoningborgGebruikerVolledigeNaam, 'email' => $dpctToezichtHouderWoningborgGebruikerEmail ), 'bijwoonmoment' => $deelplannenChecklistenToezichtmoment->bijwoonmoment, // 'string' (now) or boolean ??? What do we provide here? A date perhaps?!? or a boolean?! 'datumHercontrole' => $dpctDatumHercontrole, // '01-01-1970' // Date format! 'sorteerVolgorde' => $tzmCounter ); //d($toezichtmomentResult); $resultSet['results']['toezichtmomenten'][] = $toezichtmomentResult; } // foreach ($deelplannenChecklistenToezichtmomenten as $deelplannenChecklistenToezichtmoment) // Todo? Add more error handling? Possibly not necessary... $resultSet['success'] = true; $resultSet['message'] = 'De toezichtmomenten aanroep is succesvol uitgevoerd'; $resultSet['errorCode'] = 0; // If everything went successfully, and if this is the first time that a call to this RPC method is made for a // specific dossier, we set the project status to 'bouwfase'. We can detect this by checking if the 'btz_status' // is set to 'open' for the respective dossier/project in the bt_btz_dossiers table. if (!is_null($btBtzDossier) && ($btBtzDossier->btz_status == 'open')) { // Set the BTZ status to 'bouwfase' and let the determineAndSetProjectStatus method handle that value as required. $btBtzDossier->btz_status = 'bouwfase'; $btBtzDossier->determineAndSetProjectStatus(); } // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapGetProjectToezichtmomenten( $parameters ) // The 'soapGetProjectRapportage' RPC call is used for getting the toezichtmomenten that have been defined for a project. public function soapGetProjectRapportage( $parameters ) { // Initialise the result set negatively // 'projectId' => $parameters->projectId, $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'toetsRapport' => array( 'rapportFormaat' => '', // 'PDF' of 'DOCX' 'rapport' => '' ), 'toezichtRapport' => array( 'rapportFormaat' => '', // 'PDF' of 'DOCX' 'rapport' => '' ) ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toezicht') ); $performBtSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toets') ); // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $<PASSWORD>), 'filterCheck' => $parameters->filter, 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, 'btWoningborgRecordExistsCheck' => $performBtSoapCall, ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // Get the dossier and the BT-BTZ mapping record using the passed parameters (if valid). $btzDossierID = $btzDossierHash = null; $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; $btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); $btBtzDossier = $this->getExistingBtBtzDossier($btzDossierID, $btzDossierHash, $resultSet); // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we can perform the SOAP call(s) to the underlying 'common SOAP layer(s)'. // Variables to keep track of what to retrieve $btzSoapCallSuccessfullyPerformed = $btSoapCallSuccessfullyPerformed = false; $rpcCallMessages = array(''); $rpcCallErrorCode = -1; // At this point, we treat the 'BTZ flow' separately from the 'BT flow'. // Handle the 'BTZ flow' if ($performBtzSoapCall) { // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // If we reached this point, we can reasonably assume to have enough information to make the SOAP call to the underlying common SoapDossier service. // First get the deelplannen. In theory we could have multiple deelplannen under each dossier, but for Woningborg only // one deelplan is (or should be!!) used. Get all deelplannen, and only use the first. Error out if no deelplannen have // been defined. $dossierDeelplannen = $btzDossier->get_deelplannen(); // Return an error if no deelplannen were retrieved for this dossier if (empty($dossierDeelplannen)) { // Set the error message and code in the result set. $errorCode = 701; // BRIStoezicht dossier heeft geen deelplannen. $errorMessage = "BRIStoezicht dossier heeft geen deelplannen."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point we know that we have at least one deelplan. Simply get the first from the array and use that. $deelplan = reset($dossierDeelplannen); // Specify the WS method for getting the report for this deelplan. $btzMethodName = 'soapGetDeelplanResults'; $btzMethodParameters = array(); $btzMethodParameters['licentieNaam'] = $this->remoteBtzSoapLicentieNaam; $btzMethodParameters['licentieWachtwoord'] = $this->remoteBtzSoapLicentieWachtwoord; $btzMethodParameters['dossierId'] = $parameters->projectId; $btzMethodParameters['dossierHash'] = $parameters->projectHash; $btzMethodParameters['deelplanId'] = $deelplan->id; // Make sure to use this value instead of bluntly using the passed value! $btzMethodParameters['sjabloonId'] = ''; // Generically call the right BTZ SoapDossier service $btzSoapCallResultSet = $this->performBTZSoapDossierCall($btzMethodName, $btzMethodParameters); //d($btzSoapCallResultSet); //d($btzSoapCallResultSet['success']); //d($btzSoapCallResultSet['message']); //d($btzSoapCallResultSet['wsResult']); //d($btzSoapCallResultSet['wsResult']->results); // Check if the SOAP call was made successfully. $btzSoapCallSuccessfullyPerformed = (!empty($btzSoapCallResultSet) && !empty($btzSoapCallResultSet['success']) && ($btzSoapCallResultSet['success'])); // If we could not successfully call the BTZ SoapDossier service, error out. if (!$btzSoapCallSuccessfullyPerformed) { // Set the error message and code in the result set. $errorCode = 702; // Interne fout: BRIStoezicht SoapDossier service heeft niet succesvol een rapport geretourneerd. $errorMessage = "Interne fout: BRIStoezicht SoapDossier service heeft niet succesvol een rapport geretourneerd."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); return $resultSet; } // if (!$btzSoapCallSuccessfullyPerformed) else { // Register the successful outcome of the call to the BTZ SoapDossier service $actionResultMessage = "Het BRIStoezicht rapport is succesvol opgevraagd."; $rpcCallMessages []= $actionResultMessage; // Now get the results from the call and pass them in the result set $resultSet['results']['toezichtRapport'] = array( 'rapportFormaat' => $btzSoapCallResultSet['wsResult']->results->rapportFormaat, // 'PDF' of 'DOCX' 'rapport' => $btzSoapCallResultSet['wsResult']->results->rapport ); } // else of clause: if (!$btzSoapCallSuccessfullyPerformed) // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtzSoapCall) // If an error code has been set by the BTZ specific part above, make sure to force-abort calling BT, even if we // previously determined that we needed to call it. if ($resultSet['errorCode'] > 0) { $performBtSoapCall = false; } // Handle the 'BT flow' if ($performBtSoapCall) { // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // Specify the WS method for getting the report for the BT dossier. $btMethodName = 'soapGetDossierRapportage'; $btMethodParameters = array(); $btMethodParameters['licentieNaam'] = $this->remoteBtSoapLicentieNaam; $btMethodParameters['licentieWachtwoord'] = $this->remoteBtSoapLicentieWachtwoord; $btMethodParameters['dossierHash'] = $btzDossier->bt_dossier_hash; $btMethodParameters['dossierId'] = $btzDossier->bt_dossier_id; $btMethodParameters['formaat'] = $parameters->formaat; // Generically call the right BTZ SoapDossier service $btSoapCallResultSet = $this->performBTSoapDossierCall($btMethodName, $btMethodParameters); //d($btSoapCallResultSet); //d($btSoapCallResultSet['success']); //d($btSoapCallResultSet['message']); //d($btSoapCallResultSet['wsResult']); //d($btSoapCallResultSet['wsResult']->results); // Check if the SOAP call was made successfully. $btSoapCallSuccessfullyPerformed = (!empty($btSoapCallResultSet) && !empty($btSoapCallResultSet['success']) && ($btSoapCallResultSet['success'])); // If we could not successfully call the BT SoapDossier service, error out. if (!$btSoapCallSuccessfullyPerformed) { // Set the error message and code in the result set. $errorCode = 703; // Interne fout: BRIStoets SoapDossier service heeft niet succesvol een rapport geretourneerd. $errorMessage = "Interne fout: BRIStoets SoapDossier service heeft niet succesvol een rapport geretourneerd."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); return $resultSet; } // if (!$btSoapCallSuccessfullyPerformed) else { // Register the successful outcome of the call to the BT SoapDossier service $actionResultMessage = "Het BRIStoets rapport is succesvol opgevraagd."; $rpcCallMessages []= $actionResultMessage; // Now get the results from the call and pass them in the result set $resultSet['results']['toetsRapport'] = array( 'rapportFormaat' => $btSoapCallResultSet['wsResult']->results->toetsRapport->rapportFormaat, // 'PDF' of 'DOCX' 'rapport' => $btSoapCallResultSet['wsResult']->results->toetsRapport->rapport ); } // else of clause: if (!$btzSoapCallSuccessfullyPerformed) // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtSoapCall) // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } else { // Set the proper 'success' state in the resultset. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapGetProjectRapportage( $parameters ) /************************* RPC CALLS "GET" (END) *************************/ /************************* RPC CALLS "MANIPULATE" (BEGIN) *************************/ // The 'soapManipulateProject' RPC call is used for manipulating projects in BTZ. public function soapManipulateProject( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'projectId' => -1, 'projectHash' => '', 'actionResultMessage' => '', 'assignedBetrokkenen' => array( array( 'assignedBetrokkeneId' => -1, 'naam' => '', 'email' => '' ) ) ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toezicht') ); $performBtSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toets') ); // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $parameters->licentieWachtwoord), 'filterCheck' => $parameters->filter, 'actionCheck' => $parameters->actie, //'actionAllowedValues' => array('Add', 'Edit', 'Delete', 'Check'), 'actionAllowedValues' => array('Add', 'Edit', 'Archive'), 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, 'btWoningborgRecordExistsCheck' => $performBtSoapCall, //'passedParameterValues' => $parameters, //'requiredParameterValues' => array(), ); // !!! TODO: Add checks for existing projects for validating the projectId and projectHash values.. $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // Determine the proper Dutch translation for the called action, so we can make some generic errors specific $action = strtolower($parameters->actie); switch ($action) { case 'add': $dutchActionVerb = 'aangemaakt'; break; case 'edit': $dutchActionVerb = 'bewerkt'; break; case 'archive': $dutchActionVerb = 'gearchiveerd'; break; default: $dutchActionVerb = ''; } // At this point, we treat the 'BTZ flow' separately from the 'BT flow'. // Regardless of whether we create, edit, archive, check or skip the BTZ dossier, we will need the BTZ dossier record // for finding the corresponding BT dossier. $btzDossierID = null; $btzDossierHash = null; $btzDossier = null; // Handle the 'BTZ flow' if ($performBtzSoapCall) { // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // Get the proper 'BTZ gebruiker' or the "Nog Niet Toegewezen" dummy user record of Woningborg. $useBtzGebruikerId = $parameters->toezichtProjectVerantwoordelijkeId; $btzGebruiker = $this->getBtzGebruiker($useBtzGebruikerId, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we can reasonably assume to have enough information to make the SOAP call to the underlying common SoapDossier service. // Specify the WS method for manipulating a dossier and also fill the fields we need for the 'add' as well as the 'edit' calls. $btzMethodName = 'soapManipulateDossier'; $btzMethodParameters = array(); $btzMethodParameters['licentieNaam'] = $this->remoteBtzSoapLicentieNaam; $btzMethodParameters['licentieWachtwoord'] = $this->remoteBtzSoapLicentieWachtwoord; $btzMethodParameters['actie'] = $parameters->actie; $btzMethodParameters['dossierId'] = $parameters->projectId; $btzMethodParameters['dossierHash'] = $parameters->projectHash; $btzMethodParameters['dossierNaam'] = $parameters->projectNaam; $btzMethodParameters['identificatieNummer'] = $parameters->identificatieNummer; $btzMethodParameters['gebruikerId'] = $btzGebruiker->id; // Make sure to use this value instead of bluntly using the passed value! $btzMethodParameters['aanmaakDatum'] = $parameters->aanmaakDatum; $btzMethodParameters['bagNummer'] = $parameters->bagNummer; $btzMethodParameters['xyCoordinaten'] = $parameters->xyCoordinaten; $btzMethodParameters['locatieStraat'] = $parameters->locatieStraat; $btzMethodParameters['locatieHuisNummer'] = $parameters->locatieHuisNummer; $btzMethodParameters['locatieHuisNummerToevoeging'] = $parameters->locatieHuisNummerToevoeging; $btzMethodParameters['locatiePostcode'] = $parameters->locatiePostcode; $btzMethodParameters['locatieWoonplaats'] = $parameters->locatieWoonplaats; $btzMethodParameters['opmerkingen'] = $parameters->opmerkingen; //$btzMethodParameters['betrokkenen'] = (array) $parameters->toezichtBetrokkenen; $btzMethodParameters['betrokkenen'] = array(); foreach ($parameters->toezichtBetrokkenen as $toezichtBetrokkene) { // Note: we HAVE to loop over each member and cast the entries to an array! $btzMethodParameters['betrokkenen'][] = (array)$toezichtBetrokkene; } // Generically call the right BTZ SoapDossier service $btzSoapCallResultSet = $this->performBTZSoapDossierCall($btzMethodName, $btzMethodParameters); // d($btzSoapCallResultSet); // exit; //d($btzSoapCallResultSet['success']); //d($btzSoapCallResultSet['message']); //d($btzSoapCallResultSet['wsResult']); //d($btzSoapCallResultSet['wsResult']->results); // If the BTZ dossier was 'manipulated' successfully, process the retrieved data. $btzSoapManipulateDossierCallSuccessfullyPerformed = $btzSoapManipulateDeelplanCallSuccessfullyPerformed = false; if ($btzSoapCallResultSet['success']) { // The BTZ users were retrieved successfully, proceed to pass them to the caller in the result set $btzSoapManipulateDossierCallSuccessfullyPerformed = true; // If we just added a dossier, we also need to create a deelplan. Try to do so here. if ($parameters->actie == 'Add') { $actionResultMessage = "Het project is succesvol {$dutchActionVerb} in BRIStoezicht."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] = $actionResultMessage; // Proceed to call the SOAP service for creating a 'deelplan' for the dossier that was just created. /* // Gebouwdelen $auxiliary_gebouwdeel_1 = array('naam' => 'Badkamer'); $auxiliary_gebouwdeel_2 = array('naam' => 'Woonkamer'); $auxiliary_gebouwdeel_3 = array('naam' => 'Keuken'); $auxiliary_gebouwdeel_4 = array('naam' => 'Schuur'); $auxiliary_gebouwdeel_5 = array('naam' => 'Zolder'); $auxiliary_gebouwdelen = array($auxiliary_gebouwdeel_1, $auxiliary_gebouwdeel_2, $auxiliary_gebouwdeel_3); // Checklists $auxiliary_checklist_ids = array(); $auxiliary_checklist_id = array('checklistId' => 4415); // Achtbaan (checklistgroep_id = 385) $auxiliary_checklist_ids[] = $auxiliary_checklist_id; $auxiliary_checklist_id = array('checklistId' => 4423); // Draaimolen (checklistgroep_id = 385) $auxiliary_checklist_ids[] = $auxiliary_checklist_id; // Betrokkenen $auxiliary_betrokkenen_ids = array(); $auxiliary_betrokkene_id = array('betrokkeneId' => 26200); $auxiliary_betrokkenen_ids[] = $auxiliary_betrokkene_id; $auxiliary_betrokkene_id = array('betrokkeneId' => 26201); $auxiliary_betrokkenen_ids[] = $auxiliary_betrokkene_id; // Document IDs $auxiliary_document_ids = array(); $auxiliary_document_id = array('documentId' => 10987); $auxiliary_document_ids[] = $auxiliary_document_id; $auxiliary_document_id = array('documentId' => 10988); $auxiliary_document_ids[] = $auxiliary_document_id; */ // !!! TODO: Complete the data with the real values -- see above for sample values. $auxiliary_gebouwdelen = $auxiliary_checklist_ids = $auxiliary_betrokkenen_ids = $auxiliary_document_ids = array(); // Get the 'assigned betrokkenen IDs' from the return values of the call to the soapManipulateDossier RPC method. foreach ($btzSoapCallResultSet['wsResult']->results->assignedBetrokkenen as $assignedBetrokkene) { $auxiliary_betrokkene_id = array('betrokkeneId' => $assignedBetrokkene->assignedBetrokkeneId); $auxiliary_betrokkenen_ids[] = $auxiliary_betrokkene_id; } // Specify the WS method for manipulating a deelplan and also fill the fields we need for the 'add' call. $btzMethod2Name = 'soapManipulateDeelplan'; $btzMethod2Parameters = array(); $btzMethod2Parameters['licentieNaam'] = $this->remoteBtzSoapLicentieNaam; $btzMethod2Parameters['licentieWachtwoord'] = $this->remoteBtzSoapLicentieWachtwoord; $btzMethod2Parameters['actie'] = $parameters->actie; $btzMethod2Parameters['dossierHash'] = $btzSoapCallResultSet['wsResult']->results->dossierHash; $btzMethod2Parameters['dossierId'] = $btzSoapCallResultSet['wsResult']->results->dossierId; $btzMethod2Parameters['deelplanId'] = 0; $btzMethod2Parameters['deelplanNaam'] = $parameters->projectNaam; $btzMethod2Parameters['gebruikerId'] = $btzGebruiker->id; // Make sure to use this value instead of bluntly using the passed value! $btzMethod2Parameters['kenmerk'] = $parameters->projectNaam; $btzMethod2Parameters['oloNummer'] = ''; $btzMethod2Parameters['aanvraagDatum'] = ''; $btzMethod2Parameters['initieleDatum'] = ''; $btzMethod2Parameters['gebouwdelen'] = $auxiliary_gebouwdelen; $btzMethod2Parameters['scopes'] = $auxiliary_checklist_ids; $btzMethod2Parameters['betrokkenen'] = $auxiliary_betrokkenen_ids; $btzMethod2Parameters['documenten'] = $auxiliary_document_ids; // Generically call the right BTZ SoapDossier service $btzSoapCall2ResultSet = $this->performBTZSoapDossierCall($btzMethod2Name, $btzMethod2Parameters); $btzSoapManipulateDeelplanCallSuccessfullyPerformed = $btzSoapCall2ResultSet['success']; // If an error occurred when manipulating the deelplan, return that error to the caller. if (!$btzSoapManipulateDeelplanCallSuccessfullyPerformed) { $resultSet['errorCode'] = 205; // Interne fout: BRIStoezicht deelplan kon niet aangemaakt worden $actionResultMessage = 'Interne fout: BRIStoezicht deelplan kon niet aangemaakt worden.'; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] .= (empty($resultSet['results']['actionResultMessage']) ? '' : "\n") . $actionResultMessage." Details: " . $btzSoapCall2ResultSet['wsResult']->results->actionResultMessage; } // if (!$btzSoapManipulateDeelplanCallSuccessfullyPerformed) } // if ($parameters->actie == 'Add') else if ($parameters->actie == 'Edit') { $actionResultMessage = "Het project is succesvol {$dutchActionVerb} in BRIStoezicht."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] = $actionResultMessage; } // else if ($parameters->actie == 'Edit') else if ($parameters->actie == 'Archive') { // Set the project status to 'closed' //$actionResultMessage = "Het project is succesvol gearchiveerd in BRIStoezicht."; $actionResultMessage = "Het project is succesvol {$dutchActionVerb} in BRIStoezicht."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] = $actionResultMessage; } // else if ($parameters->actie == 'Archive') /* else if ($parameters->actie == 'Delete') { //$actionResultMessage = "Het project is succesvol verwijderd in BRIStoezicht."; $actionResultMessage = "De 'Delete' actie is vooralsnog niet ondersteund."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] = $actionResultMessage; } // else if ($parameters->actie == 'Delete') else if ($parameters->actie == 'Check') { //$actionResultMessage = "Het project bestaat in BRIStoezicht."; $actionResultMessage = "De 'Check' actie is vooralsnog niet ondersteund."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] = $actionResultMessage; } // else if ($parameters->actie == 'Check') * */ // In case of a succesful outcome, pass the results that were returned by the underlying webservice. $resultSet['results']['projectId'] = $btzSoapCallResultSet['wsResult']->results->dossierId; $resultSet['results']['projectHash'] = $btzSoapCallResultSet['wsResult']->results->dossierHash; $resultSet['results']['assignedBetrokkenen'] = $btzSoapCallResultSet['wsResult']->results->assignedBetrokkenen; // Use the ID and hash values as they were returned by the underlying webservice as those should be the new/correct ones! $btzDossierID = $btzSoapCallResultSet['wsResult']->results->dossierId; $btzDossierHash = $btzSoapCallResultSet['wsResult']->results->dossierHash; } // if ($btzSoapCallResultSet['success']) else { // The BTZ users were retrieved successfully, proceed to pass them to the caller in the result set //$btzSoapManipulateDossierCallSuccessfullyPerformed = false; $rpcCallMessages []= "Het project is niet succesvol {$dutchActionVerb} in BRIStoezicht."; } /* // If we just added a dossier, we also need to create a deelplan. Try to do so here. if ( ($parameters->actie == 'Add') && $btzSoapManipulateDossierCallSuccessfullyPerformed && $btzSoapManipulateDeelplanCallSuccessfullyPerformed ) { // Set the proper 'success' state in the resultset. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } else if ( ($parameters->actie != 'Add') && $btzSoapManipulateDossierCallSuccessfullyPerformed ) { // Set the proper 'success' state in the resultset. Note that the 'manipulate deelplan' call is not applicable to other actions than 'add'. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } */ // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtzSoapCall) // If an error code has been set by the BTZ specific part above, make sure to force-abort calling BT, even if we // previously determined that we needed to call it. if ($resultSet['errorCode'] > 0) { $performBtSoapCall = false; } // Handle the 'BT flow' if ($performBtSoapCall) { // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // If we've reached this point we will need the BTZ dossier object in order to find and/or manipulate the proper // corresponding BT object. // If a BTZ SoapDossier call was (successfully) made it should have set the below parameters with the proper values. // If not, get them from the passed parameters and (try to) proceed with those. $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; $btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); // If a BTZ dossier was successfully retrieved, get the proper data from it and handle the call to the BT SoapDossier // webservice. Otherwise error out. if (!is_null($btzDossier)) { // Get the proper 'BT gebruiker' or the "N<NAME> Toegewezen" dummy user record of Woningborg. $useBtGebruikerId = $parameters->toetsProjectVerantwoordelijkeId; //$btGebruiker = $this->getBtGebruiker($useBtGebruikerId, $resultSet); // Generate a 'locatie' identifier as a single string, in the way BT expects it. $useLocatie = $parameters->locatieStraat; if (!empty($useLocatie) && !empty($parameters->locatieHuisNummer)) { $useLocatie .= ' ' . $parameters->locatieHuisNummer; } if (!empty($useLocatie) && !empty($parameters->locatieHuisNummer) && !empty($parameters->locatieHuisNummerToevoeging)) { $useLocatie .= $parameters->locatieHuisNummerToevoeging; } // Specify the WS method for manipulating the BT dossier. $btMethodName = 'soapManipulateDossier'; $btMethodParameters = array(); $btMethodParameters['licentieNaam'] = $this->remoteBtSoapLicentieNaam; $btMethodParameters['licentieWachtwoord'] = $this->remoteBtSoapLicentieWachtwoord; $btMethodParameters['actie'] = $parameters->actie; $btMethodParameters['dossierHash'] = $btzDossier->bt_dossier_hash; $btMethodParameters['dossierId'] = $btzDossier->bt_dossier_id; $btMethodParameters['coordinatorId'] = $useBtGebruikerId; $btMethodParameters['dossierNaam'] = $parameters->projectNaam; $btMethodParameters['identificatieNummer'] = $parameters->identificatieNummer; $btMethodParameters['oloNummer'] = ''; $btMethodParameters['bagNummer'] = $parameters->bagNummer; $btMethodParameters['aanvraagDatum'] = $parameters->toetsDatum; $btMethodParameters['specificatie'] = ''; $btMethodParameters['locatie'] = $useLocatie; $btMethodParameters['locatiePostcode'] = $parameters->locatiePostcode; $btMethodParameters['locatieWoonplaats'] = $parameters->locatieWoonplaats; $btMethodParameters['aardBouwwerk'] = 'nieuwbouw'; // !!! TODO ?: add parameter for this? $btMethodParameters['isBestaandBouwwerk'] = false; // !!! TODO ?: add parameter for this? $btMethodParameters['isMonument'] = false; // !!! TODO ?: add parameter for this? $btMethodParameters['isCoa'] = false; // !!! TODO ?: add parameter for this? $btMethodParameters['isParticulier'] = false; // !!! TODO ?: add parameter for this? $btMethodParameters['bouwsom'] = ''; // !!! TODO ?: add parameter for this? $btMethodParameters['hoogteLeges'] = ''; // !!! TODO ?: add parameter for this? $btMethodParameters['opmerkingen'] = $parameters->opmerkingen; $btMethodParameters['btzDossierHash'] = $btzDossier->dossier_hash; $btMethodParameters['btzDossierId'] = $btzDossier->id; //$btMethodParameters['betrokkenen'] = array(); // TODO: add in the proper way //documenten.... // TODO: add in the proper way // Generically call the right BTZ SoapDossier service $btSoapCallResultSet = $this->performBTSoapDossierCall($btMethodName, $btMethodParameters); //d($btSoapCallResultSet); //exit; // If the dossier was successfully manipulated, return the retrieved data. if ($btSoapCallResultSet['success']) { // The BT users were retrieved successfully, proceed to pass them to the caller in the result set $btSoapCallSuccessfullyPerformed = true; $actionResultMessage = "Het project is succesvol {$dutchActionVerb} in BRIStoets."; $rpcCallMessages []= $actionResultMessage; $resultSet['results']['actionResultMessage'] .= (empty($resultSet['results']['actionResultMessage']) ? '' : "\n") . $actionResultMessage; // If the 'Add' action was called store the BT dossier ID and hash locally if ($parameters->actie == 'Add') { // Get the BT dossier ID and hash, if indeed they were returned correctly $btDossierID = (empty($btSoapCallResultSet['wsResult']->results->dossierId) || is_null($btSoapCallResultSet['wsResult']->results->dossierId)) ? null : $btSoapCallResultSet['wsResult']->results->dossierId; $btDossierHash = (empty($btSoapCallResultSet['wsResult']->results->dossierHash) || is_null($btSoapCallResultSet['wsResult']->results->dossierHash)) ? null : $btSoapCallResultSet['wsResult']->results->dossierHash; // If the values were retrieved successfully, update our local records. If not, return an error. if (is_null($btDossierID) || is_null($btDossierHash)) { // Failed to get the BT dossier ID and/or hash. Error out. $btSoapCallSuccessfullyPerformed = false; $resultSet['errorCode'] = 211; // BRIStoezicht dossier niet succesvol gekoppeld aan BRIStoets dossier $rpcCallMessages []= "BRIStoezicht dossier niet succesvol gekoppeld aan BRIStoets dossier."; } else { // Successfully obtained the BT dossier ID and hash. Update our local records. $btzDossier->bt_dossier_id = $btDossierID; $btzDossier->bt_dossier_hash = $btDossierHash; $btzDossier->save(); // Create an entry in the table that keeps track of the BT <-> BTZ dossiers. $btBtzDossierData = array( 'bt_dossier_id' => $btDossierID, 'bt_dossier_hash' => $btDossierHash, 'btz_dossier_id' => $btzDossierID, 'btz_dossier_hash' => $btzDossierHash, 'bt_status' => 'open', 'btz_status' => 'open', 'project_status' => 'open', 'kenmerk' => $parameters->identificatieNummer, 'aangemaakt_op' => date("Y-m-d H:i:s"), 'bijgewerkt_op' => date("Y-m-d H:i:s"), 'verwerkt' => true, 'verwerkt_op' => date("Y-m-d H:i:s") ); $this->_CI->btbtzdossier->insert($btBtzDossierData); } } // if ($parameters->actie == 'Add') } else { // BT did not return a successful outcome $btSoapCallSuccessfullyPerformed = false; $resultSet['errorCode'] = 210; // Fout tijdens de betreffende “manipulate” actie in BRIStoets $rpcCallMessages []= "Het dossier is niet succesvol {$dutchActionVerb} in BRIStoets."; $rpcCallMessages []= "BRIStoets errorcode: " . $btSoapCallResultSet['errorCode'] . " '" . $btSoapCallResultSet['message'] . "'"; } } // if (!is_null($btzDossier)) else { // !!! TODO: Add complete error handling for the situation where a BTZ dossier was not retrieved. // NOTE: If the filter is set to BT only in 'Add' mode, we should probably allow it, but then later there is no // way back, so maybe it is best to declare that situation as undesirable and disallow it on those grounds by // enforcing that a BT dossier MUST always have a BTZ corresponding dossier too. // BT did not return a successful outcome $btSoapCallSuccessfullyPerformed = false; $resultSet['errorCode'] = 209; // BRIStoezicht dossier kon niet bepaald worden //$rpcCallMessages[] = 'Het BRIStoezicht dossier kon niet worden opgehaald waardoor het juiste BRIStoets dossier niet bepaald kan worden'; $rpcCallMessages[] = 'Interne fout: BRIStoezicht dossier kon niet bepaald worden.'; } // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtSoapCall) // If we reached this point and an errorCode has been set, we exit early, otherwise proceed. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If the 'Archive' action was called, we (need to) update the BT-BTZ mapping record. if ($parameters->actie == 'Archive') { // Get the dossier and the BT-BTZ mapping record using the passed parameters (if valid). $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; //$btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); $btBtzDossier = $this->getExistingBtBtzDossier($btzDossierID, $btzDossierHash, $resultSet); // We don't have to return a specific error here if no mapping record was found, as that situation is already // trapped in the getExistingBtBtzDossier call (and will be returned to the caller anyway). if (!is_null($btBtzDossier)) { $btBtzDossier->bt_status = 'afgesloten'; $btBtzDossier->btz_status = 'afgesloten'; $btBtzDossier->determineAndSetProjectStatus(true); } } // if ($parameters->actie == 'Archive') // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } else { // Set the proper 'success' state in the resultset. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapManipulateProject( $parameters ) // The 'soapManipulateDocument' RPC call is used for manipulating projects in BTZ. public function soapManipulateDocument( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'documentId' => -1, 'actionResultMessage' => '' ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = $performBtSoapCall = true; // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $<PASSWORD>-><PASSWORD>), 'filterCheck' => $parameters->filter, 'actionCheck' => $parameters->actie, 'actionAllowedValues' => array('Add', 'Edit', 'Delete', 'Check'), 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, 'btWoningborgRecordExistsCheck' => $performBtSoapCall, //'passedParameterValues' => $parameters, //'requiredParameterValues' => array(), ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, the caller provided valid data. Continue. // Get the dossier and the BT-BTZ mapping record using the passed parameters (if valid). $btzDossierID = $btzDossierHash = null; $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; $btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); $btBtzDossier = $this->getExistingBtBtzDossier($btzDossierID, $btzDossierHash, $resultSet); // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // Determine the proper Dutch translation for the called action, so we can make some generic errors specific $action = strtolower($parameters->actie); switch ($action) { case 'add': $dutchActionVerb = 'aangemaakt'; break; case 'edit': $dutchActionVerb = 'bewerkt'; break; case 'delete': $dutchActionVerb = 'verwijderd'; break; case 'check': $dutchActionVerb = 'geverifieerd'; break; default: $dutchActionVerb = ''; } // If we reached this point, we can perform the SOAP call(s) to the underlying 'common SOAP layer(s)'. // Variables to keep track of what to retrieve $btzSoapCallSuccessfullyPerformed = $btSoapCallSuccessfullyPerformed = false; $rpcCallMessages = array(''); $rpcCallErrorCode = -1; // At this point, we treat the 'BTZ flow' separately from the 'BT flow'. // Handle the 'BTZ flow' if ($performBtzSoapCall) { // If we reached this point, we can reasonably assume to have enough information to make the SOAP call to the underlying common SoapDossier service. // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // Specify the WS method for manipulating a document and also fill the fields we need for the 'add' as well as the 'edit' calls. $parameters->document->bestand = base64_decode($parameters->document->bestand); $btzMethodName = 'soapManipulateDocument'; $btzMethodParameters = array(); $btzMethodParameters['licentieNaam'] = $this->remoteBtzSoapLicentieNaam; $btzMethodParameters['licentieWachtwoord'] = $this->remoteBtzSoapLicentieWachtwoord; $btzMethodParameters['actie'] = $parameters->actie; $btzMethodParameters['dossierId'] = $parameters->projectId; $btzMethodParameters['dossierHash'] = $parameters->projectHash; $btzMethodParameters['document'] = (array)$parameters->document; //d($parameters->document); //d($btzMethodParameters['document']); //exit; // Generically call the right BTZ SoapDossier service $btzSoapCallResultSet = $this->performBTZSoapDossierCall($btzMethodName, $btzMethodParameters); //d($btzSoapCallResultSet); //exit; //d($btzSoapCallResultSet['success']); //d($btzSoapCallResultSet['message']); //d($btzSoapCallResultSet['wsResult']); //d($btzSoapCallResultSet['wsResult']->results); // Check if the SOAP call was made successfully. $btzSoapCallSuccessfullyPerformed = (!empty($btzSoapCallResultSet) && !empty($btzSoapCallResultSet['success']) && ($btzSoapCallResultSet['success'])); // If we could not successfully call the BTZ SoapDossier service, error out. if (!$btzSoapCallSuccessfullyPerformed) { // Set the error message and code in the result set. $errorCode = 401; // Interne fout: BRIStoezicht SoapDossier service heeft niet succesvol een document {$dutchActionVerb} $errorMessage = "Interne fout: BRIStoezicht SoapDossier service heeft niet succesvol een document {$dutchActionVerb}."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); return $resultSet; } // if (!$btzSoapCallSuccessfullyPerformed) else { // Register the successful outcome of the call to the BTZ SoapDossier service $actionResultMessage = "Het BRIStoezicht document is succesvol {$dutchActionVerb}."; $rpcCallMessages []= $actionResultMessage; // Now get the results from the call and pass them in the result set $resultSet['results']['documentId'] = $btzSoapCallResultSet['wsResult']->results->documentId; } // else of clause: if (!$btzSoapCallSuccessfullyPerformed) // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtzSoapCall) // If an error code has been set by the BTZ specific part above, make sure to force-abort calling BT, even if we // previously determined that we needed to call it. if ($resultSet['errorCode'] > 0) { $performBtSoapCall = false; } // Handle the 'BT flow' if ($performBtSoapCall) { // Initialise an array that will hold any and all messages that are returned from the underlying webservice and/or // that are added during the processing of the data so at the end of the run they can all be passed back to the caller. $rpcCallMessages = array(); // !!! TODO: For being able to do anything other than adding a new document, we need to extend the whole mechanisms and // keep track of the document ID(s) that BT returns to us. For now, this is not yet implemented. // Specify the WS method for manipulating the document in BT. $btMethodName = 'soapManipulateDocument'; $btMethodParameters = array(); $btMethodParameters['licentieNaam'] = $this->remoteBtSoapLicentieNaam; $btMethodParameters['licentieWachtwoord'] = $this->remoteBtSoapLicentieWachtwoord; $btMethodParameters['actie'] = $parameters->actie; $btMethodParameters['dossierHash'] = $btzDossier->bt_dossier_hash; $btMethodParameters['dossierId'] = $btzDossier->bt_dossier_id; $btMethodParameters['document'] = array( 'documentId' => -1, // Set it to -1 for adding a new one, see comment above in case we also need to e.g. edit one 'naam' => $parameters->document->bestandsNaam, 'soort' => '', // What value do we use here? 'type' => '', // What value do we use here? 'specificatie' => $parameters->document->omschrijving, 'versie' => $parameters->document->versieNummer, 'datum' => '' // Leave this empty to let BT use the current date-time ); // Generically call the right BTZ SoapDossier service $btSoapCallResultSet = $this->performBTSoapDossierCall($btMethodName, $btMethodParameters); //d($btSoapCallResultSet); //d($btSoapCallResultSet['success']); //d($btSoapCallResultSet['message']); //d($btSoapCallResultSet['wsResult']); //d($btSoapCallResultSet['wsResult']->results); // Check if the SOAP call was made successfully. $btSoapCallSuccessfullyPerformed = (!empty($btSoapCallResultSet) && !empty($btSoapCallResultSet['success']) && ($btSoapCallResultSet['success'])); // If we could not successfully call the BT SoapDossier service, error out. if (!$btSoapCallSuccessfullyPerformed) { // Set the error message and code in the result set. $errorCode = 402; // Interne fout: BRIStoets SoapDossier service heeft niet succesvol een rapport geretourneerd. $errorMessage = "Interne fout: BRIStoets SoapDossier service heeft niet succesvol een document {$dutchActionVerb}."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); return $resultSet; } // if (!$btSoapCallSuccessfullyPerformed) else { // Register the successful outcome of the call to the BT SoapDossier service $actionResultMessage = "Het BRIStoets document is succesvol {$dutchActionVerb}."; $rpcCallMessages []= $actionResultMessage; // Now get the results from the call and pass them in the result set /* * ... = $btSoapCallResultSet['wsResult']->results->documentId; * */ } // else of clause: if (!$btzSoapCallSuccessfullyPerformed) // Chain in any and all of the messages that were determined in the handling of the results of the SOAP call(s). $resultSet['message'] .= (empty($resultSet['message']) ? '' : "\n") . implode("\n", $rpcCallMessages); } // if ($performBtSoapCall) // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } else { // Set the proper 'success' state in the resultset. $resultSet['success'] = true; $resultSet['errorCode'] = 0; } // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapManipulateDocument( $parameters ) // The 'soapManipulateDocument' RPC call is used for manipulating projects in BTZ. public function soapManipulateToezichtmoment( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'errorCode' => -1, // -1 = service failed to set a proper error code. Set 0 for 'no error' or to a positive integer for a specific error outcome. 'results' => array( 'toezichtmomentId' => -1, 'actionResultMessage' => '', ) ); // If we reached this point, by means of the filter value we determine if we need to consult both BT and BTZ or only one of the two of them. // Make sure to have the 'checkCommonParametersAndData' helper method properly validate the filter value and also the respective "Woningborg // client records"! $performBtzSoapCall = ( empty($parameters->filter) || ($parameters->filter == 'toezicht') ); // Determine the 'common' checks we need to perform for this RPC method and dispatch the checks to the centralised helper method for that. $checksToPerform = array( 'licenseCheck' => array('licenseName' => $parameters->licentieNaam, 'licensePassword' => $parameters->lic<PASSWORD>), 'filterCheck' => $parameters->filter, 'actionCheck' => $parameters->actie, //'actionAllowedValues' => array('Add', 'Edit', 'Delete', 'Check'), 'actionAllowedValues' => array('Edit'), 'btzWoningborgRecordExistsCheck' => $performBtzSoapCall, //'passedParameterValues' => $parameters, //'requiredParameterValues' => array(), ); $this->checkCommonParametersAndData($checksToPerform, $resultSet); // If we reached this point and no errorCode has been set, the RPC method's common data and requirement parameters were satisfied. Continue. // If, on the other hand, an error code WAS set, we exit early if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we have satisfied our common checks and we can proceed. // Get the dossier and the BT-BTZ mapping record using the passed parameters (if valid). $btzDossierID = $btzDossierHash = null; $btzDossierID = (is_null($btzDossierID)) ? $parameters->projectId : $btzDossierID; $btzDossierHash = (is_null($btzDossierHash)) ? $parameters->projectHash : $btzDossierHash; $btzDossier = $this->getExistingDossier($btzDossierID, $btzDossierHash, $resultSet); $btBtzDossier = $this->getExistingBtBtzDossier($btzDossierID, $btzDossierHash, $resultSet); // If we could not get a valid dossier and/or mapping record with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, we know that we have a valid dossier, now proceed to (try to) look up the "toezichtmoment" // using the passed data, and to update it. //d($btzDossier); // First try to get the toezichtmoment. Error out if wwe failed to get it. $toezichtmomentID = (is_null($parameters->toezichtmoment->toezichtmomentId)) ? -1 : $parameters->toezichtmoment->toezichtmomentId; $dclt = $this->_CI->deelplanchecklisttoezichtmoment->get($toezichtmomentID); // Return an error if no deelplannen were retrieved for this dossier if (is_null($dclt)) { // Set the error message and code in the result set. $errorCode = 301; // Toezichtmoment met ID {$toezichtmomentID} bestaat niet. $errorMessage = "Toezichtmoment met ID {$toezichtmomentID} bestaat niet."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // If we could not get a valid toezichtmoment with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If the toezichtmoment was successfully retrieved, get the corresponding dossier and check if the toezichtmoment belongs // to this dossier. $dcltDossier = $dclt->get_dossier(); if (is_null($dcltDossier) || ($btzDossier->id != $dcltDossier->id)) { $errorCode = 302; // Toezichtmoment met ID {$toezichtmomentID} hoort niet bij project met ID {$btzDossierID}. $errorMessage = "Toezichtmoment met ID {$toezichtmomentID} hoort niet bij project met ID {$btzDossierID}."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // if (is_null($dcltDossier) || ($btzDossier->id != $dcltDossier->id)) // If the toezichtmoment does not belong to the dossier that we obtained with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } // If we reached this point, everything is deemed to be in order, so now we simply update the existing toezichtmoment record. //d($parameters->toezichtmoment); // Note (29-2-2016): The below initialisations blank out fields in case not all values are passed back. For that reason a // different style initialisation is now used, where the old value is re-used in case nothing new was passed via SOAP. /* $newDcltNaam = (empty($parameters->toezichtmoment->naam)) ? '' : $parameters->toezichtmoment->naam; $newDcltNummer = (empty($parameters->toezichtmoment->nummer)) ? '' : $parameters->toezichtmoment->nummer; $newDcltSubNummer = (empty($parameters->toezichtmoment->subNummer)) ? '' : $parameters->toezichtmoment->subNummer; $newDcltEmailUitvoerende = (empty($parameters->toezichtmoment->emailUitvoerende)) ? '' : $parameters->toezichtmoment->emailUitvoerende; $newDcltVoornaamUitvoerende = (empty($parameters->toezichtmoment->voornaamUitvoerende)) ? '' : $parameters->toezichtmoment->voornaamUitvoerende; $newDcltAchternaamUitvoerende = (empty($parameters->toezichtmoment->achternaamUitvoerende)) ? '' : $parameters->toezichtmoment->achternaamUitvoerende; $newDcltGeslachtUitvoerende = (empty($parameters->toezichtmoment->geslachtUitvoerende)) ? '' : $parameters->toezichtmoment->geslachtUitvoerende; $newDcltMobieleNummerUitvoerende = (empty($parameters->toezichtmoment->mobieleNummerUitvoerende)) ? '' : $parameters->toezichtmoment->mobieleNummerUitvoerende; $newDcltDatumBegin = (empty($parameters->toezichtmoment->datumBegin)) ? '' : date("Y-m-d",strtotime($parameters->toezichtmoment->datumBegin)); $newDcltDatumEinde = (empty($parameters->toezichtmoment->datumEinde)) ? '' : date("Y-m-d",strtotime($parameters->toezichtmoment->datumEinde)); $newDcltStatusAkkoordWoningborg = (empty($parameters->toezichtmoment->statusAkkoordWoningborg)) ? false : intval($parameters->toezichtmoment->statusAkkoordWoningborg); $newDcltStatusGereedUitvoerende = (empty($parameters->toezichtmoment->statusGereedUitvoerende)) ? false : intval($parameters->toezichtmoment->statusGereedUitvoerende); $newDcltWBGebruikerId = (empty($parameters->toezichtmoment->toezichthouderWoningborg->gebruikerId)) ? -1 : $parameters->toezichtmoment->toezichthouderWoningborg->gebruikerId; $newDcltWBGebruikerVolledigeNaam = (empty($parameters->toezichtmoment->toezichthouderWoningborg->volledigeNaam)) ? '' : $parameters->toezichtmoment->toezichthouderWoningborg->volledigeNaam; $newDcltWBGebruikerEmail = (empty($parameters->toezichtmoment->toezichthouderWoningborg->email)) ? '' : $parameters->toezichtmoment->toezichthouderWoningborg->email; $newDcltBijwoonmoment = (empty($parameters->toezichtmoment->bijwoonmoment)) ? false : intval($parameters->toezichtmoment->bijwoonmoment); $newDcltDatumHercontrole = (empty($parameters->toezichtmoment->datumHercontrole)) ? '' : date("Y-m-d",strtotime($parameters->toezichtmoment->datumHercontrole)); */ $newDcltNaam = (empty($parameters->toezichtmoment->naam)) ? $dclt->naam : $parameters->toezichtmoment->naam; $newDcltNummer = (empty($parameters->toezichtmoment->nummer)) ? $dclt->nummer : $parameters->toezichtmoment->nummer; $newDcltSubNummer = (empty($parameters->toezichtmoment->subNummer)) ? $dclt->sub_nummer : $parameters->toezichtmoment->subNummer; $newDcltEmailUitvoerende = (empty($parameters->toezichtmoment->emailUitvoerende)) ? $dclt->email_uitvoerende : $parameters->toezichtmoment->emailUitvoerende; $newDcltVoornaamUitvoerende = (empty($parameters->toezichtmoment->voornaamUitvoerende)) ? $dclt->voornaam_uitvoerende : $parameters->toezichtmoment->voornaamUitvoerende; $newDcltAchternaamUitvoerende = (empty($parameters->toezichtmoment->achternaamUitvoerende)) ? $dclt->achternaam_uitvoerende : $parameters->toezichtmoment->achternaamUitvoerende; $newDcltGeslachtUitvoerende = (empty($parameters->toezichtmoment->geslachtUitvoerende)) ? $dclt->geslacht_uitvoerende : $parameters->toezichtmoment->geslachtUitvoerende; $newDcltMobieleNummerUitvoerende = (empty($parameters->toezichtmoment->mobieleNummerUitvoerende)) ? $dclt->mobiele_nummer_uitvoerende : $parameters->toezichtmoment->mobieleNummerUitvoerende; $newDcltDatumBegin = (empty($parameters->toezichtmoment->datumBegin)) ? $dclt->datum_begin : date("Y-m-d",strtotime($parameters->toezichtmoment->datumBegin)); $newDcltDatumEinde = (empty($parameters->toezichtmoment->datumEinde)) ? $dclt->datum_einde : date("Y-m-d",strtotime($parameters->toezichtmoment->datumEinde)); $newDcltStatusAkkoordWoningborg = (empty($parameters->toezichtmoment->statusAkkoordWoningborg)) ? $dclt->status_akkoord_woningborg : intval($parameters->toezichtmoment->statusAkkoordWoningborg); $newDcltStatusGereedUitvoerende = (empty($parameters->toezichtmoment->statusGereedUitvoerende)) ? $dclt->status_gereed_uitvoerende : intval($parameters->toezichtmoment->statusGereedUitvoerende); $newDcltWBGebruikerId = (empty($parameters->toezichtmoment->toezichthouderWoningborg->gebruikerId)) ? $dclt->toezichthouder_woningborg_gebruiker_id : $parameters->toezichtmoment->toezichthouderWoningborg->gebruikerId; $newDcltWBGebruikerVolledigeNaam = (empty($parameters->toezichtmoment->toezichthouderWoningborg->volledigeNaam)) ? '' : $parameters->toezichtmoment->toezichthouderWoningborg->volledigeNaam; $newDcltWBGebruikerEmail = (empty($parameters->toezichtmoment->toezichthouderWoningborg->email)) ? '' : $parameters->toezichtmoment->toezichthouderWoningborg->email; $newDcltBijwoonmoment = (empty($parameters->toezichtmoment->bijwoonmoment)) ? $dclt->bijwoonmoment : intval($parameters->toezichtmoment->bijwoonmoment); $newDcltDatumHercontrole = (empty($parameters->toezichtmoment->datumHercontrole)) ? $dclt->datum_hercontrole : date("Y-m-d",strtotime($parameters->toezichtmoment->datumHercontrole)); // Try to get the Woningborg gebruiker (if any). If none was specified, skip the gebruiker, otherwise try to // retrieve it and check that it is a valid Woningborg gebruiker. if ($newDcltWBGebruikerId <= 0) { $newDcltWBGebruikerId = null; } // if ($newDcltWBGebruikerId <= 0) else { // Get the data of the passed 'Woningborg toezichthouder' (if any). $toezichtHouderWoningborgGebruiker = $this->_CI->gebruiker->get($newDcltWBGebruikerId); // If a user was retrieved, check that the user really belongs to Woningborg! // If not, throw an error. if (is_null($toezichtHouderWoningborgGebruiker) || ($toezichtHouderWoningborgGebruiker->klant_id != $this->btzWoningborgKlant->id)) { // Set the error message and code in the result set. $errorCode = 303; // Woningborg toezichthouder met ID {$newDcltWBGebruikerId} is geen geldige Woningborg gebruiker. $errorMessage = "Woningborg toezichthouder met ID {$newDcltWBGebruikerId} is geen geldige Woningborg gebruiker."; $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); } // If we could not get a valid Woningborg medewerker with the passed data, we error out early. if ($resultSet['errorCode'] > 0) { return $resultSet; } } // else of clause: if ($newDcltWBGebruikerId <= 0) //d($newDcltWBGebruikerId); //d($newDcltNaam); // If we reached this point, all the data should be validated and correct, so proceed to store it. $dclt->naam = $newDcltNaam; $dclt->nummer = $newDcltNummer; $dclt->sub_nummer = $newDcltSubNummer; $dclt->email_uitvoerende = $newDcltEmailUitvoerende; $dclt->voornaam_uitvoerende = $newDcltVoornaamUitvoerende; $dclt->achternaam_uitvoerende = $newDcltAchternaamUitvoerende; $dclt->geslacht_uitvoerende = $newDcltGeslachtUitvoerende; $dclt->mobiele_nummer_uitvoerende = $newDcltMobieleNummerUitvoerende; $dclt->datum_begin = $newDcltDatumBegin; $dclt->datum_einde = $newDcltDatumEinde; $dclt->status_akkoord_woningborg = $newDcltStatusAkkoordWoningborg; $dclt->status_gereed_uitvoerende = $newDcltStatusGereedUitvoerende; $dclt->toezichthouder_woningborg_gebruiker_id = $newDcltWBGebruikerId; $dclt->bijwoonmoment = $newDcltBijwoonmoment; $dclt->datum_hercontrole = $newDcltDatumHercontrole; // Save the record, error out on exceptions try { $dclt->save(); } catch (exception $e) { // Set the error message and code in the result set. $errorCode = 304; // Het toezichtmoment met ID '{$toezichtmomentID}' is NIET succesvol opgeslagen. Reden:. $errorMessage = "Het toezichtmoment met ID '{$toezichtmomentID}' is NIET succesvol opgeslagen. Reden: " . $e->getMessage(); $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); // Perform an early return return $resultSet; } /* // Finally, generate the opdrachten from the deelplan_checklist_toezichtmoment, error out on exceptions try { $dclt->generate_deelplan_opdrachten(); } catch (exception $e) { // Set the error message and code in the result set. $errorCode = 305; // De opdrachten voor het toezichtmoment met ID '{$toezichtmomentID}' zijn NIET succesvol aangemaakt. Reden:. $errorMessage = "De opdrachten voor het toezichtmoment met ID '{$toezichtmomentID}' zijn NIET succesvol aangemaakt. Reden: " . $e->getMessage(); $this->setErrorCodeAndMessage($errorCode, $errorMessage, $resultSet); // Perform an early return return $resultSet; } * */ // If we reached this point, no errors ocurred, so return the successful outcome $resultSet['success'] = true; $resultSet['message'] = 'De manipulateToezichtmoment aanroep is succesvol uitgevoerd'; $resultSet['errorCode'] = 0; $resultSet['results'] = array( 'toezichtmomentId' => intval($parameters->toezichtmomentId), 'actionResultMessage' => 'Toezichtmoment is succesvol bewerkt' ); // Finish by returning the result set with the outcome of the call. return $resultSet; } // public function soapManipulateToezichtmoment( $parameters ) /************************* RPC CALLS "MANIPULATE" (END) *************************/ } // class WoningborgWebservice extends AbstractWebservice <file_sep>SET @comp_id = (SELECT id FROM `webservice_components` WHERE `naam` = 'Klanten koppeling'); SET @acc_id = (SELECT id FROM `webservice_accounts` WHERE `omschrijving` = 'BTZ app'); INSERT INTO `webservice_account_rechten` (`id` ,`webservice_account_id` ,`webservice_component_id`) VALUES (NULL , @acc_id, @comp_id); <file_sep><script type="text/javascript"> function annuleren() { closePopup(); } function verwijderen( btn ) { $.ajax({ url: '/beheer/matrix_verwijderen/<?=$matrix->id?>', type: 'POST', success: function( data, jqXHR, textStatus ) { if (data.errors) alert( data.errors ); else { location.href = location.href; } }, error: function() { alert( 'Fout bij communicatie met server.' ); } }); } </script> <? if (empty( $errors )): ?> <table width="100%" cellspacing="0" cellpadding="5"> <tr> <td colspan="2"><h2>Matrix &quot;<?=htmlentities( $matrix->naam, ENT_COMPAT, 'UTF-8' )?>&quot; verwijderen</h2></td> </tr> <tr> <td><b>LET OP:</b> Als er toezicht gekoppeld is aan deze matrix, zal dit automatisch terugvallen op de standaard matrix.</td> </tr> <tr> <td id="form" colspan="2"> <input type="button" onclick="verwijderen(this);" value="<?=tgng('form.verwijderen')?>" /> <input type="button" onclick="annuleren();" value="<?=tgng('form.annuleren')?>" /> </td> </tr> </table> <? else: ?> <? $this->load->view( 'elements/errors' ); ?> <? endif; ?><file_sep><? require_once 'base.php'; class VraagAandachtspuntResult extends BaseResult { function VraagAandachtspuntResult( &$arr ) { parent::BaseResult( 'vraagaandachtspunt', $arr ); } } class VraagAandachtspunt extends BaseModel { function VraagAandachtspunt() { parent::BaseModel( 'VraagAandachtspuntResult', 'bt_vraag_ndchtspntn' ); } public function check_access( BaseResult $object ) { } function get_by_vraag( $vraag_id ) { if (!$this->dbex->is_prepared( 'VraagAandachtspuntResult::get_by_vraag' )) $this->dbex->prepare( 'VraagAandachtspuntResult::get_by_vraag', 'SELECT * FROM '.$this->_table.' WHERE vraag_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'VraagAandachtspuntResult::get_by_vraag', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } } <file_sep><? global $CI; $ver = 'v' . config_item('application_version'); if (config_item( 'development_version' )) $ver .= '&t=' . round(1000*microtime(true)); // Check if the current action is inloggin if( $CI->uri->segment(2) == 'inloggen' ) { $style_absolute = ' style="position: absolute" '; $tabbar_style = ' style="width: 774px; margin:0 auto"'; $tabbar_container = ' style="width: 806px; margin:0 auto"'; $content_container_table = ' style="width: 806px; margin:0 auto"'; $gebruiker_style = ' style="width: 480px; margin: 0 auto"'; $div_content_container = ' style="width: 734px;"'; } else { $style_absolute = ' style="background-color: #fcfcfc"'; $tabbar_style = " "; $tabbar_container = ' '; $content_container_table = ' '; $gebruiker_style = ' '; $div_content_container = ' '; } ?> <!doctype html> <html> <head> <title><?=@$extra_title ? $extra_title : APPLICATION_TITLE?></title> <meta http-equiv="expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <? if ($CI->is_Mobile): ?> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <? endif; ?> <!-- css --> <link rel="shortcut icon" href="<?=site_url('/files/images/favicon.png')?>" /> <link rel="stylesheet" href="<?=site_url('/files/css/toezicht.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery-ui.css')?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery.ui.timepicker.css')?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/checklistwizard/checklistwizard.css?' . $ver)?>" type="text/css" /> <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> <? if ($CI->is_IE6or7): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE6or7.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_IE6or7or8): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE6or7or8.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_IE): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_Safari): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-safari.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_Mobile): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-mobile.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ( !isset($leaseconfiguratie) ) { $_gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $_leaseconfiguratie = $_gebruiker ? $_gebruiker->get_klant()->get_lease_configuratie() : null; } else { $_leaseconfiguratie = $leaseconfiguratie; } ?> <? if ($_leaseconfiguratie && $_leaseconfiguratie->id!=null): ?> <!-- overrides CSS files --> <style text="type/css"> body { background: url('/files/images/lease/background_<?=$_leaseconfiguratie->naam?>.png') repeat; } table.navigation td.last, ul.tabbar li.current, div.lijst-nieuwe-stijl ul.list div.checkbox.checked { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-color: #<?=$_leaseconfiguratie->achtergrondkleur?>; } div.green-topbar { background-image: url(/files/images/background-green-topbar-<?=$_leaseconfiguratie->naam?>.png); } table.tab td.selected.left, table.tab td.hover.left { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-image: url(/files/images/tableft-selected-<?=$_leaseconfiguratie->naam?>.png); } table.tab td.selected.mid, table.tab td.hover.mid { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-image: url(/files/images/tabmid-selected-<?=$_leaseconfiguratie->naam?>.png); } table.tab td.selected.right, table.tab td.hover.right { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-image: url(/files/images/tabright-selected-<?=$_leaseconfiguratie->naam?>.png); } table.greenbutton td.left { background-image: url(/files/images/greenbutton-left-<?=$_leaseconfiguratie->naam?>.png); } table.greenbutton td.mid { background-image: url(/files/images/greenbutton-mid-<?=$_leaseconfiguratie->naam?>.png); } table.greenbutton td.right { background-image: url(/files/images/greenbutton-right-<?=$_leaseconfiguratie->naam?>.png); } h3 { font-size: 18px; color: #<?=$_leaseconfiguratie->achtergrondkleur?>; } </style> <? endif; ?> <!-- javascript system libaries --> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-1.7.min.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-ui.min.js')?>"></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery.ui.timepicker.min.js')?>"></script> <? if ($CI->is_Wizard): ?> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery.ui.touch-punch.min.js')?>"></script> <? endif; ?> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/modal.popup.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/json.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/afspraak.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery.contextMenu.js')?>" ></script> <!-- BRIStoezicht libaries --> <script type="text/javascript"> var eventStopPropagation = function( e ) { if (typeof( e.stopPropagation ) == 'function') e.stopPropagation(); else if (typeof( e.cancelBubble ) != 'undefined') e.cancelBubble = true; } </script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/toezicht.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/core.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/common.helper.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/group.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/helpbutton.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/inlineedit.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/list.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/progress.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/searchablelist.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/tabbuttons.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/tools.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/upload.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/form.js?' . $ver)?>" ></script> <? if ($this->login->require_javascript()): ?> <script type="text/javascript" language="javascript" src="<?=$this->login->get_javascript_url()?>"></script> <? endif; ?> <? if (isset( $extra_scripts ) && is_array( $extra_scripts )): ?> <? foreach ($extra_scripts as $script): ?> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/' . $script . '?' . $ver)?>" ></script> <? endforeach; ?> <? endif; ?> <? global $class, $method; $js_file = '/files/js/pagescripts/' . $class . '/' . $method . '.js'; if (file_exists( APPPATH . '../' . $js_file )): ?> <script type="text/javascript" language="javascript" src="<?=site_url($js_file . '?' . $ver)?>" ></script> <? endif; ?> <? if (@$include_nokia_maps): ?> <!-- Nokia Maps --> <meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" /> <script type="text/javascript" src="https://api.maps.nokia.com/2.2.3/jsl.js?with=maps,places,search" charset="utf-8"></script> <script type="text/javascript" src="<?=site_url('/files/js/nokia.maps.helper.js?' . $ver)?>" charset="utf-8"></script> <script type="text/javascript"> $(document).ready(function(){ if (nokia.places.comm.core.get) { var oldFunc = nokia.places.comm.core.get; nokia.places.comm.core.get = function (f,b){ f = f.replace( /http:/, 'https:' ); return oldFunc( f, b ); } } }); </script> <? endif; ?> </head> <body> <a name="top"></a> <!-- main container --> <table<?= $style_absolute ?> border="0" cellspacing="0" cellpadding="0" class="main-container"> <tr><td> <!-- tabs --> <table<?= $tabbar_container ?> border="0" cellspacing="0" cellpadding="0" class="tabbar-container"> <tr> <td> <table<?= $tabbar_style ?>border="0" cellspacing="0" cellpadding="0" class="tabbar"> <tr> <td> <table border="0" cellspacing="0" cellpadding="0" class="tab"> <tr> <td class="tab" style="width: 187px; background: transparent url(<?=site_url('/files/images/' . ($_leaseconfiguratie ? 'lease/' . $_leaseconfiguratie->naam : 'bris') . '.png')?>) no-repeat 0px 3px"> &nbsp; </td> <? if ($this->login->verify( 'root', 'index' ) && $this->login->logged_in() && $this->login->verify( 'dossiers', 'index' )): ?> <? $selclass = ($this->navigation->get_active_tab() == 'dossierbeheer' )? 'selected' : ''; ?> <td class="<?=$selclass?> left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/dossiers')?>';"> <p><?=tgg( 'header.dossierbeheer' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> <? if ($this->login->verify( 'beheer', 'gebruikers' )): ?> <td class="spacer">&nbsp;</td> <? $selclass = ($this->navigation->get_active_tab() == 'gebruikersbeheer' )? 'selected' : ''; ?> <td class="<?=$selclass?> tab left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/instellingen/gebruikers')?>';"> <p><?=tgg( 'header.gebruikersbeheer' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> <? if (APPLICATION_HAVE_MATRIX && $this->login->verify( 'beheer', 'matrixbeheer' )): ?> <td class="spacer">&nbsp;</td> <? $selclass = ($this->navigation->get_active_tab() == 'matrixbeheer' )? 'selected' : ''; ?> <td class="<?=$selclass?> tab left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/instellingen/matrixbeheer')?>';"> <p><?=tgg( 'header.matrixbeheer' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> <? if (APPLICATION_HAVE_MANAGEMENT && $this->login->verify( 'beheer', 'managementinfo' )): ?> <td class="spacer">&nbsp;</td> <? $selclass = ($this->navigation->get_active_tab() == 'management' )? 'selected' : ''; ?> <td class="<?=$selclass?> tab left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/instellingen/managementinfo')?>';"> <p><?=tgg( 'header.management' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> <? if (APPLICATION_HAVE_INSTELLINGEN && $this->login->verify( 'beheer', 'index' )): ?> <td class="spacer">&nbsp;</td> <? $selclass = ($this->navigation->get_active_tab() == 'beheer' )? 'selected' : ''; ?> <td class="<?=$selclass?> tab left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/instellingen/index')?>';"> <p><?=tgg( 'header.instellingen' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> <? if ($this->login->verify( 'admin', 'index' )): ?> <td class="spacer">&nbsp;</td> <? $selclass = ($this->navigation->get_active_tab() == 'admin' )? 'selected' : ''; ?> <td class="<?=$selclass?> tab left"></td> <td class="<?=$selclass?> mid" onclick="location.href='<?=site_url('/admin/index')?>';"> <p><?=tgg( 'header.sitebeheer' )?></p> </td> <td class="<?=$selclass?> right"></td> <? endif; ?> </tr> </table> </td> <td class="skipright rollen"> <p> <? if ($this->login->logged_in()): ?> <? $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); ?> <? if (!@$CI->is_Mobile): ?> Welkom, <span style="font-weight:bold"><?=$gebruiker->volledige_naam?></span> <? endif; ?> <!-- <? $rol = $gebruiker->get_rol(); echo '<b>' . ($rol ? $rol->naam : tgg('header.geen_rol_toegekend')) . '</b>'; ?> --> <? if ($this->login->have_logout()): ?> | [<a href="<?=site_url('/gebruikers/uitloggen')?>"><?=tgg('header.uitloggen')?></a>] <? endif; ?> <? if ($this->login->verify( 'admin', 'toggle_inline_edit' )): ?> | <a href="/admin/toggle_inline_edit">[Inline edit]</a> <? endif; ?> <? if ($this->login->verify( 'admin', 'toggle_help_button_edit_mode' )): ?> | <a href="/admin/toggle_help_button_edit_mode"><? if ($this->helpbutton->edit_mode()): ?><img src="<?=site_url('/files/images/help-edit.png')?>" title="Zet help tekst bewerking uit"><? else: ?><img src="<?=site_url('/files/images/help.png')?>" title="Zet help tekst bewerking aan"><? endif; ?></a> <? endif; ?> <? else: ?> <?=tgg('header.niet_ingelogd')?> <? endif; ?> </p> </td> </tr> </table> </td> </tr> </table> <? if (!isset( $skip_regular_header ) || !$skip_regular_header): ?> <!-- content container --> <div class="content-container-table"> <table<?= $content_container_table ?>cellspacing="0" cellpadding="0" class="content-container-table" border="0"> <tr> <td class="content-container-left"></td> <td> <div class="green-topbar"></div> <div<?= $div_content_container?> class="content-container"> <? if (isset( $prenavigation )): ?> <?=$prenavigation?> <? endif; ?> <!-- navigation --> <? if ($this->login->logged_in()): ?> <table class="navigation"> <tr> <? $navigation = $this->navigation->get(); $navtotal = sizeof($navigation)-1; foreach ($navigation as $i => $row): $last = $i==$navtotal ; $text = ($last) ? call_user_func_array( 'tgg', array_merge( array( $row['text'] ), $row['params'] ) ) : call_user_func_array( 'tgga', array_merge( array( $row['text'], $row['url'] ), $row['params'] ) ); ?> <td class="<?=$last ? 'last' : ''?>" style="max-width: 250px; white-space: nowrap; overflow: hidden;" title="<?=preg_replace('/<.*?>/','',"$text")?>"> <?=($navtotal < 4 || ($navtotal>=4 && ($i < 4 || $i > ($navtotal - 2)))) ? $text : "<a href='".$row['url']."'>...</a>"?> </td> <td class="none" style="width: 10px; padding: 0px;"></td> <? endforeach; ?> <td class="none"> <?=htag('navigation')?> </td> </tr> </table> <? endif; ?> <? $this->load->view('elements/errors'); ?> <div<?= $gebruiker_style ?> class="<? global $class; echo $class?> <?=($class=='checklistwizard'||(isset($map_view)&&$map_view)?'lijst-nieuwe-stijl':'')?>"> <? endif; ?><file_sep><?php require_once 'base.php'; class StandarddocumentResult extends BaseResult { function StandarddocumentResult( &$arr ){ parent::BaseResult( 'standarddocument', $arr ); } } class Standarddocument extends BaseModel{ function Standarddocument(){ parent::BaseModel( 'StandarddocumentResult', 'standard_documents' ); } public function upload($id, $klant_id, $file_id ){ if(!empty($_FILES['document']['name'][$id])){ $this->load->helper( 'file' ); $thumbnail = NULL; $data=file_get_contents( $_FILES['document']['tmp_name'][$id] ); if (!file_exists(DIR_STANDAARTEN_DOCUMENTEN)) { mkdir(DIR_STANDAARTEN_DOCUMENTEN, 0777); } CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file(DIR_STANDAARTEN_DOCUMENTEN.'/'.$klant_id.'/',$file_id,$data); } } public function get_file_path($klant_id) { $folder = DIR_STANDAARTEN_DOCUMENTEN.'/'.$klant_id; return $folder; } public function get_file_location($klant_id,$document_id) { $folder = $this->get_file_path($klant_id); $file_name = $folder.'/'.$document_id; return $file_name; } public function laad_inhoud($klant_id,$document_id) { if (isset( $this->bestand )) return; $file_name = $this->get_file_location($klant_id, $document_id); $fhandle = fopen( $file_name, 'a+' ); $file = fread($fhandle, filesize($file_name)); fclose($fhandle); return $file; } public function get_by_klant( $klant_id, $assoc=false ){// $docs = $this->db->where('klant_id', $klant_id ) ->get( $this->_table ) ->result(); $result = array(); foreach( $docs as $row ){ $row->is_standard = TRUE; $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_document_by_id_and_klant_id($id, $klant_id, $assoc=false ){// $docs = $this->db->where('id', $id ) ->where('klant_id', $klant_id ) ->get( $this->_table ) ->result(); $result = array(); foreach( $docs as $row ){ $row->is_standard = TRUE; $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } } <file_sep>PDFAnnotator.Tool.Quad = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'quad' ); /* used during drag */ var thiz = this; this.currentQuad = null; /* handle events */ this.on( 'dragstart', function( tool, data ){ var menu = tool.engine.gui.menu; var colorSettings = menu.colors; thiz.currentQuad = new PDFAnnotator.Editable.Quad({ color: colorSettings.getLineColor(), from: data.position, to: data.position }); if (!data.container.addObject( thiz.currentQuad )) { thiz.currentQuad = null; return false; } }); this.on( 'dragmove', function( tool, data ){ if (thiz.currentQuad) thiz.currentQuad.setTo( data.position ); }); this.on( 'dragend', function( tool, data ){ if (thiz.currentQuad) { thiz.currentQuad.finish(); thiz.currentQuad = null; } }); } }); <file_sep><?php function editor( $object, $header, $nav=array(), $additional_view=array() ) { if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['__save'])) { $objname = $object->to_string(); if (editor_save( $object, $diff )) get_instance()->logger->add( null, 'edit', $object->get_stuk_naam() . ' eigenschappen aangepast van '.$objname, $diff ); } redirect( $_POST['__referer'] ); } else { get_instance()->load->view( 'editor', array_merge( $additional_view, array( 'header' => $header, 'object' => $object, 'referer' => isset($_POST['__referer']) ? $_POST['__referer'] : strval(@$_SERVER['HTTP_REFERER']), 'nav' => $nav, ) ) ); } } function editor_save( $object, &$diff=null, &$errors=null ) { // make associative array of fields by fieldname $fields = array(); foreach ($object->get_edit_fields() as $field) $fields[$field['fieldname']] = $field; // traverse list $changes = false; $errors = array(); foreach ($_POST as $fieldname => $value) { if ($fieldname != '__referer' && $fieldname != '__save') { // is this a field we know? if (!isset($fields[$fieldname])) continue; $fd =& $fields[$fieldname]; // handle setting a password $is_password = array_search('password', $fd['flags']) !== FALSE; if ($is_password) { if ($value=='') continue; $value = sha1($value); } // handle null values if ($value=='__NULL__') $value = null; // check enumeration values! $is_enum = $fd['type']=='enum'; if ($is_enum) { if (!isset( $fd['values'][$value] )) continue; } // only update when really changed if ($object->$fieldname != $value) { $changes = true; $object->$fieldname = $value; if (!$diff) $diff = '<b>Veranderingen:</b><ul>'; $diff .= '<li><b>'.$fd['name'].'</b> veranderd'; if (!$is_password) { if ($value==null) $value = '(niks)'; else if ($fd['type']=='select') $value = $fd['model']->get( $value )->to_string(); else if ($is_enum) $value = $fd['values'][$value]; $diff .= ' in <i>' . $value . '</i>'; } $diff .= '</li>'; } } } foreach ($_FILES as $name => $file) { if ($file['size'] > 0) { if (!$file['error']) { $contents = file_get_contents( $file['tmp_name'] ); if ($contents !== FALSE) { $changes = true; $object->$name = $contents; $object->bestandsnaam = $file['name']; // these are not really "netjes" ... :-P if (isset( $object->laatste_bestands_wijziging_op )) { $object->laatste_bestands_wijziging_op = date( 'Y-m-d H:i:s' ); } if (isset( $object->png_status )) { $object->png_status = 'onbekend'; } } else $errors[] = 'Fout bij verwerken van bestand ' . $file['name'] . '.'; } else if ($file['name']) $errors[] = 'Fout bij uploaden van bestand ' . $file['name'] . '.'; } else { // niks geselecteerd, geen fout } } if ($changes) $object->save(); if ($diff) $diff .= '</ul>'; return $changes; }<file_sep><? require_once 'base.php'; class DossierFotoResult extends BaseResult { function DossierFotoResult( &$arr ) { parent::BaseResult( 'dossierfoto', $arr ); } function get_edit_fields() { return array( $this->_edit_uploadfield( 'Bestand', 'bestand', $this->bestandsnaam ), ); } function to_string() { return $this->bestandsnaam; } public function get_dossier() { $CI = get_instance(); $CI->load->model( 'dossier' ); return $CI->dossier->get( $this->dossier_id ); } // Small helper function that can be used to determine the path (only) of the binary file data public function get_file_path() { $folder = DIR_DOSSIER_FOTOS . '/' . $this->dossier_id; return $folder; } // Small helper function that can be used to determine the full location (i.e. path + filename) of the binary file data public function get_file_location() { $folder = $this->get_file_path(); $file_name = $folder.'/'.$this->id; return $file_name; } public function laad_inhoud() { if (isset( $this->bestand )) return; $file_name = $this->get_file_location(); $fhandle = fopen( $file_name, 'a+' ); $file = fread($fhandle, filesize($file_name)); $this->bestand = $file; fclose($fhandle); } public function geef_inhoud_vrij() { unset( $this->bestand ); } } class DossierFoto extends BaseModel { function DossierFoto() { parent::BaseModel( 'DossierFotoResult', 'dossier_fotos' ); $CI = get_instance(); } protected function _get_select_list() { // alles behalve bestand, zie DossierBescheidenResult::geef_inhoud_vrij functie return 'id, dossier_id, bestandsnaam, laatste_bestands_wijziging_op'; } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } public function get_by_dossier( $dossier_id, $assoc=false, $parent_map_id=null ) { $query = 'SELECT ' . $this->_get_select_list() . ' FROM dossier_fotos WHERE dossier_id = ? ORDER BY id '; if (!$this->dbex->is_prepared( 'get_fotos_by_dossier' )) { $this->dbex->prepare( 'get_fotos_by_dossier', $query ); } $res = $this->dbex->execute( 'get_fotos_by_dossier', array($dossier_id) ); $result = array(); foreach ($res->result() as $row){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } $res->free_result(); return $result; } public function get_one_by_dossier_with_content($dossier_id) { // First get all pictures (this should only be maximally 1 anyway) $dossierFotos = $this->get_by_dossier($dossier_id); // Now get the first from the set (if any) $dossierFoto = (empty($dossierFotos)) ? null : $dossierFotos[0]; if (!is_null($dossierFoto)) { $dossierFoto->laad_inhoud(); } return $dossierFoto; } public function add( $dossier_id ) { // Use the base model's 'insert' method. $data = array( 'dossier_id' => $dossier_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } // Small helper function that can be used to determine the path (only) of the binary file data public function get_file_path($object) { $folder = DIR_DOSSIER_FOTOS . '/' .$object->dossier_id; return $folder; } // Small helper function that can be used to determine the full location (i.e. path + filename) of the binary file data public function get_file_location($object) { $folder = $this->get_file_path($object); $file_name = $folder.'/'.$object->id; return $file_name; } public function save( $object, $do_transaction=true, $alias=null, $error_on_no_changes=true ) { // Make sure to unset the binary data from the model before calling the parent 'save' method as the 'bestand' column no longer exists in the DB! $bestand = (!empty($object->bestand) && !is_null($object->bestand)) ? $object->bestand : null; unset($object->bestand); // Store the DB record first $res = parent::save( $object, $do_transaction, $alias, $error_on_no_changes ); //d($res); exit; /* if( !$res ) { throw new Exception( 'Failed to save in DB. Inner Error.' ); } * */ // If the DB record was successfully created, proceed to save the binary data to the file system. // Note: in case no 'bestand' was determined, we skip the attempt to save the record to the filesystem. This way we can still perform normal model calls to the // save method, without risking accidentally overwriting the file! if (!is_null($bestand)) { //$folder = BASEPATH.'../documents/'.$object->dossier_id; $folder = $this->get_file_path($object); CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file($folder, $object->id, $bestand); } // Now return either the converted result or the unconverted one. //return (is_null($convertedRes)) ? $res : $convertedRes; return $res; } public function delete( $object ){ $file_name = $this->get_file_location($object); $res = parent::delete( $object ); if( !$res ) throw new Exception( 'Failed to delete in DB. Inner Error.' ); unlink( $file_name ); } }<file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('dossiers.bekijken::betrokkenen', 'Betrokkenen', '2013-06-05 16:19:12'), ('deelplannen.checklistgroep::betrokkenen', 'Betrokkenen', '2013-06-05 10:44:38'), ('dossiers.subject_bewerken::andere.organisatie', 'Andere organisatie', '2013-06-04 20:51:21'), ('dossiers.subject_bewerken::interne.organisatie', 'Interne organisatie', '2013-06-04 20:51:21'), ('dossiers.bewerken::andere.organisatie', 'Andere organisatie', '2013-06-04 20:09:49'), ('dossiers.bewerken::interne.organisatie', 'Interne organisatie', '2013-06-04 20:09:49'); <file_sep><?php function getModelTable( $model ){ switch( $model ){ case 'btbtzdossier': $table = 'bt_btz_dossiers';break; } return $table; } function clear_db( $data = array() ){ $CI = get_instance(); foreach( $data as $dtmod ){ $model = $dtmod['model']; $CI->load->model( $model ); $field = isset($dtmod['field']) ? $dtmod['field'] : 'id'; foreach( $dtmod['items'] as $item ){ $CI->$model->where($field, $item )->delete(getModelTable( $model )); } } }<file_sep><? header( 'Content-Type: text/csv' ); ?> <? echo file_get_contents($file_name); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'mappingen.finalmapping','map_view'=>true)); ?> <h1><?=tgg('mappingen.headers.finalmapping')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list checklist-map-period-table"> <tr> <td class="checklist-map-period-td"> <b>Period&nbsp;&nbsp;&nbsp;</b> <input type="text" id="date" name="date" size="10" class="rounded5" placeholder="From"> <input type="text" id="until" name="until" size="10" class="rounded5" placeholder="Until"> <div id="save_map_period" class="button save_map_period" style="margin-left: 10px;"> <i class="icon-save" style="font-size: 12pt;"></i> <span>Save</span> </div> <?php /* ?> <?=htag('save_map_period')?> <?php */ ?> </td> </tr> </table> <? if( $matrixmapchecklist->id != NULL ): ?> <table cellspacing="0" cellpadding="0" border="0" class="list double-list"> <thead> <tr> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoets')?></li> </ul> </th> <th>&nbsp;</th> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoezicht')?></li> </ul> </th> </tr> </thead> <tbody> <tr> <td class="double-list-td"> <? foreach( $afdelingen as $i=>$afdeling): ?> <? if(count($afdeling['artikelen']) > 0 ): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => htmlentities( $afdeling['naam'], ENT_COMPAT, 'UTF-8' ), 'onclick' => 'afdeling_click('.$afdeling['id'].','.$afdeling['artikelen'][0]['id'].');', 'expanded' => TRUE, 'group_tag' => 'afdelingen', 'width' => '100%', 'height' => (36*$afdeling['count']).'px', 'id' => 'afdeling_'.$afdeling['id'] )); ?> <ul class="artikelen list mappen"> <? foreach( $afdeling['artikelen'] as $i=>$artikel ): ?> <li id="artikel_<?=$artikel['id'] ?>" class="entry top left right" entry_id="<?=$artikel['id'] ?>"> <div class="accordion-list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $artikel['beschrijving'], ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? endforeach; ?> </td> <td class="middle">&nbsp;</td> <td class="double-list-td"> <? foreach( $hoofdgroepen as $hoofdgroep): ?> <? $is_bw_css = $hoofdgroep['is_bw'] ? 'bw' : ''; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => '<table cellspacing="0" cellpadding="0" border="0" class="hf-title-tbl">'. '<tr>'. '<td class="hf-name">'.htmlentities( $hoofdgroep['naam'], ENT_COMPAT, 'UTF-8' ).'</td>'. '<td class="hf-add-info" id="hfinfo_'.$hoofdgroep['id'].'"></td>'. '</tr>'. '</table>', 'rightheader' => $hoofdgroep['is_bw_btn']?'<button entry_id="'.$hoofdgroep['id'].'" class="accordeon-header-btn bw-btn '.$is_bw_css.'">BW</button>':'<div></div>', 'onclick' => 'hoofdgroep_click('.$hoofdgroep['id'].');', 'expanded' => TRUE, 'group_tag' => 'hoofdgroepen', 'width' => '100%', 'height' => (36*$hoofdgroep['count']).'px', 'id' => 'hoofdgroep_'.$hoofdgroep['id'] )); ?> <ul class="vragen list mappen"> <? foreach( $hoofdgroep['vragen'] as $i=>$vraag ): ?> <li id="vraag_<?=$vraag['id'] ?>" class="entry top left right" entry_id="<?=$vraag['id'] ?>"> <div class="accordion-list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $vraag['naam'], ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> </td> </tr> </tbody> </table> <? endif; ?> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> <?php /* ?> var opted = { "afdeling_id":"<?=$afdelingen[0]['id'] ?>", "artikel_id":"<?=$afdelingen[0]['artikelen'][0]['id'] ?>", "hfdgrp_id":"<?=$hoofdgroepen[0]['id'] ?>", "vragen":null } <?php */ ?> var opted = { "afdeling_id":<?=isset($afdelingen[0]['id'])?$afdelingen[0]['id']:'null' ?>, "artikel_id":<?=isset($afdelingen[0]['artikelen'][0]['id'])?$afdelingen[0]['artikelen'][0]['id']:'null' ?>, "hfdgrp_id":<?=$hoofdgroepen[0]['id'] ?>, "vragen":null } ,is_save_vraag=true ,matrixmap_id=<?=$matrixmap_id ?> ,checklist_id=<?=$checklist_id ?> ,hf_busy_data=<?=json_encode($hf_busy_data) ?> ; function setOpted(){ $('.vragen li[entry_id]').off("click"); $('.vragen li[entry_id]').click(function(){ vragen_click($(this)); }); $('.artikelen li[entry_id]') .removeClass("entry-selected") .removeClass("entry-disabled") .addClass("entry"); $("#artikel_"+opted.artikel_id) .removeClass("entry") .addClass("entry-selected"); $.ajax({ url: "<?=site_url('mappingen/get_opted_vragen') ?>/"+opted.artikel_id+"/"+opted.hfdgrp_id+"/"+matrixmap_id+"/"+checklist_id, type: "POST", data: null, dataType: "json", success: function( data ){ if (data && data.success){ $.each(data.vragen, function( index,vraag ){ if( vraag.status=="owner" ){ $("#vraag_"+vraag.id) .removeClass("entry") .removeClass("entry-disabled") .addClass("entry-selected"); }else if( vraag.status == 'busy' ){ $("#vraag_"+vraag.id) .removeClass("entry") .removeClass("entry-selected") .addClass("entry-disabled") .off("click"); } }); $.each(data.hf_info, function( index,hf ){ $("#hfinfo_"+hf.id).html(hf.n_owner+" / "+hf.n_free); }); }else showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } function afdeling_click(id, first_artikel_id){ opted.afdeling_id= id; opted.artikel_id = first_artikel_id; setOpted(); } function hoofdgroep_click(id){ opted.hfdgrp_id = id; setOpted(); } function vragen_click(that){ var action='' ,class_remove ,class_add ; if(!is_save_vraag) return; is_save_vraag=false; if(that.hasClass('entry')){ class_remove= "entry"; class_add = "entry-selected"; action = "set_vraag_assigned"; }else if(that.hasClass('entry-selected')){ class_remove= "entry-selected"; class_add = "entry"; action = "set_vraag_unassigned"; } if( action != '' ){ $.ajax({ url: "<?=site_url('mappingen/') ?>/"+action+"/"+matrixmap_id+"/"+opted.artikel_id+"/"+that.attr('entry_id')+"/"+opted.hfdgrp_id+"/"+checklist_id, type: "POST", data: {}, dataType: "json", success: function( data ){ if (data && data.success){ that .removeClass(class_remove) .addClass(class_add); $("#hfinfo_"+data.hf_id).html(data.n_owner+" / "+data.n_free); if(data.is_busy) setHoofdgroepBusy(data.hf_id); else setHoofdgroepFree(data.hf_id); }else showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } is_save_vraag=true; } function setHoofdgroepBusy(hfId){ $("table.double-list #hoofdgroep_"+hfId+" td.left") .removeClass("left") .addClass("left-g"); $("table.double-list #hoofdgroep_"+hfId+" td.mid") .removeClass("mid") .addClass("mid-g"); $("table.double-list #hoofdgroep_"+hfId+" td.right") .removeClass("right") .addClass("right-g"); } function setHoofdgroepFree(hfId){ $("table.double-list #hoofdgroep_"+hfId+" td.left-g") .removeClass("left-g") .addClass("left"); $("table.double-list #hoofdgroep_"+hfId+" td.mid-g") .removeClass("mid-g") .addClass("mid"); $("table.double-list #hoofdgroep_"+hfId+" td.right-g") .removeClass("right-g") .addClass("right"); } $(document).ready(function(){ $("#date") .datepicker({ dateFormat: "dd-mm-yy" }) .datepicker("setDate","<?=$matrixmapchecklist->date ?>") .change(function(ev){ // alert("Date from"); }); //------------------------- $("#until") .datepicker({ dateFormat: "dd-mm-yy"}) .datepicker("setDate","<?=$matrixmapchecklist->until ?>") .change(function(ev){ // alert("Until"); }); //------------------------- $("#save_map_period").click(function(evn){ $.ajax({ url: "<?=site_url('mappingen/save_dmm_checklist_dates').($matrixmapchecklist->id != NULL?'/'.$matrixmapchecklist->id:'') ?>", type: "POST", data: { "matrixmap_id": <?=$matrixmap_id ?>, "checklist_id": <?=$checklist_id ?>, "date": $("#date").val(), "until":$("#until").val() }, dataType: "json", success: function( data, textStatus, jqXHR ){ if(!data.success){ alert("Error!!!\n"+data.message); $("#"+data.focus).focus(); }else{ window.location = "/mappingen/finalmapping/<?=$matrixmap_id ?>/<?=$bt_matrix_id ?>/<?=$checklist_id ?>"; } }, error: function( jqXHR, textStatus, errorThrown ) { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen (save_map_period).", type: "error", buttons: ["ok"] }); } }); }); //------------------------- <? if( $matrixmapchecklist->id != NULL ): ?> $("table[group_tag='hoofdgroepen'] tbody tr td:nth-child(3)").addClass("btn-td"); $(".bw-btn").click(function(){ var is_bw, hf_id = $(this).attr("entry_id") ; is_bw = !$(this).hasClass('bw'); $.ajax({ url: "<?=site_url('mappingen/save_bw/') ?>/"+matrixmap_id+"/"+hf_id, type: "POST", data: {"is_bw":is_bw}, dataType: "json", success: function( data ){ if (data && data.success){ $.each(data.hf_ids, function( index,hf_id ){ var bw_btn = $("[group_tag='hoofdgroepen'] [entry_id='"+hf_id+"']"); is_bw ? bw_btn.addClass('bw') : bw_btn.removeClass('bw'); }); }else showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen (1).", type: "error", buttons: ["ok"] }); } }); }); $.each(hf_busy_data, function( hf_id, is_busy ){ ( is_busy ) ? setHoofdgroepBusy(hf_id):null; }); $('.artikelen li[entry_id]').click(function(){ var id = $(this).attr('entry_id'); if( id == opted.artikel_id ) return; $("#artikel_"+opted.artikel_id) .removeClass("entry-selected") .addClass("entry"); opted.artikel_id = id; setOpted(); }); setOpted(); <? endif; ?> }); </script> <file_sep>ALTER TABLE `klanten` ADD COLUMN `risico_grafieken` tinyint(3) DEFAULT '0' NOT NULL AFTER `standaard_deelplannen`; UPDATE klanten SET risico_grafieken = 1 WHERE id = 1; REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'klant.risico_grafieken', 'Risico grafieken?', '2015-06-16 12:14:13' ); <file_sep>CREATE TABLE `lease_configuraties` ( `id` int(11) NOT NULL AUTO_INCREMENT, `naam` varchar(128) NOT NULL, `achtergrondkleur` varchar(6) NOT NULL, `voorgrondkleur` varchar(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; ALTER TABLE `lease_configuraties` ADD `eigen_nieuws_berichten` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja'; ALTER TABLE `lease_configuraties` ADD `automatisch_collega_zijn` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'nee'; ALTER TABLE `lease_configuraties` ADD UNIQUE (`naam`); ALTER TABLE `lease_configuraties` ADD `login_systeem` ENUM( 'kennisid', 'normaal', 'hybride' ) NOT NULL DEFAULT 'kennisid'; ALTER TABLE `lease_configuraties` ADD `toon_gebruikersforum_knop` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'nee' AFTER `automatisch_collega_zijn` ; ALTER TABLE `klanten` ADD `lease_configuratie_id` INT NULL DEFAULT NULL AFTER `naam` , ADD INDEX ( `lease_configuratie_id` ) ; ALTER TABLE `klanten` ADD FOREIGN KEY ( `lease_configuratie_id` ) REFERENCES `lease_configuraties` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; ALTER TABLE `nieuws` ADD `lease_configuratie_id` INT NULL DEFAULT NULL , ADD INDEX ( `lease_configuratie_id` ); ALTER TABLE `nieuws` ADD FOREIGN KEY ( `lease_configuratie_id` ) REFERENCES `lease_configuraties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; REPLACE INTO `teksten` (`tekst`, `string`, `timestamp`) VALUES ('Geen notificaties.', 'intro.index::geen-notificaties-lease', NOW()); ALTER TABLE `teksten` ADD `lease_configuratie_id` INT NOT NULL COMMENT 'dit veld heeft expres geen foreign key, zodat 0 ipv null gebruikt kan worden!!!'; ALTER TABLE `teksten` DROP PRIMARY KEY , ADD PRIMARY KEY ( `string` , `lease_configuratie_id` ) ; <file_sep><? require_once 'base.php'; class VraagGrondslagResult extends BaseResult { function VraagGrondslagResult( &$arr ) { parent::BaseResult( 'vraaggrondslag', $arr ); } function get_grondslag() { $CI = get_instance(); $CI->load->model( 'grondslag' ); return $CI->grondslag->get( $this->get_grondslag_tekst()->grondslag_id ); } function get_grondslag_tekst() { $CI = get_instance(); $CI->load->model( 'grondslagtekst' ); return $CI->grondslagtekst->get( $this->grondslag_tekst_id ); } public function rename( $grondslag_id, $artikel, $tekst ) { $CI = get_instance(); $CI->load->model( 'grondslagtekst' ); // kijk of er al een grondslag tekst is met de opgegeven grondslag_id/artikel $grondslagteksten = $CI->grondslagtekst->search( array( 'grondslag_id' => $grondslag_id, 'artikel' => $artikel ) ); if (!empty( $grondslagteksten )) { $grondslagtekst_id = reset( $grondslagteksten )->id; } else { // als de combinatie nog niet bestaat, voeg het nu toe //$CI->dbex->prepare( 'VraagGrondslag::rename2', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, tekst) VALUES (?,?,?)' ); $CI->dbex->prepare_with_insert_id( 'VraagGrondslag::rename2', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, tekst) VALUES (?,?,?)', $CI->db, $last_insert_id ); // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'isc' : ''; if (!($CI->dbex->execute( 'VraagGrondslag::rename2', array( $grondslag_id, $artikel, strval($tekst) ), false, null, $force_types ))) throw new Exception( 'Fout bij toevoegen van grondslag tekst.' ); $grondslagtekst_id = (get_db_type() == 'oracle') ? $last_insert_id : $CI->db->insert_id(); } $CI->dbex->prepare( 'VraagGrondslagResult::rename', 'UPDATE bt_vraag_grndslgn SET grondslag_tekst_id = ? WHERE id = ?' ); $CI->dbex->execute( 'VraagGrondslagResult::rename', array( $grondslagtekst_id, $this->id ) ); $this->grondslag_tekst_id = $grondslagtekst_id; } } class VraagGrondslag extends BaseModel { function VraagGrondslag() { parent::BaseModel( 'VraagGrondslagResult', 'bt_vraag_grndslgn' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'vraag', 'vraag_id' ); } function get_by_vraag( $vraag_id ) { if (!$this->dbex->is_prepared( 'VraagGrondslagResult::get_by_vraag' )) $this->dbex->prepare( 'VraagGrondslagResult::get_by_vraag', 'SELECT * FROM '.$this->_table.' WHERE vraag_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'VraagGrondslagResult::get_by_vraag', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } function get_data_by_vragen( array $vragen ) { if (empty( $vragen )) return array(); $ids = array(); foreach ($vragen as $vraag) $ids[] = $vraag->id; // 'UPPER' and 'LOWER' are both fully Oracle compatible $query = ' SELECT UPPER(g.grondslag) AS grondslag, LOWER(gt.artikel) AS artikel, vg.vraag_id FROM bt_vraag_grndslgn vg JOIN bt_grondslag_teksten gt ON vg.grondslag_tekst_id = gt.id JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE vraag_id IN (' . implode( ',', $ids ) . ') '; $res = $this->db->query( $query ); $result = array(); foreach ($res->result() as $row) { if (!isset( $result[$row->grondslag] )) $result[$row->grondslag] = array(); if (!isset( $result[$row->grondslag][$row->artikel] )) $result[$row->grondslag][$row->artikel] = array(); $result[$row->grondslag][$row->artikel][] = $row->vraag_id; } $res->free_result(); return $result; } public function add( $vraag_id, $grondslag_id, $artikel, $tekst ) { $CI = get_instance(); $CI->load->model( 'grondslagtekst' ); // kijk of er al een grondslag tekst is met de opgegeven grondslag_id/artikel $grondslagteksten = $CI->grondslagtekst->search( array( 'grondslag_id' => $grondslag_id, 'artikel' => $artikel ) ); if (!empty( $grondslagteksten )) { $grondslagtekst_id = reset( $grondslagteksten )->id; } else { // als de combinatie nog niet bestaat, voeg het nu toe //$CI->dbex->prepare( 'VraagGrondslag::add2', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, tekst) VALUES (?,?,?)' ); $CI->dbex->prepare_with_insert_id( 'VraagGrondslag::add2', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, tekst) VALUES (?,?,?)', $CI->db, $last_insert_id ); // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'isc' : ''; if (!($CI->dbex->execute( 'VraagGrondslag::add2', array( $grondslag_id, $artikel, strval($tekst) ), false, null, $force_types ))) throw new Exception( 'Fout bij toevoegen van grondslag tekst.' ); $grondslagtekst_id = (get_db_type() == 'oracle') ? $last_insert_id : $CI->db->insert_id(); } // Get the proper checklist and checklistgroep for the current question $query = "SELECT bl.checklist_groep_id AS checklist_groep_id, bl.id AS checklist_id FROM bt_vragen bv INNER JOIN bt_categorieen bc ON (bv.categorie_id = bc.id) INNER JOIN bt_hoofdgroepen bh ON (bc.hoofdgroep_id = bh.id) INNER JOIN bt_checklisten bl ON (bh.checklist_id = bl.id) WHERE bv.id = ?"; $CI->dbex->prepare( 'find_cl_clg', $query ); $res = $CI->dbex->execute( 'find_cl_clg', array( $vraag_id ) ); $checklist_id = $checklist_groep_id = 0; foreach ($res->result() as $row) { $checklist_id = $row->checklist_id; $checklist_groep_id = $row->checklist_groep_id; } /* $CI->dbex->prepare( 'VraagGrondslag::add3', 'INSERT INTO bt_vraag_grndslgn (vraag_id, grondslag_tekst_id) VALUES (?,?)' ); $args = array( 'vraag_id' => $vraag_id, 'grondslag_tekst_id' => $grondslagtekst_id, ); if (!($CI->dbex->execute( 'VraagGrondslag::add3', $args ))) throw new Exception( 'Fout bij toevoegen van grondslag/vraag koppeling' ); $args['id'] = $CI->db->insert_id(); return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'vraag_id' => $vraag_id, 'checklist_id' => $checklist_id, 'checklist_groep_id' => $checklist_groep_id, 'grondslag_tekst_id' => $grondslagtekst_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } } <file_sep>-- -- Table structure for table `annotatie_ids` -- CREATE TABLE IF NOT EXISTS `annotatie_ids` ( `id` int(11) NOT NULL AUTO_INCREMENT, `annotatie_id` INT( 11 ) NOT NULL, `x1` INT( 11 ) NOT NULL, `y1` INT( 11 ) NOT NULL, `type` TEXT NOT NULL, `deelplan_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, `dossier_bescheiden_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `dossier_bescheiden_id` (`dossier_bescheiden_id`), KEY `vraag_id` (`vraag_id`) ) ENGINE=InnoDB; -- -- Constraints for table `annotatie_ids` -- ALTER TABLE `annotatie_ids` ADD CONSTRAINT `annotatie_ids_ibfk_1` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `annotatie_ids_ibfk_2` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `annotatie_ids_ibfk_3` FOREIGN KEY (`dossier_bescheiden_id`) REFERENCES `dossier_bescheiden` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><? $this->load->view('elements/header', array('page_header'=>'intro')); ?> <div class="apptoegang-editor"> <form method="POST"> <h1><?=tg('header')?></h1> <h2><?=tg('algemene-info')?></h2> <div class="main" id="algemeen"> <ul class="list"> <li class="entry top left right"> <div class="header"><?=tg('toegang')?>:</div> <div class="content"> <input type="button" value="<?=tgn('inschakelen')?>" <?=$app_toegang ? 'disabled' : ''?> onclick="location.href='<?=site_url('/root/apptoegang/inschakelen')?>';" /> <input type="button" value="<?=tgn('uitschakelen')?>" <?=$app_toegang ? '' : 'disabled'?> onclick="location.href='<?=site_url('/root/apptoegang/uitschakelen')?>';" /> <?=htag('toegang')?> </div> <? $class = $app_toegang ? 'ja' : 'nee'; $this->tekst->set_method( 'index', 'intro' ); $text = tg('app.toegang.button.' . $class); $this->tekst->reset_method(); ?> <div style="float:right; position: relative; top: 6px;" class="apptoegang <?=$class?> rounded5"><?=$text?></div> </li> <li class="entry top left last right"> <div class="header"><?=tg('laatste_gebruik')?>:</div> <div class="content"> <?=$laatste_tijdstip ? tg('laatste_tijdstip', date('d-m-Y H:i', strtotime( $laatste_tijdstip ))) : tg('laatst_tijdstip_nooit')?> <?=htag('laatste_gebruik')?> </div> </li> </ul> </div> <? if ($app_toegang): ?> <h2><?=tg('inloggegevens')?></h2> <div class="main" id="algemeen"> <ul class="list"> <li class="entry top left last right"> <div class="header"><?=tg('email')?>:</div> <div class="content"> <b><?=$email?></b> <?=htag('email')?> </div> </li> <li class="entry top left last right"> <div class="header"><?=tg('wachtwoord')?>:</div> <div class="content"> <input type="<PASSWORD>" name="password" size="60" <?=$app_toegang ? '' : 'disabled'?> placeholder="<?=($app_toegang ? ($heeft_wachtwoord ? tgn('leeg.laten.om.niet.te.wijzigen') : tgn('vul.uw.wachtwoord.in')) : '')?>" /> <?=htag('wachtwoord')?> </div> </li> <li class="entry top left last right"> <div class="header"></div> <div class="content"> <input type="<PASSWORD>" name="password2" size="60" <?=$app_toegang ? '' : 'disabled'?> placeholder="<?=($app_toegang ? ($heeft_wachtwoord ? tgn('leeg.laten.om.niet.te.wijzigen') : tgn('vul.uw.wachtwoord.in')) : '')?>" /> </div> </li> <? if ($heeft_wachtwoord): ?> <li class="entry top left last right"> <div class="header"></div> <div class="content"> <span style="font-style:italic;"><?=tg('er.is.een.app.wachtwoord.bekend.in.het.systeem')?></span> </div> </li> <? endif; ?> </ul> </div> <? endif; ?> <div class="button opslaan"> <a href="javascript:void(0);"><?=tgg('form.opslaan')?></a> </div> </form> </div> <script type="text/javascript"> $(document).ready(function(){ $('.button.opslaan').click(function(){ $('form').submit(); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Checklist import')); ?> <form method="POST" enctype="multipart/form-data"> <p> Via deze pagina kan een csv bestand worden geimporteerd.<br/> <b>LET OP!</b> De CSV bestanden moeten een header regel bevatten! </p> <input type="file" name="upload" /><br/> <table> <tr> <th style="text-align:left">Testrun:</th> <td><input type="checkbox" name="testrun" <?=$is_testrun?'checked':''?> /></td> </tr> <tr> <th style="text-align:left">Klant:</th> <td> <select name="klant_id"> <option value="" disabled selected>-- selecteer klant --</option> <? foreach ($klanten as $klant): ?> <option <?=$klant->id == $klant_id?'selected':''?> value="<?=$klant->id?>"><?=$klant->naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <th style="text-align:left">Encoding:</th> <td> <select name="encoding"> <? foreach (array( 'ISO-8859-1', 'ASCII', 'CP437', 'Windows-1252', 'UTF-8' ) as $e): ?> <option <?=$e==$encoding?'selected':''?> value="<?=$e?>"><?=$e?></option> <? endforeach; ?> </select> </td> </tr> </table> <p> <input type="submit" value="Opsturen" /> <span style="font-style:italic; display: none">Even geduld a.u.b....</span> </p> </form> <script type="text/javascript"> $(document).ready(function(){ $('form').submit(function(){ $('[type=submit]').attr( 'disabled', 'disabled' ); $('[type=submit]').next().show(); return true; }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php class KMXMagmaClient { public $magmaUrl; public $magmaName; public $magmaSecret; public $magmaCalculationType; // sha512 or md5 public $cachePath; public function getMagmaToken() { $token = $this->tokenFromCache(); if (isset($token)) { return $token; } if ((isset($this->magmaCalculationType)) && ($this->magmaCalculationType == "sha512")) { $key = hash('sha512', $this->magmaName . $this->magmaSecret . date('d-m-Y'), FALSE); } else { $key = md5($this->magmaName . $this->magmaSecret . date('d-m-Y')); } $json = $this->tokenFromService(rtrim($this->magmaUrl, '/') . '/Api/Session/Open?name=' . urlencode($this->magmaName) . '&key=' . $key); if ($json && $json->Status == 'Valid') { $this->tokenToCache($json); return $json->Token; } else { error_log( "KMXMagmaClient error: " . var_export( $json, true ) ); return NULL; } } private function tokenFromCache() { if ((isset($this->cachePath)) && (file_exists($this->cachePath))) { if (($data = @file_get_contents( $this->cachePath )) !==false) { $parts = explode(';', $data); if (sizeof( $parts ) > 1) { $expires = strtotime($parts[1]); $now = strtotime('now'); if ($expires > $now) { return $parts[0]; } else { @unlink($this->cachePath); } } } } return NULL; } private function tokenToCache($json) { if (isset($this->cachePath)) { @file_put_contents( $this->cachePath, $json->Token . ';' . date('c', time() + 60 * $json->ExpirationMinutes ) ); } } private function tokenFromService($url) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_POST, TRUE); curl_setopt($c, CURLOPT_POSTFIELDS, ''); curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json')); $json = curl_exec($c); curl_close($c); return json_decode($json); } } ?><file_sep><? require_once 'base.php'; class DeelplanSubjectVraagResult extends BaseResult { function DeelplanSubjectVraagResult( &$arr ) { parent::BaseResult( 'deelplansubjectvraag', $arr ); } } class DeelplanSubjectVraag extends BaseModel { function DeelplanSubjectVraag() { parent::BaseModel( 'DeelplanSubjectVraagResult', 'deelplan_subject_vragen' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossiersubject', 'dossier_subject_id' ); } function get_by_deelplan( $deelplan_id ) { $result = array(); foreach ($this->search( array( 'deelplan_id' => $deelplan_id ) ) as $row) { if (!isset( $result[$row->vraag_id] )) $result[$row->vraag_id] = array(); $result[$row->vraag_id][] = $row; } return $result; } function get_gebruker_sbj_id_by_deelplan_and_vraag($deelplan_id, $vraag_id){ $query = ' select * from deelplan_subject_vragen LEFT JOIN dossier_subjecten ds on deelplan_subject_vragen.dossier_subject_id=ds.id where deelplan_id=? and vraag_id=? '; $this->dbex->prepare( 'get_by_deelplan_and_vraag', $query ); $res = $this->dbex->execute( 'get_by_deelplan_and_vraag', array( $deelplan_id, $vraag_id ) ); $result = array(); $result=$res->result(); return $result; } function set_by_deelplan_and_vraag( $deelplan_id, $vraag_id, array $subject_ids ) { // cleanup current $stmt_name = 'deelplansubjectvraag::set_by_deelplan_and_vraag::delete'; $this->_CI->dbex->prepare( $stmt_name, 'DELETE FROM deelplan_subject_vragen WHERE deelplan_id = ? AND vraag_id = ?' ); $this->_CI->dbex->execute( $stmt_name, array( $deelplan_id, $vraag_id ) ); // set new $stmt_name = 'deelplansubjectvraag::set_by_deelplan_and_vraag::insert'; $this->_CI->dbex->prepare( $stmt_name, 'INSERT INTO deelplan_subject_vragen (deelplan_id,vraag_id,dossier_subject_id) VALUES (?,?,?)' ); foreach ($subject_ids as $subject_id) $this->_CI->dbex->execute( $stmt_name, array( $deelplan_id, $vraag_id, $subject_id ) ); } } <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('gebruikers.inloggen_mobiel::header1', 'BRIStoezicht Mobiel', '2013-07-08 12:40:19'), ('gebruikers.inloggen_mobiel::header2', 'KennisID login', '2013-07-08 12:40:19'), ('gebruikers.inloggen_mobiel::wachtwoord', 'Wachtwoord', '2013-07-08 12:38:27'), ('gebruikers.inloggen_mobiel::gebruikersnaam', 'Gebruikersnaam', '2013-07-08 12:38:27'); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('gebruikers.inloggen_mobiel::remember_me', 'Aangemeld blijven', '2013-07-08 12:57:15'); <file_sep><?php $debug = $perform_timing = $direct_timing_output = $direct_timing_flush = true; $eol = "\n"; //$log_times = array(); # Helper function to get a time stamp with miliseconds precision function getmicrotime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // function getmicrotime() function log_time($additional_text = '', $comparison_idx = -1) { # Get the required global variables. global $debug, $perform_timing, $log_times, $eol, $direct_timing_output, $direct_timing_flush; # If we have to perform timing analysis, do so now if ($perform_timing) { # Get the current 'micro time' $ts = getmicrotime(); # If there aren't yet any log entries, we create the 'index 0' reference measurement. if (!isset($log_times) || empty($log_times)) { # Always create an empty (global) array, so it doesn't have to be created outside of this function $log_times = array(); if (!isset($direct_timing_output)) $direct_timing_output = false; # Store the initialisation string #$log_times[] = array("str" => ">>>> Timing (index: 0: [" . __FILE__ . ' ' . __LINE__ . "]): timer initialisation. Timer value: $ts <<<<$eol" , "pos" => 0, "ts" => $ts); $log_times[] = array("str" => ">>>> Timing (index: 0): timer initialisation. Timer value: $ts <<<<$eol" , "pos" => 0, "ts" => $ts); # Show the initialisation string if ($direct_timing_output) echo $log_times[0]["str"]; } # Determine the proper comparison index $cur_log_idx = sizeof($log_times); $prev_log_idx = ($cur_log_idx - 1); if ($comparison_idx > -1) $comp_idx = $comparison_idx; else $comp_idx = $prev_log_idx; # Calculate the time that passed since the comparison moment, the previous action and the initialisation $timing_comp_str = ">> elapsed time since previous action: " . ($ts - $log_times[$prev_log_idx]["ts"]) . " << "; if ($comp_idx != $prev_log_idx) $timing_comp_str .= " >> elapsed time since comparison action (index: $comp_idx): " . ($ts - $log_times[$comp_idx]["ts"]) . " << "; $timing_comp_str .= " >> elapsed time since initialisation: " . ($ts - $log_times[0]["ts"]) . " << "; # Now create an entry for the current action #$log_str = ">>>> Timing (index: $cur_log_idx: [" . __FILE__ . ' ' . __LINE__ . "]): $additional_text $timing_comp_str <<<<$eol"; $log_str = ">>>> Timing (index: $cur_log_idx): $additional_text $timing_comp_str <<<<$eol"; # Save the log string $log_times[] = array("str" => $log_str, "pos" => $cur_log_idx, "ts" => $ts); # Show the string if ($direct_timing_output) echo $log_str; # Flush the output buffer directly, if we need to do so if ($direct_timing_flush) flush(); } // if ($perform_timing) } // function log_time($additional_text = '', $comparison_idx = -1) // Original script from Red Fountain (but... with filled in values and some additions). log_time("Before start of script"); /* // OTA server $User="bristoezicht"; $Pass="<PASSWORD>"; $Host="127.0.0.1"; $DBName='bristoezicht'; */ /* // Localhost Olaf $User="root"; $Pass=""; $Host="127.0.0.1"; $DBName='btz_new'; */ /* // Live server $User="root"; $Pass="<PASSWORD>"; $Host="127.0.0.1"; $DBName='bristoezicht'; */ $mysqli_obj = new mysqli( $Host, $User, $Pass, $DBName ); $mysqli_obj->query( "SET NAMES 'utf8'" ); $mysqli_obj->query( "CHARACTER SET utf8 COLLATE utf8_general_ci" ); $start_id = $end_id = NULL; if(isset( $argv)){ if(isset( $argv[1])){ $start_id = explode( '=', $argv[1] ); $start_id = $start_id[1]; } if(isset( $argv[2])){ $end_id = explode( '=', $argv[2] ); $end_id = $end_id[1]; } }else{ $start_id= isset($_GET['start_id'])?$_GET['start_id']:NULL; $end_id = isset($_GET['end_id']) ? $_GET['end_id']:NULL; } $where = " WHERE 1=1"; $where .= ($start_id != NULL ) ? " AND `id`>=".$start_id:''; $where .= ($end_id != NULL ) ? " AND `id`<=".$end_id:''; $sql = "SELECT * FROM `dossier_bescheiden`".$where; log_time("Before performing SELECT query"); $result = $mysqli_obj->query( $sql ); log_time("After performing SELECT query"); if( !$result ){ $list = FALSE; die( 'Error in `dossier_bescheiden` reading.' ); }else{ //$list = []; $list = array(); while( $row = $result->fetch_assoc()){ $list[] = $row; $row = NULL; } } $count = count( $list ); echo "\nGeneral quantity of rows: ".$count."\n\n"; log_time("Before writing files to the filesystem"); $n = 0; foreach( $list as &$row ){ echo "\rProcessed Row: ".(++$n).""; $folder = 'documents/'.$row['dossier_id']; if( !is_dir( $folder )){ if (!mkdir( $folder, 0777, TRUE )) die('Failed to create folder "'.$folder.'"' ); } $file_name = $folder.'/'.$row['id']; $fhandle = fopen( $file_name, 'a' ); fwrite( $fhandle, $row['bestand'] ); fclose( $fhandle); $fhandle = NULL; } echo "\n\n"; log_time("After writing files to the filesystem. Amount of files: {$n}"); echo "\n\nSuccess!!!\n\n"; log_time("Script end"); <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <form method="POST"> <p> Hier kunnen instellingen worden gezet voor de BAG koppeling tussen SSO en BTZ.<br/> Selecteer de checklist die dient te worden gebruikt als koppelingsmechanisme.<br/> Geef ook aan voor welke klanten deze koppeling actief moet zijn.<br/> </p> <table> <tr> <th style="text-align:left">Te gebruiken checklist:</th> <td> <select name="checklist_id"> <option value="" selected disabled>-- selecteer een checklist --</option> <? foreach ($checklisten as $checklist): ?> <option <?=$checklist->id == $checklist_id ? 'selected' : ''?> value="<?=$checklist->id?>">[<?=htmlentities( $checklist->get_checklistgroep()->naam, ENT_COMPAT, 'UTF-8' )?>] <?=htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> </td> </tr> <? foreach ($klanten as $klant): ?> <tr> <th style="text-align:left"><?=htmlentities( $klant->naam, ENT_COMPAT, 'UTF-8' )?></th> <td> <input type="checkbox" name="klanten[<?=$klant->id?>]" <?=$klant_instellingen[$klant->id] ? 'checked' : ''?> /> </td> </tr> <? endforeach; ?> <tr> <td></td> <td> <input type="submit" value="Opslaan" /> </td> </tr> </table> </form> <? $this->load->view('elements/footer'); ?> <file_sep>PDFAnnotator.LayerReference = PDFAnnotator.Base.extend({ /* constructor */ init: function() { /* initialize base class */ this._super(); this.registerEventType( 'filterchanged' ); }, /* should return unique id of object */ getId: function() { return 0; }, /* should return displayed name of object */ getName: function() { return 'Naamloos'; }, /* should return filter state of object */ getFilter: function() { return 'none'; }, /* should be called by deriving classes when filter state changed. */ setFilter: function( filter ) { this.dispatchEvent( 'filterchanged' ); } }); <file_sep><? require_once 'base.php'; class HoofdgroepResult extends BaseResult { static private $global_hoofdthemas_cache = null; function HoofdgroepResult( &$arr ) { parent::BaseResult( 'hoofdgroep', $arr ); } public function get_wizard_parent() { return $this->get_checklist(); } public function get_wizard_veld( $veld ) { $veld = 'standaard_' . $veld; if (!property_exists( $this, $veld )) throw new Exception( 'Object van type ' . get_class($this) . ' bevat veld ' . $veld . ' niet!' ); return $this->$veld; } public function get_wizard_veld_recursief( $veld ) { $value = $this->get_wizard_veld( $veld ); return is_null($value) ? $this->get_wizard_parent()->get_wizard_veld_recursief( $veld ) : $value; } public function get_wizard_onderliggenden() { $result = array(); foreach ($this->get_categorieen() as $categorie) $result = array_merge( $result, $categorie->get_vragen() ); return $result; } public function is_wizard_readonly() { return $this->get_checklist()->is_wizard_readonly(); } public function get_categorieen() { $CI = get_instance(); $CI->load->model( 'categorie' ); return $CI->categorie->get_by_hoofdgroep( $this->id ); } public function rename( $name ) { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'HoofdgroepResult::rename', 'UPDATE bt_hoofdgroepen SET naam = ? WHERE id = ?', $db ); $CI->dbex->execute( 'HoofdgroepResult::rename', array( $name, $this->id ), $db ); $this->naam = $name; } public function get_checklist() { $CI = get_instance(); $CI->load->model( 'checklist' ); return $CI->checklist->get( $this->checklist_id ); } public function get_checklist_id() { return $this->checklist_id; } // If $set is not null, the prioriteiten are SET to that value. If it's NULL, nothing is initially done. // If $or is not null, the prioriteiten are OR'd with that value, making it easy to add e.g. "prio 5" to all existing prioriteiten, without changing the rest of the bits // If $clear is not null, the prioriteiten are AND (NOT $clear)'d, making it easy to remove e.g. "prio 3" from all existing prioriteiten, without changing the rest of the bits function verander_prioriteiten( $set=null, $or=null, $clear=null ) { if (is_null( $set ) && is_null( $or ) && is_null( $clear )) return; foreach ($this->get_categorieen() as $categorie) $categorie->verander_prioriteiten( $set, $or, $clear ); } public function bevat_hoofdthema( $hoofdthema_id ) { foreach ($this->get_hoofdthemas() as $hoofdthema) if ($hoofdthema['hoofdthema']->id == $hoofdthema_id) return true; return false; } public function get_hoofdthemas( $force_reload=false ) { if (!is_array( self::$global_hoofdthemas_cache ) || $force_reload) self::_load_global_hoofdthemas_cache(); if (isset( self::$global_hoofdthemas_cache[ $this->id ] )) return self::$global_hoofdthemas_cache[ $this->id ]; return array(); } static private function _load_global_hoofdthemas_cache() { $CI = get_instance(); $CI->load->model( 'hoofdthema' ); // Determine which "null function" should be used $null_func = get_db_null_function(); // !!! Note: the initial GROUP BY expression was extended on behalf of Oracle. By definition it does the same as before, but it now also // explicitly includes the other columns of the 'h' table, as an 'h.*' is included in the SELECT part. This can probably be handled more elegantly, by // only selecting that what is actually needed. // Was: GROUP BY h.id, c.hoofdgroep_id // Is now: GROUP BY h.id, h.klant_id, h.nummer, h.naam, h.bron, c.hoofdgroep_id $query = ' SELECT COUNT(*) AS aantal_vragen, h.*, h.id, c.hoofdgroep_id FROM bt_themas t JOIN bt_hoofdthemas h ON t.hoofdthema_id = h.id JOIN bt_vragen v ON (1=1) JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE '.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id))) = t.id GROUP BY h.id, h.klant_id, h.nummer, h.naam, h.bron, c.hoofdgroep_id ORDER BY h.nummer, h.naam '; $res = $CI->db->Query($query); self::$global_hoofdthemas_cache = array(); foreach ($res->result() as $row) { $aantal_vragen = $row->aantal_vragen; $hoofdgroep_id = $row->hoofdgroep_id; unset( $row->hoofdgroep_id ); unset( $row->aantal_vragen ); if (!isset( self::$global_hoofdthemas_cache[$hoofdgroep_id] )) self::$global_hoofdthemas_cache[$hoofdgroep_id] = array(); self::$global_hoofdthemas_cache[$hoofdgroep_id][] = array( 'hoofdthema' => $CI->hoofdthema->getr( $row, true /* use cache */ ), 'aantal_vragen' => $aantal_vragen, ); } } /** Kopieert deze hoofdgroep. Als er een ander checklist ID wordt meegegeven, dan * komt de kopie onder die checklist te hangen. Anders wordt het een identieke * kopie onder dezelfde checklist. * Als een andere checklist ID is opgegeven, verandert de sortering verder ook niet. * Wordt een checklist ID weggelaten, dan wordt de sortering dusdanig aangepast dat * de kopie onderaan de checklist komt te hangen. * * @return Geeft de kopie terug in object vorm. */ public function kopieer( $ander_checklist_id=null ) { $hoofdgroep = kopieer_object( $this, 'checklist_id', $ander_checklist_id ); foreach ($this->get_categorieen() as $categorie) $categorie->kopieer( $hoofdgroep->id ); return $hoofdgroep; } } class Hoofdgroep extends BaseModel { function Hoofdgroep() { parent::BaseModel( 'HoofdgroepResult', 'bt_hoofdgroepen', true ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'checklist', 'checklist_id' ); } function get_by_checklist( $checklist_id ) { if (!$this->dbex->is_prepared( 'get_by_checklist' )) $this->dbex->prepare( 'get_by_checklist', 'SELECT * FROM '.$this->_table.' WHERE checklist_id = ? ORDER BY sortering', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'get_by_checklist', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function add( $checklist_id, $name ) { // Determine which "null function" should be used $null_func = get_db_null_function(); // prepare statements //$this->dbex->prepare( 'Hoofdgroep::add', 'INSERT INTO bt_hoofdgroepen (checklist_id, sortering, naam) VALUES (?, ?, ?)' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'Hoofdgroep::search', 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS m FROM bt_hoofdgroepen WHERE checklist_id = ?' ); // lock, get max id, create new entries, and be done $res = $this->dbex->execute( 'Hoofdgroep::search', array( $checklist_id ) ); $sortering = intval( reset( $res->result() )->m ); /* $args = array( 'checklist_id' => $checklist_id, 'sortering' => $sortering, 'naam' => $name, ); if (!($this->dbex->execute( 'Hoofdgroep::add', $args ))) throw new Exception( 'Fout bij toevoegen van hoofdgroep: ' . $this->db->_error_message() ); $id = $this->db->insert_id(); $result = new $this->_model_class( $args ); $result->id = $id; return $result; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'checklist_id' => $checklist_id, 'sortering' => $sortering, 'naam' => $name, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function hoofdthema_in_hoofdgroep( $hoofdthema_id, $hoofdgroep_naam ) { static $cache = null; if (!is_array( $cache )) { $cache = array(); $db = $this->get_db(); $res = $db->Query( ' SELECT t.hoofdthema_id, h.naam FROM bt_themas t JOIN bt_vragen v ON v.thema_id = t.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id '); // WHERE t.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' foreach ($res->result() as $row) { if (!isset( $cache[$row->naam] )) $cache[$row->naam] = array(); if (!in_array( $row->hoofdthema_id, $cache[$row->naam] )) $cache[$row->naam][] = $row->hoofdthema_id; } $res->free_result(); } if (!isset( $cache[ $hoofdgroep_naam ] )) return false; return in_array( $hoofdthema_id, $cache[ $hoofdgroep_naam ] ); } public function get_for_toezichtmoment_creation( $toezichtmomentId, $checklistId, $assoc=false ){ $result = array(); $t_cound = (bool)$toezichtmomentId ? ' OR toezichtmoment_id = '.(int)$toezichtmomentId.'' : ''; $hoofdgroepen = $this->db->select($this->_table.'.id AS id,checklist_id,naam,toezichtmoment_id') ->join('bt_toezichtmomenten_hoofdgroepen', 'bt_toezichtmomenten_hoofdgroepen.hoofdgroep_id = '.$this->_table.'.id', 'left' ) ->where('checklist_id', $checklistId) ->where('(`toezichtmoment_id` IS NULL'.$t_cound.')',null, false) ->order_by('naam') ->get( $this->_table ) ->result(); foreach( $hoofdgroepen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_by_toezichtmoment( $toezichtmomentId, $assoc=false ){ $result = array(); $hoofdgroepen = $this->db->select($this->_table.'.`id` AS `id`,checklist_id,naam,toezichtmoment_id') ->join('bt_toezichtmomenten_hoofdgroepen', 'bt_toezichtmomenten_hoofdgroepen.hoofdgroep_id = '.$this->_table.'.id', 'left' ) ->where('toezichtmoment_id', $toezichtmomentId) ->order_by('naam') ->get( $this->_table ) ->result(); foreach( $hoofdgroepen as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function get_by_toezichtmoment_not_getr( $toezichtmomentId, $assoc=false ){ $result = array(); $hoofdgroepen = $this->db->select($this->_table.'.`id` AS `id`,checklist_id,naam,toezichtmoment_id') ->join('bt_toezichtmomenten_hoofdgroepen', 'bt_toezichtmomenten_hoofdgroepen.hoofdgroep_id = '.$this->_table.'.id', 'left' ) ->where('toezichtmoment_id', $toezichtmomentId) ->order_by('naam') ->get( $this->_table ) ->result(); foreach( $hoofdgroepen as $row ){ // $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } }// Class end <file_sep><? $this->load->view('elements/header', array('page_header'=>'prioriteitstelling')); ?> <form name="form" method="post"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('checklisten'), 'width' => '920px' )); ?> <p> <?=tg('checklisten_tekst')?> </p> <? $list_view_data = array( 'minwidth' => '880px', 'height' => '300px', 'headers' => array( array( 'text' => tg('checklist'), 'width' => '500px', 'align' => 'left' ), array( 'text' => tg('matrix') . ' ' . htags('matrix_keuze'), 'width' => '300px', 'align' => 'left' ), ), 'rows' => array( ), 'flat' => false, 'listclasses' => array( 'editlist' ), ); foreach ($checklistgroepen as $checklistgroep) { $any_afgerond = false; foreach ($checklistgroep['checklisten'] as $checklist) if (is_checklist_afgerond( $checklist )) { $any_afgerond = true; break; } if (!$any_afgerond) continue; $children = array(); foreach ($checklistgroep['checklisten'] as $checklist) { if (!is_checklist_afgerond( $checklist )) continue; $children[] = array( 'values' => array( '<input type="radio" name="checklist" value="' . $checklist->id . '" ' . ($checklist->id == $checklist_id ? 'checked' : '') . ' />' . htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8' ), '&nbsp', ), ); } $matrix_select = '<select style="width:150px" name="matrix[' . $checklistgroep['groep']->id . ']" onclick="eventStopPropagation(event);">'; $have_selected = false; foreach ($matrices[$checklistgroep['groep']->id] as $matrix) { $extra = ''; if ($matrix->klant_id == $this->session->userdata('kid')) { if (!$have_selected) { $have_selected = true; $selected = 'selected'; } else $selected = ''; } else { $selected = ''; $extra = '(alleen lezen)'; } $matrix_select .= '<option ' . $selected . ' value="' . $matrix->id . '">' . htmlentities( $matrix->naam, ENT_COMPAT, 'UTF-8' ) . ' ' . $extra . '</option>'; } $matrix_select .= '</select>'; $matrix_select .= ' '; $matrix_select .= '<a onclick="eventStopPropagation(event);" title="Matrix toevoegen voor deze checklist groep" href="javascript:void(0);">'; $matrix_select .= '<img class="matrix-add" checklist_groep_id="' . $checklistgroep['groep']->id . '" src="' . site_url('/files/images/add.png') . '" />'; $matrix_select .= '</a>'; $matrix_select .= ' '; $matrix_select .= '<a onclick="eventStopPropagation(event);" title="Matrix verwijderen voor deze checklist groep" href="javascript:void(0);">'; $matrix_select .= '<img class="matrix-delete" checklist_groep_id="' . $checklistgroep['groep']->id . '" src="' . site_url('/files/images/delete.png') . '" />'; $matrix_select .= '</a>'; $list_view_data['rows'][] = array( 'values' => array( '<input type="radio" name="checklist" onclick="eventStopPropagation(event);" value="cg' . $checklistgroep['groep']->id . '" ' . ('cg' . $checklistgroep['groep']->id == $checklist_id ? 'checked' : '') . ' />' . htmlentities( $checklistgroep['groep']->naam, ENT_COMPAT, 'UTF-8' ), $matrix_select, ), 'id' => 'groep' . $checklistgroep['groep']->id, 'children' => $children, 'collapsed' => true, ); } $this->load->view( 'elements/laf-blocks/generic-list', $list_view_data ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view( 'beheer/risicoanalyse_buttons', array( 'prev' => false, 'next' => true, ) ); ?> </form> <script type="text/javascript"> $(document).ready(function(){ $('img.matrix-add').click(function(){ showPopup( "Matrix toevoegen", "/instellingen/matrix_toevoegen/" + $(this).attr('checklist_groep_id'), 500, 440 ); }); $('img.matrix-delete').click(function(){ var checklist_groep_id = $(this).attr('checklist_groep_id'); var matrix_id = $(this).parent().siblings('select').val(); showPopup( "Matrix verwijderen", "/instellingen/matrix_verwijderen/" + matrix_id, 500, 200 ); }); }); </script> <? $this->load->view('elements/footer'); ?><file_sep>PDFAnnotator.GUI.Menu.Layers.LayerEntry = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( list, layer, layers ) { this._super(); var thiz = this; /** this.dom contains the main div. * this.content contains sub-members referencing our table cells with specific content * this.layer references the PDFAnnotator.Layer object we represent */ this.content = {}; this.layer = layer; this.dom = $('<div>') .appendTo( list ) .addClass( layers.entryClass ); var table = $('<table>') .appendTo( this.dom ); var tr = $('<tr>') .appendTo( table ); this.content.visibility = $('<td>') .appendTo( tr ) .addClass( layers.contentClasses.visibility ) .append( $('<img>') .attr( 'src', layers.visibleImages[layer.getVisibility() ? 'visible' : 'invisible'] ) ); this.content.filter = $('<td>') .appendTo( tr ) .addClass( layers.contentClasses.filter ) .append( $('<img>') .attr( 'src', layers.filterImages[layer.getFilter()] ) ); this.content.name = $('<td>') .appendTo( tr ) .addClass( layers.contentClasses.name ) .html( $('<div>').text( layer.getName() ) ); if (!layer.getVisibility()) this.dom.addClass( layers.invisibleClass ); /** register layer events */ this.layer.on( 'namechanged', function( layer ){ thiz.content.name.text( layer.getName() ); }); this.layer.on( 'visibilitychanged', function( layer ){ thiz.content.visibility.find('img').attr( 'src', layers.visibleImages[layer.getVisibility() ? 'visible' : 'invisible'] ); thiz.dom[ layer.getVisibility() ? 'removeClass' : 'addClass' ]( layers.invisibleClass ); }); this.layer.on( 'filterchanged', function( layer ){ thiz.content.filter.find('img').attr( 'src', layers.filterImages[layer.getFilter()] ); }); this.layer.on( 'activate', function( layer ){ layers.currentLayerInfo.text( layer.getName() ); if (thiz.dom) thiz.dom.addClass( layers.activeClass ); }); this.layer.on( 'deactivate', function( layer ){ layers.currentLayerInfo.text( '(geen laag actief)' ); if (thiz.dom) thiz.dom.removeClass( layers.activeClass ); }); /** register DOM events */ this.content.visibility.find('img').click(function(evt){ thiz.layer.toggleVisibility(); evt.stopPropagation(); }); this.dom.click(function(){ if (thiz.layer.isActivated()) thiz.layer.deactivate(); else thiz.layer.activate(); }); }, remove: function() { if (this.dom) { this.dom.remove(); this.dom = null; this.content = null; } }, hide: function() { if (this.dom) { this.dom.hide(); } }, show: function() { if (this.dom) { this.dom.show(); } } }); <file_sep><?php class CI_Dlogger{ private static function getDateTime(){ $mkarr = gettimeofday() ; $mktime = (int)$mkarr['usec']; if( $mktime < 10 ){ $mktime = '00000'.$mktime; }elseif( $mktime < 100 ){ $mktime = '0000'.$mktime; }elseif( $mktime < 1000 ){ $mktime = '000'.$mktime; }elseif( $mktime < 10000 ){ $mktime = '00'.$mktime; }elseif( $mktime < 100000 ){ $mktime = '0'.$mktime; } return date('d-m-Y H:i:s', (int)$mkarr['sec'] ).'.'.$mktime; } //______________________________________________________________________________ public function _log( $message, $place='' ){ $place = '*** '.$place.' ***'; $message = "\n\n".self::getDateTime().' *** '.$_SERVER['DOCUMENT_ROOT'].' '.$place."\n". "------------------------------------------------------------------------\n".$message; $fhandle = fopen( 'logs/debug.log', 'a' ); fwrite( $fhandle, $message ); fclose( $fhandle); } }<file_sep><?php // tg krijgt een edit-in-place icoontje, en is niet-global tekst (dus prefixed met huidige controller/method) function tg( $string ) { $s = get_instance()->tekst->get( $string, false, true ); if (func_num_args()>1) for ($i=1; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.$i, $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); if (do_inline_editing()) $s = '<span>' . $s . '</span> <img src="/files/images/ie.png" class="ie" tag="' . $string . '">'; return $s; } // tga krijgt een edit-in-place icoontje, en is niet-global tekst (dus niet prefixed met huidige controller/method) // en is een link met een URL function tga( $string, $url ) { $s = get_instance()->tekst->get( $string, false, true ); if (func_num_args()>1) for ($i=2; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.($i-1), $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); $s = '<a href="' . $url . '">' . $s . '</a>'; if (do_inline_editing()) $s .= ' <img src="/files/images/ie.png" class="ie" tag="' . $string . '">'; return $s; } // tgg krijgt een edit-in-place icoontje, en is global tekst (dus zonder prefix van huidige controller/method) function tgg( $string ) { $s = get_instance()->tekst->get( $string, true, true ); if (func_num_args()>1) for ($i=1; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.$i, $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); if (do_inline_editing()) $s = '<span>' . $s . '</span> <img src="/files/images/ie.png" class="ie" tag="' . $string . '">'; return $s; } // tgga krijgt een edit-in-place icoontje, en is global tekst (dus prefixed met huidige controller/method) // en is een link met een URL function tgga( $string, $url ) { $s = get_instance()->tekst->get( $string, true, true ); if (func_num_args()>1) for ($i=2; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.($i-1), $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); $s = '<a href="' . $url . '">' . $s . '</a>'; if (do_inline_editing()) $s .= ' <img src="/files/images/ie.png" class="ie" tag="' . $string . '">'; return $s; } // tgn krijgt nooit een edit-in-place icoontje, voor teksten op plekken // waar een img tag niet kan (in b.v. input buttons) function tgn( $string ) { $s = get_instance()->tekst->get( $string, false, true ); if (func_num_args()>1) for ($i=1; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.$i, $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); return $s; } // tgng, als tgn, maar dan global function tgng( $string ) { $s = get_instance()->tekst->get( $string, true, true ); if (func_num_args()>1) for ($i=1; $i<func_num_args(); ++$i) { $val = func_get_arg($i); $s = str_replace( '$'.$i, $val, $s ); } $s = htmlentities( $s, ENT_COMPAT, 'UTF-8' ); return $s; } function allow_inline_editing() { return get_instance()->rechten->geef_recht_modus( RECHT_TYPE_INLINE_EDIT_BESCHIKBAAR ) != RECHT_MODUS_GEEN; } function do_inline_editing() { return allow_inline_editing() && get_instance()->tekst->inline_edit_enabled(); } class CI_Tekst { var $CI; var $teksten = array(); var $prefix; var $prefix_original; var $add_missing_text_to_database = true; // do not enable in live environments! var $leaseconfiguratie = null; var $leaseconfiguratie_loaded = false; public function __construct() { global $class, $method; $this->CI = get_instance(); $this->_init_from_db( 0 ); $this->prefix = $class . '.' . $method . '::'; $this->prefix_original = $this->prefix; $this->_load_lease_config(); } public function set_method( $m, $c=null ) { global $class, $method; $method = $m; if (!is_null( $c )) $class = $c; $this->prefix = $class . '.' . $method . '::'; } public function reset_method() { $this->prefix = $this->prefix_original; } private function _load_lease_config() { // not yet ready? if (!isset( $this->CI->gebruiker )) return; // do this just once! if ($this->leaseconfiguratie_loaded) return; $this->leaseconfiguratie_loaded = true; // load lease config $gebruiker = $this->CI->gebruiker->get_logged_in_gebruiker(); if ($gebruiker) { $this->CI->load->model( 'klant' ); if (!$this->CI->gebruiker->is_external_user()) { $this->leaseconfiguratie = $gebruiker->get_klant()->get_lease_configuratie(); } } // act on it? if ($this->leaseconfiguratie) $this->_init_from_db( $this->leaseconfiguratie->id ); } public function get_all() { $this->_load_lease_config(); return $this->teksten; } public function get_all_by_date() { $this->_load_lease_config(); $this->CI->db->order_by( 'timestamp', 'desc' ); // !!! Check Oracle compatibility $res = $this->CI->db->get( 'teksten' ); $teksten = array(); foreach ($res->result() as $row) $teksten[ $row->string ] = array( 'tekst' => $row->tekst, 'datum' => $row->timestamp, // !!! Check if the Oracle version returns what we want (i.e. a real timestamp), or if it only contains a date! ); $res->free_result(); return $teksten; } public function has( $string, $global=false, $must_have_length=true ) { $this->_load_lease_config(); if (!$global) $string = $this->prefix . $string; if (!isset( $this->teksten[$string] )) return false; if (!$must_have_length) return true; return strlen($this->teksten[$string]) ? true : false; } public function get( &$string, $global=false, $decorate=true ) { $this->_load_lease_config(); if (!$global) $string = $this->prefix . $string; if (isset( $this->teksten[$string] ) && strlen($this->teksten[$string])) return $this->teksten[$string]; if ($this->add_missing_text_to_database) { //echo "String to insert: *{$string}*<br />\n"; //if (!$this->CI->dbex->prepare( 'insert_tekst_missing', 'INSERT INTO teksten (tekst,timestamp,string) VALUES (?, ?, ?)' )) $date_param = get_db_prepared_parameter_for_datetime(); // !!! Note: the lease_configuratie_id parameter was originally NOT present. No idea why it was omitted... A mere oversight, or for a specific reason?! if (!$this->CI->dbex->prepare( 'insert_tekst_missing', 'INSERT INTO teksten (tekst,timestamp,string, lease_configuratie_id) VALUES (?, '.$date_param.', ?, ?)' )) throw new Exception('insert_tekst_missing prepare failed'); //$this->CI->dbex->execute( 'insert_tekst_missing', array(' ', date('Y-m-d H:i:s'), $string), true ); $this->CI->dbex->execute( 'insert_tekst_missing', array(' ', date('Y-m-d H:i:s'), $string, $this->leaseconfiguratie ? $this->leaseconfiguratie->id : 0 ), true ); } return $decorate ? '{' . $string . '}' : ''; } public function set( $string, $tekst, $force=false ) { $this->_load_lease_config(); if ($force || !isset( $this->teksten ) || !isset( $this->teksten[$string] ) || $this->teksten[$string]!=$tekst) { $date_param = get_db_prepared_parameter_for_datetime(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... //if (!$this->CI->dbex->prepare( 'insert_tekst', 'INSERT INTO teksten (tekst,timestamp,string,lease_configuratie_id) VALUES (?, ?, ?, ?)' )) if (!$this->CI->dbex->prepare( 'insert_tekst', 'INSERT INTO teksten (tekst,timestamp,string,lease_configuratie_id) VALUES (?, '.$date_param.', ?, ?)' )) throw new Exception('insert_tekst prepare failed'); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... //if (!$this->CI->dbex->prepare( 'update_tekst', 'UPDATE teksten SET tekst = ?, timestamp = ? WHERE string = ? AND lease_configuratie_id = ?' )) if (!$this->CI->dbex->prepare( 'update_tekst', 'UPDATE teksten SET tekst = ?, timestamp = '.$date_param.' WHERE string = ? AND lease_configuratie_id = ?' )) throw new Exception('update_tekst prepare failed'); // expres deze volgorde, zodat beide queries werken met dezelfde array $data = array( $tekst, date('Y-m-d H:i:s'), $string, $this->leaseconfiguratie ? $this->leaseconfiguratie->id : 0 ); // go! $this->CI->db->trans_start(); if (!$this->CI->dbex->execute( 'insert_tekst', $data, true )) { $this->CI->db->_trans_status = true; if (!$this->CI->dbex->execute( 'update_tekst', $data, false )) throw new Exception( 'update_tekst execute failed' ); $this->CI->db->_trans_status = $this->CI->db->affected_rows()==1; } if ($success = $this->CI->db->trans_complete()) $this->teksten[ $string ] = $tekst; return $success; } else return true; } private function _init_from_db( $lease_configuratie_id ) { $this->CI->db->where( 'lease_configuratie_id', $lease_configuratie_id ); $res = $this->CI->db->get( 'teksten' ); foreach ($res->result() as $row) { $this->teksten[ $row->string ] = $row->tekst; } $res->free_result(); } public function inline_edit_enabled() { return $this->CI->session->userdata( 'do_inline_editing' )===TRUE; } public function toggle_inline_edit() { $this->CI->session->set_userdata( 'do_inline_editing', $this->inline_edit_enabled() ? false : true ); } } <file_sep>PDFAnnotator.Handle.Resize = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/edit-handle-resize.png', 32, 32, 'drag', this.execute, 'topleft' ); this.addNodeRelative( 1, 1, baseurl + 'images/nlaf/edit-handle-resize.png', 32, 32, 'drag', this.execute, 'bottomright' ); }, execute: function( relx, rely, userdata ) { switch (userdata) { case 'topleft': var newRel = this.editable.resizeRelative( -relx, -rely ); if (newRel) this.editable.moveRelative( -newRel.relx, -newRel.rely ); else this.editable.moveRelative( relx, rely ); break; case 'bottomright': this.editable.resizeRelative( relx, rely ); break; } // update position of labels this.show(); } }); <file_sep><? require_once 'base.php'; class WebserviceApplicatieDossierResult extends BaseResult { function WebserviceApplicatieDossierResult( &$arr ) { parent::BaseResult( 'webserviceapplicatiedossier', $arr ); } } class WebserviceApplicatieDossier extends BaseModel { function WebserviceApplicatieDossier() { parent::BaseModel( 'WebserviceApplicatieDossierResult', 'webservice_applicatie_dssrs', true ); } function get_for_webapplicatie_id( $webapplicatie_id ) { $stmt_name = 'WebserviceApplicatieDossier::get_for_webapplicatie_id'; $result = array(); $CI = get_instance(); $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE webservice_applicatie_id = ?' ); foreach ($this->convert_results( $CI->dbex->execute( $stmt_name, array( $webapplicatie_id ) ) ) as $wad) $result[ $wad->dossier_id ] = $wad; return $result; } function zet( $webservice_applicatie_id, $dossier_id, $laatst_bijgewerk_op ) { $stmt_name = 'webserviceapplicatiedossier::zet'; $CI = get_instance(); //$CI->dbex->prepare( $stmt_name, 'REPLACE INTO webservice_applicatie_dssrs (webservice_applicatie_id, dossier_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)' ); $CI->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO webservice_applicatie_dssrs (webservice_applicatie_id, dossier_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)', null, array('id') ); return $CI->dbex->execute( $stmt_name, array( $webservice_applicatie_id, $dossier_id, $laatst_bijgewerk_op ) ); } } <file_sep>ALTER TABLE `gebruikers` DROP `toon_keyboard_hulp`, DROP `toon_rapportage_info`, DROP `niveau`; ALTER TABLE `gebruikers` ADD `speciale_functie` ENUM( 'geen', 'nog niet toegekend' ) NOT NULL DEFAULT 'geen' AFTER `niveau` ; <file_sep><?php class AnnotatieAfbeeldingData implements AnnotatieAfbeeldingDataInterface { private $bescheidenId; private $dossierId; private $deelplanId; private $checklistgroepId; private $checklistId; private $hoofdgroepId; private $vraagId; private $annotatieNummer; private $annotatieType; private $annotatieObject; private $boundingBox; private $paginaNummer; public function __construct($bescheidenId, $dossierId, $deelplanId, $checklistgroepId, $checklistId, $hoofdgroepId, $vraagId, $annotatieType, $paginaNummer, $bescheidenOrientation) { $this->bescheidenId = $bescheidenId; $this->dossierId = $dossierId; $this->deelplanId = $deelplanId; $this->checklistgroepId = $checklistgroepId; $this->checklistId = $checklistId; $this->hoofdgroepId = $hoofdgroepId; $this->vraagId = $vraagId; $this->annotatieType = $annotatieType; $this->paginaNummer = $paginaNummer; $this->bescheidenOrientation = $bescheidenOrientation; } public function GetBescheidenId() { return $this->bescheidenId; } public function GetBescheidenOrientation() { return $this->bescheidenOrientation; } public function GetDossierId() { return $this->dossierId; } public function GetDeelplanId() { return $this->deelplanId; } public function GetChecklistGroepId() { return $this->checklistgroepId; } public function GetChecklistId() { return $this->checklistId; } public function GetHoofdgroepId() { return $this->hoofdgroepId; } public function GetVraagId() { return $this->vraagId; } public function GetAnnotatieNummer() { return $this->annotatieNummer; } public function GetAnnotatieType() { return $this->annotatieType; } public function GetAnnotatieObject() { return $this->annotatieObject; } public function GetPaginaNummer() { return $this->paginaNummer; } public function GetBoundingBox() { return $this->boundingBox; } public function SetAnnotatieNummer($annotatieNummer) { $this->annotatieNummer = $annotatieNummer; } public function SetAnnotatieObject(Annotation $annotatieObject) { $this->annotatieObject = $annotatieObject; } public function SetBoundingBox(Rectangle2 $bb) { $this->boundingBox = $bb; } } <file_sep><? require_once 'base.php'; class BacklogResult extends BaseResult { private $_checklisten = null; function BacklogResult( &$arr ) { parent::BaseResult( 'backlog', $arr ); } function get_uploads() { $CI = get_instance(); $CI->load->model( 'backlogupload' ); return $CI->backlogupload->convert_results( $CI->db->query( 'SELECT id, back_log_id, bestandsnaam, content_type, grootte, aangemaakt_op FROM back_log_uploads WHERE back_log_id = ' . $this->id ) ); } function get_actie_voor() { return $this->actie_voor_gebruiker_id ? get_instance()->gebruiker->get( $this->actie_voor_gebruiker_id ) : null; } } class Backlog extends BaseModel { function Backlog() { parent::BaseModel( 'BacklogResult', 'back_log' ); } public function check_access( BaseResult $object ) { // } public function add() { // zet actie_voor_gebruiker_id op 1 (Marc, in alle dev/test/live omgevingen) // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. /* $res = $this->db->query( 'INSERT INTO back_log (id, gebruiker_id, actie_voor_gebruiker_id) VALUES (NULL, ' . get_instance()->gebruiker->get_logged_in_gebruiker()->id . ', 1)' ); if (!$res) return null; $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $args = array( 'id' => $id, ); return new $this->_model_class( $args ); * */ // Use the base model's 'insert' method. $data = array( 'gebruiker_id' => get_instance()->gebruiker->get_logged_in_gebruiker()->id, 'actie_voor_gebruiker_id' => 1, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function search_backlog( $search, $actief_only, $wens_modus, $alleen_mijn=false ) { $conn = get_instance()->db; $query = '(0=1 '; $query .= 'OR verbeterpunt LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR actie LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR prioriteit LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR ureninschatting LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR status LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR testresultaten LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR actie_voor_gebruiker_id IN (SELECT id FROM gebruikers WHERE'; $query .= ' volledige_naam LIKE \'%' . $conn->escape_str( $search ) . '%\''; $query .= ')'; $query .= ')'; switch ($wens_modus) { case 'alleen-wensen': $query .= ' AND is_wens = 1 AND verbeterpunt NOT LIKE \'%bug%\''; break; case 'alleen-opdrachten': $query .= ' AND (is_wens = 0 OR verbeterpunt LIKE \'%bug%\')'; break; case 'alle': default: break; } if ($alleen_mijn) $query .= ' AND actie_voor_gebruiker_id = ' . intval( get_instance()->gebruiker->get_logged_in_gebruiker()->id ); if ($actief_only) $query .= ' AND afgerond = 0'; return $this->search( array(), $query ); } } <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_bescheiden` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `dossier_bescheiden_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `dossier_bescheiden_id` (`dossier_bescheiden_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; ALTER TABLE `deelplan_bescheiden` ADD CONSTRAINT `deelplan_bescheiden_ibfk_2` FOREIGN KEY (`dossier_bescheiden_id`) REFERENCES `dossier_bescheiden` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_bescheiden_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('deelplannen.checklistgroep::datum_filter_all', 'Geen hercontroledatumfilter', NOW(), 0); <file_sep><?php require_once APPPATH . 'libraries/annotatieafbeeldingprocessor/interface.php'; require_once APPPATH . 'libraries/annotatieafbeeldingprocessor/annotatieafbeeldingdata.php'; require_once APPPATH . 'libraries/annotatieafbeeldingprocessor/annotatieafbeeldingprocessorimpl.php'; require_once APPPATH . 'libraries/annotatieafbeeldingprocessor/test.php'; require_once APPPATH . 'libraries/annotatieafbeeldingprocessor/rapportage.php'; class CI_AnnotatieAfbeeldingProcessor { //public function create($deelplan_id, $checklist_groep_id, $checklist_id, $padding=50, $log_enabled=false) public function create($deelplan_id, $checklist_groep_id, $checklist_id, $padding=50, $log_enabled=false, $output_path = '') { return new AnnotatieAfbeeldingProcessorImpl($deelplan_id, $checklist_groep_id, $checklist_id, $padding, $log_enabled, $output_path); } } <file_sep>PDFAnnotator.Handle.LineDelete = PDFAnnotator.Handle.Delete.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* !!override!! */ addNodes: function() { }, /* !!show!! */ show: function() { // clear previous nodes, the lines might have moved and now become invalid! this.remove(); // recreate nodes var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); if (this.editable.getDirection() == 'up') this.addNodeRelative( 1, 0, baseurl + 'images/nlaf/edit-handle-delete.png', 32, 32, 'click', this.execute ); else this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/edit-handle-delete.png', 32, 32, 'click', this.execute ); // call super to render this._super(); }, execute: function() { this.remove(); this.editable.container.removeObject( this.editable ); } }); <file_sep>ALTER TABLE `webservice_applicaties` ADD `actief` TINYINT NOT NULL DEFAULT '1'; <file_sep><? require_once 'base.php'; class GrondslagQuestData { // settings private $_node_allow_remote_fetch = true; // if true, a new node may be queried remotely private $_node_force_when_unavailable = false; // if true, if a node is not known, try it even though it failed in the past (ignored when _node_allow_remote_fetch is false!) private $_text_allow_remote_fetch = true; // if true, allow fetching texts remotely private $_text_allow_caching = true; // if true, use caching inside the object in case the text is requested multiple times in the same object // node status private $_node_fetched_remotely; // if true, the query node was fetched remotely private $_node_fetched_alternative; // if true, the query node was not found, and an alternative was used private $_node_available; // if true, a non-empty node was found, either from cache (database) or fetched remotely // text status private $_text_fetched_remotely; // if true, the text was fetched remotely using Quest private $_text_fetched_locally; // if true, a text from the database was returned as either the remote connection failed, or no node was available private function _fetch_or_set( $member, $value=null ) { if (func_num_args() > 1) { $this->$member = $value; return $this; } else return $this->$member; } public function node_allow_remote_fetch( $allow=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_node_allow_remote_fetch' ), func_get_args() ) ); } public function node_force_when_unavailable( $allow=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_node_force_when_unavailable' ), func_get_args() ) ); } public function text_allow_remote_fetch( $allow=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_text_allow_remote_fetch' ), func_get_args() ) ); } public function text_allow_caching( $allow=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_text_allow_caching' ), func_get_args() ) ); } public function node_fetched_remotely( $fetched=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_node_fetched_remotely' ), func_get_args() ) ); } public function node_fetched_alternative( $fetched=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_node_fetched_alternative' ), func_get_args() ) ); } public function node_available( $available=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_node_available' ), func_get_args() ) ); } public function text_fetched_remotely( $fetched=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_text_fetched_remotely' ), func_get_args() ) ); } public function text_fetched_locally( $fetched=null ) { return call_user_func_array( array( $this, '_fetch_or_set' ), array_merge( array( '_text_fetched_locally' ), func_get_args() ) ); } } class GrondslagTekstResult extends BaseResult { const NIET_ACTUEEL_TEKST = '[Niet actueel]'; const GEEN_TOEGANG_TEKST_KENNISID = '[Uw BRISwarenhuis licentie bevat geen toegang tot deze inhoud]'; const GEEN_TOEGANG_TEKST_GEEN_KENNISID = '[U kunt niet beschikken over deze inhoud]'; const QUEST_FOUT_TEKST = '[Fout bij ophalen tekst]'; function GrondslagTekstResult( &$arr ) { parent::BaseResult( 'grondslagtekst', $arr ); } function get_grondslag() { $CI = get_instance(); $CI->load->model( 'grondslag' ); return $CI->grondslag->get( $this->grondslag_id ); } function get_quest_node( GrondslagQuestData $gqd=null ) { if (!$gqd) $gqd = new GrondslagQuestData(); $gqd->node_fetched_remotely( false ); if (!$this->quest_node_opgehaald || ($gqd->node_force_when_unavailable() && !$this->quest_node)) { if ($gqd->node_allow_remote_fetch()) { if ($quest_document = $this->get_grondslag()->quest_document) { $alt_ids = array(); if (preg_match( '/^hoofdstuk\s+(\d+)($|\D)/i', $this->artikel, $matches )) $id = 'hfd' . $matches[1]; else if (preg_match( '/^afdeling\s+([0-9.]+)($|\D)/i', $this->artikel, $matches )) $id = 'afd' . str_replace( '.', '-', $matches[1] ); else if (preg_match( '/^([0-9.a-z]+)/i', $this->artikel, $matches )) { $parts = explode( '.', $matches[0], 3 ); if (sizeof( $parts ) <= 2) $id = 'art' . str_replace( '.', '-', preg_replace( '/\s/', '', $matches[0] ) ); else { $id = 'art' . str_replace( '.', '-', preg_replace( '/\s/', '', $parts[0] . '.' . $parts[1] ) . '/lid' . $parts[2] ); // als ID niet gevonden kan worden, probeer dan dit ALT_ID $lid_parts = explode( '.', $parts[2] ); while (!empty( $lid_parts )) { $lid_new = (sizeof($lid_parts) > 1) ? '/lid' . implode( '.', array_slice( $lid_parts, 0, sizeof($lid_parts) - 1 ) ) : ''; $alt_ids[] = 'art' . str_replace( '.', '-', preg_replace( '/\s/', '', $parts[0] . '.' . $parts[1] ) ) . $lid_new; array_pop( $lid_parts ); } } } else $id = null; if ($id) { $CI = get_instance(); if (!isset( $CI->quest )) $CI->load->library( 'quest' ); if ($quest_node = $CI->quest->query_single_id( $quest_document, $id )) { $this->quest_node = $quest_node; $this->quest_node_alternatief_used = 0; $gqd->node_fetched_remotely( true ); $gqd->node_fetched_alternative( false ); } else if (!empty( $alt_ids )) { foreach ($alt_ids as $alt_id) { if ($quest_node = $CI->quest->query_single_id( $quest_document, $alt_id )) { $this->quest_node = $quest_node; $this->quest_node_alternatief_used = 1; $gqd->node_fetched_remotely( true ); $gqd->node_fetched_alternative( true ); break; } } } } $this->quest_node_opgehaald = 1; $this->save(); } } } $gqd->node_available( strlen($this->quest_node) ? true : false ); return strval( $this->quest_node ); } public function get_artikel_tekst( GrondslagQuestData $gqd=null ) { if (!$gqd) $gqd = new GrondslagQuestData(); if ($gqd->text_allow_caching() && isset( $this->_artikel_tekst )) return $this->_artikel_tekst; $gqd->text_fetched_remotely( false ); $gqd->text_fetched_locally( false ); if ($gqd->text_allow_remote_fetch()) { $node = $this->get_quest_node( $gqd ); if ($gqd->node_available()) { try { $text = $this->_CI->quest->data( $node ); } catch (QuestPermissionException $e) { if (isset( $this->_CI->kennisid )) $text = self::GEEN_TOEGANG_TEKST_KENNISID; else $text = self::GEEN_TOEGANG_TEKST_GEEN_KENNISID; } catch (Exception $e) { $text = self::QUEST_FOUT_TEKST; } if ($text) { $gqd->text_fetched_remotely( true ); $text = trim( preg_replace( '/(\r?\n){3,}/', "\n\n", // remove cases where there are >2 newlines following each other preg_replace( '/^\s+$/m', '', // remove any lines that contain only whitespace preg_replace( '/<.*?>/', '', // strip tags, but keep what's inside the tags preg_replace( '/<a\s+.*?<\/a>/', '', // remove <a href>'s completely $text ) ) ) ) ); if ($gqd->text_allow_caching()) $this->_artikel_tekst = $text; return $text; } } } if ($this->tekst) { $gqd->text_fetched_locally( true ); if ($gqd->text_allow_caching()) $this->_artikel_tekst = $this->tekst; return $this->tekst; } $text = self::NIET_ACTUEEL_TEKST; if ($gqd->text_allow_caching()) $this->_artikel_tekst = $text; return $text; } } class GrondslagTekst extends BaseModel { function GrondslagTekst() { parent::BaseModel( 'GrondslagTekstResult', 'bt_grondslag_teksten' ); } public function check_access( BaseResult $object ) { // disable for now // see /deelplannen/wettelijke_grondslag/XXX return; } public function get_by_grondslag_naam( $grondslag /* naam, not id! */ ) { return $this->convert_results( $this->_CI->db->query(' SELECT t.* FROM bt_grondslag_teksten t JOIN bt_grondslagen g ON t.grondslag_id = g.id WHERE g.grondslag = ' . $this->_CI->db->escape( $grondslag ) . ' GROUP BY t.artikel ')); } public function add_uitgebreid( $grondslag_id, $artikel, $quest_node, $display_hoofdstuk, $display_afdeling, $display_paragraaf, $display_artikel, $display_lid, $tekst=null ) { /* $this->dbex->prepare( 'GrondslagTekst::add_uitgebreid', 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, quest_node, display_hoofdstuk, display_afdeling, display_paragraaf, display_artikel, display_lid, tekst) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' ); $args = array( 'grondslag_id' => $grondslag_id, 'artikel' => $artikel, 'quest_node' => $quest_node, 'display_hoofdstuk' => $display_hoofdstuk, 'display_afdeling' => $display_afdeling, 'display_paragraaf' => $display_paragraaf, 'display_artikel' => $display_artikel, 'display_lid' => $display_lid, 'tekst' => $tekst, ); $this->dbex->execute( 'GrondslagTekst::add_uitgebreid', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'grondslag_id' => $grondslag_id, 'artikel' => $artikel, 'quest_node' => $quest_node, 'display_hoofdstuk' => $display_hoofdstuk, 'display_afdeling' => $display_afdeling, 'display_paragraaf' => $display_paragraaf, 'display_artikel' => $display_artikel, 'display_lid' => $display_lid, 'tekst' => $tekst, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'isssssssc' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } } <file_sep><? require_once 'base.php'; class DeelplanHoofgroepenResult extends BaseResult { function DeelplanHoofgroepenResult( $arr ) { parent::BaseResult( 'deelplanhoofgroep', $arr ); } } class DeelplanHoofgroepen extends BaseModel { function DeelplanHoofgroepen() { parent::BaseModel( 'DeelplanHoofgroepenResult', 'deelplan_hoofgroep' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplanhoofgroep', 'id' ); } function create_new_toelichting_for_hoofgroep($deelplan_id,$hoofgroep_id,$toelichting,$status){ $this->dbex->prepare( 'create_new_toelichting_for_hoofgroep', 'INSERT INTO deelplan_hoofgroep (deelplan_id, hoofgroep_id, toelichting, status) VALUES (?,?,?,?)' ); $args = array( 'deelplan_id' => $deelplan_id, 'hoofgroep_id' => $hoofgroep_id, 'toelichting' => $toelichting, 'status'=> $status, ); $this->dbex->execute( 'create_new_toelichting_for_hoofgroep',$args); } function get_toelichting_for_hoofgroep($deelplan_id,$hoofgroep_id){ $query = ' SELECT toelichting,status FROM deelplan_hoofgroep WHERE deelplan_id=? AND hoofgroep_id=? order by deelplan_id DESC '; $this->dbex->prepare( 'get_toelichting_for_hoofgroep', $query ); $res = $this->dbex->execute( 'get_toelichting_for_hoofgroep', array( $deelplan_id, $hoofgroep_id ) ); return $res->result(); } }<file_sep>ALTER TABLE `bt_checklist_groepen` CHANGE `standaard_aanwezigheid` `standaard_aanwezigheid` INT(11) NULL DEFAULT '31', CHANGE `standaard_toezicht_moment` `standaard_toezicht_moment` VARCHAR(128) NULL DEFAULT 'Algemeen', CHANGE `standaard_fase` `standaard_fase` VARCHAR(128) NULL DEFAULT 'Algemeen', CHANGE `standaard_waardeoordeel_tekst_00` `standaard_waardeoordeel_tekst_00` VARCHAR(64) NULL DEFAULT 'Geen waardeoordeel', CHANGE `standaard_waardeoordeel_is_leeg_00` `standaard_waardeoordeel_is_leeg_00` TINYINT(4) NULL DEFAULT '1', CHANGE `standaard_waardeoordeel_kleur_00` `standaard_waardeoordeel_kleur_00` ENUM('groen','oranje','rood') NULL DEFAULT 'oranje', CHANGE `standaard_waardeoordeel_tekst_01` `standaard_waardeoordeel_tekst_01` VARCHAR(64) NULL DEFAULT 'Niet van toepassing', CHANGE `standaard_waardeoordeel_is_leeg_01` `standaard_waardeoordeel_is_leeg_01` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_01` `standaard_waardeoordeel_kleur_01` ENUM('groen','oranje','rood') NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_02` `standaard_waardeoordeel_tekst_02` VARCHAR(64) NULL DEFAULT 'Nader onderzoek nodig', CHANGE `standaard_waardeoordeel_is_leeg_02` `standaard_waardeoordeel_is_leeg_02` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_02` `standaard_waardeoordeel_kleur_02` ENUM('groen','oranje','rood') NULL DEFAULT 'oranje', CHANGE `standaard_waardeoordeel_tekst_03` `standaard_waardeoordeel_tekst_03` VARCHAR(64) NULL DEFAULT 'Niet kunnen controleren', CHANGE `standaard_waardeoordeel_is_leeg_03` `standaard_waardeoordeel_is_leeg_03` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_03` `standaard_waardeoordeel_kleur_03` ENUM('groen','oranje','rood') NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_04` `standaard_waardeoordeel_tekst_04` VARCHAR( 64 ) NULL DEFAULT 'Niet gecontroleerd', CHANGE `standaard_waardeoordeel_is_leeg_04` `standaard_waardeoordeel_is_leeg_04` TINYINT( 4 ) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_04` `standaard_waardeoordeel_kleur_04` ENUM( 'groen', 'oranje', 'rood' ) NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_10` `standaard_waardeoordeel_tekst_10` VARCHAR(64) NULL DEFAULT 'Voldoet', CHANGE `standaard_waardeoordeel_is_leeg_10` `standaard_waardeoordeel_is_leeg_10` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_10` `standaard_waardeoordeel_kleur_10` ENUM('groen','oranje','rood') NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_11` `standaard_waardeoordeel_tekst_11` VARCHAR(64) NULL DEFAULT 'Bouwdeel voldoet', CHANGE `standaard_waardeoordeel_is_leeg_11` `standaard_waardeoordeel_is_leeg_11` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_11` `standaard_waardeoordeel_kleur_11` ENUM('groen','oranje','rood') NULL DEFAULT 'oranje', CHANGE `standaard_waardeoordeel_tekst_12` `standaard_waardeoordeel_tekst_12` VARCHAR(64) NULL DEFAULT 'Gelijkwaardigheid', CHANGE `standaard_waardeoordeel_is_leeg_12` `standaard_waardeoordeel_is_leeg_12` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_12` `standaard_waardeoordeel_kleur_12` ENUM('groen','oranje','rood') NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_13` `standaard_waardeoordeel_tekst_13` VARCHAR(64) NULL DEFAULT 'Na aanwijzingen toezichthouder', CHANGE `standaard_waardeoordeel_is_leeg_13` `standaard_waardeoordeel_is_leeg_13` TINYINT(4) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_13` `standaard_waardeoordeel_kleur_13` ENUM('groen','oranje','rood') NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_tekst_20` `standaard_waardeoordeel_tekst_20` VARCHAR( 64 ) NULL DEFAULT 'Voldoet niet', CHANGE `standaard_waardeoordeel_is_leeg_20` `standaard_waardeoordeel_is_leeg_20` TINYINT( 4 ) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_20` `standaard_waardeoordeel_kleur_20` ENUM( 'groen', 'oranje', 'rood' ) NULL DEFAULT 'rood', CHANGE `standaard_waardeoordeel_tekst_21` `standaard_waardeoordeel_tekst_21` VARCHAR( 64 ) NULL DEFAULT 'Voldoet niet (niet zwaar)', CHANGE `standaard_waardeoordeel_is_leeg_21` `standaard_waardeoordeel_is_leeg_21` TINYINT( 4 ) NULL DEFAULT '0', CHANGE `standaard_waardeoordeel_kleur_21` `standaard_waardeoordeel_kleur_21` ENUM( 'groen', 'oranje', 'rood' ) NULL DEFAULT 'groen', CHANGE `standaard_waardeoordeel_standaard` `standaard_waardeoordeel_standaard` VARCHAR( 4 ) NULL DEFAULT '00', CHANGE `standaard_waardeoordeel_steekproef` `standaard_waardeoordeel_steekproef` VARCHAR( 4 ) NULL DEFAULT '04', CHANGE `standaard_waardeoordeel_steekproef_tekst` `standaard_waardeoordeel_steekproef_tekst` VARCHAR( 64 ) NULL DEFAULT 'Niet gecontroleerd ivm steekproef'; <file_sep>-- -- LET OP, deze migratie kan reeds zijn toegepast op LIVE! -- ALTER TABLE `back_log` ADD `prio_nr_imotep` VARCHAR( 128 ) NOT NULL , ADD `prio_nr_bris` VARCHAR( 128 ) NOT NULL , ADD `ureninschatting_intern` VARCHAR( 128 ) NOT NULL , ADD `programmeur` VARCHAR( 128 ) NOT NULL; <file_sep>var BRISToezicht = { initialize: function( data ) { if (data) this.initializeWithData( data ); var components = ['NetworkStatus','DirtyStatus','OfflineKlaar','Maps','Group','List','SearchableList','HelpButton','TabButtons','Toets','InlineEdit', 'Telefoon']; for (var i=0; i<components.length; ++i) { if (this[components[i]]) { this[components[i]].initialize(); } } this.installLogoutHook(); }, initializeWithData: function( data ) { // temporaries var init_onderwerp_id, init_vraag_id, vraag_onderwerp_map={}, seen_data_ids=[], button_configs={}, VRAAG_FLAGS_STEEKPROEF_VERWERKT = 0x01, VRAAG_FLAGS_GROEPSANTWOORD = 0x02; // init layer data BRISToezicht.Toets.data.layerdata = {}; for (var i in data.bescheiden_layers) { var layer = data.bescheiden_layers[i]; if (typeof( layer ) == 'function') continue; BRISToezicht.Toets.data.layerdata[i] = { layers: JSON.parse( layer.layer_data ), pagetransform: JSON.parse( layer.pagetransform_data ) } } // init gebruikers BRISToezicht.Toets.data.gebruikers = {}; BRISToezicht.Toets.data.hoofgroepen_toelichting=data.hoofgroepen_toelichting; BRISToezicht.Toets.data.last_hoofgroepen_toelichting=data.last_hoofgroepen_toelichting; for (var i in data.gebruikers) BRISToezicht.Toets.data.gebruikers[i] = data.gebruikers[i]; // init bescheiden BRISToezicht.Toets.data.bescheiden = {}; for (var i in data.bescheiden) { var b = data.bescheiden[i]; BRISToezicht.Toets.data.bescheiden[b.id] = { bescheid_id: b.id, tekening_stuk_nummer: b.tekening_stuk_nummer, datum_laatste_wijziging: b.datum_laatste_wijziging, omschrijving: b.omschrijving ? b.omschrijving : b.bestandsnaam, auteur: b.auteur, bestandsnaam: b.bestandsnaam } } // init vragen // LET OP: elke vraag krijgt later een vorigeVraag en volgendeVraag member, om er een lange linked list van te maken! BRISToezicht.Toets.data.vraaguploads = {}; BRISToezicht.Toets.data.onderwerpen = {}; BRISToezicht.Toets.data.vragen = {}; //console.log(data.onderwerpen); function iterate(data) { var arr = []; var new_obj={} for (var prop in data) { if (data.hasOwnProperty(prop)) { var obj = {}; obj[prop] = data[prop]; obj.tempSortName = data[prop].order; arr.push(obj); } } arr.sort(function(a, b) { var at = a.tempSortName, bt = b.tempSortName; return at > bt ? 1 : ( at < bt ? -1 : 0 ); }); for (var i = 0, l = arr.length; i < l; i++) { var obj = arr[i]; delete obj.tempSortName; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var id = prop; //gets the obj "index" (id?) } } var item = obj[id]; //do stuff with item new_obj=arr; } return arr; } var sort_array=iterate(data.onderwerpen); /*for (var onderwerp_id in data.onderwerpen) { console.log(onderwerp_id);*/ for (var i in sort_array){ for (var onderwerp_id in sort_array[i]){ onderwerp_id=onderwerp_id; } var onderwerp = data.onderwerpen[onderwerp_id]; BRISToezicht.Toets.data.onderwerpen[onderwerp_id] = { naam: onderwerp.naam, order:onderwerp.order, samenvattingSpan: null, statusImage: null, onderwerp_id: onderwerp_id, initialize: function() { if (!this.samenvattingSpan) { var tr = VoortgangTableOnderwerp[this.onderwerp_id].onderwerpRow; this.samenvattingSpan = tr.children( 'td:nth-child(5)' ); this.statusImage = tr.find( 'img.waardeoordeel'); } }, vragen: {} } for (var i in onderwerp.vragen) { var vraag = onderwerp.vragen[i] ,vraag_id = vraag.id ,bouwnummer = vraag.bouwnummer ; // Als er nog geen onderwerp/vraag als geselecteerd te boek staat, dan altijd de eerste // die we tegenkomen selecteren. Later deze selectie overschrijven met de geselecteerde // vraag uit data! if (!init_onderwerp_id || (data.selected_vraag && data.selected_vraag.id == vraag_id && data.selected_vraag.bouwnummer == bouwnummer )) { init_onderwerp_id = onderwerp_id; init_vraag_id = vraag_id; } vraag_onderwerp_map['' + vraag_id] = onderwerp_id; // handle button/vraag config setup, don't make object for every // vraag, in stead re-use identical objects var myConfigTag = (''+vraag.vraag_type)+(''+vraag.wstandaard)+(''+vraag.wsteekproef)+(''+vraag.wsteekproeftekst)+ (''+vraag.wt00)+(''+vraag.wt01)+(''+vraag.wt02)+(''+vraag.wt03)+(''+vraag.wt04)+(''+vraag.wt10)+(''+vraag.wt11)+(''+vraag.wt12)+(''+vraag.wt13)+(''+vraag.wt20)+(''+vraag.wt21)+(''+vraag.wt22)+(''+vraag.wt23)+ (''+vraag.wl00)+(''+vraag.wl01)+(''+vraag.wl02)+(''+vraag.wl03)+(''+vraag.wl04)+(''+vraag.wl10)+(''+vraag.wl11)+(''+vraag.wl12)+(''+vraag.wl13)+(''+vraag.wl20)+(''+vraag.wl21)+(''+vraag.wl22)+(''+vraag.wl23)+ (''+vraag.wk00)+(''+vraag.wk01)+(''+vraag.wk02)+(''+vraag.wk03)+(''+vraag.wk04)+(''+vraag.wk10)+(''+vraag.wk11)+(''+vraag.wk12)+(''+vraag.wk13)+(''+vraag.wk20)+(''+vraag.wk21)+(''+vraag.wk22)+(''+vraag.wk23)+ (''+vraag.wg00)+(''+vraag.wg01)+(''+vraag.wg02)+(''+vraag.wg03)+(''+vraag.wg04)+(''+vraag.wg10)+(''+vraag.wg11)+(''+vraag.wg12)+(''+vraag.wg13)+(''+vraag.wg20)+(''+vraag.wg21)+(''+vraag.wg22)+(''+vraag.wg23) ; if (!button_configs[myConfigTag]) { button_configs[myConfigTag] = { tag: myConfigTag, type: vraag.vraag_type, standaard: vraag.wstandaard, // is b.v. "01", om aan te geven dat positie "01" de default button is steekproef: vraag.wsteekproef, // is b.v. "30", om aan te geven dat positie "30" de steekproef button is steekproeftekst: vraag.wsteekproeftekst, gebruik: [ [ vraag.wg00, vraag.wg01, vraag.wg02, vraag.wg03, vraag.wg04 ], [ vraag.wg10, vraag.wg11, vraag.wg12, vraag.wg13 ], [ vraag.wg20, vraag.wg21, vraag.wg22, vraag.wg23 ] ], tekst: [ [ vraag.wt00, vraag.wt01, vraag.wt02, vraag.wt03, vraag.wt04 ], [ vraag.wt10, vraag.wt11, vraag.wt12, vraag.wt13 ], [ vraag.wt20, vraag.wt21, vraag.wt22, vraag.wt23 ] ], is_leeg: [ [ vraag.wl00, vraag.wl01, vraag.wl02, vraag.wl03, vraag.wl04 ], [ vraag.wl10, vraag.wl11, vraag.wl12, vraag.wl13 ], [ vraag.wl20, vraag.wl21, vraag.wl22, vraag.wl23 ] ], kleur: [ [ vraag.wk00, vraag.wk01, vraag.wk02, vraag.wk03, vraag.wk04 ], [ vraag.wk10, vraag.wk11, vraag.wk12, vraag.wk13 ], [ vraag.wk20, vraag.wk21, vraag.wk22, vraag.wk23 ] ] }; } BRISToezicht.Toets.data.onderwerpen[onderwerp_id].vragen[vraag_id] = BRISToezicht.Toets.data.vragen[vraag_id] = { gebruiker_id: vraag.gebruiker_id, vraag_id: vraag_id, order : vraag.sortering, huidige_toelichting_id : vraag.huidige_toelichting_id, onderwerp_id: onderwerp_id, hoofdgroep_id: vraag.hoofdgroep_id, checklist_id: vraag.checklist_id, categorie: vraag.naam, hoofdthema_id: vraag.thema_id ? data.themas[vraag.thema_id].hoofdthema_id : null, thema_id: vraag.thema_id, thema: vraag.thema_id ? data.themas[vraag.thema_id].thema : 'Algemeen', verantwoording_locked: (vraag.status || vraag.toelichting) ? true : false, tekst: vraag.tekst, fase: vraag.fase, toezicht_moment: vraag.toezicht_moment, last_updated_at: vraag.last_updated_at, statusImage: null, samenvattingSpan: null, aantalOpdrachtenDiv: null, inputs: BRISToezicht.Toets.Vraag.createInputs( vraag_id+(bouwnummer!=""&&bouwnummer!=null?"_"+bouwnummer:""), vraag.status, vraag.seconden, vraag.toelichting, vraag.huidige_toelichting_id, vraag.hercontrole_datum, (vraag.flags & VRAAG_FLAGS_GROEPSANTWOORD) ? 1 : 0 ), deelplanuploads: {}, vraagbescheiden: {}, vraaggeschiedenis: [], subjecten: [], geplande_opdrachten: [], type: vraag.vraag_type, button_config: button_configs[myConfigTag], initialize: function() { if (!this.samenvattingSpan) { var tr = VoortgangTableOnderwerp[this.onderwerp_id].vraagRows[this.vraag_id]; this.statusImage = tr.find('td img.waardeoordeel'); this.samenvattingSpan = tr.children('td:nth-child(5)'); this.aantalOpdrachtenDiv = tr.find( 'div.notificaties' ); this.aantalOpdrachtenDiv[ this.geplande_opdrachten.length ? 'show' : 'hide' ](); } }, gebruik_grndslgn: vraag.gebruik_grndslgn, gebruik_rchtlnn: vraag.gebruik_rchtlnn, gebruik_ndchtspntn: vraag.gebruik_ndchtspntn, gebruik_verantwtkstn: vraag.gebruik_verantwtkstn }; if (data.vraag_subjecten[vraag_id]) for (var j in data.vraag_subjecten[vraag_id]) BRISToezicht.Toets.data.onderwerpen[onderwerp_id].vragen[vraag_id].subjecten.push( data.vraag_subjecten[vraag_id][j].dossier_subject_id ); if (data.deelplanuploads[vraag_id]) for (var j in data.deelplanuploads[vraag_id]) { var du = data.deelplanuploads[vraag_id][j]; var duData = { vraagupload_id: du.id, filename: du.filename, url: du.url, thumbnail_url: du.thumbnail_url, has_thumbnail: du.has_preview ? true : false, delete_url: du.delete_url, uploaded_at: du.uploaded_at, auteur: du.auteur, datatype: du.datatype }; BRISToezicht.Toets.data.onderwerpen[onderwerp_id].vragen[vraag_id].deelplanuploads[du.id] = duData; BRISToezicht.Toets.data.vraaguploads[du.id] = duData; } if (data.vraagbescheiden[vraag_id]) for (var j in data.vraagbescheiden[vraag_id]) { var bescheid = null; for (var k in data.bescheiden) if (data.bescheiden[k].id == data.vraagbescheiden[vraag_id][j].dossier_bescheiden_id) { bescheid = data.bescheiden[k]; break; } if (bescheid) BRISToezicht.Toets.data.onderwerpen[onderwerp_id].vragen[vraag_id].vraagbescheiden[bescheid.id] = BRISToezicht.Toets.data.bescheiden[ bescheid.id ]; } if (data.deelplanvraaggeschiedenis[vraag_id]) for (var j in data.deelplanvraaggeschiedenis[vraag_id]) { var rvg = data.deelplanvraaggeschiedenis[vraag_id][j]; BRISToezicht.Toets.data.onderwerpen[onderwerp_id].vragen[vraag_id].vraaggeschiedenis.push(rvg); } } } // init initiele vraag BRISToezicht.Toets.data.initiele_vraag = init_onderwerp_id ? BRISToezicht.Toets.data.onderwerpen[init_onderwerp_id].vragen[init_vraag_id] : null; // init hoofdgroepen: BRISToezicht.Toets.data.hoofdgroepen = {}; for (var hoofdgroep_id in data.hoofdgroep_prioriteiten) BRISToezicht.Toets.data.hoofdgroepen[hoofdgroep_id] = { hoofdgroep_id: hoofdgroep_id, hoofdgroep_prioriteit: data.hoofdgroep_prioriteiten[hoofdgroep_id], matrix_test_niveau: data.hoofdgroep_prioriteiten_origineel[hoofdgroep_id] }; // init achtergrondinformatie BRISToezicht.Toets.data.aandachtspunten = data.aandachtspunten; BRISToezicht.Toets.data.richtlijnen = data.richtlijnen; BRISToezicht.Toets.data.grondslagen = data.grondslagen; BRISToezicht.Toets.data.opdrachten = data.opdrachten; // init geplande geplande_opdrachten BRISToezicht.Toets.data.geplande_opdrachten = data.geplande_opdrachten; for (var i=0; i<BRISToezicht.Toets.data.geplande_opdrachten.length; ++i) { var opdracht = BRISToezicht.Toets.data.geplande_opdrachten[i]; var vraag = BRISToezicht.Toets.data.vragen[opdracht.vraag_id]; if (vraag) vraag.geplande_opdrachten.push( opdracht ); } // init subjecten BRISToezicht.Toets.data.subjecten = {} for (var i in data.subjecten) { var subject = data.subjecten[i]; BRISToezicht.Toets.data.subjecten[subject.id] = { id: subject.id, organisatie: subject.organisatie, naam: subject.naam, rol: subject.rol } } // update GUI elements: hercontrole datum select var nieuw = $('[name=hercontrole_datum_select] [value=nieuw]'); for (var i=0; i<data.hercontrole_lijst.length; ++i) nieuw.before( '<option value="' + data.hercontrole_lijst[i].value + '">' + data.hercontrole_lijst[i].html + '</option>' ); // update GUI elements: foto image set var imageset = $('.nlaf_TabContent .fotos div.image-set'); for (var i in BRISToezicht.Toets.data.vraaguploads) { var upload = BRISToezicht.Toets.data.vraaguploads[i]; imageset.append( '<img vraagupload_id="' + upload.vraagupload_id + '" class="bestand" width="430" src="/files/images/pdfview-nog-niet-geladen.png" target_url="/pdfview/vraagupload/' + upload.vraagupload_id + '" />' ); } // update GUI elements: voortgang table //console.log(BRISToezicht.Toets.data.onderwerpen); var toets_data_new_array=iterate(BRISToezicht.Toets.data.onderwerpen); //console.log(toets_data_new_array); //for (var onderwerp_id in BRISToezicht.Toets.data.onderwerpen) { for (var i in toets_data_new_array){ for (var onderwerp_id in toets_data_new_array[i]){ onderwerp_id=onderwerp_id; } var onderwerp = BRISToezicht.Toets.data.onderwerpen[onderwerp_id]; //console.log(onderwerp); var tr = $('<tr class="onderwerp" onderwerp_id="' + onderwerp_id + '" filtered="nee">' + '<td style="width: 50px">' + '<img src="/files/images/nlaf/row-collapsed.png" class="collapsed" />' + '<img src="/files/images/nlaf/row-expanded.png" class="expanded hidden" />' + '</td>' + '<td>' + onderwerp.naam + '</td>' + '<td style="width: 50px"><img src="/files/images/nlaf/waardeoordeel-geel.png" class="waardeoordeel" /></td>' + '</tr>'); VoortgangTable.append( tr ); VoortgangTableOnderwerp[onderwerp_id] = { onderwerpRow: tr, // jquery container with tr row for onderwerp vraagRows: {}, // all vraag rows indexed by their vraag id, each vraag row is a jquery container vraagRows$: $() // all vraag rows in one jquery container }; //console.log(onderwerp.vragen); var vrrag_new_array=iterate(onderwerp.vragen); for (var i in vrrag_new_array){ for (var vraag_id in vrrag_new_array[i]){ vraag_id=vraag_id; } var vraag = onderwerp.vragen[vraag_id]; var status = vraag.inputs.status.value; var kleur = BRISToezicht.Toets.Status.waardeKleur[ BRISToezicht.Toets.Vraag.getStatusVoorVraag( vraag ).waarde ]; var tr = $('<tr class="vraag" onderwerp_id="' + onderwerp_id + '" vraag_id="' + vraag_id + '" filter="' + kleur + '" filtered="nee">' + '<td style="width: 50px">&nbsp;</td>' + '<td>' + vraag.tekst + '</td>' + '<td style="width: 50px"><img src="/files/images/nlaf/status-' + kleur + '.png" class="waardeoordeel" /></td>' + '</tr>'); VoortgangTable.append( tr ); VoortgangTableOnderwerp[onderwerp_id].vraagRows[vraag_id] = tr; VoortgangTableOnderwerp[onderwerp_id].vraagRows$ = VoortgangTableOnderwerp[onderwerp_id].vraagRows$.add( tr ); } } }, installLogoutHook: function() { $('#bpbutton_logoff a').live('click', function( e ){ // disable link by setting href to nothing $(this).attr( 'href', 'javascript:void(0);' ); // redirect to uitloggen page location.href = '/gebruikers/uitloggen'; }); } }; // we have to support IE8 which doesn't have indexOf... // if we add indexOf to the prototype of Array, every object // gets it too :X teh f...? and since we "for (var i in ...)" a // lot, this causes unsuspected behaviour in IE8 function indexOfArray( arr, val ) { if (arr.indexOf) return arr.indexOf( val ); for (var i=0; i<arr.length; ++i) if (arr[i] == val) return i; return -1; } <file_sep>PDFAnnotator.Tool.Measure = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'measure' ); /* cannot be initialized at this stage */ this.helperWindow = null; /* handle tool events */ this.on( 'select', function( tool, data ){ // tool == this! tool.initHelperWindow(); tool.lookupEarlierCalibration(); if (tool.calibrated()) tool.helperWindow.show(); }); this.on( 'deselect', function( tool, data ) { if (tool.helperWindow) tool.helperWindow.hide(); tool.hideLastLinesHandles(); tool.removeCalibrationLine( true ); tool.removeMeasureLine( true ); }); /* handle engine events */ var thiz = this; engine.on( 'prelayeractivated', function( engine, data ) { thiz.removeCalibrationLine( true ); thiz.removeMeasureLine(); }); /* handle drag events */ this.calibration = { complete: false, mm: 0, pixels: 0, line: null, arrows: [] }; this.measure = { line: null, arrows: [], prev: null }; this.on( 'dragstart', function( tool, data ){ if (!tool.calibration.complete) return tool.onCalibrateStart( data ); else return tool.onMeasureStart( data ); }); this.on( 'dragmove', function( tool, data ){ if (!tool.calibration.complete) return tool.onCalibrateMove( data ); else return tool.onMeasureMove( data ); }); this.on( 'dragend', function( tool, data ){ if (!tool.calibration.complete) return tool.onCalibrateEnd( data ); else return tool.onMeasureEnd( data ); }); }, removeCalibrationLine: function( force ) { this.removeLine( this.calibration, force ); }, onCalibrateStart: function( data ) { // remove all current stuff this.removeCalibrationLine( true ); var menu = this.engine.gui.menu; var colorSettings = menu.colors; this.calibration.line = new PDFAnnotator.Editable.Line({ color: '#3f48cc', from: data.position, to: data.position }); data.container.addObject( this.calibration.line, true ); /* forcibly add */ // create arrow heads var angle = 30; this.calibration.arrows = [ new PDFAnnotator.AttachedRotatedLine( this.calibration.line.line, ((180 - angle)/180.0)*Math.PI, 25, false ), new PDFAnnotator.AttachedRotatedLine( this.calibration.line.line, ((180 + angle)/180.0)*Math.PI, 25, false ), new PDFAnnotator.AttachedRotatedLine( this.calibration.line.line, ((- angle)/180.0)*Math.PI, 25, true ), new PDFAnnotator.AttachedRotatedLine( this.calibration.line.line, (( angle)/180.0)*Math.PI, 25, true ) ]; for (var i=0; i<this.calibration.arrows.length; ++i) { this.calibration.line.line.container.dom.append( this.calibration.arrows[i].myline.dom ); } }, onCalibrateMove: function( data ) { this.calibration.line.setTo( data.position ); }, onCalibrateEnd: function( data ) { if (this.calibration.line) { var h = this.calibration.line.getHandle( 'move' ); if (h) h.show(); } this.helperWindow.show(); }, removeMeasureLine: function() { if (this.measure.prev == this.measure.line) this.measure.prev = null; this.removeLine( this.measure, true ); }, hideLastLinesHandles: function() { if (this.measure.prev) { var h = this.measure.prev.getHandle( 'move' ); if (h) h.hide(); this.measure.prev = null; } }, onMeasureStart: function( data ) { this.hideLastLinesHandles(); // remove all current stuff this.removeMeasureLine( true ); var menu = this.engine.gui.menu; var colorSettings = menu.colors; this.measure.line = new PDFAnnotator.Editable.MeasureLine({ color: '#ed1c24', from: data.position, to: data.position, mm: this.calibration.mm, pixels: this.calibration.pixels }); if (!data.container.addObject( this.measure.line )) { this.measure.line = null; return false; } }, onMeasureMove: function( data ) { if (this.measure.line) this.measure.line.setTo( data.position ); }, onMeasureEnd: function( data ) { if (this.measure.line) { var h = this.measure.line.getHandle( 'move' ); if (h) h.show(); } this.measure.prev = this.measure.line; this.measure.line = null; }, finish: function() { if (this.calibration.complete) return true; if (!this.calibration.line) return false; var mm = this.getFormCalibrationValue(); if (!mm) return false; // okay, we're done, remove the line after measuring its length var pixels = this.calibration.line.line.length(); this.removeCalibrationLine(); // setup calibration var zoomLevel = this.engine.getZoomLevel(); this.calibration.mm = mm; this.calibration.pixels = pixels / zoomLevel; this.calibration.complete = true; // update earlier calibrations this.updateEarlierCalibrations(); // disable element to indicate we've calibrated var el = this.getFormCalibrationElement(); if (el) el.attr( 'disabled', 'disabled' ); return true; }, initHelperWindow: function() { if (this.helperWindow) return; // setup basic helper window this.helperWindow = new PDFAnnotator.HelperWindow(this, { width: '240px', height: '40px', left: '500px', top: '250px', moveable: true, container: this.engine.gui.getRootContainer() }); // add handles this.helperWindow.addHandle( new PDFAnnotator.Handle.MeasureFinish( this.helperWindow ) ); this.helperWindow.addHandle( new PDFAnnotator.Handle.MeasureDelete( this.helperWindow ) ); // add our content to it $('<div>') .html( '<div style="padding: 7px 0 0 12px">IJkwaarde: <input type="text" size="12" /> mm</div>' ) .css( 'color', '#fff' ) .css( 'font-weight', 'bold' ) .css( 'font-size', '130%' ) .appendTo( this.helperWindow.visuals ); // make sure it's hidden by default this.helperWindow.hide(); }, getFormCalibrationElement: function() { return this.helperWindow ? this.helperWindow.visuals.find( 'input[type=text]' ) : null; }, getFormCalibrationValue: function() { return this.helperWindow ? parseInt( this.helperWindow.visuals.find( 'input[type=text]' ).val() ) : 0; }, setFormCalibrationValue: function( value ) { this.helperWindow.visuals.find( 'input[type=text]' ).val( '' + value ); }, reset: function() { this.removeCalibrationLine( true ); this.removeMeasureLine( true ); this.calibration.complete = false; var el = this.getFormCalibrationElement(); if (el) el.removeAttr( 'disabled' ); }, calibrated: function() { return this.calibration.complete; }, removeLine: function( internaldata, force ) { if (internaldata.line && (force || !internaldata.complete)) { // remove arrow heads for (var i=0; i<internaldata.arrows.length; ++i) internaldata.arrows[i].myline.destroy(); internaldata.arrows = []; // remove line editable object, and reference internaldata.line.container.removeObject( internaldata.line ); internaldata.line = null; } }, lookupEarlierCalibration: function() { if (this.calibration.complete) return; /* see if we can find a measureline in any of the layers for this bescheiden, then copy the settings. */ var thiz = this; var found = false; for (var i in this.engine.layers) { var layer = this.engine.layers[i]; layer.forEachEditable(function(editable){ if (!found && editable instanceof PDFAnnotator.Editable.MeasureLine) { // copy values thiz.calibration.mm = parseInt( editable.data.mm ); thiz.calibration.pixels = parseInt( editable.data.pixels ); thiz.calibration.complete = true; // initialize GUI properly thiz.helperWindow.show(); thiz.setFormCalibrationValue( thiz.calibration.mm ); found = true; } }); if (found) break; } }, updateEarlierCalibrations: function() { var thiz = this; for (var i in this.engine.layers) { var layer = this.engine.layers[i]; layer.forEachEditable(function(editable){ if (editable instanceof PDFAnnotator.Editable.MeasureLine) { editable.updateCalibration( thiz.calibration.mm, thiz.calibration.pixels ); } }); } } }); <file_sep><? if ($json_output) { $result = array(); foreach ($verantwoordingen as $verantwoording) { $data = $verantwoording->get_array_copy(); $data['tekst'] = html_entity_decode($data['tekst']); $data['status'] = $data['status'] ? preg_replace( '/_/', ' ', $data['status']) : ''; $result[] = $data; } echo json_encode($result); } else { ?> (function(){ BRISToezicht.Toets.data.verantwoordingen = [ <? $c=0; foreach ($verantwoordingen as $verantwoording): ?> <?=$c++?',':''?>{ status: '<?=$verantwoording->status?>', checklist_id: <?=$verantwoording->checklist_id ? $verantwoording->checklist_id : 'null'?>, hoofdthema_id: <?=$verantwoording->hoofdthema_id ? $verantwoording->hoofdthema_id : 'null'?>, thema_id: <?=$verantwoording->thema_id ? $verantwoording->thema_id : 'null'?>, grondslag: '<?=$verantwoording->grondslag?>', artikel: '<?=$verantwoording->artikel?>', tekst: '<?=jsstr( $verantwoording->tekst )?>' } <? endforeach; ?> ]; })(); <? } <file_sep>PDFAnnotator.Handle.CircleResize = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 1, 0.5, baseurl + 'images/nlaf/edit-handle-resize.png', 32, 32, 'drag', this.execute ); }, execute: function( relx, rely ) { // calc new x/y position of node var d = this.nodes[0].dom; var x = d.position().left + parseInt( relx ); var y = d.position().top + parseInt( rely ); d.css( 'left', x + 'px' ); d.css( 'top', y + 'px' ); // increase x/y to get middle of handle x += 16; y += 16; // calculate new radius based on center of handle var v = this.editable.visuals; var c = parseInt( v.css('width') ) / 2; var r = Math.sqrt( (x-c)*(x-c) + (y-c)*(y-c) ); this.editable.setRadius( r ); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Pagina statistieken')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Gebruiker activiteit', 'width' => '920px' ) ); ?> <div style="padding-bottom:10px"> <h2>Actieve gebruiker(s) - afgelopen 5 minuten</h2> <i><b><?=sizeof($laatste_5mins)?></b> gebruikers</i> <ul> <? foreach ($laatste_5mins as $row): ?> <li><?=$row->volledige_naam?> (<?=$row->klant?>)</li> <? endforeach; ?> </ul> </div> <div style="padding-bottom:10px"> <h2>Actieve gebruiker(s) - afgelopen 24 uur</h2> <i><b><?=sizeof($laatste_dag)?></b> gebruikers</i> <ul> <? foreach ($laatste_dag as $row): ?> <li><?=$row->volledige_naam?> (<?=$row->klant?>)</li> <? endforeach; ?> </ul> </div> <div style="padding-bottom:10px"> <h2>Actieve gebruiker(s) - afgelopen 7 dagen</h2> <i><b><?=sizeof($laatste_week)?></b> gebruikers</i> <ul> <? foreach ($laatste_week as $row): ?> <li><?=$row->volledige_naam?> (<?=$row->klant?>)</li> <? endforeach; ?> </ul> </div> <div style="padding-bottom:10px"> <h2>Actieve gebruiker(s) - afgelopen maand</h2> <i><b><?=sizeof($laatste_maand)?></b> gebruikers</i> <ul> <? foreach ($laatste_maand as $row): ?> <li><?=$row->volledige_naam?> (<?=$row->klant?>)</li> <? endforeach; ?> </ul> </div> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><?php class WettekstenCleanup { private $CI; public function __construct() { $this->CI = get_instance(); $this->CI->load->model( 'grondslag' ); } public function run( $fix=false ) { $this->CI->db->query( 'SET AUTOCOMMIT=0' ); $this->CI->db->query( 'BEGIN;' ); // $this->_fix_pgs(); // $this->_verwijder_grondslag_vragen( '.' ); // $this->_verwijder_grondslag_vragen( 'Wabo' ); $this->_merge_grondslag_in( 'AB', 'BARIM' ); $this->_merge_grondslag_in( 'AR', 'RARIM' ); $this->_merge_grondslag_in( 'B', 'BB03' ); $this->_merge_grondslag_in( 'BB', 'BB12' ); $this->_merge_grondslag_in( 'BB2012', 'BB12' ); $this->_merge_grondslag_in( 'PG', 'PGS30' ); // $this->_hernoem_grondslag( 'art.', 'WW' ); // $this->_hernoem_artikel( 'WW', '40WW', '40' ); // $this->_hernoem_artikel( 'WW', '40 WW', '40' ); // $this->_hernoem_artikel( 'BB03', '3', '3.18' ); // $this->_hernoem_artikel( 'BB03', '4', '4.12' ); // $this->_hernoem_artikel( 'BB12', '15', '1.5' ); // $this->_hernoem_artikel( 'BB12', '2118', '2.118' ); // $this->_hernoem_artikel( 'Rarim', '3', '4.102 lid 2 en 3' ); // $this->_hernoem_artikel( 'Rarim', '5', '4.104 lid 4 en 5' ); // $this->_verwijder_artikel( 'BB03', '12' ); // $this->_verwijder_artikel( 'BB03', '18' ); // $this->_verwijder_grondslag( '.' ); // $this->_verwijder_grondslag( 'Wabo' ); // $this->_verwijder_grondslag( 'AB' ); // $this->_verwijder_grondslag( 'AR' ); // $this->_teksten_legen(); // $this->_trim_artikelen(); $this->_fix_artikel_benamingen(); $this->_fix_dubbelen(); // $this->_dump(); if ($fix) { echo "COMMITTING...\n"; $this->CI->db->query( 'COMMIT;' ); } else { echo "ROLLING BACK...\n"; $this->CI->db->query( 'ROLLBACK;' ); } $this->CI->db->query( 'SET AUTOCOMMIT=1' ); } private function _fix_pgs() { echo "Fixing PGS\n"; $grondslagen = array( 19 => $this->CI->grondslag->add_conditional( 'PGS19', 1 ), 30 => $this->CI->grondslag->add_conditional( 'PGS30', 1 ), ); foreach ($this->CI->db->query( ' SELECT gt.*, g.grondslag FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.klant_id = 1 AND g.grondslag = \'PGS\' ')->result() as $row) { if (!preg_match( '/^(\d+)\s*(.*?)$/', $row->artikel, $matches )) continue; if (!isset( $grondslagen[$matches[1]] )) throw new Exception( 'Onbekende PGS ' . $matches[1] ); echo " {$row->grondslag} {$row->artikel}\n"; $this->_query_and_check_affected(' UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape($matches[2] ? $matches[2] : 'PGS' . $matches[1]) . ', grondslag_id = ' . $grondslagen[ intval($matches[1]) ]->id . ' WHERE id = ' . $row->id . ' '); } $this->_query_and_check_affected('UPDATE bt_grondslag_teksten SET artikel = \'PGS30\' WHERE artikel = \'S 30\' AND grondslag_id = ' . $this->CI->grondslag->find( 'PG', 1 )->id ); } private function _trim_artikelen() { echo "Trimmen artikelen\n"; foreach ($this->CI->db->query(' SELECT gt.* FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.klant_id = 1 ')->result() as $row) { $new_artikel = trim( $row->artikel ); if (strlen( $new_artikel ) != strlen( $row->artikel )) { echo " hernoem '{$row->artikel}' naar $new_artikel\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape( $new_artikel ) . ' WHERE id = ' . $row->id ); } } } private function _hernoem_artikel( $grondslag, $artikel, $new_artikel, $must_have_affected=true ) { echo "Hernoem $grondslag $artikel naar $new_artikel\n"; $rows = $this->CI->db->query( 'SELECT id FROM bt_grondslagen WHERE grondslag = ' . $this->CI->db->escape( $grondslag ) . ' AND klant_id = 1' )->result(); if (empty( $rows )) throw new Exception( 'Grondslag ' . $grondslag . ' onbekend' ); $grondslag_id = $rows[0]->id; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape( $new_artikel ) . ' WHERE artikel = ' . $this->CI->db->escape($artikel) . ' AND grondslag_id = ' . $grondslag_id, $must_have_affected ); } private function _verwijder_artikel( $grondslag, $artikel, $must_have_affected=true ) { echo "Verwijder $grondslag $artikel \n"; $rows = $this->CI->db->query( 'SELECT id FROM bt_grondslagen WHERE grondslag = ' . $this->CI->db->escape( $grondslag ) . ' AND klant_id' )->result(); if (empty( $rows )) throw new Exception( 'Grondslag ' . $grondslag . ' onbekend' ); $grondslag_id = $rows[0]->id; $this->_query_and_check_affected( 'DELETE FROM bt_grondslag_teksten WHERE artikel = ' . $this->CI->db->escape($artikel) . ' AND grondslag_id = ' . $grondslag_id, $must_have_affected ); } private function _teksten_legen() { echo "Teksten leeg maken\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET tekst = \'\'' ); echo "PGS teksten verwijzingen maken\n"; foreach ($this->CI->db->query( ' SELECT gt.*, g.grondslag FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.grondslag LIKE \'%PGS%\' AND g.klant_id = 1 ')->result() as $row) { echo " {$row->grondslag} {$row->artikel} gevonden\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET tekst = \'Zie http://www.publicatiereeksgevaarlijkestoffen.nl/ voor volledige tekst.\' WHERE id = ' . $row->id ); } } private function _fix_artikel_benamingen() { echo "Artikel benamingen fixen\n"; $artikelen = array(); foreach ($this->CI->db->query(' SELECT gt.grondslag_id, gt.artikel, gt.id, g.grondslag FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.klant_id = 1 ')->result() as $row) { $artikel = $row->artikel; if (preg_match( '/^artikk?(el|le)e?n?(.*?)$/i', $artikel, $matches )) { $new_artikel = trim($matches[2]); echo " gevonden: '$artikel', wordt '$new_artikel'\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape($new_artikel) . ' WHERE id = ' . $row->id ); } else if (preg_match( '/^afdelingen/i', $artikel )) { $new_artikel = preg_replace( '/^afdelingen/i', 'afdeling', $artikel ); echo " gevonden: '$artikel', wordt '$new_artikel'\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape($new_artikel) . ' WHERE id = ' . $row->id ); } else if (preg_match( '/^afd_/i', $artikel )) { $new_artikel = preg_replace( '/^afd_/i', 'afdeling ', $artikel ); echo " gevonden: '$artikel', wordt '$new_artikel'\n"; $this->_query_and_check_affected( 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->CI->db->escape($new_artikel) . ' WHERE id = ' . $row->id ); } } } private function _fix_dubbelen() { echo "Dubbelen fixen\n"; $artikelen = array(); foreach ($this->CI->db->query(' SELECT gt.grondslag_id, gt.artikel, gt.id, g.grondslag FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.klant_id = 1 ')->result() as $row) { $grondslag_tekst_id = $row->id; $artikel = $row->artikel; $grondslag_id = $row->grondslag_id; $tag = $grondslag_id . '::' . $artikel; if (!isset( $artikelen[$tag] )) $artikelen[$tag] = $grondslag_tekst_id; else { echo " dubbele gevonden: {$row->grondslag} $artikel, is id {$artikelen[$tag]} en {$grondslag_tekst_id}\n"; $this->_query_and_check_affected( 'UPDATE bt_vraag_grndslgn SET grondslag_tekst_id = ' . $artikelen[$tag] . ' WHERE grondslag_tekst_id = ' . $grondslag_tekst_id ); $this->_query_and_check_affected( 'DELETE FROM bt_grondslag_teksten WHERE id = ' . $grondslag_tekst_id ); } } } private function _hernoem_grondslag( $van_grondslag, $naar_grondslag ) { echo "Hernoem grondslag '$van_grondslag' in '$naar_grondslag'\n"; $this->_query_and_check_affected('UPDATE bt_grondslagen SET grondslag = ' . $this->CI->db->escape( $naar_grondslag ) . ' WHERE grondslag = ' . $this->CI->db->escape( $van_grondslag ) . ' AND klant_id = 1' ); } private function _merge_grondslag_in( $van_grondslag, $naar_grondslag ) { echo "Merge grondslag '$van_grondslag' in '$naar_grondslag'\n"; $rows = $this->CI->db->query( 'SELECT id FROM bt_grondslagen WHERE grondslag = ' . $this->CI->db->escape( $naar_grondslag ) . ' AND klant_id' )->result(); if (empty( $rows )) throw new Exception( 'Grondslag ' . $naar_grondslag . ' onbekend' ); $naar_grondslag_id = $rows[0]->id; foreach ($this->CI->db->query(' SELECT gt.* FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.grondslag = ' . $this->CI->db->escape( $van_grondslag ) . ' AND g.klant_id = 1 ORDER BY gt.artikel ')->result() as $van_row) { echo " artikel '{$van_row->artikel}'"; $naar_row = $this->CI->db->query(' SELECT gt.* FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.grondslag = ' . $this->CI->db->escape( $naar_grondslag ) . ' AND gt.artikel = ' . $this->CI->db->escape( $van_row->artikel ) . ' AND g.klant_id = 1 ')->result(); echo " [van_row={$van_row->id} naar_row=" . (empty($naar_row)?'':$naar_row[0]->id) . "] "; switch (sizeof($naar_row)) { case 0: echo " bestaat niet, grondslag_id wordt omgezet\n"; $this->_query_and_check_affected('UPDATE bt_grondslag_teksten SET grondslag_id = ' . $naar_grondslag_id . ' WHERE id = ' . $van_row->id); break; case 1: echo " bestaat, references worden bijgewerkt\n"; $this->_query_and_check_affected('UPDATE bt_vraag_grndslgn SET grondslag_tekst_id = ' . $naar_row[0]->id . ' WHERE grondslag_tekst_id = ' . $van_row->id); $this->_query_and_check_affected('DELETE FROM bt_grondslag_teksten WHERE id = ' . $van_row->id ); break; default: throw new Exception( 'Meer dan een regel gevonden.' ); } } } private function _verwijder_grondslag_vragen( $grondslag ) { echo "Verwijder vraag-koppelingen voor artikelen van grondslag '$grondslag'\n"; $this->_query_and_check_affected(' DELETE FROM bt_vraag_grndslgn WHERE grondslag_tekst_id IN ( SELECT gt.id FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.grondslag = ' . $this->CI->db->escape( $grondslag ) . ' AND g.klant_id = 1 ) '); } private function _verwijder_grondslag( $grondslag ) { echo "Verwijder grondslag (en artikelen) '$grondslag'\n"; $this->_query_and_check_affected('DELETE FROM bt_grondslagen WHERE grondslag = ' . $this->CI->db->escape( $grondslag ) . ' AND klant_id = 1'); } private function _dump() { $cur_grondslag = 0; foreach ($this->CI->db->query(' SELECT gt.id, g.grondslag, gt.artikel, gt.grondslag_id FROM bt_grondslag_teksten gt JOIN bt_grondslagen g ON gt.grondslag_id = g.id WHERE g.klant_id = 1 ORDER BY g.grondslag, gt.artikel ')->result() as $row) { $show_grondslag = $row->grondslag_id != $cur_grondslag; $cur_grondslag = $row->grondslag_id; echo sprintf( "[%5d] %20s '%s'\n", $row->id, $show_grondslag ? $row->grondslag : '', $row->artikel ); } } private function _query_and_check_affected( $q, $must_have_affected=true ) { echo "--------------> $q\n"; if (!$this->CI->db->query( $q)) throw new Exception( 'Fout bij uitvoeren van query: ' . $q ); if ($must_have_affected) if (!($c = $this->CI->db->affected_rows())) throw new Exception( 'Geen regels verwijderd bij uitvoeren van query: ' . $q ); echo " $c regels\n"; } } <file_sep>REPLACE INTO teksten(string, tekst, timestamp, lease_configuratie_id) VALUES ('nav.account_gebruiker_toevoegen', 'Gebruiker toevoegen', NOW(), 0);<file_sep><? $this->load->view( 'nieuwelaf/header' ); ?> <? $this->load->view( 'nieuwelaf/cssimagepreload' ); ?> <? $test_niveaus = $risicoanalyse_handler->get_risico_shortnames(); ?> <div id="nlaf_LoadingScreen" style="z-index: 1000; position: absolute; width: 100%; height: 100%; opacity: 0.92; filter:alpha(opacity=80); background-color: #555; "></div> <div id="nlaf_LoadingScreenContent" style="z-index: 1001; position: absolute; width: 100%; height: 100%; text-align: center; "> <div class="offline-klaar" style="width: 400px; margin-left: auto; margin-right: auto; margin-top: 300px; border: 2px solid #777; background-color: #eee; padding: 20px; opacity: 1.0; filter:alpha(opacity=100); font-size: 200%; font-weight: bold;"> <span> <?=tgn('even-geduld-aub')?> </span> <span class="perc"></span> <img style="vertical-align: top; padding-top: 10px;" src="<?=site_url('/files/images/loading.gif');?>"> <div style="border:0; padding:0; margin:0px 40px;"> <table width="100%"> <? if (tg('ophalen.dossierinformatie')!='-'): ?> <tr> <td style="text-align: left;"><span style="text-align: left;font-size: 10pt;"><?=tg('ophalen.dossierinformatie')?>:</span></td><td style="text-align: right;"><img src="/files/images/offline-klaar-wel.png" class="hidden status-offline-tag-klaar-dossierinfo"><img src="/files/images/offline-klaar-nog-niet.png" class="status-offline-tag-niet-klaar-dossierinfo"></td> </tr> <? endif; ?> <? if (tg('ophalen.verantwoordingen')!='-'): ?> <tr> <td style="text-align: left;"><span style="font-size: 10pt;"><?=tg('ophalen.verantwoordingen')?>:</span></td><td style="text-align: right;"><img src="/files/images/offline-klaar-wel.png" class="hidden status-offline-tag-klaar-verantwoordingen"><img src="/files/images/offline-klaar-nog-niet.png" class="status-offline-tag-niet-klaar-verantwoordingen"></td> </tr> <? endif; ?> <? if (tg('ophalen.afbeeldingen')!='-'): ?> <tr> <td style="text-align: left;"><span style="font-size: 10pt;"><?=tg('ophalen.afbeeldingen')?>:</span></td><td style="text-align: right;"><img src="/files/images/offline-klaar-wel.png" class="hidden status-offline-tag-klaar-afbeeldingen"><img src="/files/images/offline-klaar-nog-niet.png" class="status-offline-tag-niet-klaar-afbeeldingen"></td> </tr> <? endif; ?> <? if (tg('ophalen.wetteksten')!='-'): ?> <tr> <td style="text-align: left;"><span style="font-size: 10pt;"><?=tg('ophalen.wetteksten')?>:</span></td><td style="text-align: right;"><img src="/files/images/offline-klaar-wel.png" class="hidden status-offline-tag-klaar-wetteksten"><img src="/files/images/offline-klaar-nog-niet.png" class="status-offline-tag-niet-klaar-wetteksten"></td> </tr> <? endif; ?> </table> </div> </div> </div> <? $has_lease_config = $this->gebruiker->get_logged_in_gebruiker()->get_klant()->get_lease_configuratie(); ?> <form method="POST" name="form" enctype="multipart/form-data"> <input type="hidden" name="combi_onderwerp_id" id="combi_onderwerp_id" /> <div id="nlaf_MainPanel"> <div id="nlaf_Header"> <? if ($has_lease_config): ?> <div id="nlaf_HeaderHome" class="inlineblock" style="width:105px"> <div class="regular_button noselect small inlineblock" onclick="showMessageBox({message:'<?=tg('really-go-home')?>', onClose: function(res){if (res=='ok') location.href='<?=site_url()?>';}});"> <?=tg('home')?> </div> </div> <? endif; ?> <div id="nlaf_HeaderTerug" class="inlineblock" style="<? if ($has_lease_config): ?>width:105px;<? endif;?>"> <div class="regular_button noselect small inlineblock" style="display: none"> <div class="arrow_left_simple inlineblock"></div> <?=tg('terug')?> </div> </div> <div id="nlaf_HeaderSynchronisatie" class="store-status stored inlineblock" title="<?=tgn('geeft_aan_of_er_nog_onopgeslagen_werk_aanwezig_is_in_dit_venster.')?>"> <img src="<?=site_url('/files/images/nlaf/synchroniseer-nu.png')?>" /> <span class="hidden unstored"><?=tg('niet_gesynchroniseerd')?></span> <span class="stored"><?=tg('gesynchroniseerd')?></span> <span class="hidden storing-now"><?=tg('synchroniseren')?></span> <br/> <div id="nlaf_SynchronisatieStatus"> <span id="nlaf_SyncOverview"></span></br> <span id="nlaf_SyncCurrent"></span> </div> </div> <div id="nlaf_HeaderOnline" class="network-status inlineblock" title="<?=tgn('klik_om_de_online_status_bij_te_werken')?>" standaard-mode="<?=$klant->standaard_netwerk_modus?>"> <img class="require_online hidden wifi" style="vertical-align: top" src="<?=site_url('/files/images/nlaf/online-wifi.png')?>" /> <img class="require_offline hidden wifi" style="vertical-align: top" src="<?=site_url('/files/images/nlaf/offline-wifi.png')?>" /> <img class="require_online hidden 3g" style="vertical-align: top" src="<?=site_url('/files/images/nlaf/online-3g.png')?>" /> <img class="require_offline hidden 3g" style="vertical-align: top" src="<?=site_url('/files/images/nlaf/offline-3g.png')?>" /> <span><?=tg('online')?></span> </div> <div id="nlaf_HeaderKlaarVoorOffline" class="offline-klaar inlineblock" title="<?=tgn('geeft_aan_of_de_applicatie_klaar_is_voor_offline_werken')?>"> <img title="<?=tgn('klaar_voor_offline_werken')?>" class="hidden status-offline-klaar" src="<?=site_url('/files/images/nlaf/klaar-voor-offline.png')?>" /> <img title="<?=tgn('nog_niet_klaar_voor_offline_werken')?>" class="status-offline-niet-klaar" src="<?=site_url('/files/images/nlaf/niet-klaar-voor-offline.png')?>" /> <div class="notificaties perc" />0%</div> </div> <div id="nlaf_HeaderVoortgang" class="inlineblock" style="<? if ($has_lease_config): ?>width:120px;<? endif;?>"> <table class="bg" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="left"></td> <td class="mid" style="<? if ($has_lease_config): ?>width:106px;<? endif;?>"> <table class="bar" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="left"></td> <td class="mid" style="width: <?=round(186 * (0 * ((186-8)/186)))?>px"></td> <td class="right"></td> </tr> </table> </td> <td class="right"></td> </tr> </table> </div> <div id="nlaf_HeaderVoortgangPerc" class="inlineblock"><?=round( 100 * 0)?>%</div> <div id="nlaf_NaarToezichtVoortgang" class="inlineblock"><?=tg('open_toezichtvoortgang')?></div> </div> <div id="nlaf_GreenBar"></div> <div id="nlaf_ToezichtPanel"> <div id="nlaf_PrioVraagPanel"> <div id="nlaf_PrioPanel" class="inlineblock"> <div class="noselect button zeer_hoog"><?=$test_niveaus['zeer_hoog']?></div> <div class="noselect button hoog"><?=$test_niveaus['hoog']?></div> <div class="noselect button gemiddeld"><?=$test_niveaus['gemiddeld']?></div> <div class="noselect button laag"><?=$test_niveaus['laag']?></div> <div class="noselect button zeer_laag"><?=$test_niveaus['zeer_laag']?></div> </div> <div id="nlaf_VraagPanel" class="inlineblock"> <div class="hoofdgroep"><!-- hoofdgroep --></div> <div class="vraag"><!-- vraag --></div> </div> </div> <? $postfix = $lease_configuratie ? '-' . $lease_configuratie->naam : ''; ?> <div id="nlaf_TabList" class="inlineblock"> <div class="tab selected" tab-name="waardeoordeel"> <img src="<?=site_url('/files/images/nlaf/tab-oog' . $postfix . '.png')?>" class="hidden" /> <img src="<?=site_url('/files/images/nlaf/tab-oog-selected' . $postfix . '.png')?>" class="selected" /> </div> <div class="tab" tab-name="aandachtspunten" style="background-position: left -71px;"> <div id="nlaf_TotaalAantalAandachtspunten" class="hidden notificaties">0</div> <img src="<?=site_url('/files/images/nlaf/tab-aandachtspunten.png')?>" /> <img src="<?=site_url('/files/images/nlaf/tab-aandachtspunten-selected' . $postfix . '.png')?>" class="selected hidden" /> </div> <div class="tab" tab-name="fotos" style="background-position: left -142px;"> <div id="nlaf_TotaalAantalFotos" class="hidden notificaties">0</div> <img src="<?=site_url('/files/images/nlaf/tab-fotos.png')?>" /> <img src="<?=site_url('/files/images/nlaf/tab-fotos-selected' . $postfix . '.png')?>" class="selected hidden" /> </div> <div class="tab" tab-name="documenten" style="background-position: left -213px;"> <div id="nlaf_TotaalAantalBescheiden" class="hidden notificaties">0</div> <img src="<?=site_url('/files/images/nlaf/tab-documenten.png')?>" /> <img src="<?=site_url('/files/images/nlaf/tab-documenten-selected' . $postfix . '.png')?>" class="selected hidden" /> </div> <div class="tab" tab-name="opdrachten" style="background-position: left -284px;"> <div id="nlaf_TotaalAantalOpdrachten" class="hidden notificaties">0</div> <img src="<?=site_url('/files/images/nlaf/tab-opdrachten.png')?>" /> <img src="<?=site_url('/files/images/nlaf/tab-opdrachten-selected' . $postfix . '.png')?>" class="selected hidden" /> </div> </div><!-- --><div id="nlaf_TabContents" class="inlineblock"> <div class="tabcontents" tab-name="waardeoordeel"><? $this->load->view( 'nieuwelaf/tab-waardeoordeel' )?></div> <div class="tabcontents hidden" tab-name="aandachtspunten"><? $this->load->view( 'nieuwelaf/tab-aandachtspunten' )?></div> <div class="tabcontents hidden" tab-name="fotos"><? $this->load->view( 'nieuwelaf/tab-fotos' )?></div> <div class="tabcontents hidden" tab-name="documenten"><? $this->load->view( 'nieuwelaf/tab-documenten' )?></div> <div class="tabcontents hidden" tab-name="opdrachten"><? $this->load->view( 'nieuwelaf/tab-opdrachten' )?></div> </div> <br/> <div id="nlaf_VorigeVraag"> <div class="regular_button noselect inlineblock"> <div class="arrow_left_simple inlineblock"></div> <?=tg('vorige_vraag')?> </div> </div> <div id="nlaf_VolgendeVraag" style="position: absolute; right: 0;"> <div class="regular_button noselect inlineblock"> <?=tg('volgende_vraag')?> <div class="arrow_right_simple inlineblock"></div> </div> </div> <div id="nlaf_LocatieInformatie"> <? if ($access_mode == 'readonly'): ?> <span style="color:#f33"><?=tg('alleen_lezen_modus_actief')?></span> <? else: ?> <?=htmlentities( $dossier->get_locatie( false ) )?> <? endif; ?> </div> </div> <div id="nlaf_ToezichtVoortgangPanel" class="hidden"> <? $this->load->view( 'nieuwelaf/popup-voortgang' ); ?> </div> <div id="nlaf_Waardeoordeel" class="hidden"> <? $this->load->view( 'nieuwelaf/popup-waardeoordeel' ); ?> </div> <div id="nlaf_ViewImage" class="hidden"> </div> <div id="nlaf_PDFAnnotator" class="hidden"> <? // add PDF annotator HTML here load_view( 'index.php', array( // actually used 'guids' => load_current_guids(), 'embedded' => true, 'is_btz' => true, // not really used, but must be present 'pages' => null, 'document' => null, 'layers' => null, 'error' => null, 'format' => 'png', ) ); ?> </div> </div> <div style="display:none" class="store-once"></div> </form> <? // load PDF annotator upload form here (cannot be inside other form) load_view( 'upload-form.php' ); ?> <iframe src="<?=site_url('/root/session_check')?>" class="hidden" id="online-check"></iframe> <? $this->load->view( 'nieuwelaf/toetsdata-js', array('bouwnummer'=>$bouwnummer )); ?> <script type="text/javascript"> $(document).ready(function(){ // handle switching tabs $('div.tab').click(function(){ // handle selected class on tabs $('div.tab.selected img.selected').hide(); $('div.tab.selected img:not(.selected)').show(); $('div.tab.selected').removeClass('selected'); $(this).addClass('selected'); $(this).find('img.selected').show(); $(this).find('img:not(.selected)').hide(); // handle display correct tab contents $('div.tabcontents').hide(); $('div.tabcontents[tab-name=' + $(this).attr('tab-name') + ']').show(); }); // handle going back to normal view $('#nlaf_HeaderTerug div').click(function(){ // hide Terug button $('#nlaf_HeaderTerug div').hide(); // hide all content panels $('#nlaf_MainPanel').children( ':not(#nlaf_GreenBar):not(#nlaf_Header)' ).hide(); // show main panel $('#nlaf_ToezichtPanel').show(); }); // Copy the relevant 'hercontrole datum' options from the select list in the checklist to the filter for these dates. function copyHercontroleDatumFilterOptions() { var filterDatumObj = $('#filterDatum'); // First clear all current options of the target select list filterDatumObj.html(''); // Always add an 'all' option filterDatumObj.append("<option value=''><?=tgn('datum_filter_all')?></option>"); // Now copy all relevant options from the source select, stripping the option texts so the select list doesn't become too wide. // Note: we do not copy the first and last options, because they aren't actually used dates. $("#hercontrole_datum_select option").each(function() { var optionValue = $(this).val(); var optionText = $(this).text(); if ( (optionValue != 'geen') && (optionValue != 'nieuw') ) { // Drop the part between parentheses (if any) var parenthesesPosition = optionText.indexOf(' ('); var strippedText = (parenthesesPosition > -1) ? optionText.slice(0,parenthesesPosition) : optionText; // Add the (stripped) option filterDatumObj.append("<option value='"+optionValue+"'>"+strippedText+"</option>"); } }); } // Copy the relevant options from the data structure to the corresponding filter. function copyGenericVraagFilterOptions(targetFilterHook, propertyName, allOptionText) { var filterObj = $(targetFilterHook); // First clear all current options of the target select list filterObj.html(''); // Always add an 'all' option filterObj.append("<option value=''>"+allOptionText+"</option>"); // Create an empty array for holding the various distinct values encountered //var newOptions = []; var newOptions = new Array(); // Iterate over all onderwerpen and questions, storing unique new option values as we go along $.each(BRISToezicht.Toets.data.onderwerpen, function(index, onderwerpen) { // Iterate over all 'vragen' $.each(onderwerpen.vragen, function(index, vraag) { // Get the property value (NOTE: do so using array notation, so we can easily pass the property name!) var newCandidateOptionValue = vraag[propertyName]; // If the new candidate option hasn't been added yet, do so now if ($.inArray(newCandidateOptionValue, newOptions) == -1) { // Add the option to the working set of processed options newOptions.push(newCandidateOptionValue); // Add the option to the filter filterObj.append("<option value='"+newCandidateOptionValue+"'>"+newCandidateOptionValue+"</option>"); } }); }); } // handle switching to voortgangpanel $('#nlaf_NaarToezichtVoortgang').click(function(){ // Copy the 'hercontrole datum' options to the filter selector copyHercontroleDatumFilterOptions(); // Copy the 'fase' and 'toezichtmoment' options generically copyGenericVraagFilterOptions('#filterFase', 'fase', '<?=tgn('fase_filter_all');?>'); copyGenericVraagFilterOptions('#filterToezichtmoment', 'toezicht_moment', '<?=tgn('toezichtmoment_filter_all');?>'); // init onderwerp elements BRISToezicht.Toets.Vraag.initializeOnderwerpVoortgang(); // expand current onderwerp var onderwerp = BRISToezicht.Toets.Vraag.getHuidigeOnderwerpData(); if (onderwerp) voortgangExpandOnderwerp( onderwerp.onderwerp_id, true ); // hide open toezichtvoortgang button $('#nlaf_NaarToezichtVoortgang').hide(); $('#nlaf_HeaderTerug div').one('click', function(){ $('#nlaf_NaarToezichtVoortgang').show(); }); // show Terug button $('#nlaf_HeaderTerug div').show(); // hide all content panels $('#nlaf_MainPanel').children( ':not(#nlaf_GreenBar):not(#nlaf_Header)' ).hide(); // show target panel $('#nlaf_ToezichtVoortgangPanel').show(); }); <? if ($access_mode != 'readonly'): ?> $('#nlaf_HeaderSynchronisatie').css( 'cursor', 'pointer' ); $('#nlaf_HeaderSynchronisatie').click(function(){ BRISToezicht.Toets.Form.attemptStore( true ); }); <? endif; ?> }); </script> <? $this->load->view( 'nieuwelaf/footer' ); /* */ ?> <file_sep><? $this->load->view( 'extern/header' ); ?> <!-- pages --> <? if (!isset($page)) $page='dossiers'; ?> <? switch ($page): case 'dossiers': $this->load->view( 'extern/page-dossiers' ); break; case 'toezichtmomenten': $this->load->view( 'extern/page-toezichtmomenten' ); break; case 'opdrachten': $this->load->view( 'extern/page-opdrachten' ); break; case 'opdracht': $this->load->view( 'extern/page-opdracht' ); break; case 'opslaan': $this->load->view( 'extern/page-opslaan' ); break; case 'afsluiten': $this->load->view( 'extern/page-afsluiten' ); break; endswitch; ?> <? $this->load->view( 'extern/footer' ); ?> <file_sep><?php function modify_array($arr /*object as array*/,$key /*key for search*/,$type=FALSE /*returned multiple array*/,$mid=FALSE /* if key in array 0*/,$d=false ){ $array=array();//create empty $tmp array foreach ($arr as $row){ if(!$mid){ $keyellement=$row[$key]; }else{{$keyellement=$row[0][$key];}} if(!$type){$array[$keyellement]=$row;} else{$array[$keyellement][]=$row;}} return $array; // return result ))) } /******************************************************************************************************************************************************************************/ function cut_array($arr,$field){ //get single element from array $na=array(); foreach ((array)$arr as $row){ $row=(array)$row; $na[]=$row[$field]; } return $na; } /******************************************************************************************************************************************************************************/ function cut_string($str,$count=200,$end="..."){return substr($str,0,$count).$end;};//no comments! /******************************************************************************************************************************************************************************/ function update_array($keys /*ids list*/ ,$values /**/,$keys_key,$values_keys){ ///////RENNAME!!! $values=modify_array($values, "id"); $new=array(); foreach ($keys as $row){$new[]=$values[$row['id_skill']]['skill'];} return $new; }; /******************************************************************************************************************************************************************************/ function cut_elements_array($array,$count){ $tmp=array(); for($i=0;$i<$count;$i++){ $tmp[]=$array[$i]; } return $tmp; }<file_sep>PDFAnnotator.Tool.Image = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'image' ); var thiz = this; this.on( 'select', function( tool, data ){ thiz.conditionallyOpenImageList(); }); this.on( 'mouseclick', function( tool, data ){ var menu = tool.engine.gui.menu; var imageSettings = menu.imagelist; if (!imageSettings.getCurrentImageSrc()) { thiz.conditionallyOpenImageList(); return; } data.container.addObject( new PDFAnnotator.Editable.Image({ position: data.position, dimensions: imageSettings.getCurrentImageDimensions(), src: imageSettings.getCurrentImageSrc(), size: imageSettings.getCurrentImageDimensions().divided( 4 /* scale to 25% by default */ ) })); }); }, conditionallyOpenImageList: function() { var menu = this.engine.gui.menu; if (!menu.imagelist.getCurrentImageSrc()) { menu.show(); /* this is a HORRENDOUS hack, but I don't have a better solution right now */ $(menu.menuconfig.headers[2]).trigger( 'click' ); } } }); <file_sep><table width="100%" height="100%" class="messagebox"> <tr> <td class="icon notice"></td> <td class="message"> <h2>Grondslag toevoegen</h2> <input type="radio" name="soort" value="briswarenhuis" checked>Gebruik BRISwarenhuis, <b><span class="count">0</span> geselecteerd</b>.<br/> <input type="radio" name="soort" value="handmatig">Handmatig<br/> <div id="GS_briswarenhuis" style="margin-top: 10px; margin-right: 20px;"> <div style="padding: 10px;"><img src="<?=site_url('/files/checklistwizard/ajax-loader.gif')?>"> Even geduld a.u.b...</div> </div> <div id="GS_handmatig" class="hidden" style="margin-top: 10px; margin-right: 20px;"> <table> <tr> <td><b>Grondslag:</b></td> <td> <select name="grondslag_id"> <option value="" selected disabled>-- selecteer een grondslag --</option> <option value="new">-- Nieuwe grondslag toevoegen -- </option> <? foreach ($grondslagen as $grondslag): ?> <option value="<?=$grondslag->id?>"><?=htmlentities($grondslag->grondslag, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <input type="text" name="grondslag_naam" placeholder="Naam grondslag" class="hidden" maxlength="64" size="40" /> <input type="button" value="Terug" class="terug hidden"> </td> </tr> <tr> <td><b>Hoofdstuk:</b></td> <td><input type="text" name="hoofdstuk" maxlength="32" size="32" /></td> </tr> <tr> <td><b>Afdeling:</b></td> <td><input type="text" name="afdeling" maxlength="32" size="32" /></td> </tr> <tr> <td><b>Paragraaf:</b></td> <td><input type="text" name="paragraaf" maxlength="32" size="32" /></td> </tr> <tr> <td><b>Artikel:</b></td> <td><input type="text" name="artikel" maxlength="32" size="32" /></td> </tr> <tr> <td><b>Lid:</b></td> <td><input type="text" name="lid" maxlength="32" size="32" /></td> </tr> <tr> <td><b>Tekst:</b></td> <td><textarea name="tekst" style="width: 500px; height: 150px"></textarea></td> </tr> </table> </div> </td> </tr> <tr> <td class="buttons" colspan="2"> <input type="button" value="OK" class="ok" /> <input type="button" value="Annuleren" onclick="closePopup('cancel')" /> </td> </tr> </table> <script type="text/javascript"> // keep global namespace clean var GSExchange = null; (function(){ var BW = { initialize: function() { this.dom = $('#GS_briswarenhuis'); this.count = getPopup().find('.count'); this.loadBase(); this.dom.disableSelection(); }, post: function( data, success ) { $.ajax({ url: '/checklistwizard/briswarenhuis', type: 'POST', data: data, dataType: 'json', success: success, error: this.proxyError, context: this }); }, loadBase: function() { this.post( { command: 'list-collectie' }, function( data ) { if (!data || !data.success) this.proxyError(); else { this.dom.html(''); for (var i=0; i<data.result.length; ++i) { this.addNode( this.dom, data.result[i].Title, data.result[i].DocumentQuestId, null, false ) .attr( 'collection_node_id', data.result[i].Id ); } } }); }, proxyError: function() { alert( 'Er is iets fout gegaan bij het benaderen van BRISwarenhuis. Werkt uw internet connectie?' ); }, addNode: function( parent, text, document_id, node_id, no_children ) { // find UL we'll be appending to, if not exists create it :) var ul = parent.children('ul'); if (!ul.size()) ul = $('<ul>').appendTo( parent ); // add li to ul for this node var li = $('<li>').appendTo( ul ); var thiz = this; // if we have a node id, create a checkbox component and add it to the li var cb = node_id ? $('<input type="checkbox">').click( function(event) { thiz.onNodeSelected(event); } ) : null; if (cb) li.append(cb).append( ' ' ); // append the node name to the li li.append( $('<span>').text(text) ); // set document_id and node_id if present if (document_id) li.attr('document_id', document_id ); if (node_id) li.attr('node_id', node_id ); // calculate and set depth var depth = parent.attr('depth'); if (typeof(depth) != 'string') depth = 0; else depth = parseInt(depth); ++depth; li.attr( 'depth', depth ); li.addClass( 'depth' + depth ); // set click handler li.click( function(event) { BW.onNodeClicked(event); } ); // deal with leafs and nodes if (no_children) { li.attr( 'loaded', '1' ); li.addClass( 'leaf' ); } else li.addClass( 'node' ); // return i return li; }, onNodeClicked: function( event ) { eventStopPropagation(event); // if this node was already loaded, do nothing other than toggling its contents var node = $(event.currentTarget ); if (node.attr( 'loaded' ) == '1') { node.children('ul').toggle(); return; } if (node.hasClass('loading')) return; // don't load twice! node.addClass('loading'); // find context var collection_node_id = node.attr( 'collection_node_id' ); var document_id = node.attr( 'document_id' ); if (!document_id && !collection_node_id) // find collection id using parent node document_id = node.closest( '[document_id]' ).attr('document_id'); // if there's a document ID, load its nodes if (document_id) { var node_id = node.attr('node_id'); if (!node_id) node_id = ''; this.post( { command: 'list-node', document_id: document_id, node_id: node_id }, function( data ) { node.attr( 'loaded', 1 ); node.removeClass('loading'); for (var i=0; i<data.result.length; ++i) { this.addNode( node, data.result[i].Title, null, data.result[i].QuestId, !data.result[i].HasChilds ); } }); } // else if there's a collection node id, load its nodes else if (collection_node_id) { this.post( { command: 'list-collectie', parent_id: collection_node_id }, function( data ) { node.attr( 'loaded', 1 ); node.removeClass('loading'); for (var i=0; i<data.result.length; ++i) { this.addNode( node, data.result[i].Title, data.result[i].DocumentQuestId, null, false ) .attr( 'collection_node_id', data.result[i].Id ); } }); } }, onNodeSelected: function( event ) { eventStopPropagation(event); this.count.text( this.dom.find( 'input[type=checkbox]:checked' ).size() ); }, getSelection: function() { var result = []; this.dom.find( 'input[type=checkbox]:checked' ).each(function(){ var myNode = $(this).parent(); var documentNode = $(this).closest('[document_id]'); var node_id = myNode.attr('node_id'); var hoofdstuk = node_id.match( /hfd([0-9\-]+)($|\/)/ ) ? RegExp.$1 : ''; var afdeling = node_id.match( /afd([0-9\-]+)($|\/)/ ) ? RegExp.$1 : ''; var paragraaf = node_id.match( /par([0-9\-]+)($|\/)/ ) ? RegExp.$1 : ''; var artikel = node_id.match( /art([0-9\-]+)($|\/)/ ) ? RegExp.$1 : ''; var lid = node_id.match( /lid([0-9\-]+)($|\/)/ ) ? RegExp.$1 : ''; if (!hoofdstuk && !afdeling && !paragraaf && !artikel && !lid) { var parts = node_id.split( '/' ); if (parts.length >= 1) hoofdstuk = parts[0]; if (parts.length >= 2) afdeling = parts[1]; if (parts.length >= 3) artikel = parts[2]; if (parts.length >= 4) lid = parts[3]; } result.push({ document_id: documentNode.attr( 'document_id' ), quest_node: node_id, document: documentNode.children('span').text(), hoofdstuk: hoofdstuk.replace( /\-/g, '.' ), afdeling: afdeling.replace( /\-/g, '.' ), paragraaf: paragraaf.replace( /\-/g, '.' ), artikel: artikel.replace( /\-/g, '.' ), lid: lid.replace( /\-/g, '.' ) }); }); return result; } }; BW.initialize(); var popup = getPopup(); popup.find( '[name=grondslag_id]' ).change(function(){ if (this.value == 'new') { var sel = $(this); var inputs = sel.siblings(); sel.hide(); inputs.show(); $(inputs[0]).focus(); } }).siblings( '.terug' ).click(function(){ var sel = $(this).siblings('select'); var inputs = sel.siblings(); sel.show(); sel[0].selectedIndex = 0; inputs.hide(); }); popup.find( '[name=soort]' ).change(function(){ var soort = $(this).val(); popup.find( 'div[id!=GS_' + soort + '][id^=GS]' ).hide(); popup.find( 'div[id=GS_' + soort + ']' ).show(); }); popup.find( 'input[type=button].ok' ).click(function(){ var soort = popup.find( '[name=soort]:checked' ).val(); switch (soort) { case 'briswarenhuis': var elementen = BW.getSelection(); break; case 'handmatig': var elementen = []; var dom = popup.find('#GS_handmatig'); var gsSel = dom.find('[name=grondslag_id]')[0]; var gsNaam = dom.find('[name=grondslag_naam]')[0]; var isCustomName = gsSel.value == 'new'; var el = { quest_node: null, document: (!isCustomName) ? gsSel.options[gsSel.selectedIndex].innerHTML : gsNaam.value, hoofdstuk: dom.find('[name=hoofdstuk]').val(), afdeling: dom.find('[name=afdeling]').val(), paragraaf: dom.find('[name=paragraaf]').val(), artikel: dom.find('[name=artikel]').val(), lid: dom.find('[name=lid]').val(), tekst: dom.find('[name=tekst]').val() }; if (!isCustomName) el.grondslag_id = gsSel.value; else el.grondslag_naam = gsNaam.value; if ((!isCustomName && el.grondslag_id.length>0 || (isCustomName && el.grondslag_naam.length)) && (el.hoofdstuk.length || el.afdeling.length || el.paragraaf.length || el.artikel.length)) { elementen = [el]; } else { alert( 'Onvoldoende gegevens ingevoerd om een nieuwe grondslag toe te kunnen voegen.' ); return; } break; } GSExchange = elementen; /* our global exchange variable with uitgebreide_editor.js */ closePopup( 'ok' ); }); })(); </script> <file_sep><? $reload = false; $show_waiting = false; switch ($state) { case 'uploaded': case 'processing': $statetext = 'Uw verzoek wordt verwerkt, een ogenblik geduld a.u.b.'; $reload = true; $show_waiting = true; break; case 'failed': $statetext = 'Er is iets fout gegaan bij het verwerken.'; break; case 'processed': while (ob_get_level()) ob_end_clean(); header( 'Location: ' . PDFANNOTATOR_HOME_URL ); exit; default: $statetext = 'Onbekende status "' . $state . '".'; break; } ?> <? load_view( 'header.php' ); ?> <div id="PdfWait"> <?=$statetext?><br/> <br/> <i>Proces is gestart op <?=$created_at?>, nu <?=time() - strtotime($created_at)?> seconden geleden.</i><br/> <br/> <? if ($show_waiting): ?> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/loading.gif"> <? endif; ?> <? if ($reload): ?> <script type="text/javascript"> setTimeout( function() { location.href = location.href; }, 2000 ); </script> <? endif; ?> </div> <? load_view( 'footer.php' ); ?> <file_sep><? // browsers $CI = get_instance(); $CI->is_IE6or7 = preg_match( '/MSIE\s+[67]/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE6or7or8 = $CI->is_IE6or7 || preg_match( '/MSIE\s+8/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE = $CI->is_IE6or7or8 || preg_match( '/MSIE/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); // other $ver = 'v' . config_item('application_version'); if (config_item( 'development_version' )) $ver .= '&t=' . round(1000*microtime(true)); ?> <!doctype html> <html> <head> <title><?=@$extra_title ? $extra_title : APPLICATION_TITLE?></title> <meta http-equiv="expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <? if ($CI->is_Mobile): ?> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <? endif; ?> <!-- css --> <link rel="shortcut icon" href="<?=site_url('/files/images/favicon.png')?>" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery-ui.css')?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery.ui.timepicker.css')?>" type="text/css" /> <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" href="<?=site_url('/files/css/toezicht.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris-nlaf.css?' . $ver)?>" type="text/css" /> <? if ($CI->is_IE6or7): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE6or7.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris-nlaf-IE6or7.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_IE6or7or8): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE6or7or8.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_IE): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-IE.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? if ($CI->is_Mobile): ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-mobile.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris-nlaf-mobile.css?' . $ver)?>" type="text/css" /> <? else: ?> <link rel="stylesheet" href="<?=site_url('/files/css/bris-nlaf-non-mobile.css?' . $ver)?>" type="text/css" /> <? endif; ?> <? $_gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $_leaseconfiguratie = $_gebruiker ? $_gebruiker->get_klant()->get_lease_configuratie() : null; ?> <? if ($_leaseconfiguratie): ?> <!-- overrides CSS files --> <style text="type/css"> #nlaf_NaarToezichtVoortgang { background-image: url(/files/images/nlaf/green-button-<?=$_leaseconfiguratie->naam?>.png); } #nlaf_GreenBar { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-color: #<?=$_leaseconfiguratie->achtergrondkleur?>; } </style> <? endif; ?> <!-- javascript system libaries --> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-1.7.min.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-ui.min.js')?>"></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery.ui.timepicker.min.js')?>"></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/modal.popup.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/json.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/afspraak.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/sha1-min.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery.contextMenu.js')?>" ></script> <!-- BRIStoezicht libaries --> <script type="text/javascript"> var eventStopPropagation = function( e ) { if (typeof( e.stopPropagation ) == 'function') e.stopPropagation(); else if (typeof( e.cancelBubble ) != 'undefined') e.cancelBubble = true; } </script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/toezicht.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/core.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/common.helper.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/dirtystatus.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/group.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/helpbutton.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/inlineedit.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/list.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/maps.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/networkstatus.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/offlineklaar.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/performance.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/progress.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/searchablelist.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/tabbuttons.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/tools.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/upload.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/bescheiden.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/form.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/pdfannotator.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/planning.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/popup.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/specialimage.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/status.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/subject.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/teksten.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/verantwoording.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/vraag.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/vraagupload.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/buttonconfig.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/opdracht.js?' . $ver)?>" ></script> <!-- PDF annotator libraries --> <? // load view is a PDF annotator function load_view( 'html-head', array( 'exclude_jquery' => true, ) ); ?> <? if (@$include_nokia_maps): ?> <!-- Nokia Maps --> <meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" /> <script type="text/javascript" src="https://api.maps.nokia.com/2.2.3/jsl.js?with=maps,places,search" charset="utf-8"></script> <? endif; ?> </head> <body><file_sep><? // The VIIA users have a distinct set of selections that by default are checked. For those fields that deviate from the standard choices, we use the following // two variables to check/uncheck them as desired. $only_checked_if_viia = ($gebruiker->is_viia_user()) ? 'checked' : ''; $only_unchecked_if_viia = ($gebruiker->is_viia_user()) ? '' : 'checked'; $mogelijke_waardeoordelen = array( 'rood' => array(), 'oranje' => array(), 'groen' => array(), ); $invulvraag_aanwezig = array(); $waardeoordeel_deelplannen = array(); foreach ($dossier->get_deelplannen() as $deelplan) { // !!! Note: 21-3-2016: we no longer restrict the reports to be only for deelplannen that are still active. //if (!$deelplan->afgemeld) if (1) { $mw = $deelplan->get_mogelijke_waardeoordelen(); if ($mw->get_heeft_invulvraag()) $invulvraag_aanwezig[] = $deelplan->id; foreach ($mw->get_waardeoordelen() as $kleur => $waardeoordelen) { foreach ($waardeoordelen as $waardeoordeel) { // maak globale lijst van waardeoordeel/kleur combi's if (!isset( $mogelijke_waardeoordelen[$kleur] )) $mogelijke_waardeoordelen[$kleur] = array(); if (!in_array( $waardeoordeel, $mogelijke_waardeoordelen[$kleur] )) $mogelijke_waardeoordelen[$kleur][] = $waardeoordeel; // houdt bij welke deelplannen welke waardeoordelen hebben, voor betere filtering $tag = $kleur . '::' . $waardeoordeel; if (!isset( $waardeoordeel_deelplannen[$tag] )) $waardeoordeel_deelplannen[$tag] = array(); $waardeoordeel_deelplannen[$tag][] = $deelplan->id; } } } } foreach ($mogelijke_waardeoordelen as $kleur => $unused) sort( $mogelijke_waardeoordelen[$kleur] ); ?> <table class="rapportage-filter standaard" style="width: 100%;"> <tr> <th class="export-title" colspan="5" style="vertical-align: middle"><h1><?=tg('selectiemogelijkheden')?></h1></th> </tr> <tr> <td class="onderdelen-filter column"> <!-- onderdelen filter --> <table> <tr> <th colspan="3"><h2><?=tg('rapportageonderdelen')?></h2></th> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[inleiding]" <?=$only_unchecked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg('inleiding')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[dossiergegevens]" <?=$only_unchecked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg('dossiergegevens')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[documenten]" <?=$only_unchecked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg('documenten')?></td> </tr> <? $deelplannen_or_projecten = ($gebruiker->is_riepair_user()) ? 'projecten' : 'deelplannen'; ?> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[deelplannen]" <?=$only_unchecked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg($deelplannen_or_projecten)?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[samenvatting]" checked /></td> <td colspan="2" style="vertical-align: middle"><?=tg('samenvatting')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bevindingen]" checked /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bevindingen')?></td> </tr> <tr> <td></td> <td class="checkbox"><input type="checkbox" name="onderdeel[aandachtspunten]" /></td> <td style="vertical-align: middle"><?=tg('aandachtspunten')?></td> </tr> <? if ($gebruiker->is_arbode_user()): ?> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[toetsing_kerndeskundige]" checked /></td> <td colspan="2" style="vertical-align: middle"><?=tg('toetsing_kerndeskundige')?></td> </tr> <? endif; ?> <? if ($gebruiker->is_riepair_user()): ?> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-pago-pmo]" checked /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_pago_pmo')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-pbm]" checked /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_pbm')?></td> </tr> <? endif; ?> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-fotos]" <?=$only_checked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_fotos')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-annotaties]" <?=$only_checked_if_viia?> /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_annotaties')?></td> </tr> <? if ($gebruiker->is_viia_user()): ?> <tr> <td></td> <td class="checkbox"><input type="checkbox" name="onderdeel[annotaties_download]" /></td> <td style="vertical-align: middle"><?=tg('annotaties_download')?></td> </tr> <? endif; ?> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-documenten-tekeningen]" /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_documenten_tekeningen')?></td> </tr> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[bijlage-juridische-grondslag]" /></td> <td colspan="2" style="vertical-align: middle"><?=tg('bijlage_juridische_grondslag')?></td> </tr> <!-- revisies filter --> <tr> <td class="checkbox"><input type="checkbox" name="onderdeel[show-revisions]" /></td> <td colspan ="2" style="vertical-align: middle"><?=tg('revisies.tonen')?></td> </tr> </table> </td> <td class="deelplannen-filter column"> <!-- deelplannen filter --> <table> <tr> <th colspan="2" style="vertical-align: middle"><h2><?=tg('deelplannen')?></h2></th> </tr> <? foreach (array_reverse( $dossier->get_deelplannen() ) as $deelplan): ?> <? $selected_deelplan_id = null; $checked_str = (!$gebruiker->is_viia_user() || ($gebruiker->is_viia_user() && ($deelplan->naam == 'Inspectie'))) ? 'checked' : ''; ?> <tr> <td class="checkbox"><input type="radio" name="deelplan" value="<?=$deelplan->id?>" <?=$checked_str?> /></td> <td colspan="2" style="vertical-align: middle"><?=htmlentities( $deelplan->naam, ENT_COMPAT, 'UTF-8' )?></td> </tr> <? if (!empty($checked_str)) $selected_deelplan_id = $deelplan->id; ?> <? endforeach; ?> </table> </td> <? if ($gebruiker->is_viia_user()): ?> <td class="checklist-filter column"> <!-- checklist filter --> <table> <tr> <th colspan="2" style="vertical-align: middle"><h2><?=tg('checklisten')?></h2></th> </tr> <? foreach (array_reverse( $dossier->get_deelplannen() ) as $deelplan): ?> <? $dislay_dp_cls_str = ($deelplan->naam == 'Inspectie') ? 'block' : 'none'; ?> <tr class="dp_cl_row_<?=$deelplan->id?>" style="display:<?=$dislay_dp_cls_str?>;"> <td class="checkbox"><input type="radio" name="dp_checklist_<?=$deelplan->id?>" value="all" checked /></td> <td style="vertical-align: middle">Alle checklisten</td> </tr> <? foreach ($deelplan->get_checklisten() as $deelplan_checklist): ?> <tr class="dp_cl_row_<?=$deelplan->id?>" style="display:<?=$dislay_dp_cls_str?>;"> <td class="checkbox"><input type="radio" name="dp_checklist_<?=$deelplan->id?>" value="<?=$deelplan_checklist->checklist_id?>" /></td> <td style="vertical-align: middle"><?=$deelplan_checklist->naam?></td> </tr> <? endforeach; ?> <? endforeach; ?> </table> </td> <? endif; ?> <td class="grondslagen-filter column"> <!-- grondslagen filter --> <table> <tr> <th colspan="2" style="vertical-align: middle"><h2><?=tg('juridische_grondslagen')?></h2></th> </tr> <? $grondslagen = array(); foreach ($dossier->get_deelplannen() as $deelplan) foreach ($deelplan->get_checklisten() as $checklist) $grondslagen = array_merge( $grondslagen, $deelplan->get_distinct_grondslagen( $checklist->checklist_groep_id ) ); $grondslagen = array_unique( $grondslagen ); sort( $grondslagen ); ?> <? foreach ($grondslagen as $grondslag): ?> <? $checked_str = (!$gebruiker->is_viia_user() || ($gebruiker->is_viia_user() && ($grondslag == 'NEN 2767'))) ? 'checked' : ''; ?> <tr> <td class="checkbox"><input type="checkbox" name="grondslag[<?=$grondslag?>]" <?=$checked_str?> /></td> <td style="vertical-align: middle"><?=htmlentities( $grondslag, ENT_COMPAT, 'UTF-8' )?></td> </tr> <? endforeach; ?> </table> </td> <td class="waardeoordelen-filter column"> <!-- waardeoordelen filter --> <div style="border:0;padding:0;height:auto;margin:0;"> <table> <tr> <th colspan="2" style="vertical-align: middle"><h2><?=tg('waardeoordelen')?></h2></th> </tr> <? foreach ($mogelijke_waardeoordelen as $kleur => $entries): ?> <? foreach ($entries as $entry): ?> <? $checked_str = (!$gebruiker->is_viia_user() || ($gebruiker->is_viia_user() && (strtolower($entry) != 'niet van toepassing'))) ? 'checked' : ''; ?> <? $deelplan_ids = implode( ',', $waardeoordeel_deelplannen[$kleur . '::' . $entry] ); ?> <tr> <td class="checkbox"><input type="checkbox" name="waardeoordeel[<?=$entry?>]" <?=$checked_str?> deelplan_ids="<?=$deelplan_ids?>"/></td> <td style="vertical-align: middle;"> <img style="vertical-align: middle;" src="<?=site_url('/files/images/nlaf/waardeoordeel-' . $kleur . '-klein.png')?>" /> <?=htmlentities( $entry, ENT_COMPAT, 'UTF-8' )?> </td> </tr> <? endforeach; ?> <? endforeach; ?> <? if (sizeof( $invulvraag_aanwezig )): ?> <? $deelplan_ids = implode( ',', $invulvraag_aanwezig ); ?> <tr> <td class="checkbox"><input type="checkbox" name="waardeoordeel_invulvragen" checked deelplan_ids="<?=$deelplan_ids?>"/></td> <td style="vertical-align: middle;"> <?=tgg( 'toon.invul.vragen' )?> </td> </tr> <? endif; ?> </table> </div> </td> <? if (sizeof( $subjecten = $dossier->get_subjecten() )): ?> <td class="betrokkenen-filter column"> <table> <tr> <th colspan="2" style="vertical-align: middle"><h2><?=tg('betrokkenen')?></h2></th> </tr> <tr> <td><input type="checkbox" name="betrokkenen-filter" ></td> <td style="vertical-align: middle;">Filter op betrokkene(n)</td> </tr> <? foreach ($subjecten as $subject): ?> <tr> <td><input type="checkbox" name="subjecten[<?=$subject->id?>]" disabled checked></td> <td style="vertical-align: middle;"><span class="disabled"><?=htmlentities( $subject->naam . ($subject->organisatie ? ' (' . $subject->organisatie . ')' : ''), ENT_COMPAT, 'UTF-8' )?></span></td> </tr> <? endforeach; ?> </table> </td> <? endif; ?> </tr> </table> <script type="text/javascript"> // Global JS variable to keep track of the selected deelplan, initialise the content from PHP var currentDeelplanId = '<?=$selected_deelplan_id?>'; $('input[type=checkbox][name=onderdeel\\[bevindingen\\]]').click(function(){ $('.waardeoordelen-filter div')[this.checked?'slideDown':'slideUp'](); }); $('input[type=checkbox][name=betrokkenen-filter]').click(function(){ var p = $(this).parents('.betrokkenen-filter'); var inputs = p.find('[name^=subjecten]'); var texts = p.find('span'); if (this.checked) { inputs.removeAttr( 'disabled' ); texts.removeClass( 'disabled' ); } else { inputs.attr( 'disabled', 'disabled' ); texts.addClass( 'disabled' ); } }); $('input[type=checkbox][name^=deelplan]').click(function(){ var selectedDeelplanIds = []; $('input[type=checkbox][name^=deelplan]:checked').each(function(){ selectedDeelplanIds.push( $(this).attr('deelplan_id') ); }); $('tr input[type=checkbox][deelplan_ids]').each(function(){ var ids = $(this).attr('deelplan_ids').split(','); var visible = false; for (var i=0; i<ids.length; ++i) { if (indexOfArray( selectedDeelplanIds, ids[i] ) != -1) { visible = true; break; } } $(this).closest('tr')[ visible ? 'show' : 'hide' ](); }); }); // Function to show/hide checklist options based on the selected deelplan $('input[type=radio][name^=deelplan]').click(function(){ //console.log('Deelplan checklist selected'); //console.log('currently selected: ' + currentDeelplanId); //console.log('newly selected: ' + $(this).val()); // Get the ID of the currently selected deelplan and use that to disable the corresponding set of rows var disableChecklistenBlockSelector = '.dp_cl_row_' + currentDeelplanId; $(disableChecklistenBlockSelector).hide(); // Get the ID of the newly selected deelplan and use that to enable the corresponding set of rows var enableChecklistenBlockSelector = '.dp_cl_row_' + $(this).val(); $(enableChecklistenBlockSelector).show(); // Update the global variable that keeps track of which deelplan is selected currentDeelplanId = $(this).val(); }); </script> <file_sep><?php class Woborg { private $CI; public function __construct() { $this->CI = get_instance(); // $this->CI->load->library( 'pdfannotatorlib' ); $this->CI->load->model( 'btbtzdossier' ); } public function run(){ $this->_create_deelplan_checklist_toezichtmomenten(); } private function _create_deelplan_checklist_toezichtmomenten(){ $dossiers = $this->CI->btbtzdossier->get_by_verwerkt(); echo "count: ".count($dossiers); } } <file_sep><?php class ZoekInstelling extends Model { private $_CI; private $_cache = array(); public function __construct() { parent::__construct(); $this->_CI = get_instance(); } private function _get_gebruiker() { return $this->_CI->gebruiker->get( $this->login->get_user_id() ); } function get( $pagina ) { if (!($gebruiker = $this->_get_gebruiker())) return null; if (!isset( $this->_cache[$gebruiker->id][$pagina] )) { if (!isset( $this->_cache[$gebruiker->id] )) $this->_cache[$gebruiker->id] = array(); $stmt_name = 'ZoekInstelling::get'; $this->_CI->dbex->prepare( $stmt_name, 'SELECT instellingen FROM zoek_instellingen WHERE gebruiker_id = ? AND pagina = ?' ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $gebruiker->id, $pagina ) ))) throw new Exception( 'Fout bij ophalen zoekinstellingen' ); if ($res->num_rows()) { $rows = $res->result(); $instellingen = @unserialize( reset( $rows )->instellingen ); // !!! For some extremely bizarre reason the text 'images' is often erroneously set in the 'search' field. It is not yet known where this comes from // exactly, but it caused a lot of complaints. Until the true source is found, we therefore simply replace that precise text by an empty string so the // search functionality is not accidentally filtered by the presence of the text 'images'. if ($instellingen['search'] == 'images') { $instellingen['search'] = ''; } } else $instellingen = null; $this->_cache[$gebruiker->id][$pagina] = $instellingen; } return $this->_cache[$gebruiker->id][$pagina]; } function set( $pagina, $instellingen ) { if (!($gebruiker = $this->_get_gebruiker())) return null; $this->_cache[$gebruiker->id][$pagina] = $instellingen; $stmt_name = 'ZoekInstelling::set'; //$this->_CI->dbex->prepare( $stmt_name, 'REPLACE INTO zoek_instellingen (gebruiker_id, pagina, instellingen) VALUES (?, ?, ?)' ); $this->_CI->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO zoek_instellingen (gebruiker_id, pagina, instellingen) VALUES (?, ?, ?)', null, array('gebruiker_id','pagina') ); if (!$this->_CI->dbex->execute( $stmt_name, array( $gebruiker->id, $pagina, serialize( $instellingen ) ) )) throw new Exception( 'Fout bij opslaan zoekinstellingen' ); } } <file_sep>ALTER TABLE klanten ADD COLUMN vragen_alleen_voor_betrokkenen_tonen INT DEFAULT 0;<file_sep><?php // we keep track of nokia maps usage, since we're not sure if we're doing things the right way function registreer_nokia_maps_gebruik() { $jaar = date('Y'); $maand = date('m'); // try insert, if this works, we're the first this month! $CI = get_instance(); try { $stmt_name = 'registreer_nokia_maps_gebruik'; $CI->dbex->prepare( $stmt_name, "INSERT INTO stats_nokia_maps (jaar, maand, aantal) VALUES (?, ?, 1)" ); if ($CI->dbex->execute( $stmt_name, array( $jaar, $maand ), true )) return; } catch (Exception $e) { // failed, move on } // failed? then update! $CI->db->query( "UPDATE stats_nokia_maps SET aantal = aantal + 1 WHERE jaar = $jaar AND maand = $maand" ); if ($CI->db->affected_rows() != 1) throw new Exception( 'Fout bij NM registratie.' ); } <file_sep><?php class CleanupVerlopenTokens { private $CI; public function __construct() { $this->CI = get_instance(); } public function run() { $res = $this->CI->db->query( 'SELECT * FROM sessies' ); echo sprintf( "Got %d sessions to verify\n", $res->num_rows() ); $this->CI->load->library( 'kennisid' ); foreach ($res->result() as $row) { try { echo sprintf( "Examining session: %s\n", $row->session_id ); if (preg_match( '/KennisID-token\|s:\d+:"(.*?)";/', $row->data, $matches )) { // als deze sessie al op force validation staat, hoeven we niets meer te doen if (!preg_match( '/force_validation\|b:1;/', $row->data )) { $token = $matches[1]; echo "...kennisid token: $token\n"; if (!$this->CI->kennisid->validate_token( $token )) { echo "...no longer valid\n"; $row->data = preg_replace( '/force_validation\|b:\d+;/', 'force_validation|b:1;', $row->data ); $this->CI->db->set( 'data', $row->data ); $this->CI->db->where( 'session_id', $row->session_id ); $this->CI->db->update( 'sessies' ); echo "...forced validation\n"; } else echo "...validated\n"; } else echo "...already set to force validation\n"; } else throw new Exception( 'failed to extract token from session data' ); } catch (Exception $e) { echo "...error: " . $e->getMessage() . "\n"; } } } } <file_sep>SET @klant_name = '<NAME>'; --SET @klant_id = (SELECT COALESCE(id, 219) FROM klanten WHERE naam = '<NAME>'); SET @klant_id = (SELECT COALESCE(id, NULL) FROM klanten WHERE naam = @klant_name); REPLACE INTO klanten SET id = @klant_id, kennis_id_unique_id = 'bpo2f9fef37-5524-463d-af75-b9908245723b', status = 'geaccepteerd', naam = @klant_name, volledige_naam = @klant_name; -- In case the 'klant' record didn't exist yet, the @klant_id would still be NULL, so select it back now. SET @klant_id = (SELECT COALESCE(id, NULL) FROM klanten WHERE naam = @klant_name); -- Register the Woningborg webservice in the DB and create a webuser for it REPLACE INTO webservice_applicaties SET id = 7, naam = 'Woningborg', actief = 1; REPLACE INTO webservice_accounts SET webservice_applicatie_id = 7, omschrijving = 'Woningborg', gebruikersnaam = 'WB_woningborg_usr', wachtwoord = SHA1('WB_woningborg_pwd'), actief = 1, alle_klanten = 1, alle_components = 1, klant_id = @klant_id; -- Create a dummy user for associating new dossiers that are not assigned to. INSERT INTO gebruikers SET klant_id = @klant_id, gebruikersnaam = 'nog_niet_toegewezen', wachtwoord = SHA1('%^#$*$^%^%^^%'), volledige_naam = 'Nog Niet Toegewezen', status = 'geblokkeerd'; <file_sep><table width="100%"> <tr> <span style="font-size:18pt; font-weight: bold">{<?=$string?>}</span><br/> <br/> </tr> <tr> <td>Tekst:</td> </tr> <tr> <td><input type="text" name="tekst" style="width: 400px" value="<?=htmlentities( $tekst, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <tr> <td><input type="button" value="Opslaan" /></td> </tr> </table> <script type="text/javascript"> var popup = getPopup(); var input = popup.find( '[name=tekst]' ); var btn = popup.find( '[type=button]' ); input.focus(); input.keydown(function(evt){ if (evt.keyCode == 13) btn.trigger( 'click' ); }); btn.click(function(){ var tekst = input.val(); $.ajax({ url: '/admin/inline_edit/<?=$string?>', type: 'POST', data: { tekst: tekst }, dataType: 'text', success: function( data ) { if (data != '1') alert( 'Foutmelding:\n\n' + data ); else closePopup( tekst ); }, error: function() { alert( 'Er is iets fouts gegaan bij het opslaan. Is uw sessie verlopen?' ); } }); }); </script><file_sep><? $map_view=true;$this->load->view('elements/header', array('page_header'=>null,'map_view'=>true));?> <? $this->load->view( 'elements/laf-blocks/generic-bar', array( 'header' => tg( 'mapping.header' )));?> <div class="main"> <?php $bt_base_url = $this->config->item('bt_base_url'); $bt_pm_url = "{$bt_base_url}/dossier/view/id/{$bt_dossier_id}/tab/pm"; ?> <input type="button" value="<?=tgn('projectmatrix')?>" onclick="openInNewTab('<?=$bt_pm_url?>')" /> <?=htag('projectmatrix')?> <table cellspacing="0" cellpadding="0" border="0" class="list double-list"> <thead> <tr> <th> <ul class="list"> <li class="top left right tbl-titles bt-side"><?=tgg('project_specifieke_mapping.tabletitles.bristoets')?></li> </ul> </th> <th>&nbsp;</th> <th> <table cellspacing="0" cellpadding="0" border="0" class="vragen-titles"> <tr> <td class="main-title"><?=tgg('project_specifieke_mapping.tabletitles.bristoezicht')?></td> <td class="params-title"><?=tgg('project_specifieke_mapping.tabletitles.bouwnr')?></td> <td class="params-title"><?=tgg('project_specifieke_mapping.tabletitles.toezmom')?></td> <td class="params-title"><?=tgg('project_specifieke_mapping.tabletitles.bw')?></td> </tr> </table> </th> </tr> </thead> <tbody> <tr> <td class="double-list-td"> <? foreach( $bt_project_matrix['afdelingen'] as $i=>$afdeling): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => htmlentities( $afdeling['naam'], ENT_COMPAT, 'UTF-8' ), 'expanded' => TRUE, 'group_tag' => 'afdelingen', 'width' => '100%', 'height' => (25*$afdeling['count']).'px' )); ?> <table cellspacing="0" cellpadding="0" border="0" class="bt-proj-matrix"> <? foreach( $afdeling['artikelen'] as $i=>$artikel ): switch( $artikel['status'] ){ case 'P': $css_status='status-p';break; case 'S': $css_status='status-s';break; default: $css_status='status-d'; } $no_btt_line = ($afdeling['count']-1) == $i ? 'no-bottom-line' : ''; ?> <tr> <td class="status <?=$css_status.' '.$no_btt_line?>"><?=$artikel['status'] ?></td> <td class="artikel-naam <?=$no_btt_line?>"><?=$artikel['naam'] ?></td> <td class="artikel-beschrijving <?=$no_btt_line?>"><?=$artikel['beschrijving'] ?></td> </tr> <? endforeach; ?> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> </td> <td class="middle">&nbsp;</td> <td id="toezichtpunten_td"></td> </tr> </tbody> </table> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> function openInNewTab(url) { //alert('Opening URL: ' + url); var win = window.open(url, '_blank'); win.focus(); } function showToezichtpunten(){ $.ajax({ url: "<?=site_url('mappingen/show_project_toezichtpunten').'/'.$deelplan_id?>", type: 'POST', data: {}, dataType: 'html', success: function( view ) { $("#toezichtpunten_td").html( view ); }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); } function addBristoezicht(prVraagId){ showMessageBox({ message: "<?=tgg('project_specifieke_mapping.warning.change_vraag_status')."<br /><br />".tgg('project_specifieke_mapping.warning.change_vraag_status_confirm')?>", type: "warning", buttons: ["yes","no"], onClose: function( res ) { if(res=='yes'){ $.ajax({ url: "<?=site_url('mappingen/add_project_bristoezicht').'/'?>"+prVraagId, type: "POST", data: null, dataType: "json", success: function( data ){ showToezichtpunten(); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } } }); } function changeBW( prVraagId ){ showMessageBox({ message: "U staat op het punt het bijwoonmoment te activeren. Deze actie kan niet ongedaan gemaakt worden. Weet u zeker dat u door wilt gaan?", type: "warning", buttons: ["yes","no"], onClose: function( res ) { if(res=='yes'){ $.ajax({ url: "<?=site_url('mappingen/change_project_bw').'/'?>"+prVraagId, type: "POST", data: null, dataType: "json", success: function( data ){ showToezichtpunten(); }, error: function() { showMessageBox({ message: "System error while BW status changing.", type: "error", buttons: ["ok"] }); } }); } } }); } $(document).ready(function(){ showToezichtpunten(); }); </script><file_sep><? require_once 'base.php'; class GebruikerChecklistgroep extends Model { private $_cache; public function __construct() { parent::__construct(); $this->CI = get_instance(); $result = array(); $res = $this->CI->db->query( 'SELECT * FROM gebruiker_checklist_groepen' ); foreach ($res->result() as $row) { if (!isset( $result[$row->gebruiker_id] )) $result[$row->gebruiker_id] = array(); $result[$row->gebruiker_id][] = $row->checklist_groep_id; } $res->free_result(); $this->_cache = $result; } public function all() { return $this->_cache; } public function get_for_user( $gebruiker_id ) { return $this->_cache[$gebruiker_id]; } /** Replaces data as given in array for all gebruiker-ids! */ public function replace( array $data ) /* data structured like returned from all() */ { if (empty( $data )) return; $gebruiker_ids = array_keys( $data ); $this->CI->db->query( 'DELETE FROM gebruiker_checklist_groepen WHERE gebruiker_id IN (' . implode( ',', $gebruiker_ids ) . ')' ); foreach ($data as $gebruiker_id => $checklist_groep_ids) foreach ($checklist_groep_ids as $checklist_groep_id) $this->CI->db->query( 'INSERT INTO gebruiker_checklist_groepen (gebruiker_id, checklist_groep_id) VALUES (' . intval($gebruiker_id) . ',' . intval($checklist_groep_id) . ')' ); } /** Adds a single entry, does not fail when entry already exists */ public function add( $gebruiker_id, $checklist_groep_id ) { // !!! Make an Oracle compatible implementation; if possible using the standard DBEX prepared version !!! $this->CI->db->query( 'REPLACE INTO gebruiker_checklist_groepen (gebruiker_id, checklist_groep_id) VALUES (' . intval($gebruiker_id) . ',' . intval($checklist_groep_id) . ')' ); } } <file_sep>PDFAnnotator.GUI.Menu.ImageList = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( menu, config ) { /* setup */ this._super( menu ); this.container = config.container; // dom this.currentImage = config.currentImage; // dom this.selectedImage = null; // data object /* handle clicking events in the DOM */ var thiz = this; this.container.find('div[id]').click(function(){ if ($(this).hasClass( 'Expanded' )) thiz.closeSubGroup( $(this) ); else thiz.showSubGroup( $(this) ); }); this.container.find('div[image]').click(function(){ thiz.selectImage( $(this) ); }); }, showSubGroup: function( dir ) { dir.removeClass( 'Collapsed' ); dir.addClass( 'Expanded' ); this.container.find('div[belongsto=' + dir.attr('id') + ']').slideDown(); }, closeSubGroup: function( dir ) { var children = this.container.find('div[belongsto=' + dir.attr('id') + ']'); dir.removeClass( 'Expanded' ); dir.addClass( 'Collapsed' ); var thiz = this; var recurse = function( coll ) { coll.slideUp(); coll.each( function(){ thiz.closeSubGroup( $(this) ); }); }; recurse( children ); }, selectImage: function( imageDiv ) { this.selectedImage = { dimensions: new PDFAnnotator.Math.IntVector2( imageDiv.attr('image_width'), imageDiv.attr('image_height') ), src: imageDiv.attr('image') }; this.currentImage.attr( 'src', this.selectedImage.src ); this.currentImage.show(); }, getCurrentImageDimensions: function() { return this.selectedImage ? this.selectedImage.dimensions : null; }, getCurrentImageSrc: function() { return this.selectedImage ? this.selectedImage.src : null; } }); <file_sep>BRISToezicht.List = { shouldToggle: function(row) { return true; }, lists: [], // jQuery collection 0+ objects initialize: function() { // find all lists this.lists = $('.list'); if (!this.lists.size()) return; // per list, find all collapsed rows, and close their children this.lists.find('.row.collapsed').each(function(){ $(this).parents('.rows').find('div[parent="'+this.id+'"]').addClass( 'hidden' ); }); // install click handlers var thiz = this; this.lists.find('.row.haschildren').click(function(){ if (!thiz.shouldToggle( this )) return; var currentlyCollapsed = $(this).hasClass( 'collapsed' ); $(this).parents('.rows').find('div[parent="'+this.id+'"]')[currentlyCollapsed?'removeClass':'addClass']( 'hidden' ); $(this)[currentlyCollapsed?'removeClass':'addClass']( 'collapsed' ); }); } }; <file_sep>ALTER TABLE dossiers ADD COLUMN correspondentie_adres VARCHAR(255) DEFAULT NULL AFTER dossier_hash; ALTER TABLE dossiers ADD COLUMN correspondentie_postcode VARCHAR(6) DEFAULT NULL AFTER correspondentie_adres; ALTER TABLE dossiers ADD COLUMN correspondentie_plaats VARCHAR(128) DEFAULT NULL AFTER correspondentie_postcode; ALTER TABLE dossier_subjecten ADD COLUMN mobiel VARCHAR(16) DEFAULT NULL AFTER gebruiker_id; REPLACE INTO `teksten` SET `string`='dossier.correspondentie_postcode', `tekst`='Correspondentie postcode / plaats'; REPLACE INTO `teksten` SET `string`='dossier.correspondentie_adres', `tekst`='Correspondentie adres '; REPLACE INTO `teksten` SET `string`='dossiers.bewerken::mobiel', `tekst`='Mobiel'; REPLACE INTO `teksten` SET `string`='dossiers.subject_bewerken::mobiel', `tekst`='Mobiel'; <file_sep><? require_once 'base.php'; class SjabloonResult extends BaseResult { private $_checklisten = null; function SjabloonResult( &$arr ) { parent::BaseResult( 'sjabloon', $arr ); } function get_checklisten() { if (is_null( $this->_checklisten )) { $this->_checklisten = array(); $this->_CI->load->model( 'checklist' ); if (!($res = $this->_CI->db->query( 'SELECT cl.* FROM sjabloon_checklisten scl JOIN bt_checklisten cl ON scl.checklist_id = cl.id WHERE scl.sjabloon_id = ' . intval( $this->id ) ))) throw new Exception( 'Fout bij ophalen van sjabloon inhoud.' ); $this->_checklisten = $this->_CI->checklist->convert_results( $res ); } return $this->_checklisten; } function set_checklisten( array $checklisten ) { $this->_checklisten = null; // refetch $this->_CI->db->trans_start(); $this->_CI->db->query( 'DELETE FROM sjabloon_checklisten WHERE sjabloon_id = ' . intval($this->id) ); foreach ($checklisten as $checklist) $this->_CI->db->query( sprintf( 'INSERT INTO sjabloon_checklisten (sjabloon_id, checklist_groep_id, checklist_id) VALUES (%d, %d, %d)', intval($this->id), intval($checklist->checklist_groep_id), intval($checklist->checklist_id) ) ); if (!$this->_CI->db->trans_complete()) throw new Exception( 'Fout bij opslaan van sjabloon inhoud.' ); } function is_leeg() { return !sizeof($this->get_checklisten()); } } class Sjabloon extends BaseModel { function Sjabloon() { parent::BaseModel( 'SjabloonResult', 'sjablonen' ); } public function check_access( BaseResult $object ) { // } function add( $naam, $klant_id=null ) { if (!$klant_id) $klant_id = get_instance()->session->userdata('kid'); /* if (!$this->dbex->is_prepared( 'add_sjablonen' )) $this->dbex->prepare( 'add_sjablonen', 'INSERT INTO sjablonen (klant_id, naam) VALUES (?, ?)' ); $args = array( 'klant_id' => $klant_id, 'naam' => $naam, ); $this->dbex->execute( 'add_sjablonen', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $data = array_merge( array( 'id' => $id ), $args ); return new $this->_model_class( $data ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'klant_id' => $klant_id, 'naam' => $naam, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function get_sjablonen_voor_klant( $klant_id=null, $search=null ) { if ($klant_id) $query = 'klant_id = ' . intval($klant_id) . ''; else $query = 'klant_id IS NULL'; if ($search) $query .= ' AND naam LIKE \'%' . $this->get_db()->escape_str( $search ) . '\''; return $this->search( array(), $query, false, 'AND', 'naam' ); } function get_sjabloon_gebruik() /* voor het gemak over alle sjablonen, resultaat is id => aantal */ { $res = $this->db->query( 'SELECT COUNT(*) AS count, sjabloon_id FROM deelplannen WHERE sjabloon_id IS NOT NULL GROUP BY sjabloon_id' ); $result = array(); foreach ($res->result() as $row) $result[$row->sjabloon_id] = $row->count; $res->free_result(); return $result; } } <file_sep><? if ($object instanceof Model) { $modelname = strtolower(get_class($object)); $fields = call_user_func( $modelname . 'result::get_edit_fields' ); $object = null; $editname = $modelname; } else { $modelname = strtolower(get_class($object->get_model())); $editname = $object->get_edit_name(); $fields = $object->get_edit_fields(); } ?> <? $this->load->view('elements/header', array('page_header'=>$header)); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tgg( strtolower( 'editor.' . $editname ) ), 'width' => '920px' )); ?> <form id="gubriuk_form" method="post" enctype="multipart/form-data"> <input type="hidden" name="__referer" value="<?=rawurlencode($referer)?>" /> <input type="hidden" name="__save" value="1"> <table> <? foreach ($fields as $field): ?> <? $is_primary = isset($field['flags']) && array_search( 'primary', $field['flags'] )!==FALSE; ?> <? if ($is_primary) continue; ?> <tr> <td><?=tgg( strtolower(preg_replace( '/Result$/', '', $modelname)) . '.' . $field['fieldname'] )?></td> <td> <? if ($field['type']=='text'): ?> <input type="text" name="<?=$field['fieldname']?>" size="<?=$field['textsize']?>" value="<?=$field['value']?>"> <? elseif ($field['type']=='text_read_only'): ?> <?=$field['value']?> <? elseif ($field['type']=='upload'): ?> <input type="file" name="<?=$field['fieldname']?>" > <? if ($field['curfilename']): ?> <br/><i>Huidig bestand: <b><?=htmlentities( $field['curfilename'], ENT_COMPAT, 'UTF-8' )?></b></i> <? endif; ?> <? elseif ($field['type']=='enum'): ?> <select name="<?=$field['fieldname']?>"> <? foreach ($field['values'] as $k=>$v): ?> <option <?=$k==$field['value']?'selected ':''?>value="<?=$k?>"><?=$v?></option> <? endforeach; ?> </select> <? elseif ($field['type']=='select'): ?> <select name="<?=$field['fieldname']?>"> <? $idfield = $field['model']->get_id_field(); ?> <? if (array_search( 'select-null-option', $field['flags'] )!==FALSE): ?> <option <?=null==$field['value']?'selected ':''?>value="__NULL__"></option> <? endif; ?> <? $filterfunc = is_callable( @$field['filter_func'] ) ? $field['filter_func'] : null; ?> <? foreach ($field['model']->{$field['select_func']}() as $v): ?> <? $k = $v->$idfield; ?> <? if (!$filterfunc || $filterfunc( $v )): ?> <option <?=$k==$field['value']?'selected ':''?>value="<?=$k?>"><?=$v->to_string()?></option> <? endif; ?> <? endforeach; ?> </select> <? endif; ?> </td> <td> <?=htag( $modelname . '.' . $field['name'] )?> </td> </tr> <? endforeach; ?> <tr> <td></td> <td> <input type="button" id="gebruker_save" name="__save" value="<?=tgng('form.opslaan')?>" /> <input type="button" value="<?=tgng('form.annuleren')?>" onclick="location.href ='/instellingen/gebruikers/'" /> </td> </tr> </table> </form> <script> $("#gebruker_save").click(function(e){ var status=$("select[name='status']").val(); if(status=="geblokkeerd"){ e.preventDefault(); showMessageBox({ //message: "LET OP! U staat op het punt de toegangsrechten van een gebruiker te ontnemen. Deze keus kan niet ongedaan gemaakt worden.", message : "<?php print tg("doorgaan_warning_message");?>", buttons: ['doorgaan', 'cancel'], type: 'warning', onClose: function( res ) { if (res == 'doorgaan') $("#gubriuk_form").submit(); } }); } else $("#gubriuk_form").submit(); }); $('select[name="email_question_notification"]').change(function() { if( this.value == 1 ) { $('select[name="letter"]').parents().eq(1).show(); } else { $('select[name="letter"]').parents().eq(1).hide(); } }).trigger('change'); </script> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.hoofdgroepen')?></h1> <? $this->load->view( 'checklistwizard/_lijst', array( 'entries' => $hoofdgroepen, 'get_id' => function( $hg ) { return $hg->id; }, 'get_image' => function( $hg ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $hg ) { return $hg->naam; }, 'delete_url' => '/checklistwizard/hoofdgroep_verwijderen', 'add_url' => '/checklistwizard/hoofdgroep_toevoegen/' . $checklist->id, 'add_uitgebreid_url' => '/checklistwizard/hoofdgroep_uitgebreid_toevoegen/' . $checklist->id, 'copy_url' => '/checklistwizard/hoofdgroep_kopieren', 'defaults_url' => '/checklistwizard/hoofdgroep_bewerken', ) ); ?> <div class="button"> <a href="<?=site_url('/checklistwizard/hoofdgroep_volgorde/' . $checklist->id)?>">Wijzig volgorde</a> </div> <?=htag('wijzig-volgorde')?> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = '<?=site_url('/checklistwizard/vragen/')?>/' + $(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? if (!isset( $width )) $width = '200px'; if (!isset( $proc )) $proc = '25'; if (!isset( $extra_class )) $extra_class = ''; ?> <div class="progressbar rounded10 <?=$extra_class?>" style="width:<?=$width?>; height: 12px; background: #ffffff url(/files/images/pbbackground.png) repeat-x left top; padding: 1px; margin: 0px; text-align: left; border: 0px; vertical-align: middle; "> <div class="progress rounded10" style="width:<?=$proc?>%; background: #ffffff url(/files/images/pbbarbackground.png) repeat-x left top; height: 11px; padding: 0px; margin: 0px; border: 0px; z-index: 1000"></div> </div><file_sep>INSERT INTO `webservice_components` (`id`,`naam`) VALUES (NULL , 'Spotdog koppeling'); <file_sep>#Create new teksten for opdrachtenoverzicht REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('deelplannen.opdrachtenoverzicht::omschrijving', 'Omschrijving', NOW(), 0), ('deelplannen.opdrachtenoverzicht::omschrijving', 'Omschrijving', NOW(), 1), ('deelplannen.opdrachtenoverzicht::bouwnummer', 'Bouwnummer', NOW(), 0), ('deelplannen.opdrachtenoverzicht::bouwnummer', 'Bouwnummer', NOW(), 1), ('deelplannen.opdrachtenoverzicht::gereeddatum', 'Datum', NOW(), 0), ('deelplannen.opdrachtenoverzicht::gereeddatum', 'Datum', NOW(), 1), ('deelplannen.opdrachtenoverzicht::status', 'Status', NOW(), 0), ('deelplannen.opdrachtenoverzicht::status', 'Status', NOW(), 1), ('deelplannen.opdrachtenoverzicht::statusopdrachtgever', 'WB', NOW(), 0), ('deelplannen.opdrachtenoverzicht::statusopdrachtgever', 'WB', NOW(), 1), ('deelplannen.opdrachtenoverzicht::statusopdrachtnemer', 'Uitv', NOW(), 0), ('deelplannen.opdrachtenoverzicht::statusopdrachtnemer', 'Uitv', NOW(), 1), ('deelplannen.opdrachtenoverzicht::opdrachtgever', 'Opdrachtgever', NOW(), 0), ('deelplannen.opdrachtenoverzicht::opdrachtgever', 'Opdrachtgever', NOW(), 1), ('deelplannen.opdrachtenoverzicht::opdrachtnemer', 'Opdrachtnemer', NOW(), 0), ('deelplannen.opdrachtenoverzicht::opdrachtnemer', 'Opdrachtnemer', NOW(), 1), ('deelplannen.opdrachtenoverzicht::annotatie', 'Annotatie', NOW(), 0), ('deelplannen.opdrachtenoverzicht::annotatie', 'Annotatie', NOW(), 1);<file_sep>CREATE TABLE IF NOT EXISTS `deelplan_opdrachten_uploads` ( `id` int(11) NOT NULL AUTO_INCREMENT, `opdracht_id` int(11) NOT NULL, `upload_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uk__opdracht_upload` (`opdracht_id`,`upload_id`), CONSTRAINT `fk_deelplan_opdrachten_uploads_upload` FOREIGN KEY (`upload_id`) REFERENCES `deelplan_uploads` (`id`) , CONSTRAINT `fk_deelplan_opdrachten_uploads_opdracht` FOREIGN KEY (`opdracht_id`) REFERENCES `deelplan_opdrachten` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 <file_sep><?php /** * This code is (c) Copyright Marc 'Foddex' <NAME> <<EMAIL>> */ class Dumper { private function _foreach( $value, $depth, $depth_left, $strip=false ) { if ($depth_left) { $indent = str_repeat( ' ', $depth * 2 ); $indent1 = str_repeat( ' ', (1 + $depth) * 2 ); echo "\n"; foreach ($value as $k => $v) { if ($strip) $k = preg_replace( '/^\x00(.*?)\x00/', '$1::', $k ); echo $indent1; $this->dump( $k, 0, 0 ); // depths not used for non-arrays/objects echo ' => '; $this->dump( $v, $depth + 1, $depth_left-1 ); echo "\n"; } echo $indent; } else echo ' ... '; } public function dump( $value, $depth, $depth_left ) { if (is_null( $value )) echo 'null'; else if (is_bool( $value )) echo $value ? 'true' : 'false'; else if (is_object( $value )) { $CI = get_instance(); if ($value==$CI) echo '<<< CodeIgniter controller >>>'; else if ($value instanceof Model) echo '<<< ' . $value->get_model_name() . ' model >>>'; else if (preg_match( '/^CI_(.*?)$/', get_class( $value ), $matches )) echo '<<< ' . $matches[1] . ' library >>>'; else { echo 'object (' . get_class($value) . ') {'; $this->_foreach( (array)$value, $depth, $depth_left, true ); echo '}'; } } else if (is_array( $value )) { echo 'array ['; $this->_foreach( $value, $depth, $depth_left ); echo ']'; } else if (is_string( $value )) { if (strlen( $value ) < 1024) echo '\'' . $value . '\''; else if (ctype_print( $value )) echo '\'' . substr( $value, 0, 1024 ) . '...\''; else echo '[binary data with size ' . strlen($value) . ']'; } else echo $value; } } function dump( $value, $max_depth=4 ) { static $dumper = null; if (!$dumper) $dumper = new Dumper(); if (!IS_CLI) echo '<pre style="background-color:white;border:1px solid black;padding:10px;font-size:9pt;">'; $dumper->dump( $value, 0, $max_depth ); if (!IS_CLI) echo '</pre>'; else echo "\n"; } function vdf($var,$kuda='/tmp/vdf.txt') { if(!empty($var)){ ob_start(); print_r($var); $result = ob_get_clean(); file_put_contents($kuda,$result); } } function vdfa($var,$kuda='vdf.txt') { if(!empty($var)){ ob_start(); print_r($var); $result = ob_get_clean(); file_put_contents($kuda,$result.PHP_EOL,FILE_APPEND); } } function vd($array,$type_result=false){ $array=(array)$array; foreach ($array as $key=>$value){ if($type_result){ if(!is_array($value)){ echo $key.' =>'.$value."<hr>";}else{ echo $key.' => Array <hr>'; } }else{ echo $key."<hr>"; } } } function sql_dump_role($data){ $query="INSERT INTO rollen (klant_id,naam,gemaakt_door_gebruiker_id) VALUES (".$data['klant_id'].",'".$data['naam']."',1);"; vdfa($query); } function sql_dump_rules($rol_id, $recht, $modus){ $query="REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (".$rol_id.",".$recht.",".$modus.");"; vdfa($query); } <file_sep><?php define( 'COL_CHECKLISTGROEP', 0 ); define( 'COL_CHECKLIST', 1 ); define( 'COL_HOOFDGROEP', 2 ); define( 'COL_CATEGORIE', 3 ); define( 'COL_VRAAG', 4 ); define( 'COL_PRIO_S', 5 ); define( 'COL_PRIO_1', 6 ); define( 'COL_PRIO_2', 7 ); define( 'COL_PRIO_3', 8 ); define( 'COL_PRIO_4', 9 ); define( 'COL_HOOFDTHEMA', 10 ); define( 'COL_THEMA', 11 ); define( 'COL_RICHTLIJN', 12 ); define( 'COL_AANDACHTSPUNT', 13 ); define( 'COL_GRONDSLAG_1', 14 ); define( 'COL_ARTIKEL_1', 15 ); define( 'COL_TOEZICHTMOMENT', 16 ); define( 'COL_FASE', 17 ); define( 'COL_VERANTWOORDINGSTEKSTEN', 18); define( 'COL_BIJ_STATUS', 19); define( 'COL_VGGM_VERANTWOORDINGSTEKSTEN', 20); define( 'COL_WO_TEKST_00', 21); define( 'COL_WO_TEKST_10', 22); define( 'COL_WO_TEKST_20', 23); define( 'COL_WO_TEKST_01', 24); define('COL_OPDRACHTEN', 25); define( 'COL_MAX_COLUMN', COL_OPDRACHTEN ); class CI_ChecklistImport { public function create( $csvfile, $klant_id, $file_encoding='ISO-8859-1' ) { return new ChecklistImport( $csvfile, $klant_id, $file_encoding ); } } class ChecklistImport { private $CI; private $csvfile; private $counts = array(); private $klant_id; private $file_encoding; private $speciale_tekens_teksten = array(); private $queries = array(); public function __construct( $csvfile, $klant_id, $file_encoding ) { $this->CI = get_instance(); $this->csvfile = $csvfile; $this->klant_id = intval( $klant_id ); $this->file_encoding = $file_encoding; } private function _detect_delimiter( $fd ) { // try to determine delimiter $num = array(); foreach (array( ',', ';', "\t" ) as $delim) { $row = fgetcsv( $fd, 1024, $delim ); $num[$delim] = is_array( $row ) ? sizeof($row) : 0; fseek( $fd, 0, SEEK_SET ); } $max = 0; $delimiter = null; foreach ($num as $delim => $actualnum) if ($actualnum > 1 && $actualnum > $max) { $max = $actualnum; $delimiter = $delim; } if (is_null( $delimiter )) throw new Exception( 'Kon scheidingsteken voor kolommen niet bepalen.' ); return $delimiter; } public function get_queries() { return $this->queries; } private function _exec_query( $query, $message=null ) { $this->queries[] = $query; $this->CI->db->db_debug = false; if (!$this->CI->db->query( $query )) { throw new Exception( $message ? $message : ('Failed to execute query: ' . $query . ' (error: ' . $this->CI->db->_error_message() . ')' ) ); } $this->CI->db->db_debug = true; } public function run() { $this->_exec_query( 'SET @KLANT_ID = ' . $this->klant_id . ';' ); $this->counts = array( 'checklistgroepen' => 0, 'checklisten' => 0, 'hoofdgroepen' => 0, 'categorieen' => 0, 'vragen' => 0, 'hoofdthemas' => 0, 'themas' => 0, 'grondslagen' => 0, 'artikelen' => 0, 'verantwoordingsteksten' => 0, 'bij_status'=> 0, ); $this->speciale_tekens_teksten = array(); $richtlijnen = array(); $checklistgroepen = array(); $hoofdthemas = array(); $themas = array(); $grondslagen = array(); $checklist_teller = 0; $hoofdgroep_teller = 0; $categorie_teller = 0; $vrrag_teller = 0; $artikel_teller = 0; /************************************ * LEES CSV FILE * ************************************/ $fd = fopen( $this->csvfile, 'r' ); if (!$fd) throw new Exception( 'Kon csv bestand niet openen, interne fout.' ); $delim = $this->_detect_delimiter( $fd ); $regel = 0; while ($row = fgetcsv( $fd, 0, $delim )) { // skip 1e regel ++$regel; if ($regel == 1) continue; // converteer alles naar UTF-8 foreach ($row as $i => $element) { $row[$i] = iconv( $this->file_encoding, 'UTF-8', $element ); if (strlen($element) && !strlen($row[$i])) throw new Exception( 'Encoding fout: "' . $element . '" is nu "' . $row[$i] . '"' ); if ($element != $row[$i]) $this->speciale_tekens_teksten[] = $row[$i]; } if (sizeof($row) <= COL_MAX_COLUMN) throw new Exception( 'Verwachtte ' . (COL_MAX_COLUMN+1) . ' kolommen, maar vond er maar ' . sizeof($row) . ' op regel ' . $regel ); // Determine which "null function" should be used $null_func = get_db_null_function(); // checklistgroep if (!($checklistgroep = $row[COL_CHECKLISTGROEP])) throw new Exception( 'Lege checklistgroep op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep] )) { $j = sizeof($checklistgroepen); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_exec_query( 'SET @SORTERING = (SELECT '.$null_func.'(MAX(sortering),0)+1 FROM bt_checklist_groepen WHERE klant_id = @KLANT_ID);' ); $this->_exec_query( 'INSERT INTO bt_checklist_groepen (klant_id, naam, modus, themas_automatisch_selecteren, sortering) VALUES (@KLANT_ID, \'' . $this->CI->db->escape_str($checklistgroep) . '\', \'niet-combineerbaar\', 0, @SORTERING);' ); $this->_exec_query( 'SET @CHECKLISTGROEP' . $j . ' = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep] = array( 'index' => $j, 'checklisten' => array(), ); $this->counts['checklistgroepen']++; } // checklist if (!($checklist = $row[COL_CHECKLIST])) throw new Exception( 'Lege checklist op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist] )) { $j = $checklist_teller++; $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten']); $this->_exec_query( 'INSERT INTO bt_checklisten (checklist_groep_id, naam, status, sortering, beschikbaarheid) VALUES (@CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] . ', \'' . $this->CI->db->escape_str($checklist) . '\', \'afgerond\', ' . $sortering . ', \'publiek-voor-iedereen\');' ); $this->_exec_query( 'SET @CHECKLIST' . $j . ' = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist] = array( 'index' => $j, 'hoofdgroepen' => array(), ); $this->counts['checklisten']++; } // hoofdgroep if (!($hoofdgroep = $row[COL_HOOFDGROEP])) throw new Exception( 'Lege hoofdgroep op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep] )) { $j = $hoofdgroep_teller++; $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen']); $this->_exec_query( 'INSERT INTO bt_hoofdgroepen (checklist_id, naam, naam_kort, sortering) VALUES (@CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'] . ', \'' . $this->CI->db->escape_str($hoofdgroep) . '\', \'' . $this->CI->db->escape_str($hoofdgroep) . '\', ' . $sortering . ');' ); $this->_exec_query( 'SET @HOOFDGROEP' . $j . ' = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep] = array( 'index' => $j, 'categorieen' => array(), ); $this->counts['hoofdgroepen']++; } // categorie if (!($categorie = $row[COL_CATEGORIE])) throw new Exception( 'Lege categorie op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie] )) { $j = $categorie_teller++; $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen']); $this->_exec_query( 'INSERT INTO bt_categorieen (hoofdgroep_id, naam, sortering) VALUES (@HOOFDGROEP' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['index'] . ', \'' . $this->CI->db->escape_str($categorie) . '\', ' . $sortering . ');' ); $this->_exec_query( 'SET @CATEGORIE' . $j . ' = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie] = array( 'index' => $j, 'vragen' => array(), ); $this->counts['categorieen']++; } // hoofd thema if (!($hoofdthema = $row[COL_HOOFDTHEMA])) throw new Exception( 'Leeg hoofdthema op regel ' . $regel . ', niet toegestaan' ); if (!isset( $hoofdthemas[$hoofdthema] )) { $j = sizeof($hoofdthemas); $this->_exec_query( 'INSERT INTO bt_hoofdthemas (klant_id, naam) SELECT @KLANT_ID, \'' . $this->CI->db->escape_str($hoofdthema) . '\' FROM dual WHERE NOT EXISTS (SELECT * FROM bt_hoofdthemas WHERE klant_id = @KLANT_ID AND naam = \'' . $this->CI->db->escape_str($hoofdthema) . '\');' ); $this->_exec_query( 'SET @HOOFDTHEMA' . $j . ' = (SELECT id FROM bt_hoofdthemas WHERE klant_id = @KLANT_ID AND naam = \'' . $this->CI->db->escape_str($hoofdthema) . '\' LIMIT 1);' ); $hoofdthemas[$hoofdthema] = array( 'index' => $j, 'themas' => array() ); $this->counts['hoofdthemas']++; } // (sub) thema if (!($thema = $row[COL_THEMA])) throw new Exception( 'Leeg subthema op regel ' . $regel . ', niet toegestaan' ); if (!isset( $hoofdthemas[$hoofdthema]['themas'][$thema] )) { $j = sizeof($themas); $this->_exec_query( 'INSERT INTO bt_themas (klant_id, thema, hoofdthema_id) SELECT @KLANT_ID, \'' . $this->CI->db->escape_str($thema) . '\', @HOOFDTHEMA' . $hoofdthemas[$hoofdthema]['index'] . ' FROM dual WHERE NOT EXISTS (SELECT * FROM bt_themas WHERE klant_id = @KLANT_ID AND thema = \'' . $this->CI->db->escape_str($thema) . '\' AND hoofdthema_id = @HOOFDTHEMA' . $hoofdthemas[$hoofdthema]['index'] . ');' ); $this->_exec_query( 'SET @THEMA' . $j . ' = (SELECT id FROM bt_themas WHERE klant_id = @KLANT_ID AND thema = \'' . $this->CI->db->escape_str($thema) . '\' AND hoofdthema_id = @HOOFDTHEMA' . $hoofdthemas[$hoofdthema]['index'] . ' LIMIT 1);' ); $hoofdthemas[$hoofdthema]['themas'][$thema] = $j; $this->counts['themas']++; $themas[] = $thema; } if (!($vraag = $row[COL_VRAAG])) throw new Exception( 'Lege vraag op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag] )) { $toezichtmoment = @$row[COL_TOEZICHTMOMENT]; if (!$toezichtmoment) $toezichtmoment = 'Algemeen'; $fase = @$row[COL_FASE]; if (!$fase) $fase = 'Algemeen'; // aanwezigheid $aanwezigheid = 0; foreach (array( COL_PRIO_S => 0x01, COL_PRIO_1 => 0x02, COL_PRIO_2 => 0x04, COL_PRIO_3 => 0x08, COL_PRIO_4 => 0x10 ) as $col => $bits) if (strlen( $row[$col] )) $aanwezigheid |= $bits; $j = $vrrag_teller++; $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen']); $this->_exec_query( 'INSERT INTO bt_vragen (categorie_id, tekst, aanwezigheid, thema_id, sortering, toezicht_moment, fase) VALUES (@CATEGORIE' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['index'] . ', \'' . $this->CI->db->escape_str($vraag) . '\', ' . $aanwezigheid . ', @THEMA' . $hoofdthemas[$hoofdthema]['themas'][$thema] . ', ' . $sortering . ', ' . $this->CI->db->escape( $toezichtmoment ) . ', ' . $this->CI->db->escape( $fase ) . ');' ); $this->_exec_query( 'SET @VRAAG = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag] = array( 'index' => $j, 'aandachtspunt' => array(), 'verantwoordingsteksten' => array(), 'bij_status' => array(), 'vggm_verantwoordingsteksten'=> array(), 'opdrachten' => array(), ); $this->counts['vragen']++; } // vraag if (!($vraag = @$row[COL_VRAAG])) throw new Exception( 'Lege vraag op regel ' . $regel . ', niet toegestaan' ); // toezichtmoment en fase // vraag /* $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen']); $this->_exec_query( 'INSERT INTO bt_vragen (categorie_id, tekst, aanwezigheid, thema_id, sortering, toezicht_moment, fase) VALUES (@CATEGORIE' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['index'] . ', \'' . $this->CI->db->escape_str($vraag) . '\', ' . $aanwezigheid . ', @THEMA' . $hoofdthemas[$hoofdthema]['themas'][$thema] . ', ' . $sortering . ', ' . $this->CI->db->escape( $toezichtmoment ) . ', ' . $this->CI->db->escape( $fase ) . ');' ); $this->_exec_query( 'SET @VRAAG = LAST_INSERT_ID();' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][] = $j; $this->counts['vragen']++; */ // aandachtspunt? if (!($aandachtspunt = $row[COL_AANDACHTSPUNT])) throw new Exception( 'Lege aandachtspunt op regel ' . $regel . ', niet toegestaan' ); if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['aandachtspunt'][$aandachtspunt] )) { $sortering = sizeof($checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen']); $this->_exec_query( 'UPDATE bt_vragen SET gebruik_ndchtspntn = 1 WHERE id = @VRAAG;' ); $this->_exec_query( 'INSERT INTO bt_vraag_ndchtspntn (vraag_id, aandachtspunt, checklist_groep_id, checklist_id) VALUES (@VRAAG, \'' . $this->CI->db->escape_str($aandachtspunt) . '\', @CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] . ', @CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'] . ');' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['aandachtspunt'][$aandachtspunt] = array( 'index' => $j, ); } // richtlijn if ($richtlijn = @$row[COL_RICHTLIJN]) { // als er een richtlijn is opgegeven, dient deze vooraf geupload te zijn, dus we doen niks met de filename // anders dan em opzoeken in de richtlijnen tabel; als de richtlijn niet bestaat, dan zal @RICHTLIJN NULL // worden en de query dus automatisch falen $this->_exec_query( 'SET @RICHTLIJN = (SELECT id FROM bt_richtlijnen WHERE klant_id = @KLANT_ID AND filename = \'' . $this->CI->db->escape_str( $richtlijn ) . '\' LIMIT 1);' ); $this->_exec_query( 'UPDATE bt_vragen SET gebruik_rchtlnn = 1 WHERE id = @VRAAG;' ); $this->_exec_query( 'INSERT INTO bt_vraag_rchtlnn (vraag_id, richtlijn_id) VALUES (@VRAAG, @RICHTLIJN);', 'Kon richtlijn "' . $richtlijn . '" niet vinden. Is er een bestand met exact die bestandsnaam ge&uuml;pload als richtlijn?' ); } //Verantwoordingsteksten if (($verantwoordingsteksten = $row[COL_VERANTWOORDINGSTEKSTEN]) && ($bij_status = $row[COL_BIJ_STATUS])){ if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['verantwoordingsteksten'][$verantwoordingsteksten] ) || !isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['bij_status'][$bij_status] )) { $this->_exec_query( 'UPDATE bt_vragen SET gebruik_verantwtkstn = 1 WHERE id = @VRAAG;' ); $this->_exec_query( 'INSERT INTO bt_vraag_verantwtkstn (vraag_id, checklist_id, checklist_groep_id,verantwoordingstekst,status) VALUES (@VRAAG, @CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'].', @CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] .', "'.$this->CI->db->escape_str($verantwoordingsteksten).'", "'.@$row[COL_BIJ_STATUS].'");' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['verantwoordingsteksten'][$verantwoordingsteksten] = array( 'index' => $j, ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['bij_status'][$bij_status] = array( 'index' => $j, ); } } //Aggm verantwoordingsteksten if($row[COL_VGGM_VERANTWOORDINGSTEKSTEN] && ($row[COL_WO_TEKST_00] || $row[COL_WO_TEKST_10] || $row[COL_WO_TEKST_20] || $row[COL_WO_TEKST_01])) { if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['vggm_verantwoordingsteksten'][$row[COL_VGGM_VERANTWOORDINGSTEKSTEN]] )) { $this->_exec_query( 'INSERT INTO bt_vraag_verantwtkstn_automatic (vraag_id, checklist_id, checklist_groep_id,verantwoordingstekst,automatic,automatish_generate) VALUES (@VRAAG, @CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'].', @CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] .', "'.$this->CI->db->escape_str($row[COL_VGGM_VERANTWOORDINGSTEKSTEN]).'", "1",0);' ); $this->_exec_query( 'SET @VGGM = LAST_INSERT_ID();' ); $button_text=array(21=>"w00", 22 =>"w10", 23 => "w20", 24=>"w01"); for($i=COL_WO_TEKST_00; $i<=COL_WO_TEKST_01; $i++){ if(isset($row[$i]) && $row[$i]==1){ $this->_exec_query( 'INSERT INTO verantwoordingstekst_config (vraag_id, vraag_verantwtkstn_id, name) VALUES (@VRAAG, @VGGM, "'.$this->CI->db->escape_str($button_text[$i]).'")'); } } $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['vggm_verantwoordingsteksten'][$row[COL_VGGM_VERANTWOORDINGSTEKSTEN]] = array( 'index' => $j, ); } } //opdrachten if($row[COL_OPDRACHTEN]){ if (!isset( $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['opdrachten'][$row[COL_OPDRACHTEN]] )){ $this->_exec_query( 'INSERT INTO bt_vraag_opdrachten (vraag_id, checklist_groep_id, checklist_id,opdracht) VALUES (@VRAAG, @CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] .', @CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'].', "'.$this->CI->db->escape_str($row[COL_OPDRACHTEN]).'");' ); $this->_exec_query( 'UPDATE bt_vragen SET gebruik_opdrachten = 1 WHERE id = @VRAAG;' ); $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['hoofdgroepen'][$hoofdgroep]['categorieen'][$categorie]['vragen'][$vraag]['opdrachten'][$row[COL_OPDRACHTEN]] = array( 'index' => $j, ); } } // grondslagen for ($i=COL_GRONDSLAG_1; $i<=COL_GRONDSLAG_1; $i+=2) { if (!($grondslag = @$row[$i])) continue; $artikel = @$row[$i+1]; if (!$artikel) throw new Exception( 'Op regel ' . $regel . ' staat wel een grondslag, maar geen artikel.' ); // resolve grondslag if (!isset( $grondslagen[$grondslag] )) { $j = sizeof($grondslagen); $this->_exec_query( 'INSERT INTO bt_grondslagen (klant_id, grondslag) SELECT @KLANT_ID, \'' . $this->CI->db->escape_str($grondslag) . '\' FROM dual WHERE NOT EXISTS (SELECT * FROM bt_grondslagen WHERE klant_id = @KLANT_ID AND grondslag = \'' . $this->CI->db->escape_str($grondslag) . '\');' ); $this->_exec_query( 'SET @GRONDSLAG' . $j . ' = (SELECT id FROM bt_grondslagen WHERE klant_id = @KLANT_ID AND grondslag = \'' . $this->CI->db->escape_str($grondslag) . '\' LIMIT 1);' ); $grondslagen[$grondslag] = array( 'index' => $j, 'artikelen' => array() ); $this->counts['grondslagen']++; } // resolve artikel if (!isset( $grondslagen[$grondslag]['artikelen'][$artikel] )) { $j = $artikel_teller++; $this->_exec_query( 'INSERT INTO bt_grondslag_teksten (grondslag_id, artikel) SELECT @GRONDSLAG' . $grondslagen[$grondslag]['index'] . ', \'' . $this->CI->db->escape_str($artikel) . '\' FROM dual WHERE NOT EXISTS (SELECT * FROM bt_grondslag_teksten WHERE grondslag_id = @GRONDSLAG' . $grondslagen[$grondslag]['index'] . ' AND artikel = \'' . $this->CI->db->escape_str($artikel) . '\');' ); $this->_exec_query( 'SET @ARTIKEL' . $j . ' = (SELECT id FROM bt_grondslag_teksten WHERE grondslag_id = @GRONDSLAG' . $grondslagen[$grondslag]['index'] . ' AND artikel = \'' . $this->CI->db->escape_str($artikel) . '\' LIMIT 1);' ); $grondslagen[$grondslag]['artikelen'][$artikel] = $j; $this->counts['artikelen']++; $this->_exec_query( 'INSERT INTO bt_vraag_grndslgn (vraag_id, checklist_groep_id, checklist_id, grondslag_tekst_id) VALUES (@VRAAG, @CHECKLISTGROEP' . $checklistgroepen[$checklistgroep]['index'] . ', @CHECKLIST' . $checklistgroepen[$checklistgroep]['checklisten'][$checklist]['index'] . ', @ARTIKEL' . $grondslagen[$grondslag]['artikelen'][$artikel] . ');' ); } // voeg link toe $this->_exec_query( 'UPDATE bt_vragen SET gebruik_grndslgn = 1 WHERE id = @VRAAG;' ); } } $this->_exec_query( 'UPDATE bt_grondslag_teksten SET display_artikel = artikel WHERE 1 AND display_hoofdstuk = \'\' AND display_afdeling = \'\' AND display_paragraaf = \'\' AND display_artikel = \'\' AND display_lid = \'\';' ); fclose( $fd ); } public function get_counts() { return $this->counts; } public function get_speciale_tekens_teksten() { return $this->speciale_tekens_teksten; } } <file_sep>PDFAnnotator.Window = PDFAnnotator.Base.extend({ instance: null, init: function() { this._super(); this.registerEventType( 'resize' ); var thiz = this; $(window).resize(function(){ thiz.dispatchEvent( 'resize', PDFAnnotator.Server.prototype.instance.getWindowProportions() ); }); }, getInstance: function() { var staticThis = PDFAnnotator.Window.prototype; if (!staticThis.instance) staticThis.instance = new PDFAnnotator.Window(); return staticThis.instance; }, triggerNow: function() { $(window).trigger( 'resize' ); } });<file_sep>-- zorg dat het volgende commando elke dag aan het eind van de dag draait: -- php index.php /cli/pdfannotator_processor <file_sep><? $this->load->view('elements/header', array('page_header'=>'prioriteiten')); ?> <? $test_niveaus = $risico_handler->get_risico_shortnames(); ?> <? $this->load->view( 'beheer/prioriteitstelling_matrix_js' ) ?> <form name="form" method="post" class="vamiddle" onsubmit="alert( 'Het opslaan van de matrix kan enige tijd duren, en begint zodra u dit scherm sluit. Even geduld aub...' ); return true;"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Prioriteitenmatrix - ' . htmlentities( $checklistgroep->naam, ENT_COMPAT, 'UTF-8'), 'width' => '100%' )); ?> <table> <tr> <td> <? if (!$readonly): ?> <input type="submit" value="<?=tgng('form.opslaan')?>"/> <input type="button" value="<?=tgng('form.annuleren')?>" onclick="location.href='<?=site_url('/instellingen/matrixbeheer')?>';"/> <?=htag('opslaan')?> <? endif; ?> <input type="button" value="Toon bestuurlijke matrix" class="toon_bestuurlijke_matrix" style="display:none" /> <?=htag('bestuurlijke_matrix')?> </td> <td style="text-align: right"> <input type="button" value="Eenvoudige weergave" onclick="if (confirm( 'Niet-opgeslagen wijzigingen gaan verloren. Eenvoudige weergave nu tonen?' )) location.href='<?=site_url('/instellingen/prioriteitstelling_matrix/' . $checklistgroep->id . '/' . $matrix->id . '/eenvoudig')?>';" /> <?=htag('eenvoudige weergave')?> <input type="button" value="Legenda" onclick=" modalPopup({ width: 800, height: 400, html: $('.legenda').html() })" /> <?=htag('legenda')?> </td> </tr> </table> <input type="hidden" name="per_thema" value="1" /> <div class="please_wait"> <h2>EVEN GEDULD AUB...</h2> <img src="<?=site_url('/files/images/ajax-loader.gif')?>" /> </div> <div style="width:<?=$this->is_Mobile ? 950 : 1150?>px; overflow:auto"> <? $this->load->view( 'beheer/prioriteitstelling_matrix_bestuurlijke_matrix', array( 'test_niveaus' => $test_niveaus, 'tag' => 0, ) ); ?> <? foreach ($hoofdthemas as $hoofdthema): ?> <? $this->load->view( 'beheer/prioriteitstelling_matrix_ambtelijke_matrix', array( 'hoofdthema' => $hoofdthema, 'test_niveaus' => $test_niveaus, 'tag' => $hoofdthema->id, ) ); ?> <? endforeach; ?> </div> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> </form> <? $this->load->view( 'beheer/prioriteitstelling_legenda', array( 'bestuurlijk' => true ) ); ?> <script type="text/javascript"> $(document).ready(function(){ // // Zorg dat prioriteiten-editen werkt zodra een "kleurvlakje" geklikt wordt // <? if (!$readonly): ?> $('.hoofdgroep').click(function(evt){ var div = $(this); var sel = $(this).siblings('select:not([disabled])'); if (sel.size() == 0) { alert( 'Deze prioriteitstelling is gebaseerd op een risico analyse, u kunt deze daarom niet wijzigen.\nKlik op de naam van de checklist om in een nieuw scherm naar de risico analyse te gaan.' ); return; } div.hide(); sel.show(); sel.focus(); sel[0].click(); }); <? endif; ?> // // Zorg dat de prioriteiten-editor weer verdwijnt zodra een select z'n focus verliest // var onChangeOrBlur = function(evt){ var sel = $(this); var div = $(this).siblings('div'); var newtext; for (var i in this.options) if (this.options[i].value == sel.val()) { newtext = this.options[i].text || this.options[i].label; break; } sel.hide(); div.show(); div.removeClass( 'prio_zeer_laag prio_laag prio_gemiddeld prio_hoog prio_zeer_hoog' ); div.html( newtext ); $(this).siblings('div').addClass( 'prio_' + $(this).val() ); // recalculate average var hoofdthema_id = sel.parents('div.hoofdthema[tag]').attr( 'tag' ); updateBestuurlijkeMatrix( hoofdthema_id ); } $('.hoofdgroep').siblings('select').change(onChangeOrBlur); $('.hoofdgroep').siblings('select').blur(onChangeOrBlur); // // Zorg dat het switchten van matrices geregeld is // var switchToMatrix = function ( hoofdthema_id ) { $('.hoofdthema').hide(); $('.hoofdthema[tag=' + hoofdthema_id + ']').show(); $('.toon_bestuurlijke_matrix')[ hoofdthema_id ? 'show' : 'hide' ](); } $('img.thema_selectie').click(function(){ var hoofdthema_id = $(this).attr('tag'); switchToMatrix( hoofdthema_id ); }); $('.toon_bestuurlijke_matrix').click(function(){ switchToMatrix( 0 ); }); // // Zorg dat de globale selects de andere selects voor een hoofdthema beinvloeden // var zetHoofdThemaGlobaal = function() { var hoofdthema_id = $(this).attr('tag'); var newprio = $(this).val(); $('div.hoofdthema[tag=0] td[hoofdthema_id=' + hoofdthema_id + '] select').each(function(){ $(this).val( newprio ); $(this).blur(); // trigger blur event }); }; $('select.globaal[tag]').change(zetHoofdThemaGlobaal); $('select.globaal[tag]').blur(zetHoofdThemaGlobaal); // // Zorg dat veranderingen in de bestuurlijke matrix doorgevoerd worden de ambtelijke // var updateAmbtelijkeMatrix = function( ) { // gather data var checklist_id = $(this).parents('[checklist_id]').attr('checklist_id'); var hoofdthema_id = $(this).parents('[hoofdthema_id]').attr('hoofdthema_id'); var newprio = $(this).val(); // set it in all NON DISABLED ambtelijke matrix selects and divs var ambtmat = $('div[tag=' + hoofdthema_id + '] table'); ambtmat.find('select[name^=checklist\\[' + checklist_id + '\\]]:not([disabled])').each(function(){ // set in select $(this).val( newprio ); // set in div (visual display) var text; switch (newprio) { case 'zeer_laag': text = '<?=$test_niveaus['zeer_laag']?>'; break; case 'laag': text = '<?=$test_niveaus['laag']?>'; break; case 'gemiddeld': text = '<?=$test_niveaus['gemiddeld']?>'; break; case 'hoog': text = '<?=$test_niveaus['hoog']?>'; break; case 'zeer_hoog': text = '<?=$test_niveaus['zeer_hoog']?>'; break; } var div = $(this).parent().find('div'); div.text( text ); div.removeClass( 'prio_zeer_laag prio_laag prio_gemiddeld prio_hoog prio_zeer_hoog prio_tobedetermined' ); div.addClass( 'prio_' + newprio ); }); }; $('div.hoofdthema[tag=0]').find('select').change( updateAmbtelijkeMatrix ); $('div.hoofdthema[tag=0]').find('select').blur( updateAmbtelijkeMatrix ); // // Zorg dat de bestuurlijke matrix netjes de gemiddelde waarde weergeeft // var updateBestuurlijkeMatrix = function( hoofdthema_id ) { // get source & destination matrix var ambtmat = $('div[tag=' + hoofdthema_id + '] table'); var bestmat = $('div[tag=0] table'); // go over all cells for this hoofdthema in the destination matrix bestmat.find( 'tr[checklist_id] td[hoofdthema_id='+hoofdthema_id+']' ).each(function(){ var checklist_id = $(this).parents('tr[checklist_id]').attr( 'checklist_id' ); // for each cell, find all selects in the source matrix that are tagged to be for this checklist var total = 0; var count = 0; ambtmat.find( 'select[name^=checklist\\[' + checklist_id + '\\]]' ).each(function(){ switch (this.value) { case 'zeer_laag': total += 1; count++; break; case 'laag': total += 2; count++; break; case 'gemiddeld': total += 3; count++; break; case 'hoog': total += 4; count++; break; case 'zeer_hoog': total += 5; count++; break; } }); // calc average, is there is one to calc if (count) { var avg = Math.round( total / count ); var prio; switch (avg) { case 1: prio = 'zeer_laag'; break; case 2: prio = 'laag'; break; case 3: prio = 'gemiddeld'; break; case 4: prio = 'hoog'; break; case 5: prio = 'zeer_hoog'; break; } var div = $(this).find('div'); div.removeClass( 'prio_zeer_laag prio_laag prio_gemiddeld prio_hoog prio_zeer_hoog prio_tobedetermined' ); div.addClass( 'prio_' + prio ); switch (avg) { case 1: avgText = '<?=$test_niveaus['zeer_laag']?>'; break; case 2: avgText = '<?=$test_niveaus['laag']?>'; break; case 3: avgText = '<?=$test_niveaus['gemiddeld']?>'; break; case 4: avgText = '<?=$test_niveaus['hoog']?>'; break; case 5: avgText = '<?=$test_niveaus['zeer_hoog']?>'; break; } div.text( avgText ); var sel = $(this).find('select'); sel.val( prio ); } else $(this).text( '-' ); }); } // recalc all <? foreach ($hoofdthemas as $hoofdthema): ?> updateBestuurlijkeMatrix( <?=$hoofdthema->id?> ); <? endforeach; ?> // show! $('div.please_wait').hide(); switchToMatrix( 0 ); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class WebserviceAccountResult extends BaseResult { private $_components = null; private $_klanten = null; function WebserviceAccountResult( &$arr ) { parent::BaseResult( 'webserviceaccount', $arr ); } function get_applicatie() { $this->_CI->load->model( 'webserviceapplicatie' ); return $this->_CI->webserviceapplicatie->get( $this->webservice_applicatie_id ); } function mag_bij_component( $component_naam ) { if ($this->alle_components) return true; if (!is_array( $this->_components )) { $this->_CI->load->model( 'webserviceaccountrecht' ); $this->_components = array(); foreach ($this->_CI->webserviceaccountrecht->get_by_webservice_account( $this->id ) as $c) $this->_components[ $c->get_webservice_component()->naam ] = $c; } return isset( $this->_components[ $component_naam ] ); } function mag_bij_klant( $klant_id ) { if ($this->alle_klanten) return true; if (!is_array( $this->_klanten )) { $this->_CI->load->model( 'webserviceaccountklant' ); $this->_klanten = array(); foreach ($this->_CI->webserviceaccountklant->get_by_webservice_account( $this->id ) as $k) $this->_klanten[ $k->klant_id ] = $k; } return isset( $this->_klanten[ $klant_id ] ); } } class WebserviceAccount extends BaseModel { function WebserviceAccount() { parent::BaseModel( 'WebserviceAccountResult', 'webservice_accounts', true ); } public function check_access( BaseResult $object ) { // disabled for model } public function find_by_username_and_password( $username, $password ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_by_webservice_account'; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE gebruikersnaam = ? AND wachtwoord = ? LIMIT 1' ); $res = $CI->dbex->execute( $stmt_name, array( $username, sha1( $password ) ) ); if (!$res) return null; if ($res->num_rows()!=1) { $res->free_result(); return null; } $row = $res->result(); $row = reset( $row ); $account = $this->getr( $row ); $res->free_result(); return $account; } } <file_sep><? if(count($vragen) > 0):?> <ul id="sortable" class="vragen list mappen" style="margin-top: 10px;"> <? foreach ($vragen as $i => $vraag): ?> <li class="<?=($vraag->is_active?'entry-selected':'entry')?> top left right <?=(($i==sizeof($vragen)-1)?'bottom':'')?>" id="vrg_li_<?=$vraag->vraag_map_id ?>"> <div class="list-entry" style="margin-top:6px;padding-left:5px;font-weight:bold;"> <table cellspacing="0" cellpadding="0" border="0" class="risk-vraag" style="width: 567px;"> <tr> <td onclick="<?=($is_active=='true'?'processVraag($(this));':'')?>" entry_id="<?=$vraag->vraag_map_id ?>" style="white-space: normal;"><?=htmlentities( $vraag->naam, ENT_COMPAT, 'UTF-8' )?></td> <td style="width: 1px;"> <? if( $vraag->is_btn): ?> <button onclick="setRisicoBw(<?=$vraag->vraag_map_id ?>,$(this));" class="<?=$vraag->bw_css ?>" style="width: 40px;font-weight: bold;"><?=$vraag->prompt_bw ?></button> <?else:?> <div>&nbsp;</div> <?endif ?> </td> </tr> </table> </div> </li> <? endforeach; ?> </ul> <?else:?> <div style="padding-top:10px;padding-left:5px;font-weight:bold;"><?=tgg('list.noitems') ?></div> <?endif ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'wettelijke_grondslag')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => htmlentities( $grondslag->grondslag . ' ' . $artikel, ENT_COMPAT, 'UTF-8'), 'width' => '920px' )); ?> <p> Artikel <b><?=$artikel?></b> uit <b><?=$grondslag->grondslag?></b> wordt gebruikt in orderstaande checklisten. </p> <div class="grondslag_gebruik"> <? $current_cg = $current_cl = $current_h = $current_c = null; ?> <? foreach ($contents as $row): ?> <? if ($current_cg != $row->cg_id) { $current_cg = $row->cg_id; echo '<h1>' . $row->cg_naam . '</h1>'; } if ($current_cl != $row->cl_id) { $current_cl = $row->cl_id; echo '<h2>' . $row->cl_naam . '</h2>'; } if ($current_h != $row->h_id) { $current_h = $row->h_id; echo '<h3>' . $row->h_naam . '</h3>'; } /* if ($current_c != $row->c_id) { $current_c = $row->c_id; echo '<h4>' . $row->c_naam . '</h4>'; } echo '<p title="' . $row->v_id . '">' . $row->tekst . '</p>'; */ ?> <? endforeach; ?> </div> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <p> Er zijn <?=$count?> tekst elementen in het systeem. </p> <p> <? if ($this->gebruiker->get_logged_in_gebruiker()->get_klant()->allow_lease_administratie()): ?> <? if (!$sort): ?> <input type="button" value="Toon teksten gesorteerd op laatste bewerkingsdatum" onclick="location.href='/admin/tekst_beheer/1';" /> <? else: ?> <input type="button" value="Toon teksten gesorteerd op groep" onclick="location.href='/admin/tekst_beheer';" /> <? endif; ?> <i>(Let op! Eerst opslaan!)</i> <? endif; ?> </p> <form method="POST"> <? foreach ($groepen as $groep => $elementen): ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => $groep, 'width' => '920px' ) ); ?> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 300px;">String</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Tekst</th> </tr> <? $c = 0; foreach ($elementen as $string => $tekst): ?> <tr style="background-color: <?=($c++%2)?'#fff':'#eee'?>"> <td style="padding: 4px; background-color:transparent; word-break: break-all"><?=$string?></td> <td> <? if (strpos( $tekst, "\n" )!==false): ?> <textarea style="width: 500px" name="text[<?=$string?>]"><?=htmlentities( $tekst, ENT_COMPAT, 'UTF-8' )?></textarea> <? else: ?> <input type="text" name="text[<?=$string?>]" value="<?=htmlentities( $tekst, ENT_COMPAT, 'UTF-8' )?>" style="width: 500px"> <? endif; ?> </td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <input type="submit" value="Alles opslaan" /> <? endforeach; ?> </form> <? $this->load->view('elements/footer'); ?> <file_sep>-- toevoegen aan CLI!! -- LIVE ONLY php index.php /cli/wet_tekst_fetcher <file_sep><? require_once 'base.php'; class DossierSubjectResult extends BaseResult { function DossierSubjectResult( &$arr ) { parent::BaseResult( 'dossiersubject', $arr ); } function get_edit_fields() { // ????!!!!!????!!!! This cannot possibly be right! Surely this was copied across in error from the DossierBescheiden model!!!! /* return array( $this->_edit_textfield( 'Tekening/Stuk nummer', 'tekening_stuk_nummer', $this->tekening_stuk_nummer ), $this->_edit_textfield( 'Auteur', 'auteur', $this->auteur ), $this->_edit_textfield( 'Omschrijving', 'omschrijving', $this->omschrijving ), $this->_edit_textfield( 'Datum laatste wijziging', 'datum_laatste_wijziging', $this->datum_laatste_wijziging ), $this->_edit_uploadfield( 'Bestand', 'bestand', $this->bestandsnaam ), ); * */ return array(); } function is_zichtbaar() { $res = strlen(trim($this->rol))>0 || strlen(trim($this->naam))>0 || strlen(trim($this->adres))>0 || strlen(trim($this->postcode))>0 || strlen(trim($this->woonplaats))>0 || strlen(trim($this->telefoon))>0 || strlen(trim($this->email))>0; if (!$res) $this->delete(); return $res; } function get_gebruiker() { if (!$this->gebruiker_id) return null; return $this->_CI->gebruiker->get( $this->gebruiker_id ); } } class DossierSubject extends BaseModel { function DossierSubject() { parent::BaseModel( 'DossierSubjectResult', 'dossier_subjecten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } private function setSubjectOrganisatieType( $subject ){ $this->_CI->load->model( 'gebruiker' ); $gebruikers = $this->_CI->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ); if( isset($subject->gebruiker_id) ) { $subject->organisatie_type = isset($gebruikers[$subject->gebruiker_id]) ? SUBJECT_INTERN_ORG : SUBJECT_KID_ORG; }else { $subject->organisatie_type = SUBJECT_EXTERN_ORG; } return $subject; } public function get( $id ){ $row = parent::get($id); return $this->setSubjectOrganisatieType( $row ); } function get_by_dossier( $dossier_id, $assoc=false ) { $list = $this->db ->where('dossier_id', $dossier_id ) ->order_by('naam') ->get( $this->_table ) ->result(); $res_list = array(); foreach( $list as $row ) { $row = $this->getr( $row ); $row = $this->setSubjectOrganisatieType( $row ); ($assoc) ? $res_list[$row->id] = $row : $res_list[] = $row; } return $res_list; } function add( $dossier_id, $rol ) { // Use the base model's 'insert' method. $data = array( 'dossier_id' => $dossier_id, 'rol' => $rol, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function get_subject_by_deelplan_id($dossier_id=null, $deelplan_id=null){ if (!$this->dbex->is_prepared( 'get_subject_by_deelplan_id' )) $this->dbex->prepare( 'get_subject_by_deelplan_id', ' SELECT * FROM dossier_subjecten LEFT JOIN deelplan_subjecten AS ds on dossier_subjecten.id=dossier_subject_id WHERE dossier_id = ? and deelplan_id = ? ORDER BY dossier_subjecten.id ' ); $res = $this->dbex->execute( 'get_subject_by_deelplan_id', array( $dossier_id, $deelplan_id) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } } <file_sep>-- First step: drop the foreign keys that refer to tables/fields that need to renamed: -- ALTER TABLE ... DROP FOREIGN KEY ...; ALTER TABLE custom_report_data_155_organisatie_kenmerken DROP FOREIGN KEY `FK_custom_report_data_155_organisatie_kenmerken_dossiers_id`; ALTER TABLE custom_report_data_155_organisatie_kenmerken DROP KEY `UK_custom_report_data_155_organisatie_kenmerken_dossier_id`; ALTER TABLE custom_report_data_155_pago_pmo DROP FOREIGN KEY `FK_custom_report_data_155_pago_pmo_dossiers_id`; ALTER TABLE custom_report_data_155_pago_pmo DROP KEY `FK_custom_report_data_155_pago_pmo_dossiers_id`; ALTER TABLE custom_report_data_155_pbm_sub_taak DROP FOREIGN KEY `FK_custom_report_data_155_pbm_sub_taak_taak_id`; ALTER TABLE custom_report_data_155_pbm_sub_taak DROP KEY `FK_custom_report_data_155_pbm_sub_taak_taak_id`; ALTER TABLE custom_report_data_155_pbm_taak DROP FOREIGN KEY `FK_custom_report_data_155_pbm_taak_dossiers_id`; ALTER TABLE custom_report_data_155_pbm_taak DROP KEY `FK_custom_report_data_155_pbm_taak_dossiers_id`; ALTER TABLE bt_checklist_groep_verantwtkstn DROP FOREIGN KEY `bt_checklist_groep_verantwtkstn_ibfk_1`; -- Now rename the table(s): RENAME TABLE custom_report_data_155_organisatie_kenmerken TO cust_rep_data_155_org_kenm; RENAME TABLE custom_report_data_155_pago_pmo TO cust_rep_data_155_pago_pmo; RENAME TABLE custom_report_data_155_pbm_sub_taak TO cust_rep_data_155_pbm_sub_taak; RENAME TABLE custom_report_data_155_pbm_taak TO cust_rep_data_155_pbm_taak; RENAME TABLE bt_checklist_groep_verantwtkstn TO bt_checklist_groep_veranttkstn; -- Rename the column names that are too long: ALTER TABLE bt_grondslag_teksten CHANGE COLUMN `quest_node_alternatief_gebruikt` `quest_node_alternatief_used` tinyint(4) NOT NULL DEFAULT '0'; -- Create the keys again, using the new names: ALTER TABLE cust_rep_data_155_org_kenm ADD UNIQUE KEY `UK_c_r_d_155_o_k_dossier_id` (`dossier_id`); ALTER TABLE cust_rep_data_155_org_kenm ADD CONSTRAINT `FK_c_r_d_155_o_k_dossier_id` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE cust_rep_data_155_pago_pmo ADD KEY `IDX_c_r_d_155_p_p_dossier_id` (`dossier_id`); ALTER TABLE cust_rep_data_155_pago_pmo ADD CONSTRAINT `FK_c_r_d_155_p_p_dossier_id` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE cust_rep_data_155_pbm_taak ADD KEY `IDX_c_r_d_155_p_t_dossier_id` (`dossier_id`); ALTER TABLE cust_rep_data_155_pbm_taak ADD CONSTRAINT `FK_c_r_d_155_p_t_dossier_id` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE cust_rep_data_155_pbm_sub_taak ADD KEY `IDX_c_r_d_155_p_s_t_taak_id` (`taak_id`); ALTER TABLE cust_rep_data_155_pbm_sub_taak ADD CONSTRAINT `FK_c_r_d_155_p_s_t_taak_id` FOREIGN KEY (`taak_id`) REFERENCES `cust_rep_data_155_pbm_taak` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE bt_checklist_groep_veranttkstn ADD CONSTRAINT `FK_b_c_g_v__checklist_groep_id` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.bescheiden_popup::bestand(en)', 'bestand(en)', '2014-02-04 16:50:00', 0); <file_sep><?php function prepare_soap_call() { global $old_error_reporting; $old_error_reporting = error_reporting( 0 ); } function finish_soap_call() { global $old_error_reporting; error_reporting( $old_error_reporting ); } prepare_soap_call(); require_once( 'SOAP/Client.php' ); require_once( 'SOAP/WSDL.php' ); finish_soap_call(); class CI_KennisID { const APPLICATION_LABEL = 'bristoezicht'; const APPLICATION_LABEL_BW = 'bw'; const SESSION_KEY_TOKEN = 'KennisID-token'; const SESSION_KEY_TOKEN_BW = 'KennisID-token-bw'; const SESSION_KEY_LICENSEID = 'KennisID-licenseid'; const SESSION_KEY_LICENSEID_BW = 'KennisID-licenseid-bw'; const SESSION_KEY_PASSPORT = 'KennisID-email'; const USER_AGENT = 'OData Service'; const URL_REQ_EMAIL = ''; private static $_headers = array('Accept' => 'application/atom+xml,application/xml', 'Accept-Charset' => 'UTF-8', 'DataServiceVersion' => '1.0', 'MaxDataServiceVersion' => '2.0'); private $CI; private $_soapclient; /**************************************************************************************************** * * * * * HELPER FUNCTIONS * * * * * ****************************************************************************************************/ private function _get_soapclient() { if (is_null( $this->_soapclient )) { prepare_soap_call(); { $wsdl = new SOAP_WSDL( 'http://service.kennisid.nl/Authentication.svc?wsdl', array(), config_item('kennisid_cache_dir'), config_item('kennisid_cache_time') ); $this->_check_soapresult( $wsdl ); $this->_soapclient = $wsdl->getProxy(); $this->_check_soapresult( $this->_soapclient ); } finish_soap_call(); } return $this->_soapclient; } private function _check_soapresult( $result ) { if (PEAR::isError( $result )) show_error( 'Fout bij benaderen van KennisID SOAP service.' ); } /**************************************************************************************************** * * * * * PUBLIC FUNCTIONS * * * * * ****************************************************************************************************/ public function __construct() { $this->CI = get_instance(); if (!class_exists( 'SOAP_Client' )) show_error( 'Vereiste SOAP libraries niet geinstalleerd.' ); } /** Redirects user to the login page, with the given return URL as the * URL to return the user to after successful login. * * NOTE: the return url should NOT be raw url encoded yet! */ public function redirect_login( $return_url ) { // !!! OJG (17-7-2015): We used to be able to pass a return URL to KennisID but this functionality appears to no longer work correctly, as when we // explicitely click on the 'inloggen' link when a session has expired, we always end up on the same page with the same error again. // By not passing a ReturnUrl value we at least get the right KennisID log in screen and can log in again. // Possibly this needs to be fixed later, so leave both assignments here, so as to avoid the first one from being considered obsolete and hence // easily get deleted and forgotten afterwards. ;) $url = 'http://www.kennisid.nl/Authenticate?ReturnUrl=' . rawurlencode( $return_url ); //$url = 'https://www.kennisid.nl/Authenticate'; //$url = 'http://system.kennisid.nl/Authenticate?ReturnUrl=' . rawurlencode( $return_url ); //$url = 'https://kennisidsystem2-2015.azurewebsites.net/Authenticate?ReturnUrl=' . rawurlencode( $return_url ); redirect( $url ); exit; } /** Returns current session token, or NULL if none present. */ public function get_session_token() { return $this->CI->session->userdata( self::SESSION_KEY_TOKEN ); } /** Returns current session token voor bw, or NULL if none present. */ public function get_session_token_bw() { return $this->CI->session->userdata( self::SESSION_KEY_TOKEN_BW ); } /** Returns true if A session token is present (doesn't have to be valid, just * that a token is in the session data.) */ public function has_session_token() { return is_string( $this->get_session_token() ); } /** Returns true if current user is still authenticated with KennisID system. * * Checks if session has a KennisID token, and if that token is still ok * according to KennisID. * * When false is returned, the user should be forwarded to the KennisID login * system. */ public function validate_session_token() { $token = $this->get_session_token(); if (!$token) return false; return $this->validate_token( $token ); } /** Validates the string to be a valid token. Shouldn't be used directly if you * don't know what you're doing. Only here so the return URL can validate the token * before setting it! */ public function validate_token( $token ) { $client = $this->_get_soapclient(); prepare_soap_call(); { global $__RequestTimer; if ($__RequestTimer) $__RequestTimer->sub( 'kennisid checktoken' ); $result = $client->CheckToken( $token ); if ($__RequestTimer) $__RequestTimer->subfinish(); $this->_check_soapresult( $result ); } finish_soap_call(); return is_bool($result) ? $result : ($result == 'true'); } /** Should be called whenever a user returns to the after-login-return-url with * a fresh new token. The specified token is stored in the user's session data * and will be used in future requests. * * Resultaat is TRUE als token en licentie geverifieerd zijn. Anders wordt een * foutmeldingscode teruggeven, die naar /gebruikers/licensie_probleem doorgezet * kan worden. */ public function set_session_token( $token ) { $debug = false; //$debug = true; if ($debug) { echo "--- KennisID::set_session_token ---<br />"; } $client = $this->_get_soapclient(); prepare_soap_call(); { // fetch passport info $passport = $client->PassportInfoByToken( $token, self::APPLICATION_LABEL ); if ($debug) { echo "+++ KID: passport +++<br />"; d($passport); } $this->_check_soapresult( $passport ); if (!is_object( $passport ) || is_null( $passport )) return 'PassportInfoByTokenFout'; // fetch license id voor bristoezicht $licenseid = $client->LicenseIdByToken( $token, self::APPLICATION_LABEL ); if ($debug) { echo "+++ KID: license ID +++<br />"; d($licenseid); } $this->_check_soapresult( $licenseid ); if (!is_string( $licenseid )) return 'LicenseIdByTokenFout'; // fetch license id voor briswarenhuis $licenseid_bw = $client->LicenseIdByToken( $token, self::APPLICATION_LABEL_BW ); $this->_check_soapresult( $licenseid_bw ); } finish_soap_call(); // Some KID users have no BTZ license, yet are allowed to act in the role of 'externe opdrachtnemer'. In order to do this, we must "trick" the // normal security system, and allow a bypass for only that particular situation. For ALL other situations we use our normal security checks! $allow_bypass_for_telephone_interface = false; if (empty($licenseid)) { // Use the 'request restore' mechanism to check if access to the telephone interface is requested. if ($debug) { echo "+++ KID: no valid license retrieved. Checking Request Restore +++<br />"; } $rr = new RequestRestore(); if ($rr->has_request_to_restore()) { // Get the 'request restore' URI. If it starts with the value '/telefoon/' and if the passport appears to be valid, allow the bypass of the normal security // system. $uri_to_restore = strtolower($rr->get_uri_to_restore()); if ($debug) { echo "+++ KID: URI for Restore: {$uri_to_restore} +++<br />"; } $uri_to_restore_start = strtolower(substr($uri_to_restore,0,10)); //if ( !empty($uri_to_restore) && ($uri_to_restore == '/telefoon/') && !empty($passport) && !empty($passport->PassportUniqueId) && !empty($passport->OrganisationUniqueId) ) if ( !empty($uri_to_restore) && ($uri_to_restore_start == '/telefoon/') && !empty($passport) && !empty($passport->PassportUniqueId) && !empty($passport->OrganisationUniqueId) ) { if ($debug) { echo "+++ KID: bypass allowed +++<br />"; } $allow_bypass_for_telephone_interface = true; $token_bw = ''; } else { if ($debug) { echo "+++ KID: bypass NOT allowed +++<br />"; } } } } // ONLY bypass this piece of code in case the above checks give us a reasonable level of certainty that the respective user has access to the telephone // interface. if (!$allow_bypass_for_telephone_interface) { if ($debug) { echo "+++ Verify the license +++<br />"; } // verifieer de opgehaalde licensie if (true !== ($result = $this->CI->kmxlicensesystem->claim_license_seat( self::APPLICATION_LABEL, $licenseid, $passport->PassportUniqueId ))) return $result; // claim ook license seat voor briswarenhuis $token_bw = null; if ($licenseid_bw) { // negeer fouten, dit is secundair if ($this->CI->kmxlicensesystem->claim_license_seat( self::APPLICATION_LABEL_BW, $licenseid_bw, $passport->PassportUniqueId )) { $token_bw = $this->CI->kmxlicensesystem->get_token_for_application( self::APPLICATION_LABEL_BW ); } } } // store in session $this->CI->session->set_userdata( self::SESSION_KEY_TOKEN, $token ); $this->CI->session->set_userdata( self::SESSION_KEY_TOKEN_BW, $token_bw ); $this->CI->session->set_userdata( self::SESSION_KEY_LICENSEID, $licenseid ); $this->CI->session->set_userdata( self::SESSION_KEY_LICENSEID_BW, $licenseid_bw ); $this->CI->session->set_userdata( self::SESSION_KEY_PASSPORT, $passport ); if ($debug) { echo "+++ set_session_token call done +++<br />"; } return true; } /** Should be called whenever a user logs out. */ public function reset_session_token() { $this->CI->session->unset_userdata( self::SESSION_KEY_TOKEN ); $this->CI->session->unset_userdata( self::SESSION_KEY_TOKEN_BW ); $this->CI->session->unset_userdata( self::SESSION_KEY_LICENSEID ); $this->CI->session->unset_userdata( self::SESSION_KEY_LICENSEID_BW ); $this->CI->session->unset_userdata( self::SESSION_KEY_PASSPORT ); } /** Send log out to KennisID. */ public function logout() { $client = $this->_get_soapclient(); prepare_soap_call(); { $result = $client->LogOff( $this->CI->session->userdata( self::SESSION_KEY_TOKEN ) ); $result = $client->LogOff( $this->CI->session->userdata( self::SESSION_KEY_TOKEN_BW ) ); } finish_soap_call(); } /** Returns license ID */ public function get_license_id() { return $this->CI->session->userdata( self::SESSION_KEY_LICENSEID ); } /** Returns license ID voor BRISwarenhis */ public function get_license_id_bw() { return $this->CI->session->userdata( self::SESSION_KEY_LICENSEID_BW ); } /** Returns passport */ public function get_passport() { return $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); } /** Returns user unique id from passport */ public function get_user_unique_id() { $data = $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); if (!is_object( $data ) || !$data->PassportUniqueId) return null; return $data->PassportUniqueId; } /** Returns user unique id from passport */ public function get_user_fullname() { $data = $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); if (!is_object( $data ) || !$data->PassportDisplayFullName) return null; return $data->PassportDisplayFullName; } /** Returns user unique id from passport */ public function get_user_email() { $data = $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); if (!is_object( $data ) || !$data->PassportEmail) return null; return $data->PassportEmail; } /** Returns organisation (klant) unique id from passport */ public function get_organisation_unique_id() { $data = $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); if (!is_object( $data ) || !$data->OrganisationUniqueId) return null; return $data->OrganisationUniqueId; } /** Returns organisation (klant) unique id from passport */ public function get_organisation_fullname() { $data = $this->CI->session->userdata( self::SESSION_KEY_PASSPORT ); if (!is_object( $data ) || !$data->OrganisationName) return null; return $data->OrganisationName; } /** * @param $email * @return BRIS_HttpResponse_Passport * @throws Exception */ public function getPassportByEmail($email) { $token = $this->_getTmpToken(); $url = 'http://service.kennisid.nl/Data.svc/Passports?$filter=Email+eq+\'' . urlencode($email) . '\'&Token=' . $token; // $url = 'http://service.kennisid.nl/Data.svc/Passports?$filter=Email+eq+\'' . urlencode($email) . '\'&Token=' . $token . // '&$expand=Licenses/Application&apiname=DEFAULT_ODATA_SERVICE_API_USER&apikey=e779d883062ee9d991dd2f2365262ba4'; return new BRIS_HttpResponse_Passport($this->_httpRequest($url)); } /** * @param string|int $id * @return BRIS_HttpResponse_Organization * @throws Exception */ public function getOrganisationById($id) { $token = $this->_getTmpToken(); $url = 'http://service.kennisid.nl/Data.svc/Organisations?$filter=Id+eq+' . $id . '&Token='.$token; return new BRIS_HttpResponse_Organization($this->_httpRequest($url)); } /** * @return string */ private function _getTmpToken() { $client = new SoapClient('http://service.kennisid.nl/Authentication.svc?wsdl', array('location' => 'http://service.kennisid.nl/Authentication.svc/basic')); $apiparams = new stdClass(); $apiparams->userName = '<EMAIL>'; $apiparams->key = hash("sha512", $apiparams->userName . "<KEY>"); return $client->ApiLogOn($apiparams)->ApiLogOnResult->Token; } /** * @param $url * @return string * @throws Exception */ private function _httpRequest($url) { $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url); curl_setopt($curl_handle, CURL_HTTP_VERSION_1_1, true); curl_setopt($curl_handle, CURLOPT_HEADER, false); curl_setopt($curl_handle, CURLOPT_USERAGENT, self::USER_AGENT); curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true); // Determines the amount of seconds until a connection attempt gives a time-out, 0 = indefinitely curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($curl_handle, CURLOPT_TIMEOUT, 6000); foreach(self::$_headers as $key => $value) { $headers[] = $key.': '.$value; } curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers); $httpResponse = curl_exec($curl_handle); if( !$httpResponse ) { throw new Exception('Error occured during the request ' . curl_error($curl_handle)); } curl_close($curl_handle); return $httpResponse; } }<file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer') ); $allow_list_own_user = $this->login->verify('admin', 'account_list_users'); $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $parent_admin = $this->login->verify( 'admin', 'parentadmin' ); $site_admin = $parent_admin ? !$parent_admin : $this->login->verify('admin', ''); if( $allow_list_own_user || $site_admin || $parent_admin ) { $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Sitebeheer', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <? if( !$parent_admin && ($allow_list_own_user || $site_admin) ) {?> <li><a href="/admin/account_list_users/<?= $klant->id ?>">Gebruikerslijst</a></li> <? } ?> <? if( $site_admin || $parent_admin ) { ?> <li><a href="/admin/account_beheer">Accountbeheer</a></li> <? if( !$parent_admin ) { ?> <li><a href="/admin/account_logo">Logobeheer</a></li> <? } ?> <li><a href="/admin/checklistgroep_beheer">Checklistgroepbeheer</a></li> <? if( !$parent_admin ) { ?> <li><a href="/admin/tekst_beheer">Tekstbeheer</a></li> <? } ?> <? if( $klant->naam == CLIENT_NAME_IMOTEP ) { ?> <li><a href="/admin/gebruiks_overzicht">Gebruiksoverzicht</a></li> <? } ?> <? } ?> <? if( !$parent_admin && $this->klant->allow_lease_administratie() ) { ?> <li><a href="/admin/lease_beheer">Leasebeheer</a></li> <? } ?> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? } ?> <? if($site_admin) { ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Externe applicatie beheer', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <li><a href="/admin/webservice_beheer">Webservice beheer</a></li> <li><a href="/admin/koppelvoorwaarden_beheer">BRIStoets-koppeling checklistbeheer</a></li> <li><a href="/admin/bag_koppeling_beheer">BAG-koppeling beheer</a></li> <li><a href="/admin/quest_beheer">Quest beheer</a></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Statistieken', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <li><a href="/admin/stats_paginas">Pagina's</a></li> <li><a href="/admin/stats_sessies">Sessies</a></li> <li><a href="/admin/stats_uris">Laatste URI's</a></li> <li><a href="/admin/stats_gebruiker_activiteit">Gebruiker activiteit</a></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? } ?> <? if ($this->login->verify( 'admin', 'nieuws' )): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Nieuws', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <li><a href="/admin/nieuws">Nieuws editor</a></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? if ($this->login->verify( 'admin', 'itpimport' ) && !$parent_admin): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Import/Export', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <li><a href="/admin/itpimport">ITP import</a></li> <li><a href="/admin/checklist_import">Checklist import</a></li> <li><a href="/admin/checklist_export">Checklist export</a></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? if ($this->login->verify( 'admin', 'backlog' )): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Backlog', 'expanded' => true, 'width' => '600px', 'height' => '300px' ) ); ?> <ul> <li><a href="/admin/backlog">Backlog</a></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view( 'telefoon/header' ); ?> <!-- loading screen --> <? $this->load->view( 'telefoon/loading-screen' ); ?> <!-- message texts for JS --> <div class="hidden"> <div error="geen-status"><?=tgn('er.is.nog.geen.waardeoordeel.gegeven')?></div> <div error="geen-foto"><?=tgn('er.is.nog.geen.foto.gemaakt')?></div> <div warning="echt-opnieuw"><?=tgn('opdracht.echt.opnieuw.uitvoeren')?></div> <div warning="echt-afsluiten"><?=tgn('echt.afsluiten')?></div> <div progress="form-uploaden"><?=tgn('form.uploaden')?></div> <div progress="foto-uploaden"><?=tgn('foto.uploaden')?></div> </div> <!-- pages --> <div id="telefoon"> <? $this->load->view( 'telefoon/page-dossiers' ); ?> <? $this->load->view( 'telefoon/page-deelplannen' ); ?> <? $this->load->view( 'telefoon/page-opdrachten' ); ?> <? $this->load->view( 'telefoon/page-toezicht' ); ?> <? $this->load->view( 'telefoon/page-afsluiten' ); ?> <? $this->load->view( 'telefoon/bottom-bar' ); ?> </div> <!-- image viewer --> <div id="imageviewer" class="hidden"> </div> <script type="text/javascript"> $(document).ready(function(){ BRISToezicht.Toets.data = {} BRISToezicht.Telefoon.initial_command = '<?=$initial_command?>'; BRISToezicht.initialize(); BRISToezicht.OfflineKlaar.markeerKlaar(); BRISToezicht.OfflineKlaar.markeerKlaar(); BRISToezicht.OfflineKlaar.markeerKlaar(); }); </script> <? $this->load->view( 'telefoon/footer' ); ?> <file_sep>CREATE TABLE IF NOT EXISTS `bt_checklist_groep_opdrachten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_groep_id` int(11) NOT NULL, `opdracht` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB; ALTER TABLE `bt_checklist_groep_opdrachten` ADD CONSTRAINT `bt_checklist_groep_opdrachten_ibfk_1` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE IF NOT EXISTS `bt_checklist_opdrachten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `opdracht` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `checklist_id` (`checklist_id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB; ALTER TABLE `bt_checklist_opdrachten` ADD CONSTRAINT `bt_checklist_opdrachten_ibfk_1` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `bt_checklist_opdrachten_ibfk_2` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE IF NOT EXISTS `bt_hoofdgroep_opdrachten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hoofdgroep_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `opdracht` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `hoofdgroep_id` (`hoofdgroep_id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB; ALTER TABLE `bt_hoofdgroep_opdrachten` ADD CONSTRAINT `bt_hoofdgroep_opdrachten_ibfk_1` FOREIGN KEY (`hoofdgroep_id`) REFERENCES `bt_hoofdgroepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `bt_hoofdgroep_opdrachten_ibfk_2` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE IF NOT EXISTS `bt_vraag_opdrachten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `vraag_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `checklist_id` int(11) NOT NULL, `opdracht` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `vraag_id` (`vraag_id`), KEY `checklist_groep_id` (`checklist_groep_id`), KEY `checklist_id` (`checklist_id`) ) ENGINE=InnoDB; ALTER TABLE `bt_vraag_opdrachten` ADD CONSTRAINT `bt_vraag_opdrachten_ibfk_1` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `bt_vraag_opdrachten_ibfk_2` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `bt_vraag_opdrachten_ibfk_3` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>ALTER TABLE `deelplan_vraag_geschiedenis` DROP FOREIGN KEY `deelplan_vraag_geschiedenis_ibfk_5`, ADD FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `rollen` DROP FOREIGN KEY `rollen_ibfk_2` , ADD FOREIGN KEY ( `gemaakt_door_gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep><? if (@$width && @$centered): ?> <div style="border:0;margin:0;padding:0;<?=isset($width)?'width:'.$width:''?>;margin:0 auto;height:auto;"> <? endif; ?> <!-- mode1 bar --> <table border="0" cellspacing="0" cellpadding="0" class="<?=@$class ? $class : 'greenbutton'?>" style="<?=isset($width)?'width:'.$width:''?>" onclick=" <? if (preg_match('/^javascript:(.*?)$/i', $url, $matches)): ?> <?=$matches[1]?> <? else: ?> <? if ($blank): ?> window.open( '<?=$url?>' ); // this is the crux of this entire onclick problem :/ we can't fake a user click find('a').trigger('click'); doesn't work :( <? else: ?> location.href='<?=$url?>'; <? endif; ?> <? endif; ?> "> <tr> <td width="6" class="left"></td> <td class="mid"><a style="color:inherit; text-decoration: inherit;" <?=$blank ? 'target="_blank"' : ''?> href="<?=$url?>" onclick="eventStopPropagation(event);"><?=$text?></a></td> <td width="6" class="right"></td> </tr> </table> <? if (@$width && @$centered): ?> </div> <? endif; ?> <file_sep>/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; DROP TABLE IF EXISTS users_group; DROP TABLE IF EXISTS users_groups; DROP TABLE IF EXISTS group_user_map; CREATE TABLE users_groups ( id int(11) NOT NULL AUTO_INCREMENT, garage_naam varchar(255) DEFAULT NULL, straat varchar(255) DEFAULT NULL, huisnummer varchar(255) DEFAULT NULL, toevoeging varchar(255) DEFAULT NULL, postcode varchar(255) DEFAULT '0', woonplaats varchar(255) DEFAULT NULL, land varchar(255) DEFAULT NULL, kvk_nummer varchar(255) DEFAULT NULL, btw_nummer varchar(255) DEFAULT NULL, contactpersoon_technisch varchar(255) DEFAULT NULL, contactpersoon_functioneel varchar(255) DEFAULT NULL, klant_id int(255) NOT NULL, PRIMARY KEY (id), CONSTRAINT FK_users_groups_klanten FOREIGN KEY (klant_id) REFERENCES klanten (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE group_user_map ( id int(11) NOT NULL AUTO_INCREMENT, users_group_id int(11) NOT NULL, user_id int(11) NOT NULL, PRIMARY KEY (id), UNIQUE INDEX UK_distributeur_user_map (users_group_id, user_id), CONSTRAINT FK_group_user_map_users_group_id FOREIGN KEY (users_group_id) REFERENCES users_groups (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_usersGroup_user_map_users FOREIGN KEY (user_id) REFERENCES gebruikers (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; ALTER TABLE `klanten` ADD COLUMN `usergroup_activate` tinyint(3) DEFAULT '0' NOT NULL AFTER `heeft_fine_kinney_licentie`; ALTER TABLE `klanten` ADD COLUMN `standaard_documenten` tinyint(3) DEFAULT '0' NOT NULL AFTER `usergroup_activate`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoanalyse')); ?> <form name="form" method="post"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('prio_genereren'), 'width' => '920px' ) ); ?> <?=tg('prio_genereren_info')?> <? $this->load->view( 'beheer/risicoanalyse_buttons', array( 'prev' => '/instellingen/risicoanalyse_invullen', 'next' => true, ) ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> </form> <? $this->load->view('elements/footer'); ?><file_sep><?php /** Webservice class. Implement your own functions in here. * Register them, and the types they need, as shown in the example code in the constructor. */ class DossierWebservice extends AbstractWebservice { private $_CI = null; public function __construct() { // Note: the following 'define' is VERY important, as not setting it causes the security mechanism to act up on us where we do not want it to!!! define('IS_WEBSERVICE', true); // Get a reference to the CI object $this->_CI = get_instance(); // Load the models we will be using $this->_CI->load->model( 'webserviceaccount' ); $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'dossier' ); $this->_CI->load->model( 'dossiersubject' ); $this->_CI->load->model( 'dossierbescheiden' ); $this->_CI->load->model( 'deelplan' ); $this->_CI->load->model( 'deelplanbouwdeel' ); $this->_CI->load->model( 'deelplanchecklist' ); $this->_CI->load->model( 'deelplanchecklistgroep' ); $this->_CI->load->model( 'deelplansubject' ); $this->_CI->load->model( 'deelplanbescheiden' ); $this->_CI->load->model( 'deelplanthema' ); $this->_CI->load->model( 'thema' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'hoofdgroep' ); $this->_CI->load->model( 'categorie' ); // Load the helpers we will be using $this->_CI->load->helper( 'encoding' ); // // STEP 1: Call parent constructor, and initialize // parent::__construct(); $this->_initialize(); // // STEP 2: Register types, starting with simple types, and working to structs and arrays // of structs and/or simple types. Remember that types must be known when used, so register // them in the proper order. // The abstract base class knows the following simple types: string, int, boolean and base64Binary. // //$this->_register_compound_type( 'MyStruct', array( 'fieldname1'=>'int', 'fieldname2'=>'string' ) ); //$this->_register_array_type( 'MyStructArray', 'MyStruct' ); /* * Define the auxiliary types. */ // Define an auxiliary type for the 'betrokkenen' $this->_register_compound_type( 'typeBetrokkene', array( 'betrokkeneId' => 'int', 'organisatie' => 'string', 'naam' => 'string', 'rol' => 'string', 'straat' => 'string', 'huisNummer' => 'string', 'huisNummerToevoeging' => 'string', 'postcode' => 'string', 'woonplaats' => 'string', 'telefoon' => 'string', 'email' => 'string', //'gebruikerId' => 'int' // !! Maybe we should make this available? ) ); $this->_register_array_type( 'arrayTypeBetrokkene', 'typeBetrokkene' ); // Define an auxiliary type for the 'gebouwdelen' $this->_register_compound_type( 'typeGebouwdeel', array( //'gebouwdeelId' => 'int', 'naam' => 'string' ) ); $this->_register_array_type( 'arrayTypeGebouwdeel', 'typeGebouwdeel' ); // Define an auxiliary type for the 'checklist IDs' $this->_register_compound_type( 'typeChecklistId', array( 'checklistId' => 'int' ) ); $this->_register_array_type( 'arrayTypeChecklistId', 'typeChecklistId' ); // Define an auxiliary type for the 'document' $this->_register_compound_type( 'typeDocument', array( 'documentId' => 'int', 'omschrijving' => 'string', 'zaakNummerRegistratie' => 'string', 'tekeningNummer' => 'string', 'versieNummer' => 'string', 'datumLaatsteWijziging' => 'string', 'auteur' => 'string', 'bestandsNaam' => 'string', 'bestand' => 'base64Binary' ) ); //$this->_register_array_type( 'arrayTypeDocument', 'typeDocument' ); // Define an auxiliary type for the 'document IDs' $this->_register_compound_type( 'typeDocumentId', array( 'documentId' => 'int' ) ); $this->_register_array_type( 'arrayTypeDocumentId', 'typeDocumentId' ); // Define an auxiliary type for the 'betrokkene IDs' $this->_register_compound_type( 'typeBetrokkeneId', array( 'betrokkeneId' => 'int' ) ); $this->_register_array_type( 'arrayTypeBetrokkeneId', 'typeBetrokkeneId' ); // Define an auxiliary type for the deelplan hercontroledatums $this->_register_compound_type( 'typeHercontroleDatum', array( 'hercontroleDatumId' => 'int', 'gebruikerId' => 'int', 'hercontroleDatum' => 'string', 'hercontroleStartTijd' => 'string', 'hercontroleEindTijd' => 'string', 'voortgangsPercentage' => 'string' ) ); $this->_register_array_type( 'arrayTypeHercontroleDatum', 'typeHercontroleDatum' ); $this->_register_compound_type( 'typeHercontroleDatumsResult', array( 'actionResultMessage' => 'string', 'hercontroleDatums' => 'arrayTypeHercontroleDatum' ) ); /* * Define the method return types. */ // Define a return type for the klanten data $this->_register_compound_type( 'typeKlant', array( 'klantId' => 'int', 'klantNaam' => 'string', 'aantalChecklists' => 'int' ) ); $this->_register_array_type( 'arrayTypeKlant', 'typeKlant' ); $this->_register_compound_type( 'resultSoapGetKlanten', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'arrayTypeKlant' ) ); // Define a return type for the gebruikers data $this->_register_compound_type( 'typeGebruiker', array( 'gebruikerId' => 'int', 'volledigeNaam' => 'string', 'email' => 'string' ) ); $this->_register_array_type( 'arrayTypeGebruiker', 'typeGebruiker' ); $this->_register_compound_type( 'resultSoapGetGebruikers', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'arrayTypeGebruiker' ) ); // Define a return type for the checklistgroep - checklist combinations $this->_register_compound_type( 'typeChecklistGroepChecklist', array( 'checklistGroepId' => 'int', 'checklistGroepNaam' => 'string', 'checklistId' => 'int', 'checklistNaam' => 'string' ) ); $this->_register_array_type( 'arrayTypeChecklistGroepChecklist', 'typeChecklistGroepChecklist' ); $this->_register_compound_type( 'resultSoapGetChecklists', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'arrayTypeChecklistGroepChecklist' ) ); // Define a return type for the deelplan hercontroledatums $this->_register_compound_type( 'resultSoapGetDeelplanHercontroleDatums', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeHercontroleDatumsResult' ) ); // Define a type for the checklist questions (and answers) data $this->_register_compound_type( 'typeChecklistVraag', array( 'checklistId' => 'int', 'checklistNaam' => 'string', 'hoofdgroepNaam' => 'string', 'hoofdThemaNaam' => 'string', 'themaNaam' => 'string', 'vraagTekst' => 'string', 'statusTekst' => 'string', 'statusKleur' => 'string', 'toelichting' => 'string', 'grondslagen' => 'string', 'datumTijd' => 'string' ) ); $this->_register_array_type( 'arrayTypeChecklistVraag', 'typeChecklistVraag' ); // Define a return type for the deelplan result data $this->_register_compound_type( 'typeDeelplanResult', array( 'deelplanId' => 'int', 'status' => 'string', 'actionResultMessage' => 'string', 'rapportFormaat' => 'string', // 'PDF' of 'DOCX' 'rapport' => 'base64Binary', 'checklistVragen' => 'arrayTypeChecklistVraag' ) ); $this->_register_compound_type( 'resultSoapGetDeelplanResults', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeDeelplanResult' ) ); // Define a return type for the result of adding a dossier and/or deelplan /* $this->_register_compound_type( 'typeDossierDeelplanId', array( 'dossierId' => 'int', 'deelplanId' => 'int' ) ); $this->_register_compound_type( 'resultSoapAddDossier', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeDossierDeelplanId' ) ); * */ // Define a return type for the result of manipulating a 'dossier' $this->_register_compound_type( 'typeAssignedBetrokkene', array( 'assignedBetrokkeneId' => 'int', 'naam' => 'string', 'email' => 'string' ) ); $this->_register_array_type( 'arrayTypeAssignedBetrokkene', 'typeAssignedBetrokkene' ); $this->_register_compound_type( 'typeManipulateDossierResult', array( 'dossierId' => 'int', 'dossierHash' => 'string', 'actionResultMessage' => 'string', 'assignedBetrokkenen' => 'arrayTypeAssignedBetrokkene' ) ); $this->_register_compound_type( 'resultSoapManipulateDossier', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeManipulateDossierResult' ) ); // Define a return type for the result of manipulating a 'deelplan' $this->_register_compound_type( 'typeManipulateDeelplanResult', array( 'deelplanId' => 'int', 'actionResultMessage' => 'string' ) ); $this->_register_compound_type( 'resultSoapManipulateDeelplan', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeManipulateDeelplanResult' ) ); // Define a return type for the result of manipulating a 'document' $this->_register_compound_type( 'typeManipulateDocumentResult', array( 'documentId' => 'int', 'actionResultMessage' => 'string' ) ); $this->_register_compound_type( 'resultSoapManipulateDocument', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeManipulateDocumentResult' ) ); // Define a return type for the result of adding a 'hercontroledatum' $this->_register_compound_type( 'typeAddDeelplanHercontroleDatumResult', array( 'hercontroleDatumId' => 'int', 'actionResultMessage' => 'string' ) ); $this->_register_compound_type( 'resultSoapAddDeelplanHercontroleDatum', array( 'success' => 'boolean', 'message' => 'string', 'results' => 'typeAddDeelplanHercontroleDatumResult' ) ); /* * Define the method parameter types. */ // Define the 'parameters' type for the 'soapGetKlanten' method $this->_register_compound_type( 'parametersSoapGetKlanten', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'filter' => 'string', ) ); // Define the 'parameters' type for the 'soapGetGebruikers' method $this->_register_compound_type( 'parametersSoapGetGebruikers', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'klantId' => 'int', ) ); // Define the 'parameters' type for the 'soapGetChecklists' method $this->_register_compound_type( 'parametersSoapGetChecklists', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'klantId' => 'int', 'gebruikerId' => 'int', // Optional. Do not implement this yet (tricky to get 100% right!) ) ); // Define the 'parameters' type for the 'soapGetDeelplanHercontroleDatums' method $this->_register_compound_type( 'parametersSoapGetDeelplanHercontroleDatums', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'dossierHash' => 'string', 'dossierId' => 'int', 'deelplanId' => 'int' ) ); // Define the 'parameters' type for the 'soapGetDeelplanResults' method $this->_register_compound_type( 'parametersSoapGetDeelplanResults', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'dossierHash' => 'string', 'dossierId' => 'int', 'deelplanId' => 'int', 'sjabloonId' => 'int', // Not yet available ) ); // Define the 'parameters' type for the 'soapManipulateDossier' method $this->_register_compound_type( 'parametersSoapManipulateDossier', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'dossierHash' => 'string', // Applicable to: Edit, Delete, Check 'dossierId' => 'int', // Applicable to: Add, Edit, Delete, Check 'dossierNaam' => 'string', // Applicable to: Add, Edit, Check 'identificatieNummer' => 'string', // Applicable to: Add, Edit, Check 'gebruikerId' => 'int', // Applicable to: Add, Edit 'aanmaakDatum' => 'string', // Applicable to: Add, Edit 'bagNummer' => 'string', // Applicable to: Add, Edit 'xyCoordinaten' => 'string', // Applicable to: Add, Edit 'locatieStraat' => 'string', // Applicable to: Add, Edit 'locatieHuisNummer' => 'string', // Applicable to: Add, Edit 'locatieHuisNummerToevoeging' => 'string', // Applicable to: Add, Edit 'locatiePostcode' => 'string', // Applicable to: Add, Edit 'locatieWoonplaats' => 'string', // Applicable to: Add, Edit 'opmerkingen' => 'string', // Applicable to: Add, Edit 'betrokkenen' => 'arrayTypeBetrokkene' // Applicable to: Add, Edit ) ); // Define the 'parameters' type for the 'soapManipulateDeelplan' method $this->_register_compound_type( 'parametersSoapManipulateDeelplan', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'dossierHash' => 'string', // Applicable to: Add, Edit, Delete, Check 'dossierId' => 'int', // Applicable to: Add, check 'deelplanId' => 'int', // Applicable to: Add, Edit, Delete, Check 'deelplanNaam' => 'string', // Applicable to: Add, Edit, Check 'gebruikerId' => 'int', // Applicable to: Add, Edit - toezichthouder 'kenmerk' => 'string', // Applicable to: Add, Edit, Check 'oloNummer' => 'string', // Applicable to: Add, Edit, Check 'aanvraagDatum' => 'string', // Applicable to: Add, Edit 'initieleDatum' => 'string', // Applicable to: Add, Edit 'gebouwdelen' => 'arrayTypeGebouwdeel', // Applicable to: Add, Edit 'scopes' => 'arrayTypeChecklistId', // Applicable to: Add, Edit //'themas' => 'arrayTypeThema', // Applicable to: Add, Edit - needed eventually? - not supported at this time 'betrokkenen' => 'arrayTypeBetrokkeneId', // Applicable to: Add, Edit - simply pass the IDs, do NOT allow full data 'documenten' => 'arrayTypeDocumentId' // Applicable to: Add, Edit - simply pass the IDs, do NOT allow full data ) ); // Define the 'parameters' type for the 'soapManipulateDocument' method $this->_register_compound_type( 'parametersSoapManipulateDocument', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'actie' => 'string', // Valid values: Add, Edit, Delete, Check, ... 'dossierHash' => 'string', // Applicable to: Add, Edit, Delete, Check 'dossierId' => 'int', // Applicable to: Add, Edit, Delete, Check 'document' => 'typeDocument' // Applicable to: Add, Edit, Delete, Check - could be changed to 'arrayTypeDocument' for multiple documents ) ); // Define the 'parameters' type for the 'soapAddDeelplanHercontroleDatum' method $this->_register_compound_type( 'parametersSoapAddDeelplanHercontroleDatum', array( 'licentieNaam' => 'string', 'licentieWachtwoord' => 'string', 'dossierHash' => 'string', // Applicable to: Add, Edit, Delete, Check 'dossierId' => 'int', // Applicable to: Add, check 'deelplanId' => 'int', 'vraagId' => 'int', // Optional. Not implemented yet. 'hercontroleDatum' => 'typeHercontroleDatum' ) ); // // STEP 3: Register methods. All types used here must be registered in step 2, except for the // aforementioned list of simple types in step 2. // Register the RPC calls we want to make available. $this->_register_method( 'resultSoapGetKlanten', 'soapGetKlanten', array( 'parameters' => 'parametersSoapGetKlanten' ) ); $this->_register_method( 'resultSoapGetGebruikers', 'soapGetGebruikers', array( 'parameters' => 'parametersSoapGetGebruikers' ) ); $this->_register_method( 'resultSoapGetChecklists', 'soapGetChecklists', array( 'parameters' => 'parametersSoapGetChecklists' ) ); $this->_register_method( 'resultSoapGetDeelplanHercontroleDatums', 'soapGetDeelplanHercontroleDatums', array( 'parameters' => 'parametersSoapGetDeelplanHercontroleDatums' ) ); $this->_register_method( 'resultSoapGetDeelplanResults', 'soapGetDeelplanResults', array( 'parameters' => 'parametersSoapGetDeelplanResults' ) ); $this->_register_method( 'resultSoapManipulateDossier', 'soapManipulateDossier', array( 'parameters' => 'parametersSoapManipulateDossier' ) ); $this->_register_method( 'resultSoapManipulateDeelplan', 'soapManipulateDeelplan', array( 'parameters' => 'parametersSoapManipulateDeelplan' ) ); $this->_register_method( 'resultSoapManipulateDocument', 'soapManipulateDocument', array( 'parameters' => 'parametersSoapManipulateDocument' ) ); $this->_register_method( 'resultSoapAddDeelplanHercontroleDatum', 'soapAddDeelplanHercontroleDatum', array( 'parameters' => 'parametersSoapAddDeelplanHercontroleDatum' ) ); // // STEP 4: Finalize! // $this->_finalize(); } // Helper method for checking the validity of the passed license name and password. private function checkCredentials($licenseName, $licensePassword) { // Try to retrive the user record with the passed credentials $userAccount = $this->_CI->webserviceaccount->find_by_username_and_password($licenseName, $licensePassword); // If the result was 'null' it means the user credentials provided no match, hence, a result that is not null means the user was found. return (!is_null($userAccount)); } // Helper method for retrieving the dossier and performing the security checks on it. private function getExistingDossier($dossierId, $dossierHash, &$resultSet) { // Initialise the dossier to null $existingDossier = null; // Try to obtain the dossier, error out on exceptions. try { // Use the model to (try to) retrieve the dossier. $existingDossier = $this->_CI->dossier->get( $dossierId ); } catch (exception $e) { // If the call failed, register the unsuccessful outcome and return early $resultSet['results']['actionResultMessage'] = "Het dossier met ID '{$dossierId}' is NIET succesvol opgehaald. Reden: " . $e->getMessage(); // Perform an early return, making sure to return null return null; } // Check if a (valid) dossier has been retrieved, and if so, if the passed credentials match, so we allow edits. if (is_null($existingDossier)) { // If no dossier could be found for the passed ID, return early $resultSet['results']['actionResultMessage'] = "Het dossier met ID '{$dossierId}' bestaat niet."; } else { // Check the dossierHash against the passed value $dossierHashValid = ( (strlen($dossierHash) == 40) && (strlen($existingDossier->dossier_hash) == 40) && ($dossierHash == $existingDossier->dossier_hash) ); // Only allow further processing if the dossier came in through the webservice, AND if it passes the check on the dossier hash. if ( !$dossierHashValid || ($existingDossier->herkomst != 'koppeling') ) { // Reset the retrieved dossier to null, to signal that we do not have access over it $existingDossier = null; // Set a descriptive error message too. $resultSet['results']['actionResultMessage'] = "Het dossier met ID '{$dossierId}' mag niet via de koppeling bewerkt worden."; } else { // Returning the dossier hash for other actions than 'Add' is not really necessary, but it can be used by the caller as a double check. // Make sure to only set the dossier hash in case it was predefined in the result set. if (array_key_exists('results', $resultSet) && array_key_exists('dossierHash', $resultSet['results'])) { $resultSet['results']['dossierHash'] = strval($existingDossier->dossier_hash); } } } // Return the retrieved dossier, if any, and if the passed credentials allow access to it. If not, make sure to return null. return $existingDossier; } // Helper method for retrieving the deelplan. Note: this method does not perform security checks! The security checks are performed on a private function forceToUTF8($textToForceToUTF8 = '') { if (mb_detect_encoding($content,'UTF-8', true) == false) { $textToForceToUTF8 = Encoding::toUTF8($textToForceToUTF8); } return $textToForceToUTF8; } // Helper method for retrieving the deelplan. Note: this method does not perform security checks! The security checks are performed on a // dossier level, which means that the getExistingDossier method must be used prior to getting the deelplan, so as to be sure we are allowed to // make changes to the deelplan. private function getExistingDeelplan($deelplanId, $dossierId, &$resultSet) { // Initialise the deelplan to null $existingDeelplan = null; // Try to obtain the deelplan, error out on exceptions. try { // Use the model to (try to) retrieve the deelplan. $existingDeelplan = $this->_CI->deelplan->get( $deelplanId ); } catch (exception $e) { // If the call failed, register the unsuccessful outcome and return early $resultSet['results']['actionResultMessage'] = "Het deelplan met ID '{$deelplanId}' is NIET succesvol opgehaald. Reden: " . $e->getMessage(); // Perform an early return, making sure to return null return null; } // Check if a (valid) deelplan has been retrieved, and if so, if it belongs to the dossier we are editing. if (is_null($existingDeelplan)) { // If no deelplan could be found for the passed ID, return early $resultSet['results']['actionResultMessage'] = "Het deelplan met ID '{$deelplanId}' bestaat niet."; } else { // Only allow further processing if the deelplan came in through the webservice, AND if it belongs to the dossier. if ( is_null($dossierId) || empty($dossierId) || ($existingDeelplan->dossier_id != $dossierId) ) { // Reset the retrieved deelplan to null, to signal that we do not have access over it $existingDeelplan = null; // Set a descriptive error message too. $resultSet['results']['actionResultMessage'] = "Het deelplan met ID '{$deelplanId}' behoort niet toe aan het dossier met ID '{$dossierId}' en mag daarom niet via de koppeling bewerkt worden."; } else { // The deelplan is valid and is allowed to be edited via this webservice call. Do nothing here... } } // Return the retrieved deelplan, if any. If not, make sure to return null. return $existingDeelplan; } // Helper method for retrieving the document. Note: this method does not perform security checks! The security checks are performed on a // dossier level, which means that the getExistingDossier method must be used prior to getting the document, so as to be sure we are allowed to // make changes to the document. private function getExistingDocument($documentId, $dossierId, &$resultSet) { // Initialise the document to null $existingDocument = null; // Try to obtain the document, error out on exceptions. try { // Use the model to (try to) retrieve the document. $existingDocument = $this->_CI->dossierbescheiden->get( $documentId ); } catch (exception $e) { // If the call failed, register the unsuccessful outcome and return early $resultSet['results']['actionResultMessage'] = "Het document met ID '{$documentId}' is NIET succesvol opgehaald. Reden: " . $e->getMessage(); // Perform an early return, making sure to return null return null; } // Check if a (valid) document has been retrieved, and if so, if it belongs to the dossier we are editing. if (is_null($existingDocument)) { // If no document could be found for the passed ID, return early $resultSet['results']['actionResultMessage'] = "Het document met ID '{$documentId}' bestaat niet."; } else { // Only allow further processing if the document came in through the webservice, AND if it belongs to the dossier. if ( is_null($dossierId) || empty($dossierId) || ($existingDocument->dossier_id != $dossierId) ) { // Reset the retrieved document to null, to signal that we do not have access over it $existingDocument = null; // Set a descriptive error message too. $resultSet['results']['actionResultMessage'] = "Het document met ID '{$documentId}' behoort niet toe aan het dossier met ID '{$dossierId}' en mag daarom niet via de koppeling bewerkt worden."; } else { // The document is valid and is allowed to be edited via this webservice call. Do nothing here... } } // Return the retrieved document, if any. If not, make sure to return null. return $existingDocument; } // RPC implementation of 'soapGetKlanten'. public function soapGetKlanten( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( array( 'klantId' => -1, 'klantNaam' => '', 'aantalChecklists' => -1 ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the passed filter (if any) from the parameters, and apply the filter if necessary. // Note: partially implemented at this time. $filter = $parameters->filter; $additional_joins = ''; $where_conditions = '1 = 1'; if (!empty($filter)) { // ... Actual filter implementation. // Note: filters can consists of multiple values, space separated, so extract the various parts for making them work easily. $filter_parts = explode(' ', $filter); // Handle the 'registered_clients' filter. // Format: 'registered_clients <klant_id>' // Note: the above format was later revised. It's now no longer necessary to pass the klant ID. Instead, the text 'registered_clients' suffices // (as long as the proper klant_id value is registered in the webservice_accounts table). if ($filter_parts[0] == 'registered_clients') { // Try to retrieve the webservice account record with the passed credentials $wsAccount = $this->_CI->webserviceaccount->find_by_username_and_password($parameters->licentieNaam, $parameters->licentieWachtwoord); // Now use the webservice_applicatie_id value to determine if we need to filter anything or not. //if ( !is_null($wsAccount) && is_int($wsAccount->webservice_applicatie_id) && !empty($filter_parts[1]) ) if ( !is_null($wsAccount) && is_int($wsAccount->webservice_applicatie_id) && !is_null($wsAccount->klant_id) ) { // Extract the filter values $filterWebserviceApplicatieId = $wsAccount->webservice_applicatie_id; //$filterKlantId = $filter_parts[1]; $filterKlantId = $wsAccount->klant_id; //$additional_joins .= "LEFT JOIN webservice_account_filter_01 t3"; $where_conditions = "t1.id IN ( SELECT target_id FROM webservice_account_filter_01 WHERE (webservice_applicatie_id = {$filterWebserviceApplicatieId}) AND (source_id = {$filterKlantId}) )"; } } // if ($filter_parts[0] == 'registered_clients') } // if (!empty($filter)) // Define the query to get the data we need. $query = "SELECT t1.id AS k_id, t1.naam AS k_naam, COUNT(t1.id) AS cnt FROM klanten t1 INNER JOIN bt_checklist_groepen t2 ON (t1.id = t2.klant_id) INNER JOIN bt_checklisten t3 ON (t2.id = t3.checklist_groep_id) {$additional_joins} WHERE {$where_conditions} GROUP BY t1.id ORDER BY k_naam"; //echo $query; // Perform the query $this->_CI->dbex->prepare( 'find', $query ); $res = $this->_CI->dbex->execute( 'find', array( ) ); if ($res->num_rows < 1) { $resultSet['message'] = "Er zijn geen klanten gedefinieerd voor de opgegeven combinatie van licentie- en filtergegevens"; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De klanten zijn succesvol opgehaald'; // Make sure to remove the negatively asserted initial result data $resultSet['results'] = array(); } // Process the results, store them in an array $res_cnt = 0; foreach ($res->result() as $row) { $res_cnt++; // Extract the results and store them in the (properly formatted) result set $k_id = $row->k_id; $k_naam = strval($row->k_naam); $cnt = $row->cnt; //echo "$res_cnt: ID: {$k_id}: {$k_naam} - {$cnt}\n"; // Compile the result such that it matches the 'typeKlant' type $result = array( 'klantId' => $k_id, 'klantNaam' => $k_naam, 'aantalChecklists' => $cnt ); // Store it in the result set array, such that it matches the 'arrayTypeKlant' type $resultSet['results'][] = $result; } // When we're done, return the result set return $resultSet; } // public function soapGetKlanten( $parameters ) // RPC implementation of 'soapGetGebruikers'. public function soapGetGebruikers( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( array( 'gebruikerId' => -1, 'volledigeNaam' => '', 'email' => '' ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the passed 'klant ID' from the parameters. $klantId = $parameters->klantId; // Define the query to get the data we need. $query = "SELECT id, volledige_naam, email FROM gebruikers WHERE ( (klant_id = ?) AND (status = 'actief') ) ORDER BY volledige_naam"; //echo $query; // Perform the query $this->_CI->dbex->prepare( 'find', $query ); $res = $this->_CI->dbex->execute( 'find', array( $klantId ) ); if ($res->num_rows < 1) { $resultSet['message'] = "Er zijn geen actieve gebruikers gedefinieerd voor de opgegeven klant"; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De gebruikers zijn succesvol opgehaald'; // Make sure to remove the negatively asserted initial result data $resultSet['results'] = array(); } // Process the results, store them in an array $res_cnt = 0; foreach ($res->result() as $row) { $res_cnt++; // Extract the results and store them in the (properly formatted) result set $id = $row->id; $naam = strval($row->volledige_naam); $email = strval($row->email); //echo "$res_cnt: ID: {$id}: {$naam}\n"; // Compile the result such that it matches the 'typeGebruiker' type $result = array( 'gebruikerId' => $id, 'volledigeNaam' => $naam, 'email' => $email ); // Store it in the result set array, such that it matches the 'arrayTypeGebruiker' type $resultSet['results'][] = $result; } // When we're done, return the result set return $resultSet; } // public function soapGetGebruikers( $parameters ) // RPC implementation of 'soapGetChecklists'. public function soapGetChecklists( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( array( 'checklistGroepId' => -1, 'checklistGroepNaam' => '', 'checklistId' => -1, 'checklistNaam' => '' ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the passed 'klant ID' from the parameters. $klantId = $parameters->klantId; // Define the query to get the data we need. /* $query = "SELECT t2.id AS clg_id, t2.naam AS clg_naam, t3.id AS cl_id, t3.naam AS cl_naam FROM klanten t1 INNER JOIN bt_checklist_groepen t2 ON (t1.id = t2.klant_id) INNER JOIN bt_checklisten t3 ON (t2.id = t3.checklist_groep_id) WHERE t1.id = ? ORDER BY clg_naam, t2.sortering, cl_naam, t3.sortering"; * */ // NOTE: The above query ONLY returns the checklists that were created by a specific client! The below one also returns those to which access was granted, but // that don't (necessarily) belong to the respective client. $query = "SELECT t2.id AS clg_id, t2.naam AS clg_naam, t2.sortering AS clg_sortering, t3.id AS cl_id, t3.naam AS cl_naam, t3.sortering AS cl_sortering FROM klanten t1 INNER JOIN bt_checklist_groepen t2 ON (t1.id = t2.klant_id) INNER JOIN bt_checklisten t3 ON (t2.id = t3.checklist_groep_id) WHERE (t1.id = ?) AND (((t3.status IS NULL) OR (t3.status = 'afgerond')) AND (t2.standaard_checklist_status = 'afgerond')) UNION SELECT t4.id AS clg_id, t4.naam AS clg_naam, t4.sortering AS clg_sortering, t3.id AS cl_id, t3.naam AS cl_naam, t3.sortering AS cl_sortering FROM klanten t1 INNER JOIN bt_checklist_groep_klanten t2 ON (t1.id = t2.klant_id) INNER JOIN bt_checklisten t3 ON (t2.checklist_groep_id = t3.checklist_groep_id) INNER JOIN bt_checklist_groepen t4 ON (t2.checklist_groep_id = t4.id) WHERE (t1.id = ?) AND (((t3.status IS NULL) OR (t3.status = 'afgerond')) AND (t4.standaard_checklist_status = 'afgerond')) ORDER BY clg_naam, clg_sortering, cl_naam, cl_sortering"; //echo $query; // Perform the query $this->_CI->dbex->prepare( 'find', $query ); $res = $this->_CI->dbex->execute( 'find', array( $klantId, $klantId ) ); if ($res->num_rows < 1) { $resultSet['message'] = "De klant met ID '{$klantId}' bestaat niet of er zijn geen checklistgroep(en) en/of checklists voor gedefinieerd"; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De checklistgroep(en) en bijbehorende checklists zijn succesvol opgehaald'; // Make sure to remove the negatively asserted initial result data $resultSet['results'] = array(); } // Process the results, store them in an array $res_cnt = 0; foreach ($res->result() as $row) { $res_cnt++; // Extract the results and store them in the (properly formatted) result set $clg_id = $row->clg_id; $clg_naam = $row->clg_naam; $cl_id = $row->cl_id; $cl_naam = $row->cl_naam; //echo "$res_cnt: ID: {$cl_id}: {$clg_naam} - {$cl_naam}\n"; // Compile the result such that it matches the 'typeChecklistGroepChecklist' type $result = array( 'checklistGroepId' => $clg_id, 'checklistGroepNaam' => $clg_naam, 'checklistId' => $cl_id, 'checklistNaam' => $cl_naam ); // Store it in the result set array, such that it matches the 'arrayTypeChecklistGroepChecklist' type $resultSet['results'][] = $result; } // When we're done, return the result set return $resultSet; } // public function soapGetChecklists( $parameters ) // RPC implementation of 'soapGetDeelplanHercontroleDatums'. public function soapGetDeelplanHercontroleDatums( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( 'actionResultMessage' => '', 'hercontroleDatums' => array( array( 'hercontroleDatumId' => -1, 'gebruikerId' => -1, 'hercontroleDatum' => '', 'hercontroleStartTijd' => '', 'hercontroleEindTijd' => '', 'voortgangsPercentage' => '' ) ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Check if a valid dossier ID and hash have been passed, this is our security mechanism, and we are only allowed to continue if we // can successfully obtain a dossier object for the passed parameters. $dossierId = ($parameters->dossierId > 0) ? $parameters->dossierId : 0; $dossierHash = (!empty($parameters->dossierHash)) ? $parameters->dossierHash : ''; $existingDossier = $this->getExistingDossier($dossierId, $dossierHash, $resultSet); // If no valid dossier was retrieved, or if we don't have any access rights over it, return early. if (is_null($existingDossier) ) { return $resultSet; } // If we reached this point, we have managed to determine that a valid dossier has been specified and that we have proper access to it. Proceed to try to retrieve // the requested deelplan and check if it belongs to the previously retrieved dossier. If so, we have satisfied the security checks. $deelplanId = ($parameters->deelplanId > 0) ? $parameters->deelplanId : 0; // If a deelplan ID was passed, we try to get that deelplan and check if it belongs to the retrieved dossier. If no ID was passed, or if the deelplan does not belong // to the retrieved dossier, we throw an error. if (empty($deelplanId) || !is_int($deelplanId)) { $resultSet['message'] = 'Er is geen geldige deelplan ID opgegeven.'; return $resultSet; } else { // Get the existing deelplan (if any) as an object. // Note: the last parameter (being the "result set") is taken by reference, as it too will be manipulated in the method. $existingDeelplan = $this->getExistingDeelplan($deelplanId, $dossierId, $resultSet); // Now, if we did not obtain a valid deelplan, it means the above call did not retrieve a deelplan, or that we otherwise do // not have the rights to manipulate it. In that situation we return early. if (is_null($existingDeelplan) ) { // If no valid deelplan was retrieved, or if we don't have any access rights over it, return early. return $resultSet; } } // If we have reached this point, we should have established that the deelplan is valid and belongs to the dossier. All securty checks have at this point // been satisfied, and the actual work can then be done next. // Note: the model has been extended on behalf of this webservice based call. It now features a 'simple' and a 'full' mode, the latter of which must be used // in order to obtain all of the required data. //$deelplanHercontroleData = $this->_CI->deelplan->get_hercontrole_data( $deelplanId, 0, 0, false, null, false ); // 'Simple' mode $deelplanHercontroleData = $this->_CI->deelplan->get_hercontrole_data( $deelplanId, 0, 0, false, null, true ); // 'Full' mode //if (is_null($deelplanHercontroleData) || empty($deelplanHercontroleData)) if (empty($deelplanHercontroleData)) { $resultSet['message'] = 'Er zijn geen hercontrole datums opgegeven voor het gekozen deelplan.'; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De hercontroledatums zijn succesvol opgehaald'; // Make sure to remove the negatively asserted initial result data $resultSet['results']['hercontroleDatums'] = array(); // Process the results, store them in an array //$res_cnt = 0; foreach ($deelplanHercontroleData as $deelplanHercontroleDatum) { //$res_cnt++; // Compile the result such that it matches the 'typeHercontroleDatum' type $result = array( 'hercontroleDatumId' => $deelplanHercontroleDatum['vraag_id'], // This value is hardly useful. Multiple occurences of the same date result in only one entry! 'gebruikerId' => $deelplanHercontroleDatum['gebruiker_id'], 'hercontroleDatum' => $deelplanHercontroleDatum['hercontrole_datum'], 'hercontroleStartTijd' => $deelplanHercontroleDatum['hercontrole_start_tijd'], 'hercontroleEindTijd' => $deelplanHercontroleDatum['hercontrole_eind_tijd'], 'voortgangsPercentage' => $deelplanHercontroleDatum['voortgang_percentage'] ); // Store it in the result set array, such that it matches the 'arrayTypeChecklistGroepChecklist' type $resultSet['results']['hercontroleDatums'][] = $result; } } // When we're done, return the result set return $resultSet; } // public function soapGetDeelplanHercontroleDatums( $parameters ) // RPC implementation of 'soapGetDeelplanResults'. public function soapGetDeelplanResults( $parameters ) { ini_set('default_socket_timeout', 600); // For now, hard-code the document type to 'docx' $doc_type = 'docx'; // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( 'deelplanId' => -1, 'status' => '', 'actionResultMessage' => '', 'rapportFormaat' => strtoupper($doc_type), // 'PDF' of 'DOCX' 'rapport' => '', // 'base64Binary' 'checklistVragen' => array( array( 'checklistId' => -1, 'checklistNaam' => '', 'hoofdgroepNaam' => '', 'hoofdThemaNaam' => '', 'themaNaam' => '', 'vraagTekst' => '', 'statusTekst' => '', 'statusKleur' => '', 'toelichting' => '', 'grondslagen' => '', 'datumTijd' => '' ) ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Check if a valid dossier ID and hash have been passed, this is our security mechanism, and we are only allowed to continue if we // can successfully obtain a dossier object for the passed parameters. $dossierId = ($parameters->dossierId > 0) ? $parameters->dossierId : 0; $dossierHash = (!empty($parameters->dossierHash)) ? $parameters->dossierHash : ''; $existingDossier = $this->getExistingDossier($dossierId, $dossierHash, $resultSet); // If no valid dossier was retrieved, or if we don't have any access rights over it, return early. if (is_null($existingDossier) ) { return $resultSet; } // If we reached this point, we have managed to determine that a valid dossier has been specified and that we have proper access to it. Proceed to try to retrieve // the requested deelplan and check if it belongs to the previously retrieved dossier. If so, we have satisfied the security checks. $deelplanId = ($parameters->deelplanId > 0) ? $parameters->deelplanId : 0; // If a deelplan ID was passed, we try to get that deelplan and check if it belongs to the retrieved dossier. If no ID was passed, or if the deelplan does not belong // to the retrieved dossier, we throw an error. if (empty($deelplanId) || !is_int($deelplanId)) { $resultSet['message'] = 'Er is geen geldige deelplan ID opgegeven.'; return $resultSet; } else { // Get the existing deelplan (if any) as an object. // Note: the last parameter (being the "result set") is taken by reference, as it too will be manipulated in the method. $existingDeelplan = $this->getExistingDeelplan($deelplanId, $dossierId, $resultSet); // Now, if we did not obtain a valid deelplan, it means the above call did not retrieve a deelplan, or that we otherwise do // not have the rights to manipulate it. In that situation we return early. if (is_null($existingDeelplan) ) { // If no valid deelplan was retrieved, or if we don't have any access rights over it, return early. return $resultSet; } // Set the ID of the actually retrieved deelplan (this should by definition match the deelplanId value that was passed, but it serves as an extra // check to ascertain that indeed the full steps have been completed to actually get the deelplan. $resultSet['results']['deelplanId'] = $existingDeelplan->id; } // If we have reached this point, we should have established that the deelplan is valid and belongs to the dossier. All securty checks have at this point // been satisfied, and the actual work can then be done next. // No time limit, export might take a while! set_time_limit( 0 ); // Load the library that creates the report for us $this->_CI->load->library('dossierexport'); // We now have to carefully mimick the POST data that would normally in the application have been POSTed. // It should be duly noted that this, by definition, is somewhat dangerous, as the filter settings in the report mechanism may change at any time, // at which moment the below SHOULD be changed accordingly to properly reflect the changes. There does not seem to be an easy way around this, so // we will have to make-do with properly mimicking the POST data... // Start by specifying which report parts need to be present in the report. $_POST['onderdeel'] = array( 'inleiding' => 'on', 'dossiergegevens' => 'on', 'documenten' => 'on', 'deelplannen' => 'on', 'samenvatting' => 'on', 'bevindingen' => 'on', 'aandachtspunten' => 'on', 'bijlage-fotos' => 'on', 'bijlage-annotaties' => 'on', 'bijlage-documenten-tekeningen' => 'on', 'bijlage-juridische-grondslag' => 'on', 'show-revisions' => 'on' ); // Then specify the proper deelplan ID $_POST['deelplan'] = $deelplanId; // Specify which 'grondslagen' data to include $_POST['grondslag'] = array( 'NEN' => 'on', 'NEN-EN' => 'on' ); // Specify the 'waardeoordelen' that should be included. // !!!! Check this for completeness !!!! $_POST['waardeoordeel'] = array( 'Voldoet niet' => 'on', 'Geen waardeoordeel' => 'on', 'Niet van toepassing' => 'on', 'Voldoet' => 'on' ); // Specify the output format. This should/could be made more dynamic to allow for other types too. For now, hard-code it to 'docx' $_POST['output_format'] = 'output_format:docx'; // Specify the 'target' $_POST['target'] = 'target:download'; // Specify the email address to use. Leave this blank when generating a download. $_POST['custom_email'] = ''; // Specify a 'download tag'. Simply use a date-time seeded SHA1 value for this. $_POST['download-tag'] = sha1(date("Ymd-His")); // On behalf of 'fooling' the security mechanism, and/or other necessary manipulation of the base levels that in the normal application context have // specific information available, we have to pass in some additional data in the $_POST values, so we can properly trap and handle these situations // elsewhere in the code. Add in such information from this point onwards. // The matrix::add model::method requires a properly defined 'klant_id'. Specify an override value here. if (!is_null($existingDossier->gebruiker_id) && !empty($existingDossier->gebruiker_id)) { $dossierGebruiker = $this->_CI->gebruiker->get($existingDossier->gebruiker_id); $_POST['overridden_gebruiker_id'] = $dossierGebruiker->id; $_POST['overridden_klant_id'] = $dossierGebruiker->klant_id; } // Note that the following code should occur AFTER the $_POST array has been properly provided with the 'overridden_klant_id' value, as some // of the underlying code requires the override to be applied! $deelplanVragen = array(); foreach ($existingDeelplan->get_checklisten() as $i => $checklist) { //d($checklist); $checklistVragen = $existingDeelplan->get_checklist_vragen( $checklist->checklist_id ); //d($checklistVragen); //d($this->_CI->deelplan->filter_vragen( $existingDeelplan->id, $checklistVragen, $prioriteiten )); $deelplanVragen[$checklist->checklist_id] = $this->_CI->deelplan->filter_vragen( $existingDeelplan->id, $checklistVragen, $prioriteiten ); } if (is_null($deelplanVragen) || empty($deelplanVragen)) { $resultSet['message'] = 'Er zijn geen vragen beschikbaar voor het gekozen deelplan.'; } else { // Indicate that the call was successful //$resultSet['success'] = true; $resultSet['message'] = 'De vragen zijn succesvol opgehaald.'; // Make sure to remove the negatively asserted initial result data $resultSet['results']['checklistVragen'] = array(); // Process the results, store them in an array foreach ($deelplanVragen as $checklistId => $checklistVragen) { // Get the checklist, for extracting the data we need from it $checklist = $this->_CI->checklist->get($checklistId); //d($checklist); // Then proceed to store the relevant data of the questions. //$res_cnt = 0; foreach($checklistVragen as $checklistVraag) { //$res_cnt++; $statusTekst = $checklistVraag->get_waardeoordeel( false, $checklistVraag->status ); $statusKleur = $checklistVraag->get_waardeoordeel_kleur( false, $checklistVraag->status ); $vraagGrondslagen = $checklistVraag->get_grondslagen(); /* d($statusTekst); d($statusKleur); d($vraagGrondslagen); exit; * */ $grondslagen = ''; foreach ($vraagGrondslagen as $vraagGrondslag) { if (!empty($grondslagen)) { $grondslagen .= ', '; } $grondslagen .= $vraagGrondslag->get_grondslag()->grondslag; } // Compile the result such that it matches the 'typeChecklistVraag' type $toelichtingValue = strval($checklistVraag->toelichting); $toelichtingValue = str_replace( '[GERELATEERDE BEVINDING]', '', str_replace( '[TEKSTBALLON]', '', $toelichtingValue ) ); $toelichtingValue = str_replace('<', '[', $toelichtingValue); $toelichtingValue = str_replace('&lt;', '[', $toelichtingValue); $toelichtingValue = str_replace('>', ']', $toelichtingValue); $toelichtingValue = str_replace('&gt;', ']', $toelichtingValue); $result = array( 'checklistId' => $checklist->id, 'checklistNaam' => $this->forceToUTF8($checklist->naam), 'hoofdgroepNaam' => $this->forceToUTF8($checklistVraag->hoofdgroep_naam), 'hoofdThemaNaam' => $this->forceToUTF8($checklistVraag->hoofdthema), 'themaNaam' => $this->forceToUTF8($checklistVraag->thema), 'vraagTekst' => $this->forceToUTF8($checklistVraag->tekst), 'statusTekst' => $this->forceToUTF8(strval($statusTekst)), 'statusKleur' => $this->forceToUTF8(strval($statusKleur)), 'toelichting' => $this->forceToUTF8($toelichtingValue), 'grondslagen' => $this->forceToUTF8($grondslagen), 'datumTijd' => $checklistVraag->last_updated_at ); // Store it in the result set array, such that it matches the 'arrayTypeChecklistGroepChecklist' type $resultSet['results']['checklistVragen'][] = $result; } } } //d($resultSet['results']['checklistVragen']); exit; $skip_generate_report = false; //$skip_generate_report = true; // Finally, generate the report if (!$skip_generate_report) { $docdata = $this->_CI->dossierexport->export( $existingDossier, $doc_type, $_POST, $deelplan_objecten ); //d($docdata); // d($docdata->get_contents()); // d(base64_encode($docdata->get_contents())); // $resultSet['results']['rapport'] = $docdata->get_contents(); $report_data = $docdata->get_contents(); } else { $report_data = ''; } // Note: it's important that we take care of the base64 encoding ourselves, as otherwise a 'looks like we got no data' SOAP exception occurs! $resultSet['results']['rapport'] = base64_encode($report_data); if (empty($resultSet['results']['rapport']) || is_null($resultSet['results']['rapport'])) { $resultSet['results']['status'] = 'Het rapport is niet succesvol gegenereerd'; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De deelplangegevens zijn succesvol opgehaald'; $resultSet['results']['status'] = 'Het rapport is succesvol gegenereerd'; } //d($resultSet); // genereer daadwerkelijke rapport //$doc_type = ($_POST['output_format'] == 'output_format:docx') ? 'docx' : 'standaard'; //$doc_type = 'docx'; //$docdata = $this->dossierexport->export( $dossier, $doc_type, $_POST, $deelplan_objecten ); // $docdata = $this->dossierexport->export( $existingDossier, $doc_type, $_POST, $deelplan_objecten ); // d($docdata); /* // // Note: the model has been extended on behalf of this webservice based call. It now features a 'simple' and a 'full' mode, the latter of which must be used // in order to obtain all of the required data. //$deelplanHercontroleData = $this->_CI->deelplan->get_hercontrole_data( $deelplanId, 0, 0, false, null, false ); // 'Simple' mode $deelplanHercontroleData = $this->_CI->deelplan->get_hercontrole_data( $deelplanId, 0, 0, false, null, true ); // 'Full' mode //if (is_null($deelplanHercontroleData) || empty($deelplanHercontroleData)) if (empty($deelplanHercontroleData)) { $resultSet['message'] = 'Er zijn geen hercontrole datums opgegeven voor het gekozen deelplan.'; } else { // Indicate that the call was successful $resultSet['success'] = true; $resultSet['message'] = 'De hercontroledatums zijn succesvol opgehaald'; // Make sure to remove the negatively asserted initial result data $resultSet['results'] = array(); // Process the results, store them in an array //$res_cnt = 0; foreach ($deelplanHercontroleData as $deelplanHercontroleDatum) { //$res_cnt++; // Compile the result such that it matches the 'typeHercontroleDatum' type $result = array( 'hercontroleDatumId' => $deelplanHercontroleDatum['vraag_id'], // This value is hardly useful. Multiple occurences of the same date result in only one entry! 'gebruikerId' => $deelplanHercontroleDatum['gebruiker_id'], 'hercontroleDatum' => $deelplanHercontroleDatum['hercontrole_datum'], 'hercontroleStartTijd' => $deelplanHercontroleDatum['hercontrole_start_tijd'], 'hercontroleEindTijd' => $deelplanHercontroleDatum['hercontrole_eind_tijd'], 'voortgangsPercentage' => $deelplanHercontroleDatum['voortgang_percentage'] ); // Store it in the result set array, such that it matches the 'arrayTypeChecklistGroepChecklist' type $resultSet['results'][] = $result; } } * */ // When we're done, return the result set return $resultSet; } // public function soapGetDeelplanResults( $parameters ) // RPC implementation of 'soapManipulateDossier'. public function soapManipulateDossier( $parameters ) { // At least during the development phase, set the error_reportuing level such that we can see what is going on if something fails! error_reporting(E_ALL); // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( 'dossierId' => -1, 'dossierHash' => '', 'actionResultMessage' => '', 'assignedBetrokkenen' => array( array( 'assignedBetrokkeneId' => -1, 'naam' => '', 'email' => '' ) ) ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; return $resultSet; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the desired action from the parameters and check if it is a valid action. $action = strtolower($parameters->actie); $allowedActions = array('add', 'edit', 'delete', 'check', 'archive'); if (!in_array($action, $allowedActions)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven actie '{$action}' is niet ondersteund. Geldige waarden: " . implode(', ', $allowedActions); return $resultSet; } // If we reached this point, we have managed to determine that a supported action has been specified; handle it as required. // Extract the values we need, making sure they have the correct data type, etc. $dossierId = ($parameters->dossierId > 0) ? $parameters->dossierId : 0; $dossierHash = (!empty($parameters->dossierHash)) ? $parameters->dossierHash : ''; $kenmerk = (!empty($parameters->identificatieNummer)) ? $parameters->identificatieNummer : ''; $beschrijving = (!empty($parameters->dossierNaam)) ? $parameters->dossierNaam : ''; $aanmaakDatum = (!empty($parameters->aanmaakDatum)) ? strtotime($parameters->aanmaakDatum) : strtotime("now"); $locatieAdres = (!empty($parameters->locatieStraat)) ? $parameters->locatieStraat : ''; $locatieAdres .= (!empty($parameters->locatieHuisNummer)) ? ' '.$parameters->locatieHuisNummer : ''; $locatieAdres .= (!empty($parameters->locatieHuisNummerToevoeging)) ? $parameters->locatieHuisNummerToevoeging : ''; $locatiePostcode = (!empty($parameters->locatiePostcode)) ? str_replace(' ', '', $parameters->locatiePostcode) : ''; $locatieWoonplaats = (!empty($parameters->locatieWoonplaats)) ? $parameters->locatieWoonplaats : ''; $locatieKadastraal = ''; // Do we need to add this to the interface? $locatieSectie = ''; // Do we need to add this to the interface? $locatieNummer = ''; // Do we need to add this to the interface? $opmerkingen = (!empty($parameters->opmerkingen)) ? $parameters->opmerkingen : ''; $herkomst = 'koppeling'; $bagNummer = (!empty($parameters->bagNummer)) ? $parameters->bagNummer : ''; $xyCoordinaten = (!empty($parameters->xyCoordinaten)) ? $parameters->xyCoordinaten : ''; $gebruikerId = (!empty($parameters->gebruikerId)) ? $parameters->gebruikerId : null; $betrokkenen = (!empty($parameters->betrokkenen)) ? $parameters->betrokkenen : array(); // Define the models we will need. //$this->_CI->load->model( 'dossier' ); //$this->_CI->load->model( 'dossiersubject' ); // For calls that require an existing dossier, we first try to get that dossier. // Note: make sure to do this in such a way that ample error and security checking is performed! //$existingDossier = null; //if (in_array($action, array('edit', 'delete', 'check')) && !empty($dossierId)) if ( ($action != 'add') && !empty($dossierId) ) { // Get the existing dossier (if any) as an object. // Note: the last parameter (being the "result set") is taken by reference, as it too will be manipulated in the method. $existingDossier = $this->getExistingDossier($dossierId, $dossierHash, $resultSet); // Now, if we did not obtain a valid dossier hash value, it means the above call did not retrieve a dossier, or that we otherwise do // not have the rights to manipulate it. In that situation we return early. //if ( strlen($resultSet['results']['dossierHash']) != 40 ) if (is_null($existingDossier) ) { // If no valid dossier was retrieved, or if we don't have any access rights over it, return early. return $resultSet; } } // if (in_array($action, array('edit', 'delete', 'check')) && !empty($dossierId)) // Handle the request in the way it should be handled. This is determined by the specific action that was passed. if ($action == 'add') { // Check if the required fields have been filled in //$requiredFields = (); // Use the model to create the dossier. try { // Use the model to (try to) create the dossier. $createdDossierId = $this->_CI->dossier->add( $kenmerk, $beschrijving, $aanmaakDatum, $locatieAdres, $locatiePostcode, $locatieWoonplaats, $locatieKadastraal, $locatieSectie, $locatieNummer, $opmerkingen, '', $herkomst, $gebruikerId ); // Create a properly seeded hash for this dossier $createdDossierHash = sha1($createdDossierId . date("Ymd-His")); // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['dossierId'] = $createdDossierId; $resultSet['results']['dossierHash'] = $createdDossierHash; $resultSet['results']['actionResultMessage'] = "Het dossier is succesvol aangemaakt."; // Now, semi-silently (try to) set the passed fields that we cannot set through the 'add' call. This does almost the same thing as is done in // the 'Edit' action, but it doesn't use the same error handling, as at least the dossier was created. // First, get the dossier we just created $existingDossier = $this->_CI->dossier->get( $createdDossierId ); // Then edit the additional fields $existingDossier->bag_identificatie_nummer = $bagNummer; $existingDossier->xy_coordinaten = $xyCoordinaten; $existingDossier->dossier_hash = $createdDossierHash; // Try to save the changes if ($existingDossier->save($existingDossier, true, null, false)) { // Success. Do nothing. At least for now. } else { // If the call failed, notify the user. $resultSet['results']['actionResultMessage'] .= " N.B. enkele velden konden NIET succesvol worden opgeslagen!"; } } catch (exception $e) { /* echo $e->getMessage() . $e->getTraceAsString() . "<br />"; echo '<pre>'; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo '</pre>'; //$debug_trace_messages = debug_backtrace(nl2br(DEBUG_BACKTRACE_IGNORE_ARGS)); //d($debug_trace_messages); * */ $createdDossierId = -1; // If the call failed, register the unsuccessful outcome $resultSet['results']['dossierId'] = $createdDossierId; $resultSet['results']['actionResultMessage'] = "Het dossier is NIET succesvol aangemaakt. Reden: " . $e->getMessage(); } //d($createdDossierId); exit; } // if ($action == 'add') else if ($action == 'edit') { // Update the fields we are allowed to edit through this call. $existingDossier->kenmerk = $kenmerk; $existingDossier->beschrijving = $beschrijving; $existingDossier->locatie_adres = $locatieAdres; $existingDossier->locatie_postcode = $locatiePostcode; $existingDossier->locatie_woonplaats = $locatieWoonplaats; $existingDossier->opmerkingen = $opmerkingen; $existingDossier->bag_identificatie_nummer = $bagNummer; $existingDossier->xy_coordinaten = $xyCoordinaten; $existingDossier->gebruiker_id = $gebruikerId; //$existingDossier->beschrijving = $beschrijving; //$existingDossier->locatie_kadastraal = $locatieKadastraal; //$existingDossier->locatie_sectie = $locatieSectie; //$existingDossier->locatie_nummer = $locatieNummer; // Try to save the changes if ($existingDossier->save($existingDossier, true, null, false)) { // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['dossierId'] = $existingDossier->id; $resultSet['results']['actionResultMessage'] = "Het dossier is succesvol bewerkt."; } else { // If the call failed, register the unsuccessful outcome $resultSet['results']['dossierId'] = $existingDossier->id; $resultSet['results']['actionResultMessage'] = "Het dossier is NIET succesvol bewerkt."; } } // else if ($action == 'edit') else if ($action == 'archive') { // Call the dossier model's 'archiveer' method. $existingDossier->archiveer(); // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['dossierId'] = $existingDossier->id; $resultSet['results']['actionResultMessage'] = "Het dossier is succesvol gearchiveerd."; } // else if ($action == 'archive') else if ($action == 'delete') { // TODO: implement this. Do we do a 'soft delete' (via 'verwijder()') or a hard one? } // else if ($action == 'delete') else if ($action == 'check') { // Since we reached this point, the dossier apparently exists and we are allowed to edit it. $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['actionResultMessage'] = "Het dossier met ID '{$dossierId}' bestaat en mag via de koppeling bewerkt worden."; } // else if ($action == 'check') //d($resultSet['results']['actionResultMessage']); // If any of the above actions resulted in an unsuccessful outcome, return early. if (!$resultSet['success']) { return $resultSet; } // For the 'Add' and 'Edit' actions we need to process the 'betrokkenen' too if (in_array($action, array('add', 'edit'))) { // When we have reached this point, we should have a valid existing dossier object. Nevertheless, check if this is the case if (!is_null($existingDossier)) { // Start by getting the existing 'betrokkenen'. // Note: the second parameter causes the result set to be associative, which is handy for our purposes. $existingDossierSubjects = $this->_CI->dossiersubject->get_by_dossier( $existingDossier->id, true ); $existingDossierSubjectsKeys = array_keys($existingDossierSubjects); // Now we have to handle them as required, this can mean that the (newly) passed 'betrokkenen' get added or edited. // At this moment we do not remove existing betrokkenen that are not passed in the call. In the future we may choose to do so, but for now // we only allow additions and changes to existing ones. // Loop over the passed subjects (if any) and handle them as required. //d($existingDossierSubjects); foreach ($betrokkenen as $betrokkene) { // Assume no details need to be stored $updateBetrokkene = false; // Check if we need to add or edit. If we need to edit, we only allow edits to existing betrokkenen of the dossier we are processing. // Note 1: one can pass a negative betrokkeneId value if no action is desired. // Note 2: At present there is no mechanism to remove a betrokkene. If this is needed in due time, we need to extend the below logic to // accomodate for it. There is a catch though: when removing existing betrokkenen, the data they may be associated too needs to be properly // purified too. if ($betrokkene->betrokkeneId == 0) { // Add this betrokkene, if enough data has been provided for them. // The base model call is very limited, just the dossier ID and the role. $dossierSubject = $this->_CI->dossiersubject->add($existingDossier->id, $betrokkene->rol); // If a subject was successfully created, signal that we need to update the rest of the information too. if (!is_null($dossierSubject)) { $updateBetrokkene = true; } } //else if ( ($betrokkene->betrokkeneId > 0) && array_key_exists($betrokkene->betrokkeneId, $existingDossierSubjectsKeys) ) else if ( ($betrokkene->betrokkeneId > 0) && in_array($betrokkene->betrokkeneId, $existingDossierSubjectsKeys) ) { // We are dealing with an existing betrokkene of the dossier that is currently being processed, edit the data // If not, bail out (either silently or with a warning) // Get the subject $dossierSubject = $this->_CI->dossiersubject->get($betrokkene->betrokkeneId); // If a subject was successfully retrieved, signal that we need to update the rest of the information too. if (!is_null($dossierSubject)) { $updateBetrokkene = true; } } // If we need to update the (rest of the) fields, fill in the other passed fields and save the values. if ($updateBetrokkene) { $dossierSubject->rol = $betrokkene->rol; $dossierSubject->organisatie = $betrokkene->organisatie; $dossierSubject->naam = $betrokkene->naam; $dossierSubject->adres = (!empty($betrokkene->straat)) ? $betrokkene->straat : ''; $dossierSubject->adres .= (!empty($betrokkene->huisNummer)) ? ' '.$betrokkene->huisNummer : ''; $dossierSubject->adres .= (!empty($betrokkene->huisNummerToevoeging)) ? $betrokkene->huisNummerToevoeging : ''; $dossierSubject->postcode = $betrokkene->postcode; $dossierSubject->woonplaats = $betrokkene->woonplaats; $dossierSubject->telefoon = $betrokkene->telefoon; $dossierSubject->email = $betrokkene->email; // Try to save the changes if ($dossierSubject->save($dossierSubject, true, null, false)) { // Success. Do nothing. At least for now. } else { // If the call failed, notify the user. $resultSet['results']['actionResultMessage'] .= " N.B. enkele velden van de betrokkene met id " . $dossierSubject->id . " konden NIET succesvol worden opgeslagen!"; } } // if ($updateBetrokkene) } // foreach ($betrokkenen as $betrokkene) } // if (!is_null($existingDossier)) else { // Do nothing for now... We could throw an error here, but basically that situation should already have been trapped above. } } // if (in_array($action, array('add', 'edit'))) // Once everything is done, we get the current set of 'betrokkenen' from the DB, so we can add them to the result set too. By postponing this action until this // point, we are sure we have the proper set of 'betrokkenen' including any and all potential edits/additions that may have been made above. if (!is_null($existingDossier)) { // If we have a valid dossier object, we register the successful outcome. $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['dossierId'] = $existingDossier->id; //$resultSet['results']['actionResultMessage'] = ""; // Add the dossier 'betrokkenen'. // Start by getting the existing 'betrokkenen'. $existingDossierSubjects = $this->_CI->dossiersubject->get_by_dossier( $existingDossier->id ); // If subjects are assigned to this dossier, return their data if (!empty($existingDossierSubjects)) { // Start by initialising a empty set of subjects $resultSet['results']['assignedBetrokkenen'] = array(); // Now pass the ID and name of each of the subjects. foreach ($existingDossierSubjects as $existingDossierSubject) { $resultSet['results']['assignedBetrokkenen'][] = array( 'assignedBetrokkeneId' => $existingDossierSubject->id, 'naam' => $existingDossierSubject->naam, 'email' => $existingDossierSubject->email ); } } } // if (!is_null($existingDossier)) // When we're done, return the result set return $resultSet; } // public function soapManipulateDossier( $parameters ) // RPC implementation of 'soapManipulateDeelplan'. public function soapManipulateDeelplan( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( 'deelplanId' => -1, 'actionResultMessage' => '' ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { return "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the desired action from the parameters and check if it is a valid action. $action = strtolower($parameters->actie); $allowedActions = array('add', 'edit', 'delete', 'check'); if (!in_array($action, $allowedActions)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven actie '{$action}' is niet ondersteund. Geldige waarden: " . implode(', ', $allowedActions); return $resultSet; } // Check if a valid dossier ID and hash have been passed, this is our security mechanism, and we are only allowed to continue if we // can successfully obtain a dossier object for the passed parameters. $dossierId = ($parameters->dossierId > 0) ? $parameters->dossierId : 0; $dossierHash = (!empty($parameters->dossierHash)) ? $parameters->dossierHash : ''; $existingDossier = $this->getExistingDossier($dossierId, $dossierHash, $resultSet); // If no valid dossier was retrieved, or if we don't have any access rights over it, return early. if (is_null($existingDossier) ) { return $resultSet; } // If we reached this point, we have managed to determine that a supported action has been specified and that we have proper access to it, so handle // the data as required. $deelplanId = ($parameters->deelplanId > 0) ? $parameters->deelplanId : 0; $deelplanNaam = (!empty($parameters->deelplanNaam)) ? $parameters->deelplanNaam : ''; //$gebruikerId = ($parameters->gebruikerId > 0) ? $parameters->gebruikerId : 0; $gebruikerId = ($parameters->gebruikerId > 0) ? $parameters->gebruikerId : $existingDossier->gebruiker_id; // If no gebruiker was passed, get the one from the dossier $kenmerk = (!empty($parameters->kenmerk)) ? $parameters->kenmerk : ''; $oloNummer = (!empty($parameters->oloNummer)) ? $parameters->oloNummer : ''; $aanvraagDatum = (!empty($parameters->aanvraagDatum)) ? $parameters->aanvraagDatum : null; $initieleDatum = (!empty($parameters->initieleDatum)) ? $parameters->initieleDatum : null; $gebouwdelen = (!empty($parameters->gebouwdelen)) ? $parameters->gebouwdelen : array(); $scopes = (!empty($parameters->scopes)) ? $parameters->scopes : array(); $betrokkenen = (!empty($parameters->betrokkenen)) ? $parameters->betrokkenen : array(); $documenten = (!empty($parameters->documenten)) ? $parameters->documenten : array(); // For calls that require an existing deelplan, we first try to get that deelplan. // Note: make sure to do this in such a way that ample error and security checking is performed! //$existingDossier = null; //if (in_array($action, array('edit', 'delete', 'check')) && !empty($dossierId)) if ( ($action != 'add') && !empty($deelplanId) ) { // Get the existing deelplan (if any) as an object. // Note: the last parameter (being the "result set") is taken by reference, as it too will be manipulated in the method. $existingDeelplan = $this->getExistingDeelplan($deelplanId, $dossierId, $resultSet); // Now, if we did not obtain a valid deelplan, it means the above call did not retrieve a deelplan, or that we otherwise do // not have the rights to manipulate it. In that situation we return early. if (is_null($existingDeelplan) ) { // If no valid deelplan was retrieved, or if we don't have any access rights over it, return early. return $resultSet; } } // if ( ($action != 'add') && !empty($deelplanId) ) // Handle the request in the way it should be handled. This is determined by the specific action that was passed. if ($action == 'add') { // Check if the required fields have been filled in //$requiredFields = (); // Use the model to create the dossier. try { // Use the model to (try to) create the deelplan. $createdDeelplanId = $this->_CI->deelplan->add($dossierId, $deelplanNaam); // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['deelplanId'] = $createdDeelplanId; $resultSet['results']['actionResultMessage'] = "Het deelplan is succesvol aangemaakt."; // Now, semi-silently (try to) set the passed fields that we cannot set through the 'add' call. This does almost the same thing as is done in // the 'Edit' action, but it doesn't use the same error handling, as at least the dossier was created. // First, get the deelplan we just created $existingDeelplan = $this->_CI->deelplan->get( $createdDeelplanId ); // Then edit the additional fields //$existingDeelplan->foreignid = 0; $existingDeelplan->kenmerk = $kenmerk; //$existingDeelplan->afgemeld = 0; //$existingDeelplan->afgemeld_op = ''; // datetime //$existingDeelplan->sjabloon_id = 0; //$existingDeelplan->sjabloon_naam = ''; $existingDeelplan->olo_nummer = $oloNummer; $existingDeelplan->aanvraag_datum = $aanvraagDatum; //$existingDeelplan->outlook_synchronisatie = 1; // Try to save the changes if ($existingDeelplan->save($existingDeelplan, true, null, false)) { // Success. Do nothing. At least for now. } else { // If the call failed, notify the user. $resultSet['results']['actionResultMessage'] .= " N.B. enkele velden konden NIET succesvol worden opgeslagen!"; } } catch (exception $e) { /* echo $e->getMessage() . $e->getTraceAsString() . "<br />"; echo '<pre>'; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo '</pre>'; //$debug_trace_messages = debug_backtrace(nl2br(DEBUG_BACKTRACE_IGNORE_ARGS)); //d($debug_trace_messages); * */ $createdDeelplanId = -1; // If the call failed, register the unsuccessful outcome $resultSet['results']['deelplanId'] = $createdDeelplanId; $resultSet['results']['actionResultMessage'] = "Het deelplan is NIET succesvol aangemaakt. Reden: " . $e->getMessage(); } //d($createdDossierId); exit; } // if ($action == 'add') else if ($action == 'edit') { // Update the fields we are allowed to edit through this call. //$existingDeelplan->foreignid = 0; $existingDeelplan->naam = $deelplanNaam; $existingDeelplan->kenmerk = $kenmerk; //$existingDeelplan->afgemeld = 0; //$existingDeelplan->afgemeld_op = ''; // datetime //$existingDeelplan->sjabloon_id = 0; //$existingDeelplan->sjabloon_naam = ''; $existingDeelplan->olo_nummer = $oloNummer; $existingDeelplan->aanvraag_datum = $aanvraagDatum; //$existingDeelplan->outlook_synchronisatie = 1; // Try to save the changes if ($existingDeelplan->save($existingDeelplan, true, null, false)) { // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['deelplanId'] = $existingDeelplan->id; $resultSet['results']['actionResultMessage'] = "Het deelplan is succesvol bewerkt."; } else { // If the call failed, register the unsuccessful outcome $resultSet['results']['deelplanId'] = $existingDeelplan->id; $resultSet['results']['actionResultMessage'] = "Het deelplan is NIET succesvol bewerkt."; } } // else if ($action == 'edit') else if ($action == 'delete') { // TODO: implement this. Do we do a 'soft delete' (via 'verwijder()') or a hard one? } // else if ($action == 'delete') else if ($action == 'check') { // Since we reached this point, the deelplan apparently exists and we are allowed to edit it. $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['actionResultMessage'] = "Het deelplan met ID '{$deelplanId}' bestaat en mag via de koppeling bewerkt worden."; } // else if ($action == 'check') // For the 'Add' and 'Edit' actions we need to perform further actions, like assigning 'betrokkenen', documents, etc. too if (in_array($action, array('add', 'edit'))) { // When we have reached this point, we should have a valid existing deelplan object. Nevertheless, check if this is the case if (!is_null($existingDeelplan)) { // Start by processing the passed 'gebouwdelen'. First we need to transform the passed data to the format the model expects. $passedGebouwdelen = array(); foreach($gebouwdelen as $gebouwdeel) { $passedGebouwdelen[] = $gebouwdeel->naam; } $this->_CI->deelplanbouwdeel->set_for_deelplan( $existingDeelplan->id, $passedGebouwdelen); // Proceed to process the scopes, assigning the passed checklists (and checklist groups) to the 'deelplan'. // Note: the below code does not (yet) check if the passed checklists are valid for the used 'klant'. This could/should be added later. foreach ($scopes as $checklistData) { if (is_null($checklistData->checklistId) || empty($checklistData->checklistId)) { continue; } // First assign the checlist and the checklist group $curChecklist = $this->_CI->checklist->get($checklistData->checklistId); $this->_CI->deelplanchecklistgroep->add( $existingDeelplan->id, $curChecklist->checklist_groep_id ); $this->_CI->deelplanchecklist->add( $existingDeelplan->id, $checklistData->checklistId ); // Set the initial date if (!empty($initieleDatum)) { //$this->_CI->deelplanchecklist->update_planningdatum( $existingDeelplan->id, $checklistData->checklistId, $initieleDatum, null, null ); $this->_CI->deelplanchecklist->update_planningdatum( $existingDeelplan->id, $checklistData->checklistId, $initieleDatum, '00:01', '01:01' ); } // Make sure a 'toezichthouder' is specified if (!is_null($gebruikerId) && !empty($gebruikerId)) { $this->_CI->deelplanchecklist->update_toezichthouder( $existingDeelplan->id, $checklistData->checklistId, $gebruikerId ); } } /* // Then proceed to assign the corresponding "thema's". // Note: instead of relying on successful outcomes of the above code, we make sure to use the deelplanchecklist model to get the currently active set // of deelplan-checklist assignments! $curDeelplanChecklists = $this->_CI->deelplanchecklist->get_by_deelplan( $existingDeelplan->id ); //echo "+++ Deelplan checklists: +++"; //d($curDeelplanChecklists); // d($curDeelplanChecklists); exit; if (!is_null($curDeelplanChecklists) && !empty($curDeelplanChecklists)) { // Initialise the sets that contain the currently assigned deelplanthema's as well as the thema IDs of the thema's that // are associated with the checklists. //$curDeelplanThemas = array(); $curDeelplanThemas = $this->_CI->deelplanthema->get_by_deelplan( $existingDeelplan->id ); // echo '+++ 2 +++<br />'; $checklistThemaIds = array(); // d($curDeelplanChecklists); exit; // Loop over each deelplanchecklist and extract the thema's foreach($curDeelplanChecklists as $curDeelplanChecklist) { // d($curDeelplanChecklist); exit; // As we normally don't have a filled in checklist at this point, we cannot use the following call: // $this->_CI->thema->get_by_checklist($checklistData->checklistId, true)); // Instead, we simply assign all possible themas to the deelplan, which requires 'drilling down' to the 'questions level'. $curChecklist = $this->_CI->checklist->get($curDeelplanChecklist->checklist_id); // d($curChecklist); exit; if (!is_null($curChecklist) && !empty($curChecklist)) { $curHoofdgroepen = $curChecklist->get_hoofdgroepen(); if (!is_null($curHoofdgroepen) && !empty($curHoofdgroepen)) { foreach($curHoofdgroepen as $curHoofdgroep) { $curCategorien = $curHoofdgroep->get_categorieen(); if (!is_null($curCategorien) && !empty($curCategorien)) { foreach($curCategorien as $curCategorie) { $curVragen = $curCategorie->get_vragen(); if (!is_null($curVragen) && !empty($curVragen)) { foreach($curVragen as $curVraag) { if (!is_null($curVraag->thema_id) && !empty($curVraag->thema_id) && !in_array($curVraag->thema_id, $checklistThemaIds)) { $checklistThemaIds[] = $curVraag->thema_id; } } // foreach($curVragen as $curVraag) } // if (!is_null($curVragen) && !empty($curVragen)) } // foreach($curCategorien as $curCategorie) } // if (!is_null($curCategorien) && !empty($curCategorien)) } // foreach($curHoofdgroepen as $curHoofdgroep) } // if (!is_null($curHoofdgroepen) && !empty($curHoofdgroepen)) } // if (!is_null($curChecklist) && !empty($curChecklist)) } // foreach($curDeelplanChecklists as $curDeelplanChecklist) // Once all currently assigned thema's have been determined, as well as those that are associatied with the checklists, we assign the // current set. //$curDeelplanThemas = array_unique($curDeelplanThemas, SORT_REGULAR); //$checklistThemaIds = array_unique($checklistThemaIds, SORT_REGULAR); $this->_CI->deelplanthema->set_for_deelplan( $existingDeelplan->id, $checklistThemaIds, $curDeelplanThemas ); } // if (!is_null($curDeelplanChecklists) && !empty($curDeelplanChecklists)) * */ // Assign all of the available themas of the checklists that are assigned to this deelplan directly to the deelplan too. $existingDeelplan->zet_alle_themas_van_checklisten(); // Now, force-update the content of the deelplan, this copies the proper questions for the checklists, etc. // Note that as we are NOT logged in to BTZ, we need to pass the user ID, as it cannot be determined from the base level! $existingDeelplan->update_content($gebruikerId); // Now process the betrokkenen (if any). if (!empty($betrokkenen)) { // First get the 'dossier subjects' these are the only subjects we are allowed to assign to the deelplan, regardless of what is // requested to be associated to the deelpan. $dossierSubjects = $this->_CI->dossiersubject->get_by_dossier( $existingDossier->id, true ); $allowedDossierSubjectIds = array_keys($dossierSubjects); // Now loop over the 'betrokkenen' values, and select those IDs that we are allowed to add. $passedAllowedDeelplanSubjectIds = array(); foreach ($betrokkenen as $betrokkene) { if (in_array($betrokkene->betrokkeneId, $allowedDossierSubjectIds)) { $passedAllowedDeelplanSubjectIds[] = $betrokkene->betrokkeneId; } } // Get the currently assigned subjects for this deelplan $currentlyAssignedDeelplanSubjects = $this->_CI->deelplansubject->get_by_deelplan($existingDeelplan->id); // Now use the model to assign the proper set of subjects to the deelplan. $this->_CI->deelplansubject->set_for_deelplan($existingDeelplan->id, $passedAllowedDeelplanSubjectIds, $currentlyAssignedDeelplanSubjects); } // Finally, process the documenten (if any). // !!! OJG (8-5-2015): The 'correct' and prescribed functionality has been changed by explicit requests of the clients! // The commented out 'if (!empty($documenten))' part is the correct code, as it was designed and prescribed in the documentation! // For now though, instead of doing it the 'correct' way, the demand has been bestowed on us to simply add ALL dossier bescheiden to ALL of the // deelplannen of the currently processed dossier. That is a thing for which the below set_all_bescheiden_for_all_deelplannen method was // explicitly designed. At a later time this functionality may be required to work as previously designed again, so we only comment out the code // and do NOT remove it just yet! $existingDossier->set_all_bescheiden_for_all_deelplannen(); /* if (!empty($documenten)) { // First get the 'dossier bescheiden' these are the only documents we are allowed to assign to the deelplan, regardless of what is // requested to be associated to the deelpan. $dossierBescheidenen = $this->_CI->dossierbescheiden->get_by_dossier( $existingDossier->id, true ); $allowedDossierBescheidenenIds = array_keys($dossierBescheidenen); // Now loop over the 'documenten' values, and select those IDs that we are allowed to add. $passedAllowedDeelplanBescheidenenIds = array(); foreach ($documenten as $document) { if (in_array($document->documentId, $allowedDossierBescheidenenIds)) { $passedAllowedDeelplanBescheidenenIds[] = $document->documentId; } } // Get the currently assigned documents for this deelplan $currentlyAssignedDeelplanBescheidenen = $this->_CI->deelplanbescheiden->get_by_deelplan($existingDeelplan->id); // Now use the model to assign the proper set of documents to the deelplan. $this->_CI->deelplanbescheiden->set_for_deelplan($existingDeelplan->id, $passedAllowedDeelplanBescheidenenIds, $currentlyAssignedDeelplanBescheidenen); } * */ } // if (!is_null($existingDeelplan)) else { // Do nothing for now... We could throw an error here, but basically that situation should already have been trapped above. } } // if (in_array($action, array('add', 'edit'))) // Once everything is done, and we have a valid deelplan object, we make sure to register a successful outcome. if (!is_null($existingDeelplan)) { // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['deelplanId'] = $existingDeelplan->id; } // if (!is_null($existingDossier)) // When we're done, return the result set return $resultSet; } // public function soapManipulateDeelplan( $parameters ) // RPC implementation of 'soapManipulateDocument'. public function soapManipulateDocument( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => '', 'results' => array( 'documentId' => -1, 'actionResultMessage' => '' ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { return "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; } // If we reached this point, the caller provided valid credentials, so we can do the actual work. // Extract the desired action from the parameters and check if it is a valid action. $action = strtolower($parameters->actie); $allowedActions = array('add', 'edit', 'delete', 'check'); if (!in_array($action, $allowedActions)) { // Store the error message to the result set and return early $resultSet['message'] = "De opgegeven actie '{$action}' is niet ondersteund. Geldige waarden: " . implode(', ', $allowedActions); return $resultSet; } // Check if a valid dossier ID and hash have been passed, this is our security mechanism, and we are only allowed to continue if we // can successfully obtain a dossier object for the passed parameters. $dossierId = ($parameters->dossierId > 0) ? $parameters->dossierId : 0; $dossierHash = (!empty($parameters->dossierHash)) ? $parameters->dossierHash : ''; $existingDossier = $this->getExistingDossier($dossierId, $dossierHash, $resultSet); // If no valid dossier was retrieved, or if we don't have any access rights over it, return early. // !!! TODO: Set a proper error message for this situation! if (is_null($existingDossier) ) { return $resultSet; } // If we reached this point, we have managed to determine that a supported action has been specified and that we have proper access to it, so handle // the data as required. // Start by extracting the compound document data. $document = (!empty($parameters->document)) ? $parameters->document : array(); // Then extract the subparts of the document $documentId = (!empty($document->documentId)) ? $document->documentId : 0; $omschrijving = (!empty($document->omschrijving)) ? $document->omschrijving : ''; $zaakNummerRegistratie = (!empty($document->zaakNummerRegistratie)) ? $document->zaakNummerRegistratie : ''; $tekeningNummer = (!empty($document->tekeningNummer)) ? $document->tekeningNummer : ''; $versieNummer = (!empty($document->versieNummer)) ? $document->versieNummer : ''; $datumLaatsteWijziging = (!empty($document->datumLaatsteWijziging)) ? $document->datumLaatsteWijziging : ''; $auteur = (!empty($document->auteur)) ? $document->auteur : ''; $bestandsNaam = (!empty($document->bestandsNaam)) ? $document->bestandsNaam : ''; $bestand = (!empty($document->bestand)) ? base64_decode($document->bestand) : ''; // Make sure we have enough data to be able to successfully create the file. For this we require at least the filename and file data. // Check if the filename is present. Only necessary when adding. if (empty($bestandsNaam) && ($action == 'add')) { // Store the error message to the result set and return early $resultSet['message'] = "Het bestand kon niet verwerkt worden omdat geen bestandsnaam is ontvangen."; return $resultSet; } // Check if the file data is present. Only necessary when adding. if (empty($bestand) && ($action == 'add')) { // Store the error message to the result set and return early $resultSet['message'] = "Het bestand kon niet verwerkt worden omdat geen bestandsinhoud is ontvangen."; return $resultSet; } // For calls that require an existing document, we first try to get that document. // Note: make sure to do this in such a way that ample error and security checking is performed! //$existingDocument = null; //if (in_array($action, array('edit', 'delete', 'check')) && !empty($documentId)) if ( ($action != 'add') && !empty($documentId) ) { // Get the existing document (if any) as an object. // Note: the last parameter (being the "result set") is taken by reference, as it too will be manipulated in the method. $existingDocument = $this->getExistingDocument($documentId, $dossierId, $resultSet); // Now, if we did not obtain a valid document, it means the above call did not retrieve a document, or that we otherwise do // not have the rights to manipulate it. In that situation we return early. if (is_null($existingDocument) ) { // If no valid document was retrieved, or if we don't have any access rights over it, return early. return $resultSet; } } // if ( ($action != 'add') && !empty($documentId) ) // Handle the request in the way it should be handled. This is determined by the specific action that was passed. if ($action == 'add') { // Check if the required fields have been filled in //$requiredFields = (); // Use the model to create the document. try { // Use the model to (try to) create the document. //$createdDocumentId = $this->_CI->dossierbescheiden->add($dossierId); $createdDocument = $this->_CI->dossierbescheiden->add($dossierId); // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['documentId'] = $createdDocument->id; $resultSet['results']['actionResultMessage'] = "Het document is succesvol aangemaakt."; // Now, semi-silently (try to) set the passed fields that we cannot set through the 'add' call. This does almost the same thing as is done in // the 'Edit' action, but it doesn't use the same error handling, as at least the document was created. // First, get the document we just created //$existingDeelplan = $this->_CI->deelplan->get( $createdDeelplanId ); $existingDocument = $createdDocument; // Then edit the additional fields $existingDocument->tekening_stuk_nummer = $tekeningNummer; $existingDocument->auteur = $auteur; $existingDocument->omschrijving = $omschrijving; $existingDocument->zaaknummer_registratie = $zaakNummerRegistratie; $existingDocument->versienummer = $versieNummer; $existingDocument->datum_laatste_wijziging = $datumLaatsteWijziging; $existingDocument->bestand = $bestand; $existingDocument->bestandsnaam = $bestandsNaam; //$existingDocument->png_status = 'onbekend'; //$existingDocument->laatste_bestands_wijziging_op = ''; //$existingDocument->dossier_bescheiden_map_id = 0; // Try to save the changes if ($existingDocument->save($existingDocument, true, null, false)) { // Success. Do nothing. At least for now. // !!! OJG (8-5-2015): The 'correct' and prescribed functionality has been changed by explicit requests of the clients! // Instead of explicitly assigning the proper set of bescheiden for the various 'deelplannen', the demand has been bestowed on us to simply add // ALL dossier bescheiden to ALL of the deelplannen of the currently processed dossier. That is a thing for which the below // set_all_bescheiden_for_all_deelplannen method was explicitly designed. At a later time this functionality may be required to work as previously // designed again, in which case the below call should be removed. $existingDossier->set_all_bescheiden_for_all_deelplannen(); } else { // If the call failed, notify the user. $resultSet['results']['actionResultMessage'] .= " N.B. enkele velden konden NIET succesvol worden opgeslagen!"; } } catch (exception $e) { /* echo $e->getMessage() . $e->getTraceAsString() . "<br />"; echo '<pre>'; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo '</pre>'; //$debug_trace_messages = debug_backtrace(nl2br(DEBUG_BACKTRACE_IGNORE_ARGS)); //d($debug_trace_messages); * */ $createdDocumentId = -1; // If the call failed, register the unsuccessful outcome $resultSet['results']['documentId'] = $createdDocumentId; $resultSet['results']['actionResultMessage'] = "Het document is NIET succesvol aangemaakt. Reden: " . $e->getMessage(); } //d($createdDocumentId); exit; } // if ($action == 'add') else if ($action == 'edit') { // Update the fields we are allowed to edit through this call. $existingDocument->tekening_stuk_nummer = $tekeningNummer; $existingDocument->auteur = $auteur; $existingDocument->omschrijving = $omschrijving; $existingDocument->zaaknummer_registratie = $zaakNummerRegistratie; $existingDocument->versienummer = $versieNummer; $existingDocument->datum_laatste_wijziging = $datumLaatsteWijziging; if (!empty($bestand)) { $existingDocument->bestand = $bestand; } if (!empty($bestandsNaam)) { $existingDocument->bestandsnaam = $bestandsNaam; } //$existingDocument->png_status = 'onbekend'; //$existingDocument->laatste_bestands_wijziging_op = ''; //$existingDocument->dossier_bescheiden_map_id = 0; // Try to save the changes if ($existingDocument->save($existingDocument, true, null, false)) { // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['documentId'] = $existingDocument->id; $resultSet['results']['actionResultMessage'] = "Het document is succesvol bewerkt."; } else { // If the call failed, register the unsuccessful outcome $resultSet['results']['documentId'] = $existingDocument->id; $resultSet['results']['actionResultMessage'] = "Het document is NIET succesvol bewerkt."; } } // else if ($action == 'edit') else if ($action == 'delete') { // TODO: implement this. Do we do a 'soft delete' (via 'verwijder()') or a hard one? } // else if ($action == 'delete') else if ($action == 'check') { // Since we reached this point, the deelplan apparently exists and we are allowed to edit it. $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['actionResultMessage'] = "Het document met ID '{$documentId}' bestaat en mag via de koppeling bewerkt worden."; } // else if ($action == 'check') // Once everything is done, and we have a valid document object, we make sure to register a successful outcome. if (!is_null($existingDocument)) { // If we succeeded, register the successful outcome $resultSet['success'] = true; //$resultSet['message'] = ''; $resultSet['results']['documentId'] = $existingDocument->id; } // if (!is_null($existingDossier)) // When we're done, return the result set return $resultSet; } // public function soapManipulateDocument( $parameters ) // RPC implementation of 'soapAddDeelplanHercontroleDatum'. public function soapAddDeelplanHercontroleDatum( $parameters ) { // Initialise the result set negatively $resultSet = array( 'success' => false, 'message' => 'This method has not yet been implemented. Please do NOT call it.', 'results' => array( /* array( 'checklistGroepId' => -1, 'checklistGroepNaam' => '', 'checklistId' => -1, 'checklistNaam' => '' ) * */ ) ); // First check the license. If the credentials do not grant access, inform the caller of this. if (!$this->checkCredentials($parameters->licentieNaam, $parameters->licentieWachtwoord)) { return "De opgegeven combinatie van licentienaam en licentiewachtwoord is ongeldig"; } // When we're done, return the result set return $resultSet; } // public function soapAddDeelplanHercontroleDatum( $parameters ) } // class DossierWebservice extends AbstractWebservice<file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_instellingen')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Instellingen', 'expanded' => true, 'width' => '920px', 'height' => '300px' ) ); ?> <form name="form" method="post"> <table> <tr> <td id="form_header" style="width:200px">Steekproef interval:</td> <td><input type="text" name="steekproef_interval" value="<?=$klant->steekproef_interval?>" /></td> </tr> <tr> <td id="form_value" colspan="2"><i>Hier geeft u aan hoe vaak een vraag die op prioriteit "Steekproef (S)" staat ingesteld ook daadwerkelijk getoetst moet worden. Als u hier bijvoorbeeld 10 invoert, zal 9 keer "niet gecontroleerd ivm steekproef" als standaard antwoord gelden, en 1 keer zal uw toezichthouder moeten toetsen.</i></td> </tr> <tr> <td id="form_header">Email synchronisatie:</td> <td><input type="checkbox" name="outlook_synchronisatie" <?=$klant->outlook_synchronisatie ? 'checked' : ''?> /></td> </tr> <tr> <td id="form_value" colspan="2"><i>Hiermee kunt u agenda synchronisatie met veel voorkomende emailprogramma's, waaronder Outlook, aan of uit zetten. Alle afspraken die u inplant in dit systeem zullen automatisch ook in uw emailprogramma verschijnen.</i></td> </tr> <tr> <td id="form_header">Standaard netwerk modus:</td> <td> <select name="standaard_netwerk_modus"> <option value="wifi" <?=$klant->standaard_netwerk_modus == 'wifi' ? 'selected' : ''?>>wifi</option> <option value="3g" <?=$klant->standaard_netwerk_modus == '3g' ? 'selected' : ''?>>3g</option> </select> </td> </tr> <tr> <td id="form_value" colspan="2"><i>Hiermee geeft u aan wat de standaard netwerk modus is voor het toezichtscherm. Voor meer informatie neem contact met ons op, of lees uw gebruikershandleiding.</i></td> </tr> <tr> <td id="form_header">Dossierregels rood kleuren?</td> <td> <select name="dossierregels_rood_kleuren"> <option value="1" <?=$klant->dossierregels_rood_kleuren == '1' ? 'selected' : ''?>>Ja</option> <option value="0" <?=$klant->dossierregels_rood_kleuren == '0' ? 'selected' : ''?>>Nee</option> </select> </td> </tr> <tr> <td id="form_header">Dossiers als startpagina openen?</td> <td> <select name="dossiers_als_startpagina_openen"> <option value="0" <?=$klant->dossiers_als_startpagina_openen == '0' ? 'selected' : ''?>>Nee</option> <option value="1" <?=$klant->dossiers_als_startpagina_openen == '1' ? 'selected' : ''?>>Ja</option> </select> </td> </tr> <tr> <td id="form_header">Niet automatisch selecteren Betrokkenen?</td> <td> <select name="not_automaticly_select_betrokkenen"> <option value="0" <?=$klant->not_automaticly_select_betrokkenen == '0' ? 'selected' : ''?>>Nee</option> <option value="1" <?=$klant->not_automaticly_select_betrokkenen == '1' ? 'selected' : ''?>>Ja</option> </select> </td> </tr> <tr> <td id="form_header">Alleen deelplannen betrokkene/toezichthouder tonen?</td> <td> <select name="alleen_deelplannen_betrokkene"> <option value="1" <?=$klant->alleen_deelplannen_betrokkene == '1' ? 'selected' : ''?>>Ja</option> <option value="0" <?=$klant->alleen_deelplannen_betrokkene == '0' ? 'selected' : ''?>>Nee</option> </select> </td> </tr> <tr> <td id="form_header">Vragen alleen voor betrokkenen tonen?</td> <td> <select name="vragen_alleen_voor_betrokkenen_tonen"> <option value="1" <?=$klant->vragen_alleen_voor_betrokkenen_tonen == '1' ? 'selected' : ''?>>Ja</option> <option value="0" <?=$klant->vragen_alleen_voor_betrokkenen_tonen == '0' ? 'selected' : ''?>>Nee</option> </select> </td> </tr> <tr> <td id="form_button" colspan="2"><input type="submit" value="<?=tgng('form.opslaan')?>"/></td> </tr> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><?php class DossierGeolocatieUpdater { const LOCKNAME = 'dossiergeolocatieupdater'; private $CI; private $_filelock; public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'filelock' ); $this->CI->load->library( 'googlemaps' ); $this->CI->load->model( 'geolocatie' ); $this->CI->load->model( 'dossier' ); $this->_filelock = $this->CI->filelock->create( self::LOCKNAME ); } public function run() { if ($this->_filelock->is_locked()) throw new Exception( "WetTekstFetcher::run: Filelock already locked" ); if ($this->_filelock->try_lock() != LOCKFILE_SUCCESS) throw new Exception( "WetTekstFetcher::run: Filelock failed, already locked or no write access" ); try { $this->_run(); $this->_filelock->unlock(); } catch (Exception $e) { $this->_filelock->unlock(); throw $e; } } private function _run() { $dossiers = $this->CI->dossier->search( array(), 'geo_locatie_opgehaald = 0 AND (geo_locatie_volgende_poging IS NULL OR geo_locatie_volgende_poging < NOW())' ); echo "Found " . sizeof($dossiers) . " dossiers\n"; $over_limit = false; foreach ($dossiers as $i => $dossier) { // if there's no locatie adres or woonplaats, skip this dossier // or, if the adres or woonplaats is just 1 char, it's probably a test char if (strlen(trim($dossier->locatie_adres))<=1 || strlen(trim($dossier->locatie_woonplaats))<=1 || preg_match('/^test(straat|weg)(\s|$)/i', $dossier->locatie_adres) || preg_match('/^marctest/i', $dossier->locatie_adres) ) { $dossier->geo_locatie_opgehaald = 1; if (!$dossier->save(0,0,0)) throw new Exception( 'Database exception' ); continue; } // header echo sprintf("%05d/%05d ", $i+1, sizeof($dossiers)); // over limit? then schedule for retry in an hour if ($over_limit) { echo "... OVER_QUERY_LIMIT\n"; $dossier->geo_locatie_foutmelding = 'OVER_QUERY_LIMIT'; $this->_schedule_dossier( $dossier, 24*60 ); continue; } // get full address $volledigAdres = $dossier->locatie_adres; if ($dossier->locatie_postcode) $volledigAdres .= ', ' . $dossier->locatie_postcode; $volledigAdres .= ', ' . $dossier->locatie_woonplaats; // see if geo locatie for this address is already known $geolocaties = $this->CI->geolocatie->search( array( 'adres' => $volledigAdres ) ); if (!empty( $geolocaties )) { echo "Using cached result for geolocation of '$volledigAdres'\n"; $dossier->geo_locatie_opgehaald = 1; $dossier->geo_locatie_id = reset( $geolocaties )->id; if (!$dossier->save(0,0,0)) throw new Exception( 'Database exception' ); continue; } // resolve it! echo "Resolving geolocation of '$volledigAdres' ... "; $dossier->geo_locatie_volgende_poging = NULL; $result = $this->CI->googlemaps->geocode( new GoogleMapsGeocodeParameters( $volledigAdres ), function( $e, $result ) use (&$over_limit, $dossier) { // whoops! something went wrong! let's find out what! $resObj = json_decode( $result ); if (is_object( $resObj ) && $resObj->status) { echo $resObj->status . "\n"; // store error in database $dossier->geo_locatie_foutmelding = $resObj->status; if ($resObj->status == 'OVER_QUERY_LIMIT') // whoops, got maximum for the day! { $over_limit = true; $this->_schedule_dossier( $dossier, 3600 ); } } else var_dump( $result ); return false; } ); if ($result) { echo sprintf( "to %.6f, %.6f\n", $result->lat, $result->lng ); $obj = $this->CI->geolocatie->insert( array( 'adres' => $volledigAdres, 'latitude' => $result->lat, 'longitude' => $result->lng, ) ); $dossier->geo_locatie_opgehaald = 1; $dossier->geo_locatie_id = $obj->id; $dossier->geo_locatie_foutmelding = NULL; } else if (!$over_limit) { $dossier->geo_locatie_opgehaald = 1; $dossier->geo_locatie_id = reset( $geolocaties )->id; } if (!$dossier->save(0,0,0)) throw new Exception( 'Database exception' ); usleep( 500000 ); } } public function _schedule_dossier( DossierResult $dossier, $secs ) { $dossier->geo_locatie_opgehaald = 0; $dossier->geo_locatie_volgende_poging = date('Y-m-d H:i:s', time() + $secs ); if (!$dossier->save(0,0,0)) throw new Exception( 'Database exception' ); } } <file_sep>ALTER TABLE `deelplannen` ADD `afgemeld` TINYINT NOT NULL DEFAULT '0'; ALTER TABLE `deelplannen` ADD `afgemeld_op` DATETIME NULL DEFAULT NULL ; <file_sep><? $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); ?> <? $this->load->view('elements/header', array('page_header'=>null)); ?> <? if ($klant->heeft_toezichtmomenten_licentie == 'nee' && $deelplan_access == 'write'): ?> <input type="button" value="<?=tgn('deelplan_bewerken')?>" onclick="location.href='<?=site_url('/deelplannen/bewerken/' . $deelplan->id)?>';" /><br/> <br/> <? endif; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('registratiegegevens'), 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table> <tr> <th style="text-align: left; width: 150px"><?=tgg('deelplan.deelplan_naam')?>:</th> <td><?=$deelplan->naam?></td> </tr> <tr> <th style="text-align: left; width: 150px"><?=tgg('deelplan.identificatienummer')?>:</th> <td width="25%"><?=$deelplan->kenmerk?></td> </tr> <tr> <th style="text-align: left; width: 150px"><?=tgg('deelplan.olo_nummer')?>:</th> <td><?=$deelplan->olo_nummer?></td> </tr> <tr> <th style="text-align: left; width: 150px"><?=tgg('deelplan.aanvraagdatum')?>:</th> <td width="25%"><?=$deelplan->aanvraag_datum ? date( 'd-m-Y', strtotime($deelplan->aanvraag_datum) ) : ''?></td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('scopes'), 'expanded' => true, 'width' => '100%', 'height' => 'auto' ) ); ?> <? $deelplan_checklistgroepen = $deelplan->get_checklistgroepen_assoc(); $deelplan_checklisten = $deelplan->get_checklisten_assoc(); ?> <? foreach ($checklistgroepen as $checklistgroep): ?> <? $local_scope_access = @$scope_access[$checklistgroep->id]; if (!$local_scope_access) $local_scope_access = $deelplan_access; $checklistgroep_selected = isset($deelplan_checklistgroepen[$checklistgroep->id]); if (!$checklistgroep_selected) continue; ?> <h2> <? if ($checklistgroep->image_id): ?> <img src="<?=$checklistgroep->get_image()->get_url()?>" /> <? endif; ?> <b><?=$checklistgroep->naam?></b> </h2> <table style="width: 600px"> <tr> <td style="vertical-align: top; width: 250px;"><b><?=tg('scopes')?></b></td> <td style="vertical-align: top"> <? $any_selected = false; foreach ($checklistgroep->get_checklisten() as $checklist) if (isset($deelplan_checklisten[$checklist->id])) { $any_selected = true; break; } ?> <? foreach ($checklistgroep->get_checklisten() as $checklist): ?> <? $checklist_checked = isset($deelplan_checklisten[$checklist->id]); if (!$checklist_checked) continue; ?> <?=$checklist->naam?><br/> <? endforeach; ?> </td> </tr> </table> <? endforeach; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('themas'), 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table> <? foreach ($hoofdthemas as $hoofdthema): ?> <? $themas = $hoofdthema->get_themas(); if (empty( $themas )) continue; $any_selected = false; foreach ($themas as $thema) if (isset($current_themas[$thema->id])) { $any_selected = true; break; } if (!$any_selected) continue; ?> <tr> <td style="vertical-align:top; width: 150px;"><b><?=htmlentities( $hoofdthema->naam, ENT_COMPAT, 'UTF-8' )?>:</b></td> <td style="vertical-align:top"> <? $c=0; foreach ($themas as $thema) { $thema_selected = isset($current_themas[$thema->id]); if (!$thema_selected) continue; if ($c++) echo ', '; echo htmlentities($thema->thema, ENT_COMPAT, 'UTF-8'); } ?> </td> </tr> <? endforeach; ?> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('betrokkenen'), 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table> <? foreach ($subjecten as $subject): ?> <? if (!isset($current_subjecten[$subject->id])) continue; ?> <tr> <td style="vertical-align:top;"> <b><?=htmlentities( $subject->naam, ENT_COMPAT, 'UTF-8' )?></b> <? if ($subject->organisatie): ?> <i>(<?=htmlentities( $subject->organisatie, ENT_COMPAT, 'UTF-8' )?>)</i> <? endif; ?> <? if ($subject->rol): ?> - <?=htmlentities( $subject->rol, ENT_COMPAT, 'UTF-8' )?> <? endif; ?> </td> </tr> <? endforeach; ?> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('bescheiden'), 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table width="100%"> <tr> <? $columns = 4; $index = 0; ?> <? foreach ($bescheiden as $b): ?> <? $bescheiden_selected = isset($current_bescheiden[$b->id]); if (!$bescheiden_selected) continue; ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <a target="_blank" href="<?=site_url('/dossiers/bescheiden_downloaden/' . $b->id)?>"> <img src="<?=site_url( '/pdfview/bescheiden/' . $b->id . '/1' )?>" /> </a> </div> <div style="display: inline-block; overflow:hidden; width:190px; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; " title="<?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?>"><input type="checkbox" name="bescheiden[<?=$b->id?>]" <?=$bescheiden_selected?'checked':''?> /> <b><?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?></b></div> </td> <? $index++; ?> <? endforeach;?> <? for ($i=0; $i<($columns - (($index % $columns)+1)); ++$i): ?> <td style="width:<?=round(100/$columns)?>%"></td> <? endfor; ?> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>INSERT INTO `webservice_applicaties` (`id` ,`naam`) VALUES (NULL , 'BRIStoets' ); SET @appid = LAST_INSERT_ID(); INSERT INTO `webservice_accounts` (`id`, `webservice_applicatie_id`, `omschrijving`, `gebruikersnaam`, `wachtwoord`, `actief`, `alle_klanten`, `alle_components`) VALUES (NULL, @appid, 'BRIStoets koppeling', 'bristoets', SHA1('12345Abc'), '1', '1', '0'); SET @accountid = LAST_INSERT_ID(); INSERT INTO `webservice_components` (`id` ,`naam`) VALUES (NULL , 'BRIStoets koppeling'); SET @componentid = LAST_INSERT_ID(); INSERT INTO `webservice_account_rechten` (`id`, `webservice_account_id`, `webservice_component_id`) VALUES (NULL, @accountid, @componentid); <file_sep><? require_once 'base.php'; class PagoPmoResult extends BaseResult { function PagoPmoResult( $arr ){ // parent::BaseResult( 'org_kenmerken', $arr ); foreach ($arr as $k => $v) $this->$k = $v; } //------------------------------------------------------------------------------ }// Class end class Pago_pmo extends BaseModel { private $_cache = array(); function Pago_pmo(){ parent::BaseModel( 'PagoPmoResult', 'cust_rep_data_155_pago_pmo' ); } //------------------------------------------------------------------------------ function get_funcs( $dossier ){ $sql = "SELECT * FROM cust_rep_data_155_pago_pmo WHERE dossier_id = ? "; $stmt_name = 'pago_pmo::all'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $dossier->id ) ))) throw new Exception( 'Failed getting data from cust_rep_data_155_pago_pmo / by method get_funcs' ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } //------------------------------------------------------------------------------ function get_func_by_id( $id ){ //$sql = "SELECT * FROM cust_rep_data_155_pago_pmo WHERE id = ? LIMIT 1"; $sql = "SELECT * FROM cust_rep_data_155_pago_pmo WHERE id = ?"; $stmt_name = 'pago_pmo::by_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $id ) ))) throw new Exception( 'Failed getting data from cust_rep_data_155_pago_pmo / by method get_func_by_id' ); $result = $res->result(); return $this->getr( $result[0] ); } //------------------------------------------------------------------------------ public function add( DossierResult $dossier, array $postdata ){ $postdata['dossier_id'] = $dossier->id; return $this->insert( $postdata ); } //------------------------------------------------------------------------------ public function save( DossierResult $dossier, array $postdata ){ $postdata['dossier_id'] = $dossier->id; if( $postdata['id'] == '' ){ return $this->insert( $postdata ); }else{ return parent::save( (object)$postdata ); } } //------------------------------------------------------------------------------ }// Class end <file_sep><?php class WettenRegelgeving extends Controller { // loaded by _load_grondslagen private $_grondslagen; private $_grondslag_vraag_stats; private $_grondslag_artikel_stats; public function __construct() { parent::__construct(); $this->navigation->push( 'nav.instellingen', '/instellingen' ); $this->navigation->push( 'nav.wetteksten_en_regelgeving', '/wettenregelgeving' ); $this->navigation->set_active_tab( 'beheer' ); } public function index() { $this->_load_grondslagen(); $this->load->view( 'wettenregelgeving/index', array( 'grondslagen' => $this->_grondslagen, 'vraag_stats' => $this->_grondslag_vraag_stats, 'artikel_stats' => $this->_grondslag_artikel_stats, ) ); } public function grondslag( $grondslag_id=null ) { $this->_load_grondslagen(); if (!($grondslag = $this->grondslag->get( $grondslag_id ))) redirect( '/wettenregelgeving' ); if ($grondslag->klant_id != $this->gebruiker->get_logged_in_gebruiker()->klant_id) redirect( '/wettenregelgeving' ); $this->navigation->push( 'nav.grondslag', '/wettenregelgeving/grondslag/' . $grondslag->id, array( $grondslag->grondslag ) ); $this->load->model( 'grondslagtekst' ); // !!! Note: the Oracle implementation of 'GROUP BY' is stricter than the MySQL one: the former ONLY allows one to select GROUP BY or AGGREGATE // columns. Selecting so-called 'non-unique' columns results in an "ORA-00979: not a GROUP BY expression" error. // The solution is to nest the GROUP BY in a subselect and to use the outcome of that in an IN clause in the main query. $res = $this->db->query( ' SELECT id, grondslag_id, TRIM(artikel) AS artikel, tekst FROM bt_grondslag_teksten WHERE grondslag_id = (' . $grondslag->id . ') '); $grondslagteksten = array(); foreach ($res->result() as $row) { if (!isset( $grondslagteksten[ $row->artikel ] )) $grondslagteksten[ $row->artikel ] = $this->grondslagtekst->getr( $row ); } $res->free_result(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $stmt_name = 'WettenRegelgeving::grondslag:update'; if (!$this->dbex->prepare( $stmt_name, $q = 'UPDATE bt_grondslag_teksten SET tekst = ? WHERE id = ?' )) throw new Exception( 'Interne fout bij opslaan in de database (1).' ); foreach ($grondslagteksten as $grondslagtekst) { $args = array( trim( $_POST['tekst'][$grondslagtekst->id] ), $grondslagtekst->id ); var_dump($args); if (!$this->dbex->execute( $stmt_name, $args )) throw new Exception( 'Interne fout bij opslaan in de database (2).' ); } redirect( '/wettenregelgeving/grondslag/' . $grondslag_id ); } usort( $grondslagteksten, function( $a, $b ) { return strnatcmp( $a->artikel, $b->artikel ); } ); $this->load->view( 'wettenregelgeving/grondslag', array( 'grondslag' => $grondslag, 'grondslagteksten' => $grondslagteksten, ) ); } public function grondslag_gebruik( $grondslag_tekst_id=null ) { $this->_load_grondslagen(); if (!($grondslagtekst = $this->grondslagtekst->get( $grondslag_tekst_id ))) redirect( '/wettenregelgeving' ); $grondslag = $grondslagtekst->get_grondslag(); if ($grondslag->klant_id != $this->gebruiker->get_logged_in_gebruiker()->klant_id) redirect( '/wettenregelgeving' ); $this->navigation->push( 'nav.grondslag_artikel_gebruik', '/wettenregelgeving/grondslag_gebruik/' . $grondslag_tekst_id, array( $grondslag->grondslag, $grondslagtekst->artikel ) ); $stmt_name = 'WettenRegelgeving::grondslag:grondslag_gebruik'; if (!$this->dbex->prepare( $stmt_name, ' SELECT cg.naam AS cg_naam, cl.naam AS cl_naam, h.naam AS h_naam, c.naam AS c_naam, v.tekst, cg.id AS cg_id, cl.id AS cl_id, h.id AS h_id, c.id AS c_id, v.id AS v_id FROM bt_vraag_grndslgn vg JOIN bt_grondslag_teksten gt ON vg.grondslag_tekst_id = gt.id JOIN bt_vragen v ON vg.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE gt.id = ? ORDER BY cg.sortering, cl.sortering, h.sortering, c.sortering, v.sortering ')) throw new Exception( 'Fout bij ophalen gegevens uit database (1).' ); if (!($res = $this->dbex->execute( $stmt_name, array( $grondslag_tekst_id ) ))) throw new Exception( 'Fout bij ophalen gegevens uit database (2).' ); $contents = $res->result(); $res->free_result(); $this->load->view( 'wettenregelgeving/grondslag_gebruik', array( 'grondslagtekst' => $grondslagtekst, 'grondslag' => $grondslag, 'artikel' => $grondslagtekst->artikel, 'contents' => $contents, ) ); } private function _load_grondslagen() { $this->load->model( 'grondslag' ); $this->load->model( 'grondslagtekst' ); $this->load->model( 'vraaggrondslag' ); // load grondslagen vraag stats $res = $this->db->query( ' SELECT COUNT(*) AS count, gt.grondslag_id FROM bt_vraag_grndslgn vg JOIN bt_grondslag_teksten gt ON vg.grondslag_tekst_id = gt.id GROUP BY gt.grondslag_id '); $this->_grondslag_vraag_stats = array(); foreach ($res->result() as $row) $this->_grondslag_vraag_stats[ $row->grondslag_id ] = $row->count; $res->free_result(); // load grondslagen artikel stats $res = $this->db->query( ' SELECT COUNT(DISTINCT(TRIM(artikel))) AS count, gt.grondslag_id FROM bt_vraag_grndslgn vg JOIN bt_grondslag_teksten gt ON vg.grondslag_tekst_id = gt.id GROUP BY gt.grondslag_id '); $this->_grondslag_artikel_stats = array(); foreach ($res->result() as $row) $this->_grondslag_artikel_stats[ $row->grondslag_id ] = $row->count; $res->free_result(); // load grondslagen $this->_grondslagen = array(); foreach ($this->grondslag->get_for_huidige_klant() as $grondslag) if (isset( $this->_grondslag_vraag_stats[ $grondslag->id ] )) $this->_grondslagen[] = $grondslag; } } <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | File and Directory Modes |-------------------------------------------------------------------------- | | These prefs are used when checking and setting modes when working | with the file system. The defaults are fine on servers with proper | security, but you may wish (or even need) to change the values in | certain environments (Apache running a separate process for each | user, PHP under CGI with Apache suEXEC, etc.). Octal values should | always be used to set the mode correctly. | */ define('FILE_READ_MODE', 0644); define('FILE_WRITE_MODE', 0666); define('DIR_READ_MODE', 0755); define('DIR_WRITE_MODE', 0777); /* |-------------------------------------------------------------------------- | File Stream Modes |-------------------------------------------------------------------------- | | These modes are used when working with fopen()/popen() | */ define('FOPEN_READ', 'rb'); define('FOPEN_READ_WRITE', 'r+b'); define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care define('FOPEN_WRITE_CREATE', 'ab'); define('FOPEN_READ_WRITE_CREATE', 'a+b'); define('FOPEN_WRITE_CREATE_STRICT', 'xb'); define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); // Directories for store binary data. //define('DIR_DOSSIER_BESCHEIDEN', BASEPATH . '../documents/dossier_bescheiden'); define('DIR_DOSSIER_BESCHEIDEN', BASEPATH . '../documents/dossier_bescheiden'); define('DIR_DOSSIER_FOTOS', BASEPATH . '../documents/dossier_fotos'); define('DIR_STANDAARTEN_DOCUMENTEN', BASEPATH . '../documents/standaarten_documenten'); //define('DIR_DEELPLAN_UPLOAD', BASEPATH . '../documents/deelplan_upload'); define('DIR_DEELPLAN_UPLOAD', BASEPATH . '../documents/deelplan_upload'); define('DIR_DISTRIBUTEUR_UPLOAD', BASEPATH . '../documents/distributeur_upload'); define('DIR_NB_DISTRIBUTEUR_UPLOAD', '/documents/distributeur_upload'); //define('DIR_DOSSIER_RAPPORT', BASEPATH . '../documents/dossier_rapport'); define('DIR_DOSSIER_RAPPORT', BASEPATH . '../documents/dossier_rapport'); define('PATH_TO_IMAGE', BASEPATH . '../files/images/no.image.png'); define('DIR_THUMBNAIL', 'thumbs'); define('ALLOWED_EXTENSIONS', 'bak, bmp, ctb, db, doc, docm, docx, dwg, exe, fmp, gif, gml, GWI, htm, jpeg, '. 'jpg, lnk, MOV, mp4, msg, pc3, pdf, png, pptx, rar, rtf, shx, tif, ttf, txt, '. 'xls, xlsx, zip'); define('IMAGE_EXTESIONS', 'jpg, jpeg, png, gif'); define('DOC_EXTESIONS', 'bak, bmp, ctb, db, doc, docm, docx, dwg, exe, fmp, gml, GWI, htm, lnk, MOV, '. 'mp4, msg, pc3, pdf, pptx, rar, rtf, shx, tif, ttf, txt, xls, xlsx, zip'); define('CLIENT_NAME_IMOTEP', 'imotep'); define('EMAIL_OPT_QUESTION', 'question'); define('EMAIL_OPT_QUESTION_STATUS', 'question_status'); define('EMAIL_OPT_SUPERVISOR', 'supervisor'); define('EMAIL_OPT_DATE', 'date'); define('EMAIL_OPT_ANWSER', 'anwser'); define('EMAIL_OPT_DOSSIER_DATA', 'dossier_data'); define('EMAIL_OPT_LETTER', 'letter'); define('STATUS_RED', 'rood'); define('STATUS_ORANGE', 'oranje'); define('STATUS_GREEN', 'groen'); define('STATUS_ALL_COLORS', 'all'); define('RETURN_URL', 'return_url'); define('SUBJECT_EXTERN_ORG', 'ander'); define('SUBJECT_INTERN_ORG', 'intern'); define('SUBJECT_KID_ORG', 'kid'); define('ROL_ASSIGNMENTS_NAME', 'Externe opdrachtnemer'); define('AUTH_KENNIS_ID', 'KennisID'); define('KENNIS_ID_USER_INTERNAL', 'ja'); define('KENNIS_ID_USER_EXTERNAL', 'nee'); /* End of file constants.php */ /* Location: ./system/application/config/constants.php */<file_sep><div class="scrolldiv hidden" id="TelefoonPaginaDossiers"> <div class="header"> <span><?=APPLICATION_TITLE?></span> </div> <div class="content"> <h1><?=tg('dossiers.welkom')?></h1> <? if (sizeof( $dossiers )): ?> <span><?=tg('dossiers.kies.adres')?></span> <ul class="list"> <? $i=0; foreach ($dossiers as $dossierdata): $dossier = $dossierdata['dossier']; ?> <? if (sizeof($dossiers) > 1) $class = !$i ? 'first' : ($i == sizeof($dossiers)-1 ? 'last' : ''); else $class = 'first last'; ?> <li class="arrow-right <?=$class?> clickable bold" dossier_id="<?=$dossier->id?>"><?=htmlentities( $dossier->get_locatie(), ENT_COMPAT, 'UTF-8' )?></li> <? ++$i; endforeach; ?> </ul> <? else: ?> <div class="melding">Er zijn momenteel geen opdrachten voor u ingepland.</div> <? endif; ?> </div> </div> <script type="text/javascript"> $(document).ready(function(){ var base = $('#TelefoonPaginaDossiers'); base.find( 'ul.list li[dossier_id]' ).click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_DEELPLANNEN, $(this).attr('dossier_id') ); }); }); </script><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Laatste opgevraagde URI\'s')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Laatste URI\'s', 'width' => '920px' ) ); ?> <table width="900" cellpadding="0" cellspacing="0"> <tr> <th align="left"><a href="<?=site_url('/admin/stats_uris/'.($mode=='ip'?'hostname':'ip'))?>"><?=$mode=='ip'?'IP':'Hostname'?></a></th> <th align="left">URI</th> <th align="left">Tijdstip</th> </tr> <? foreach ($data as $stat): ?> <tr> <td><?=($mode=='ip') ? $stat->ip : $hostnames[$stat->ip]?></td> <td><?=strlen( $stat->uri ) < 50 ? $stat->uri : (substr($stat->uri, 0, 47 ) . '...') ?></td> <td><?=date("d-m-Y G:i:s", $stat->timestamp)?></td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php class PDFView extends Controller { const MODE_ORIGINAL = 0; const MODE_THUMBNAIL = 1; const MODE_OVERVIEW = 2; public function __construct() { parent::__construct(); $this->load->library( 'imageprocessor' ); // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit( 3600 ); } /**************************************************************************************** * * * MAIN FUNCTIONS * * * ****************************************************************************************/ public function bescheiden( $bescheiden_id, $mode=0, $slice=null ) { $this->_get_contents_through_imageprocessor( $bescheiden_id, 'bescheiden', $mode, $slice ); } public function vraagupload( $vraagupload_id, $mode=0, $slice=null ) { $this->_get_contents_through_imageprocessor( $vraagupload_id, 'vraagupload', $mode, $slice ); } /**************************************************************************************** * * * HELPER FUNCTIONS * * * ****************************************************************************************/ private function _get_contents_through_imageprocessor( $id, $type, $mode, $slice ) { $this->imageprocessor->id( $id ); $this->imageprocessor->type( $type ); $this->imageprocessor->mode( $mode==self::MODE_ORIGINAL ? 'original' : ($mode==self::MODE_THUMBNAIL ? 'thumbnail' : ($mode==self::MODE_OVERVIEW ? 'overview' : 'unknown')) ); $this->imageprocessor->slice( $slice ); $this->imageprocessor->page_number( 1 ); $available = $this->imageprocessor->available(); if (empty( $available )) $this->_output_no_example_image(); else { $contents = $this->imageprocessor->contents( $mimetype ); $this->_output_contents( $contents, $mimetype, 365*86400 ); } } private function _output_no_example_image() { switch ($mode = $this->imageprocessor->get_mode()) { case 'thumbnail': case 'overview': $this->_output_contents( @file_get_contents( $this->imageprocessor->get_cache_base_path() . '/geen-voorbeeld-' . $mode . '.png' ), 'image/png', 60 /* cache just for a minute */ ); break; default: $this->_output_contents( @file_get_contents( $this->imageprocessor->get_cache_base_path() . '/geen-voorbeeld.png' ), 'image/png', 60 /* cache just for a minute */ ); break; } } private function _output_contents( $contents, $content_type, $cachetime=null ) { // output headers if (!is_null( $cachetime )) { $cacheTime = $cachetime ? $cachetime : (86400 * 30 * 12); // "12 months" if not specified $etag = sha1( $contents ); header( 'Cache-Control: max-age=' . $cacheTime . ',public' ); header( 'Pragma: public' ); header( 'Expires: ' . date( 'D, d M Y H:i:s ', time() + $cacheTime ) ) . ' UTC'; header( 'Last-Modified: ' . date( 'D, d M Y H:i:s ', strtotime( '2000-01-01' ) ) . ' GMT' ); header( 'Etag: ' . $etag ); } else $etag = null; header( 'Content-Type: ' . $content_type ); header( 'Content-Length: ' . strlen($contents) ); // check etag if (!is_null( $etag )) { $headers = function_exists( 'apache_request_headers' ) ? apache_request_headers() : array(); if ( (isset( $headers['If-None-Match'] ) && $headers['If-None-Match'] == $etag) || (@$_SERVER['HTTP_IF_NONE_MATCH'] == $etag) ) { header("HTTP/1.1 304 Not Modified"); exit; } } // output contents echo $contents; // quit PHP exit; } } <file_sep><div class="pbm_page_header"> <p class="description">Naast de kolom "Functie en erbij behorende risicoberekening" moet de adviseur ook de kolommen "risico's/blootstelling", "Bronmaatregelen" en "PBM i.v.m. restrisico's" verder aanvullen/aanpassen, afhankelijk van soort bedrijf, in aanmerking komende functies en daaraan gekoppelde risico's.</p> </div> <button type="button" onclick="show_pbm_form('');">Toevoegen</button> <?if( count( $tasks ) > 0 ):?> <table class="appendix_tbl"> <thead> <tr> <th rowspan="2" class="left_th" style="width:25%;"><?=tg('kritieke_taak')?></th> <th rowspan="2" class="mid_th" style="width:20%;"><?=tg('risico_blootstelling')?></th> <th colspan="4" class="mid_th" style="width:15%;"><?=tg('wxbxe')?></th> <th rowspan="2" class="mid_th" style="width:20%;"><?=tg('bronmaatregelen')?></th> <th rowspan="2" class="right_th" style="width:20%;"><?=tg('pbm')?></th> </tr> <tr> <th class="mid_th">W</th> <th class="mid_th">B</th> <th class="mid_th">E</th> <th class="mid_th">R</th> </tr> </thead> <tbody> <?foreach( $tasks as $task ):?> <?$risks = $task->risks;?> <?$count_risks = count( $risks );?> <?$is_first_risk = TRUE;?> <?$n_risk=0;?> <?foreach( $risks as $risk ):?> <?$brd = (++$n_risk==$count_risks) ? '' : ' last_row_td'?> <tr> <?if( $is_first_risk ):?> <td class="left_td" rowspan="<?=$count_risks?>"> <a href="#" title="Bewerk" onclick="show_pbm_form(<?=$task->id?>);"><?=$task->pbm_taak_name?></a> <input type="button" class="risk_btn" onclick="show_pbm_risk_form(<?=$task->id?>,'');" value="Toevoegen" title="Bewerk" /> </td> <?endif;?> <?$a_tag = $task->real_count_risks ? '<a href="#" title="Bewerk" onclick="show_pbm_risk_form('.$task->id.','.$risk->id.');">'.$risk->risico_blootstelling.'</a>' : ''; ?> <td class="mid_td<?=$brd?>"><?=$a_tag?></td> <td class="mid_td<?=$brd?>"><?=$risk->w?></td> <td class="mid_td<?=$brd?>"><?=$risk->b?></td> <td class="mid_td<?=$brd?>"><?=$risk->e?></td> <td class="mid_td<?=$brd?>"><?=$risk->r?></td> <td class="mid_td<?=$brd?>"><?=$risk->bronmaatregelen?></td> <td class="right_td<?=$brd?>"><?=$risk->pbm?></td> <?$is_first_risk = FALSE;?> </tr> <?endforeach;?> <?endforeach;?> </tbody> </table> <? else: ?> <div><?=tg('no_items_found');?></div> <? endif; ?> <div class="bpm_report_footer"> <p class="bpm_footer_title">Aanvulling t.b.v. VCA. Indien de RI&E niet voor VCA certificatie is bestemd dan moet deze tabel verwijderd worden.</p> </div> <script> function show_pbm_form(taskId){ var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/show_pbm_form/' . $dossier->id)?>/'+taskId ); } function show_pbm_risk_form(taskId,riskId){ var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/show_pbm_risk_form')?>'+"/"+taskId+"/"+riskId ); } </script><file_sep><?php class Telefoon extends Controller { private function _get_my_opdrachten() { $this->load->model( 'deelplanopdracht' ); return $this->deelplanopdracht->get_my_opdrachten(); } public function index( $initial_command=null ) { /* if( !preg_match('~^deelplan=\d+,\d+$~', $initial_command, $matches) ) { throw new Exception('Bad Request'); } * */ $dossiers = array(); foreach ($this->_get_my_opdrachten() as $opdracht) { $deelplan = $opdracht->get_deelplan(); $dossier = $deelplan->get_dossier(); $vraag = $opdracht->get_vraag(); $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); if (!isset( $dossiers[$dossier->id] )) $dossiers[$dossier->id] = array( 'dossier' => $dossier, 'deelplannen' => array(), ); if (!isset( $dossiers[$dossier->id]['deelplannen'][$deelplan->id] )) $dossiers[$dossier->id]['deelplannen'][$deelplan->id] = array( 'deelplan' => $deelplan, 'hoofdgroepen' => array(), ); if (!isset( $dossiers[$dossier->id]['deelplannen'][$deelplan->id]['hoofdgroepen'][$hoofdgroep->id] )) $dossiers[$dossier->id]['deelplannen'][$deelplan->id]['hoofdgroepen'][$hoofdgroep->id] = array( 'hoofdgroep' => $hoofdgroep, 'opdrachten' => array(), ); $dossiers[$dossier->id]['deelplannen'][$deelplan->id]['hoofdgroepen'][$hoofdgroep->id]['opdrachten'][] = $opdracht; } $this->load->view( 'telefoon/index', array( 'dossiers' => $dossiers, 'initial_command' => $initial_command, ) ); } public function post() { $this->load->model( 'deelplanopdracht' ); $this->load->model( 'deelplanvraaggeschiedenis' ); try { // check post if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'Verzoek is geen POST verzoek.' ); // start transactie $this->db->trans_start(); try { // loop over de vragen die gereed zijn if (!isset( $_POST['gereed'] )) throw new Exception( 'Geen vragen die gereed zijn gemeld, zou niet mogen voorkomen op deze plek.' ); foreach ($_POST['gereed'] as $opdracht_id => $gereed) { // is de vraag gereed? we komen hier ook zeker niet-gereed vragen tegen if (!$gereed) continue; // haal data op, controleer of alles er is if (!isset( $_POST['status'][$opdracht_id] ) || !isset( $_POST['toelichting'][$opdracht_id] )) throw new Exception( 'Onvolledige data, status of toelichting niet gezet voor opdracht ID ' . $opdracht_id ); $status = $_POST['status'][$opdracht_id]; $toelichting = $_POST['toelichting'][$opdracht_id]; if (!($opdracht = $this->deelplanopdracht->get( $opdracht_id ))) throw new Exception( 'Ongeldige opdracht ID ' . $opdracht_id ); $gebruiker_id = $this->gebruiker->get_logged_in_gebruiker()->id; $opdracht->antwoord = $status; $opdracht->toelichting = $toelichting; $opdracht->save( 0, 0, 0 ); /* * --> we doen dit niet langer, in plaats hiervan veranderen we de foto opdracht * annotatie nu in een compound annotatie, die alle informatie van deze * opdracht bevatten zal! * * dit gebeurt in de verwerk_in_layer() call hieronder! * * // is er een status gezet? dit is niet verplicht if ($status) { // bekijk of we een revisie moeten toevoegen, dit is het geval wanneer er in de deelplanvraag al // iets staat ingevuld; // LET OP: deelplan_vragen heeft geen model, omdat het geen ID veld heeft! We krijgen dus een // stdClass standaard PHP object terug uit _get_deelplan_vraag ! if (!($deelplanvraag = $this->_get_deelplan_vraag( $opdracht->deelplan_id, $opdracht->vraag_id ))) throw new Exception( 'Kan deelplan vraag niet vinden: deelplan ID ' . $opdracht->deelplan_id . ', vraag ID ' . $opdracht->vraag_id ); if ($deelplanvraag->status) $this->deelplanvraaggeschiedenis->add( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $deelplanvraag->status, $deelplanvraag->toelichting, $deelplanvraag->gebruiker_id, $deelplanvraag->last_updated_at ); // zet de data nu! $this->_zet_deelplan_vraag( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $status, $toelichting, $gebruiker_id ); } */ // werk opdracht bij $opdracht->markeer_gereed(); // verwerk opdracht in z'n layer $result = $opdracht->verwerk_in_layer(); if (is_array( $result )) { // bekijk of we een revisie moeten toevoegen, dit is het geval wanneer er in de deelplanvraag al // iets staat ingevuld; // LET OP: deelplan_vragen heeft geen model, omdat het geen ID veld heeft! We krijgen dus een // stdClass standaard PHP object terug uit _get_deelplan_vraag ! if (!($deelplanvraag = $this->_get_deelplan_vraag( $opdracht->deelplan_id, $opdracht->vraag_id ))) throw new Exception( 'Kan deelplan vraag niet vinden: deelplan ID ' . $opdracht->deelplan_id . ', vraag ID ' . $opdracht->vraag_id ); if ($deelplanvraag->status) $this->deelplanvraaggeschiedenis->add( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $deelplanvraag->status, $deelplanvraag->toelichting, $deelplanvraag->gebruiker_id, $deelplanvraag->last_updated_at ); // zet de data nu! $this->_zet_deelplan_vraag( $deelplanvraag->deelplan_id, $deelplanvraag->vraag_id, $result['nieuwe_status'], $result['nieuwe_toelichting'], $gebruiker_id ); } } // commit! if (!$this->db->trans_complete()) throw new Exception( 'Fout bij committen naar database.' ); } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); throw $e; } // done! echo json_encode(array( 'success' => true, ) ); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage(), ) ); } } private function _get_deelplan_vraag( $deelplan_id, $vraag_id ) { $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->where( 'vraag_id', $vraag_id ); if (!($res = $this->db->get( 'deelplan_vragen' ))) throw new Exception( 'Fout bij lezen van deelplan vragen database' ); $deelplanvraag = $res->row_object(); $res->free_result(); return $deelplanvraag ? $deelplanvraag : null; } private function _zet_deelplan_vraag( $deelplan_id, $vraag_id, $status, $toelichting, $gebruiker_id ) { $this->db->set( 'status', $status ); $this->db->set( 'toelichting', $toelichting ); $this->db->set( 'gebruiker_id', $gebruiker_id ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->where( 'vraag_id', $vraag_id ); if (!$this->db->update( 'deelplan_vragen' )) throw new Exception( 'Fout bij bewerken van deelplan vragen database' ); } public function upload() { try { // doordat we in onze input type=file een name hebben met een array waarde // (b.v. name="foto[1]"), is de _FILES structuur een beetje verwarrend. Zoek // op welk ID we hebben ontvangen. Als we niets kunnen vinden, is er niks // geupload! if (!isset( $_FILES['foto'] )) throw new Exception( '$_FILES["foto"] is niet gezet.' ); $opdracht_id = $tmp_name = $name = null; foreach ($_FILES['foto']['error'] as $id => $error) if (!$error && @$_FILES['foto']['tmp_name'][$id]) { $opdracht_id = $id; $tmp_name = $_FILES['foto']['tmp_name'][$id]; $name = $_FILES['foto']['name'][$id]; break; } if (is_null( $opdracht_id )) throw new Exception( 'Geen file upload ontvangen!' ); if (false === ($contents = @file_get_contents( $tmp_name ))) throw new Exception( 'Fout bij lokaal ophalen van upload!' ); // laad opdracht $this->load->model( 'deelplanopdracht' ); if (!($opdracht = $this->deelplanopdracht->get( $opdracht_id ))) throw new Exception( 'Ongeldig opdracht ID ontvangen: ' . $opdracht_id ); // start transactie $this->db->trans_start(); try { // heeft deze opdracht al een foto? die dan verwijderen! $this->load->model( 'deelplanupload' ); $upload = $opdracht->get_deelplan_upload(); if ($upload) { $upload->delete(); // eerst upload, dan data! $opdracht->deelplan_upload_id = null; /* gaat automatisch in DB al op null, maar ook hier zetten */ } // creeer een nieuwe deelplan upload! $upload = $this->deelplanupload->add( $opdracht->deelplan_id, $opdracht->vraag_id, /* filename */ date('d-m-Y H.i.s') . ' #' . $opdracht->id . '.jpg', $contents ); $opdracht->deelplan_upload_id = $upload->id; $opdracht->save(); // commit! if (!$this->db->trans_complete()) throw new Exception( 'Fout bij committen naar database.' ); } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); throw $e; } // done! echo json_encode(array( 'success' => true, ) ); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage(), ) ); } } } <file_sep><?php define( 'PDFANNOTATOR_VERSION', '3.0.8-SNAPSHOT' ); <file_sep><?php class CI_Logger { var $CI; public function CI_Logger() { $this->CI = get_instance(); $this->CI->load->model( 'gebruiker' ); $this->CI->load->model( 'log' ); } public function add( $deelplan, $soort, $omschrijving, $extra_info=null ) { $this->CI->log->add( $deelplan, $soort, $omschrijving, $extra_info ); } } <file_sep>PDFAnnotator.GUI.Menu.Panel = PDFAnnotator.Base.extend({ init: function( menu ) { this._super(); this.menu = menu; }, getMenu: function() { return this.menu; }, reset: function() { } }); <file_sep><?php require_once('KMXMagmaClient.php'); class KMXLicenseSystem extends KMXMagmaClient { public $serviceUrl; public $licenseSystemLabel; public $lastToken; private function get($url) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, rtrim($this->serviceUrl, '/') . $url); curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($c, CURLOPT_HTTPHEADER, array('MagmaToken: ' . $this->getMagmaToken(), 'Accept: application/json')); $result = curl_exec($c); curl_close($c); return json_decode($result); } private function post($url) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, rtrim($this->serviceUrl, '/') . $url); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, ''); curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($c, CURLOPT_HTTPHEADER, array('MagmaToken: ' . $this->getMagmaToken(), 'Accept: application/json')); $result = curl_exec($c); curl_close($c); return json_decode($result); } private function openLicense($data) { if (array_key_exists('password', $data)) { // Always hash password $data['key'] = md5($data['password'] . date('d-m-Y')); unset($data['password']); } return $this->post('/Api/License/Open?licenseSystemLabel=' . $this->licenseSystemLabel . '&' . http_build_query($data)); } /** * Claimt licentieplaats aan de hand van inloggegevens voor een bepaalde * Knowmax Licentiesysteem identitieit. */ public function claimLicenseSeatForIdentity($identity, $password) { return $this->claimLicenseSeat(array('identity'=>$identity, 'password'=>$password)); } /** * Claimt licentieplaats aan de hand van array met gegevens. Het Knowmax Licentiesysteem * kent behalve inlogmogelijkheden via Knowmax Licentiesysteem identiteiten ook mogelijkheden * om direct toegang te krijgen tot een bepaalde licentie via andere waarden zoals ipv4, md5, referrer, * onetimetoken. * Informatie over geclaimde licentieplaats wordt opgeslagen in sessie. */ public function claimLicenseSeat($data) { $this->lastToken = null; $data['ipv4'] = $_SERVER['REMOTE_ADDR']; $licensesession = $this->openLicense($data); if (!$licensesession) return null; if ($licensesession->Status == 'Valid') { unset($data['password']); $licenseseat = $this->post('/Api/License/ClaimSeat?token=' . urlencode($licensesession->Token) . '&' . http_build_query($data)); if ($licenseseat->Status == 'Valid') { $this->lastToken = strval($licensesession->Token); $_SESSION['License.Token'] = strval($licensesession->Token); $_SESSION['License.Json'] = json_encode($licenseseat); } return $licenseseat; } else { return $licensesession; } } /** * Hef claim op licentieplaats in huidige sessie op. Roep aan bij het afmelden van een gebruiker. */ public function clearLicenseSeat() { $token = $this->getClaimedLicenseSeatToken(); if (isset($token)) { $this->post('/Api/License/ClearSeat?token=' . urlencode($token)); unset($_SESSION['License.Token']); unset($_SESSION['License.Json']); } } /** * Geeft object met informatie over geclaimde licentieplaats in huidige sessie. */ public function getClaimedLicenseSeatInfo() { if (isset($_SESSION['License.Json'])) { return json_decode($_SESSION['License.Json']); } else { return null; } } /** * Geeft token van geclaimde licentieplaats in huidige sessie. */ public function getClaimedLicenseSeatToken() { if (isset($_SESSION['License.Token'])) { return $_SESSION['License.Token']; } else { return null; } } /** * Controleer of gebruiker in huidige sessie de beschikking heeft over een * geclaimde licentieplaats. Optioneel kan met de boolean $test worden aangegeven * of de geclaimde licentieplaats opnieuw gecontroleerd moet worden bij de * Knowmax Licentieservice. het is belangrijk dit periodiek te doen o.a. om * te zorgen dat de licentie niet door de service uit getimed wordt bij gebrek * aan activiteit. */ public function hasClaimedLicenseSeat($test = false) { $token = $this->getClaimedLicenseSeatToken(); if (isset($token)) { if (!$test) { return true; } else { $status = $this->get('/Api/License/TestSeat?token=' . urlencode($token)); if ($status[0] == 'true') { return true; } else { $this->clearLicenseSeat(); } } } return false; } /** * Geeft object met token voor eenmalige toegang tot licentieplaats. Dit token is ten minste een jaar geldig en kan * gebruikt worden om in de toekomst via claimLicenseSeat een licentieplaats te claimen. Gebruik dit token bijvoorbeeld * om op te slaan in een cookie en bij een volgend bezoek automatisch in te loggen. * Object attributen: Token, Expires en Status. */ public function getOneTimeToken() { $token = $this->getClaimedLicenseSeatToken(); if (isset($token)) { return $this->post('/Api/License/OneTimeToken?token=' . urlencode($token)); } return null; } /** * Geeft object met status informatie voor licentie-onderdeel met opgegeven label. Gebruik deze * informatie om te bepalen of de gebruiker met een licentieplaats in de huidige sessie toegang * heeft tot een bepaald applicatie-onderdeel. */ public function getLicenseItem($label) { $token = $this->getClaimedLicenseSeatToken(); if (isset($token)) { return $this->get('/Api/LicenseItem/Info?token=' . urlencode($token) . '&label=' . urlencode($label)); } return null; } /** * Verzoekt Knowmax Licentiesysteem om gebruiker op opgegeven Knowmax Licentiesysteem identificatie * een email te sturen met instructies om wachtwoord opnieuw in te stellen. Gebruik deze functie * voor gebruikers die hun wachtwoord vergeten zijn. * Optioneel kan het label van een email template worden opgegeven dat gebruikt zal worden voor de * te versturen email. */ public function resetIdentityPasswordRequest($identity, $emailTemplateLabel = '') { $licensesession = $this->openLicense(array('identity'=>$identity, '3thpartyauth'=>'1')); if ($licensesession) { if ($licensesession->Status == 'Valid') { $status = $this->post('/Api/LicenseIdentity/ResetPasswordRequest?token=' . urlencode(strval($licensesession->Token)) . '&emailtemplatelabel=' . urlencode($emailTemplateLabel)); return ($status[0] == 'true'); } } } /** * Wijzig wachtwoord van Knowmax Licentiesysteem identiteit in huidige sessie. Alleen voor gebruikers * die ook met hun licentieplaats verkregen hebben via hun Knowmax Licentiesysteem identiteit. * Resultaat object attribuut: Status (Waarden: Done, Failure, NoAccess, NoIdentity, NotAllowed, InvalidPassword) */ public function updateIdentityPassword($oldPassword, $newPassword) { $licenseseat = $this->getClaimedLicenseSeatInfo(); $token = $this->getClaimedLicenseSeatToken(); if ((isset($token)) && (isset($licenseseat)) && (isset($licenseseat->LicenseInfo->Identity)) && ($licenseseat->LicenseInfo->Identity->AllowPasswordChange == 'true')) { $hash = md5($oldPassword . $newPassword . date('d-m-Y')); return $this->post('/Api/LicenseIdentity/UpdatePassword?token=' . urlencode($token) . '&password=' . urlencode($newPassword) . '&hash=' . $hash); } } } ?><file_sep><? require_once 'base.php'; class ThemaResult extends BaseResult { function ThemaResult( &$arr ) { parent::BaseResult( 'thema', $arr ); } public function get_klant() { $CI = get_instance(); return $CI->klant->get( $this->klant_id ); } public function get_hoofdthema() { $CI = get_instance(); $CI->load->model( 'hoofdthema' ); return $CI->hoofdthema->get( $this->hoofdthema_id ); } } class Thema extends BaseModel { function Thema() { parent::BaseModel( 'ThemaResult', 'bt_themas' ); } public function check_access( BaseResult $object ) { return; } public function add( $thema, $nummer=0, $hoofdthema_id=null, $klant_id=null ) { /* $db = $this->get_db(); $this->dbex->prepare( 'Thema::add', 'INSERT INTO bt_themas (thema, nummer, hoofdthema_id, klant_id) VALUES (?, ?, ?, ?)', $db ); $args = array( 'thema' => $thema, 'nummer' => $nummer, 'hoofdthema_id' => $hoofdthema_id, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, ); $this->dbex->execute( 'Thema::add', $args, false, $db ); $args['id'] = $db->insert_id(); return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'thema' => $thema, 'nummer' => $nummer, 'hoofdthema_id' => $hoofdthema_id, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function find( $thema, $klant_id=null, $hoofdthema_id=null ) { $db = $this->get_db(); if ($hoofdthema_id) { if (!($this->dbex->prepare( 'Thema::find', 'SELECT * FROM bt_themas WHERE thema = ? AND klant_id = ? AND hoofdthema_id = ?', $db ))) throw new Exception( 'Failed to prepare statement.' ); $args = array( $thema, $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, $hoofdthema_id, ); } else { $this->dbex->prepare( 'Thema::find', 'SELECT * FROM bt_themas WHERE thema = ? AND klant_id = ?', $db ); $args = array( $thema, $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id ); } if (!($res = $this->dbex->execute( 'Thema::find', $args, false, $db ))) throw new Exception( 'Failed to execute statement.' ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function get_alle_actieve_themas() { $db = $this->get_db(); $res = $db->Query( ' SELECT * FROM bt_themas WHERE id IN ( SELECT DISTINCT(v.thema_id) FROM bt_vragen v WHERE v.thema_id IS NOT NULL AND klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' ) ORDER BY thema '); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $res->free_result(); return $result; } function get_by_hoofdthema_id( $hoofdthema_id ) { if (!$this->dbex->is_prepared( 'get_by_hoofdthema_id' )) $this->dbex->prepare( 'get_by_hoofdthema_id', 'SELECT * FROM '.$this->_table.' WHERE hoofdthema_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'get_by_hoofdthema_id', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function get_by_checklist( $checklist_id, $assoc=false ) { static $cache = null; if (!is_array( $cache )) { // execute only once per request! $CI = get_instance(); $CI->load->model( 'checklistgroep' ); $also_available = $CI->checklistgroep->get_also_beschikbaar_for_huidige_klant( true ); if (empty( $also_available )) $also_available = array( -1 => -1 ); $cache = array(); // Determine which "null function" should be used $null_func = get_db_null_function(); // Note: the "JOIN bt_vragen v ON (1=1)" part comes across as wildly odd. In fact, it is the joined in the WHERE clause. The '1=1' is done for compatibility with Oracle. $db = $this->get_db(); $res = $db->Query( $query = ' SELECT DISTINCT(t.id), t.*, hg.checklist_id, t.nummer as sort_col1, t.thema as sort_col2 FROM bt_themas t JOIN bt_vragen v ON (1=1) JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE (0=1 OR t.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' OR cl.checklist_groep_id IN (' . implode( ',', array_keys( $also_available ) ) . ') ) AND '.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id))) = t.id ORDER BY sort_col1, sort_col2 '); if (!$res) throw new Exception( 'Fout bij query: ' . $query ); foreach ($res->result() as $row) { if (!isset( $cache[$row->checklist_id] )) $cache[$row->checklist_id] = array(); $cache[$row->checklist_id][] = $this->getr( $row ); } $res->free_result(); } if (isset( $cache[$checklist_id] )) { // return indexed if (!$assoc) return $cache[$checklist_id]; // return assoc $result = array(); foreach ($cache[$checklist_id] as $row) $result[$row->id] = $row; return $result; } return array(); } public function get_for_klant( $klant_id, $assoc=false ) { if (!$this->dbex->is_prepared( 'get_by_klant_id' )) $this->dbex->prepare( 'get_by_klant_id', 'SELECT * FROM '.$this->_table.' WHERE klant_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'get_by_klant_id', array( $klant_id ), false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) if ($assoc) $result[$row->id] = $this->getr( $row ); else $result[] = $this->getr( $row ); return $result; } public function get_for_huidige_klant( $assoc=false, $klant_only=false, $remove_duplicates=false ) { static $cache = null; if (!is_array( $cache ) || $klant_only) { // execute only once per request! if (!$klant_only) { $CI = get_instance(); $CI->load->model( 'checklistgroep' ); $also_available = $CI->checklistgroep->get_also_beschikbaar_for_huidige_klant( true ); if (empty( $also_available )) $also_available = array( -1 => -1 ); } else $also_available = array( -1 => -1 ); // Determine which "null function" should be used $null_func = get_db_null_function(); $res = $this->db->Query( $query = ' SELECT t.* FROM bt_themas t WHERE t.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' UNION SELECT t.* FROM bt_themas t JOIN ( SELECT DISTINCT('.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id)))) AS id FROM bt_vragen v JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE cl.checklist_groep_id IN (' . implode( ',', array_keys( $also_available ) ) . ') ) a ON (a.id = t.id) '); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[$row->id] = $this->getr( $row, false ); $res->free_result(); if ($remove_duplicates) { $seen = array(); foreach ($result as $i => $row) if (in_array( $row->thema, $seen )) unset( $result[$i] ); else $seen[] = $row->thema; $result = array_values( $result ); } if ($assoc) uasort( $result, function( $a, $b ) { return strcasecmp( $a->thema, $b->thema ); } ); else usort( $result, function( $a, $b ) { return strcasecmp( $a->thema, $b->thema ); } ); if ($klant_only) return $result; $cache = $result; } return $cache; } } <file_sep><?php // webservice server require_once( APPPATH . 'controllers/soap.php' ); // webservice class require_once( APPPATH . 'webservices/mvv-suite.php' ); // set that we use the above class define( 'WEBSERVICE_SOAP_URL', '/mvvsuite/' ); // url of our controller below define( 'WEBSERVICE_SOAP_CLASSNAME', 'MVVSuiteWebservice' ); // Instantiate the 'wrapper' class. This is everything that needs to be done in this file, the actual work is done in the above 'required webservice class'. class MvvSuite extends Soap { } <file_sep><?php class DossierExportDocx extends DossierExportDocxBase { const FONTNAME = 'dejavusans'; const FONTSIZE = 9; const FONTHEADERSIZE = 12; private $deelplannen = array(); private $deelplan_vragen = array(); private $deelplan_prioriteiten = array(); private $deelplan_bescheiden = array(); private $deelplan_bouwdelen = array(); private $deelplan_subjecten = array(); private $deelplan_vraag_bescheiden = array(); private $deelplan_toelichtinggeschiedenis = array(); private $deelplan_uploads = array(); private $deelplan_onderwerpstatussen = array(); // alleen voor bevindingen, niet voor samenvatting! private $deelplan_vraag_subjecten = array(); private $deelplan_aandachtspunten = array(); private $deelplan_toezicht_data = array(); private $deelplan_onderwerpen = array(); private $deelplan_scopes = array(); private $deelplan_checklists = array(); private $checklistgroep_grondslagen = array(); private $checklistgroep_richtlijnen = array(); private $waardeoordelen = array(); private $betrokkenen = null; private $kenmerk = null; private $omschrijving = null; private $revisiedatum = null; private $checklists = array(); private $item_number = 0; private $item_count = 0; // Some globally stored data, that is constructed in one method, to be used elsewhere private $used_grondslagen = array(); // Document content private $docx_content = ''; // SOAP specific members, used for constructing the content, parameters, etc. //private $soap_wsdl = ""; private $soap_method = 'soapGenerateGenericDocument'; private $soap_parameters = array(); // Main data set, fill this with the actual data that comprises the document definition private $documents = array(); // Sections, fill this with the actual data that comprises the various sections private $sections = array(); // Pageheaders, fill this with the actual data that comprises the various page headers private $pageheaders = array(); // Pagefooters, fill this with the actual data that comprises the various page headers private $pagefooters = array(); //show_revisions, used to make decisions based on whether or not the user selected to show revisions. private $show_revisions = false; // Images, fill this with the "document global" images, that can be used throughout the ENTIRE document. private $document_images = array(); // Global annotations and overviews data sets private $annotation_data_set = array(); private $overview_data_set = array(); private $overview_thumbs_data_set = array(); private $photo_annotaties = array(); // Define the various image paths that are used for this document private $images_path_icons = ''; private $images_path_snapshots = ''; // The following two members are used throughout the report (where applicable) to properly switch between using // overridden data or base data. private $use_overriden_data = false; private $overriden_data_context = ''; private $section_number = 0; private $addendum_number = 0; private $global_initialisation_done = false; /******************************************************************************** * * * MAIN FUNCTIONS * * * ********************************************************************************/ public function get_docx_content() { return $this->docx_content; } protected function _init_overrides() { // !!! TEMPORARY OVERRIDE FOR TESTING/DEVELOPMENT ONLY. DO NOT COMMIT THE NEXT THREE LINES. //$this->overriden_data_context = 'arbode'; //$this->use_overriden_data = true; //return; // When we are being called from the webservice context, we do not have a logged in user. We then check if a specific override // of a user ID has been specified. If so, use that user for setting the context. If not, return early and fall back to the BTZ // common report style. if (defined('IS_WEBSERVICE') && IS_WEBSERVICE) { // If a user ID was explicitely passed, use that for trying to get the proper user for setting the context. $overriden_gebruiker_id = (!empty($_POST['overridden_gebruiker_id'])) ? intval($_POST['overridden_gebruiker_id']) : 0; $gebruiker = null; if (!empty($overriden_gebruiker_id)) { // Get the proper user to specify the context that should be used. $gebruiker = $this->_CI->gebruiker->get($overriden_gebruiker_id); } // If no valid user was obtained, we return early (causing the common BTZ report context to be used). if (is_null($gebruiker)) { return; } } else { // Use the currently logged in user data to specify the context that should be used. $gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker(); } // First check if the context user is allowed to have the 'Riegitaal' context. $this->overriden_data_context = ($gebruiker->is_riepair_user()) ? 'riegitaal' : ''; // Now, we check if the context user forms part of the subset of Riegitaal users that should get the 'Arbode' context. $this->overriden_data_context = ($gebruiker->is_arbode_user()) ? 'arbode' : $this->overriden_data_context; // Check if the context user is allowed to have the 'Nijha' context. $this->overriden_data_context = ($gebruiker->is_nijha_user()) ? 'nijha' : $this->overriden_data_context; // Finally check if the context user is allowed to have the 'VIIA' context. $this->overriden_data_context = ($gebruiker->is_viia_user()) ? 'viia' : $this->overriden_data_context; // At this point in time we should have a properly set context. //d($this->overriden_data_context); } protected function _generate() { // Get the proper location of the webservice we need to call. Note: this must be specified in the application/config/config.php file! $randval = rand(); $this->soap_wsdl = $this->_CI->config->item('ws_url_wsdl_brimo_soapdocument') . '/' . $randval; //create the document containing the first page $this->_generate_doc(true); //clear all attributes $this->_clear_attributes(); //clear the rest of the $this->_generate_doc(false); //MJ (20-04-2015): added this to prevent a timout during the retrieval of the Soap document, causing the browser to hang. ini_set('default_socket_timeout',1800); // Construct the compound set of parameters that the SOAP call expects $this->soap_parameters['licentie_naam'] = 'BTZ'; $this->soap_parameters['licentie_wachtwoord'] = 'BTZ'; $this->soap_parameters['documents'] = $this->documents; // Instantiate a wrapped SoapClientHelper for generating the report using BRIMO. // Note: for 'silent' connections that do not generate output, the following settings should be used. $debug = false; $silent = true; // Note: for 'chatty' debug connections that generate output, the following settings should be used. //$debug = true; //$silent = false; $randval = rand(); $wrappedSoapClient = getWrappedSoapClientHelper($this->soap_wsdl."/{$randval}", $this->soap_method, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $this->soap_parameters); if (empty($wsResult)) { echo "De webservice aanroep heeft geen data geretourneerd!<br /><br />"; //exit; } } else { echo "Foutmelding(en) bij maken connectie:<br />\n"; echo "<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { echo $curError . "<br />\n"; // exit; } // Return early, so no attempt is made to proceed (which would fail anyway). return; } // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { echo "Foutmelding(en) bij RPC aanroep:<br />\n"; echo "<br />\n"; foreach ($errorsDuringCall as $curError) { echo $curError . "<br />\n"; } d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; // Return early, so no attempt is made to proceed (which would fail anyway). return; } $this->docx_content = $wsResult; return $wsResult; } private function _generate_doc($first = false) { //if( !$this->global_initialisation_done ){ // First initialise any and all overrides that must be enforced. $this->_init_overrides(); // The 'Encoding' helper is used in the _add_section method and must therefore always be loaded, instead of conditionally // being loaded $this->_CI->load->helper( 'encoding' ); // Now confitionally do things, depending on whether this is the first page or not if( !$first ) { // init models $this->_CI->load->model( 'gebruiker' ); $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'deelplanchecklistgroep' ); $this->_CI->load->model( 'deelplanthema' ); $this->_CI->load->model( 'hoofdthema' ); $this->_CI->load->model( 'thema' ); $this->_CI->load->model( 'matrix' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'deelplanbescheiden' ); $this->_CI->load->model( 'deelplanbouwdeel' ); $this->_CI->load->model( 'deelplansubject' ); $this->_CI->load->model( 'deelplanvraagbescheiden' ); $this->_CI->load->model( 'deelplanvraaggeschiedenis' ); $this->_CI->load->model( 'deelplanvraagemail' ); $this->_CI->load->model( 'deelplanupload' ); $this->_CI->load->model( 'deelplanopdracht' ); $this->_CI->load->model( 'dossierbescheiden' ); $this->_CI->load->model( 'dossiersubject' ); $this->_CI->load->model( 'deelplansubjectvraag' ); $this->_CI->load->model( 'grondslagtekst' ); $this->_CI->load->library( 'prioriteitstelling' ); $this->_CI->load->library( 'quest' ); $this->_CI->load->library( 'pdfannotatorlib' ); $this->_CI->load->library( 'annotatieafbeeldingprocessor' ); // init data we need (multiple) times during document generation $this->_init_data(); $this->_init_global_images(); $this->_init_status_filter(); $this->_init_betrokkene_filter(); // initialize progress $this->_init_progress(); // set creator, author, etc. $this->_initialize_meta_data(); } else { // First initialise any and all overrides that must be enforced. //$this->_init_overrides(); $this->_init_global_images(); // init data also for the first page to allow using the revision date and checklist name in the front page $this->_init_firstpage_data(); } // Generate the main content if($first == true) { // Create the first (front page) document. $this->_generate_front_page(); $this->_generate_pageheaders(); $this->_generate_pagefooters(); } else { // Create the second (remainder) document if ($this->overriden_data_context != 'viia') { $this->_generate_disclaimer_page(); $this->_generate_toc(); } $this->_generate_dossier_gegevens(); // Add in additional report parts for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { $this->_generate_organisatie_kenmerken(); $this->_generate_inleiding_pages_fine_and_kinney(); } else { $this->_generate_inleiding_pages_standaard(); } $this->_generate_samenvatting(); $this->_generate_bevindingen(); $this->_generate_opdrachten(); // Initialise the appendices counter $bijlage_nr = 1; // Add in additional report parts for Arbode only. Note that we do not need to check the override context for this, as the proper filter options // take care of that. $this->_generate_toetsing_kerndeskundige(); // Add in additional report parts for Arbode and Riegitaal. Note that we do not need to check the override context for this, as the proper filter options // take care of that. $this->_generate_pago_pmo_bijlage( $bijlage_nr ); $this->_generate_pbm_bijlage( $bijlage_nr ); // Bijlage Foto's $this->_generate_foto_bijlage( $bijlage_nr ); //$this->_generate_documenten_bijlage( $bijlage_nr ); // Bijlage Annotaties $this->_generate_annotaties_bijlage( $bijlage_nr ); // Bijlage Grondslagen $this->_generate_juridische_grondslag_bijlage( $bijlage_nr ); } // !!! SOAP stuff //die('foddex: done'); // Combine the document data //$this->document_data['type'] = 'docx'; // 'DOCX'|'PDF'|'XLSX' $this->documenttype = parent::get_output_format(); // 'DOCX'|'PDF'|'XLSX' // Default report settings. $this->template = ''; // template name (optional) //create a document object: type, template, title, pageheaders, pagefooters, sections, document_images, firstpage $this->_add_document($this->documenttype, $this->template,'',$this->pageheaders,$this->pagefooters,$this->sections,$this->document_images); } private function _init_firstpage_data() { //Get the selected checklists $dos = $this->get_dossier(); $this->kenmerk = $dos->get_kenmerk(); $this->omschrijving = $dos->get_omschrijving(); $checklists = array(); $revisiondates = array(); foreach ($dos->get_deelplannen() as $j => $deelplan) { $selected_deelplan = $this->get_filter( 'deelplan' ); $include_deelplan = ( (is_array($selected_deelplan) && array_key_exists( $deelplan->id, $selected_deelplan)) || (!is_array($selected_deelplan) && ( $deelplan->id == $selected_deelplan)) ); if (!$include_deelplan) continue; foreach ($deelplan->get_checklisten() as $checklist) { //Get checklists $deelplan_checklist_filter_name = "dp_checklist_" . $deelplan->id; $dp_cl_filter_value = $this->get_filter($deelplan_checklist_filter_name); if ( !is_null($dp_cl_filter_value) && ($dp_cl_filter_value == 'all' || $dp_cl_filter_value == $checklist->id) ) { $checklists[] = $checklist->naam; } //Get revision date for this deelplan $revisiedatum = $deelplan->get_laatste_revisie_datum(); if ($revisiedatum) { $revisiondates[] = $revisiedatum ; } } } $this->checklists = $checklists; if ($revisiondates) { $this->revisiedatum = date( 'd-m-Y', strtotime( max($revisiondates) )); } else { $this->revisiedatum = null; } } private function _init_data() { $dos = $this->get_dossier(); $this->toon_aandachtspunten = $this->get_filter( 'onderdeel' ) ? array_key_exists( 'aandachtspunten', $this->get_filter( 'onderdeel' )) : false; foreach ($dos->get_deelplannen() as $j => $deelplan) { // Note: the commented out part was used for allowing multiple deelplan selections using checkboxes. This is currently no longer supported and // instead a single deelplan is chosen, using a radio button. The old code is left here, commented out, in case we need to support multiple // deelplan selections too again. The code has been made backwards compatible. //if (!@array_key_exists( $deelplan->id, $this->get_filter( 'deelplan' ))) // continue; $selected_deelplan = $this->get_filter( 'deelplan' ); $include_deelplan = ( (is_array($selected_deelplan) && array_key_exists( $deelplan->id, $selected_deelplan)) || (!is_array($selected_deelplan) && ( $deelplan->id == $selected_deelplan)) ); if (!$include_deelplan) continue; // Check if we need to limit to a specific checklist for this deelplan. We can simply get the desired filter value and store it in the deelplan_checklists member. // By storing it in an array, we can more easily extend the code at a later time to support multiple selected checklists (which is a foreseeable feature request). // It suffices to only store actively selected values. When we need to limit to specific checklists, we can then simply check if the array is empty. If so: skip // filtering. If not: limit to the checklists of which we have stored the ID(s). $deelplan_checklist_filter_name = "dp_checklist_" . $deelplan->id; //d($this->get_filter( $deelplan_checklist_filter_name )); $dp_cl_filter_value = $this->get_filter($deelplan_checklist_filter_name); if ( !is_null($dp_cl_filter_value) && ($dp_cl_filter_value != 'all') ) { $this->deelplan_checklists[] = $dp_cl_filter_value; } //if ( $deelplan->id != $this->get_filter( 'deelplan' ))) // continue; $this->deelplannen[] = $deelplan; $this->deelplan_vragen[$deelplan->id] = array(); $this->deelplan_prioriteiten[$deelplan->id] = array(); $this->deelplan_bescheiden[$deelplan->id] = $this->_CI->deelplanbescheiden->get_by_deelplan( $deelplan->id ); $this->deelplan_bouwdelen[$deelplan->id] = $this->_CI->deelplanbouwdeel->get_by_deelplan_id( $deelplan->id ); $this->deelplan_subjecten[$deelplan->id] = $this->_CI->deelplansubject->get_by_deelplan( $deelplan->id ); $this->deelplan_vraag_bescheiden[$deelplan->id] = $this->_CI->deelplanvraagbescheiden->get_by_deelplan( $deelplan->id ); $this->deelplan_toelichtinggeschiedenis[$deelplan->id] = $this->_CI->deelplanvraaggeschiedenis->get_by_deelplan( $deelplan->id ); $this->deelplan_uploads[$deelplan->id] = $this->_CI->deelplanupload->find_by_deelplan( $deelplan->id, '', true /* assoc by vraag id */ ); $this->deelplan_vraag_subjecten[$deelplan->id] = $this->_CI->deelplansubjectvraag->get_by_deelplan( $deelplan->id ); $this->deelplan_themas[$deelplan->id] = array(); $this->deelplan_aandachtspunten[$deelplan->id] = array(); $this->deelplan_toezicht_data[$deelplan->id] = array(); $this->deelplan_onderwerpen[$deelplan->id] = array(); $this->deelplan_scopes[$deelplan->id] = $deelplan->get_scopes(null, true); foreach ($this->deelplan_scopes[$deelplan->id] as $i => $scope){ // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($scope['checklist_id'], $this->deelplan_checklists)){ continue; } // set scope id (not a real db id, just a unique string identifying the scope) $bnwl = $scope['bouwnummer'] ? '_'.$scope['bouwnummer'] : ''; $scope_id = $scope['checklist_groep_id'] . '_' . intval(@$scope['checklist_id']).$bnwl; $this->deelplan_scopes[$deelplan->id][$i]['scope_id'] = $scope_id; $checklistgroep = $this->_CI->checklistgroep->get($scope['checklist_groep_id']); $checklist = null; if(isset($scope['checklist_id'])){ $checklist = $this->_CI->checklist->get($scope['checklist_id']); $checklist->bouwnummer = $scope['bouwnummer']; // $checklist->bouwnummer = $scope['bouwnummer']; } $dp_tzh_data = $deelplan->get_toezicht_data($checklistgroep, $checklist, false, $scope['bouwnummer'] ); $this->deelplan_toezicht_data[$deelplan->id][$scope_id] = $dp_tzh_data; $this->deelplan_vragen[$deelplan->id][$scope_id] = $dp_tzh_data['vragen']; $this->deelplan_onderwerpen[$deelplan->id][$scope_id] = $dp_tzh_data['onderwerp_data']->onderwerpen; $this->deelplan_prioriteiten[$deelplan->id][$scope_id] = @ $dp_tzh_data['onderwerp_data']->prioriteiten; if ($this->toon_aandachtspunten) { $this->deelplan_aandachtspunten[$deelplan->id][$scope_id] = $deelplan->get_aandachtspunten( $checklistgroep->id, $checklist ? $checklist->id : null ); } $cg_id = $checklistgroep->id; if (!isset( $this->checklistgroep_grondslagen[$cg_id] )){ $this->checklistgroep_grondslagen[$cg_id] = $deelplan->get_grondslagen( $cg_id ); } $volgende_vraag_nummer = 1; $this->deelplan_onderwerpstatussen[$deelplan->id][$scope_id] = array(); foreach ($this->deelplan_onderwerpen[$deelplan->id][$scope_id] as $onderwerp_id => $onderwerp) { foreach ($onderwerp['vragen'] as $vraag) { $vraag->rapportage_vraag_nummer = $volgende_vraag_nummer++; if (isset( $vraag->thema_id )) if (!in_array( $vraag->thema_id, $this->deelplan_themas[$deelplan->id] )) $this->deelplan_themas[$deelplan->id][] = $vraag->thema_id; $waarde = $this->_status_to_waarde( $vraag ); if (!isset( $this->deelplan_onderwerpstatussen[$deelplan->id][$scope_id][$onderwerp_id] ) || $waarde < $this->deelplan_onderwerpstatussen[$deelplan->id][$scope_id][$onderwerp_id]['waarde']) { $this->deelplan_onderwerpstatussen[$deelplan->id][$scope_id][$onderwerp_id] = array( 'waarde' => $waarde, ); } } } } } } private function _init_global_images() { // First set the paths for the locations that are 'static' and do not depend on dynamic data $this->images_path_icons = APPPATH . '/../files/images/rapportage/'; // Then continue by creating a temporary directory that is used for holding the images that are to be included in the document and that do not exist globally. $cur_date_time = date("Ymd_Hisu"); $tempFilesBaseDir = APPPATH . '/../files/reports_temp_data/' . $cur_date_time; //$tempFilesUrl = PHPDOCX_TEMPDIR_BASEURL . DIRECTORY_SEPARATOR . $cur_date_time; if (!file_exists($tempFilesBaseDir)){ if (!mkdir($tempFilesBaseDir)) { throw new Exception("Directory {$tempFilesBaseDir} could not be created"); } } // Work out the location for the snapshots $this->images_path_snapshots = $tempFilesBaseDir . DIRECTORY_SEPARATOR . 'snapshots'; //$this->images_path_fotos = APPPATH . '/../files/images/'; // Try to create the (temporary) snapshots location. // Note: create the directory without a trailing directory separator! if (!file_exists($this->images_path_snapshots)){ if (!mkdir($this->images_path_snapshots)) { throw new Exception("Directory {$this->images_path_snapshots} could not be created"); } } // Now, let the snapshots directory directly be followed by the directory separator so we don't have to pass that all of the time $this->images_path_snapshots .= DIRECTORY_SEPARATOR; // We already know in advance that we will be needing the 'waardeoordeel' (i.e. 'status') icons, so register these directly with the global images set. /* $status_icon_names = array('status-bouwdeel_voldoet', 'status-gelijkwaardig', 'status-in_bewerking', 'status-nader_onderzoek_nodig', 'status-niet_gecontroleerd_ivm_steekproef', 'status-niet_gecontroleerd', 'status-niet_kunnen_controleren', 'status-nvt', 'status-voldoet_na_aanwijzingen', 'status-voldoet_niet_niet_zwaar', 'status-voldoet_niet', 'status-voldoet'); * */ // Use the 'square' images and force their width to 23x23 pixels if ($this->overriden_data_context == 'viia') { $status_icon_names = array('status-geel', 'status-groen', 'status-rood-viia'); } else { $status_icon_names = array('status-geel', 'status-groen', 'status-rood'); } //$this->_add_images($this->document_images, $this->images_path_icons, $status_icon_names, 'png', '100', '100'); $this->_add_images($this->document_images, $this->images_path_icons, $status_icon_names, 'png', '23', '23'); //$this->_add_images($this->document_images, $this->images_path_icons, $status_icon_names); } private function _init_betrokkene_filter() { $doe_filter = $this->get_filter( 'betrokkenen-filter' ) && $this->get_filter( 'betrokkenen-filter' )=='on'; if (!$doe_filter) { $this->betrokkenen = null; // geeft aan: niet filteren op betrokkenen } else { $this->betrokkenen = array(); $betrokkenen_ids = $this->get_filter( 'subjecten' ); if (is_array( $betrokkenen_ids ) && sizeof($betrokkenen_ids) > 0) { foreach ($this->get_dossier()->get_subjecten() as $subject) { if (isset( $betrokkenen_ids[$subject->id] ) && $betrokkenen_ids[$subject->id]=='on') $this->betrokkenen[ $subject->id ] = $subject; } } } } private function _init_status_filter() { // meerkeuze instellingen ophalen $this->waardeoordelen = $this->get_filter( 'waardeoordeel' ); // invulvraag instellingen ophalen $this->waardeoordeel_invulvragen = $this->get_filter( 'waardeoordeel_invulvragen' ); } private function _init_progress() { //foreach (array( 'inleiding', 'dossiergegevens', 'documenten', 'deelplannen', 'samenvatting', 'bevindingen', 'bijlage-fotos', 'bijlage-documenten-tekeningen', 'bijlage-juridische-grondslag' ) as $onderdeel) foreach (array( 'inleiding', 'dossiergegevens', 'documenten', 'deelplannen', 'samenvatting', 'bevindingen', 'aandachtspunten', 'toetsing_kerndeskundige', 'bijlage_pago_pmo', 'bijlage-pbm', 'bijlage-fotos', 'bijlage-documenten-tekeningen', 'bijlage-juridische-grondslag' ) as $onderdeel) { if (@array_key_exists( $onderdeel, $this->get_filter( 'onderdeel' ))) { $this->item_count++; } } if (is_array($this->get_filter( 'onderdeel' )) && array_key_exists( 'bijlage-juridische-grondslag', $this->get_filter( 'onderdeel' ))) { $grondslagen = $this->get_filter( 'grondslag' ); if (is_array( $grondslagen )) $this->item_count += sizeof( $grondslagen ); } } private function _initialize_meta_data() { /* $this->_tcpdf->SetCreator('BRIStoezicht'); $this->_tcpdf->SetAuthor('BRIStoezicht'); $this->_tcpdf->SetTitle('Bevindingenrapportage ' . $this->get_dossier()->get_omschrijving()); $this->_tcpdf->SetSubject($this->get_dossier()->get_kenmerk()); $this->_tcpdf->SetKeywords('BRIStoezicht'); // some defaults $this->_tcpdf->SetImageScale(PDF_IMAGE_SCALE_RATIO); $this->_tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $this->_tcpdf->SetFontSubsetting( false ); * */ } private function _generate_front_page() { // Get the dossier data $dossier = $this->get_dossier(); // Set the maximum dimensions for the logo's. 2.605 inch with 96 DPI comes at 250px $max_logo_image_width = intval(2.605*96); $max_logo_image_height = 'auto'; // Add the images that are used in this section $section_images = array(); //Retrieve customer specific Logo //$logo = $this->get_dossier()->get_gebruiker()->get_klant()->logo; if ($this->overriden_data_context == 'arbode'){ $base_path = $this->images_path_icons; $logo = file_get_contents($base_path . 'rapportage_front_arbode.png'); $max_logo_image_width = intval(5.210*96); // For Arbode a wider image is desired, set the max to 500px } elseif ($this->overriden_data_context == 'riegitaal') { $base_path = $this->images_path_icons; $logo = file_get_contents($base_path . 'rapportage_front_riegitaal.png'); } else { $logo = $dossier->get_gebruiker()->get_klant()->logo; } // If no customer specific logo exists, fall back to the normal BRIStoezicht logo if (empty($logo)) { $base_path = $this->images_path_icons; $logo = file_get_contents($base_path . 'bristoezicht_narrow_logo.png'); } $this->_process_raw_image_data($logo,$max_logo_image_width, $max_logo_image_height, $logo_width, $logo_height,$templogofilename, TRUE); //Set the logo fragment $identifier = 'logo'; $this->_add_image($section_images, 'dummy_path', $identifier, file_get_contents($templogofilename), 'png', $logo_width, $logo_height, 'data'); $foto_height = 0; //Retrieve dossier specific foto if customer is VIIA if ($this->overriden_data_context == 'viia') { $foto = isset($dossier->get_foto()->bestand) ? $dossier->get_foto()->bestand : ''; // Set the maximum dimensions for the foto's. 2.605 inch with 96 DPI comes at 250px $max_foto_image_width = intval(2.605*96); $max_foto_image_height = intval(3.770*96); if ($foto) { $tempfotofilename = null; $foto_width=0; $foto_height=0; $this->_process_raw_image_data($foto,$max_foto_image_width, $max_foto_image_height, $foto_width, $foto_height,$tempfotofilename, TRUE); //Set the foto fragment $identifier = 'foto'; $this->_add_image($section_images, 'dummy_path', $identifier, file_get_contents($tempfotofilename), 'png', $foto_width, $foto_height, 'data'); } } //Determine the approprate information $document_titles = array(); if ($this->overriden_data_context == 'viia'){ $author_name = 'Teamleider'; if (!$this->revisiedatum) { $this->revisiedatum = date( 'd-m-Y' ); $document_date_name = "Printdatum"; } else { $document_date_name = "Revisiedatum"; } $document_date = $this->revisiedatum; if ($foto) { $foto_fragment = "<tr><td>[IMG:foto]</td></tr>"; } else { $foto_fragment = ''; } $kenmerk = $dossier->get_kenmerk(); $omschrijving = $dossier->get_omschrijving() ; $revisiedatum = $this->revisiedatum; $document_titles = $this->checklists; $document_titles[] = "$kenmerk $omschrijving"; } else { $author_name = 'Dossierverantwoordelijke'; $document_date_name = "Printdatum"; $document_date = date( 'd-m-Y' ); $foto_fragment = ''; $document_titles[] = 'RAPPORTAGE'; } $voorblad_html_fragment = ' <table class="fullwidth"> <tbody> <tr> <td><h1>'.implode("<br />",$document_titles).'</h1></td> </tr> </tbody> </table> <table class="narrow"> <tbody> <tr> <td>[IMG:logo]</td> </tr> '.$foto_fragment.' <tr class=\'dossier-row\'> <td class=\'dossier-info\'>'. 'ID: ' . $dossier->get_kenmerk() . '<br/>' . 'Locatie: ' . $dossier->get_locatie() . '<br/>' . $author_name .': ' . $dossier->get_gebruiker()->get_status() . '<br/>' . $document_date_name.': ' . $document_date . '<br/>' . '</td> </tr> </tbody> </table><br/>'; // Create the HTML fragment that comprises the front page $table_width = $logo_width + 10; $page_width = 582.72; $page_height = 630; $side_width = ($page_width - $table_width )/2; if (empty($foto_height)) { $foto_height = 0; } $dosinfoheight = $page_height - $logo_height - $foto_height - (count($document_titles)*20); $html_fragment = '<style> table {border-collapse: collapse; border:0px; cellpadding:0;table-layout:fixed;} .fullwidth {width:100%} .narrow {width:'.$table_width.'px;margin-left:'.$side_width .'} .dossier-info { vertical-align: bottom; text-align:left; padding-top: '.$dosinfoheight.'px} td {font-family: calibri; font-size:10pt;text-align:center;} </style>'. $voorblad_html_fragment; // 'Dossierdatum: ' . date( 'd-m-Y', $dossier->aanmaak_datum ) . '<br/>' . // Add a section for the front page //$section_header = $this->_create_section_header(1, 'Inhoudsopgave'); $section_header = $this->_create_empty_section_header(); $this->_add_section($html_fragment, $section_header, $section_images, 'front', 'none', 'A4', 'portrait', 'html', true, false, false); } private function _generate_pageheaders() { //To position a text within the header or footer, preceed the fragment with //[ELM:<position>] where position can be 'left', 'center' or 'right' //Retrieve customer specific Logo $max_logo_image_width = 'auto'; $max_logo_image_height = intval(0.3*96); $logo = $this->get_dossier()->get_gebruiker()->get_klant()->logo_klein; // If no customer specific logo exists, fall back to the normal BRIStoezicht logo if (empty($logo)) { $base_path = $this->images_path_icons; $logo = file_get_contents($base_path . 'bris.png'); } //Set the logo fragment $this->_process_raw_image_data($logo,$max_logo_image_width, $max_logo_image_height, $logo_width, $logo_height,$tempfilename, TRUE); $identifier = 'logo_small'; $this->_add_image($pageheader_images, 'dummy_path', $identifier, file_get_contents($tempfilename), 'png', $logo_width, $logo_height, 'data'); $logo_html_fragment = '<p style="border-bottom-style: solid;font-size:10pt;">[IMG:'.$identifier.']</p>'; // Define the first page header fragments //TODO: Allow empty header $pageheader_position = 'left'; $pageheader_section = 'first'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages $pageheader_content = ' '; // (HTML) $pageheader_images = array(); $this->_add_pageheader ($pageheader_section, $pageheader_position, $pageheader_content, $pageheader_images, true, false); // Define the even page header fragments $pageheader_section = 'even'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages $pageheader_content = $logo_html_fragment; // (HTML) // Add the logo $this->_add_image($pageheader_images, 'dummy_path', $identifier, $logo, 'png', 'auto', 'auto', 'data'); $this->_add_pageheader ($pageheader_section, $pageheader_position, $pageheader_content, $pageheader_images, true, false); // Define the default page header fragments $pageheader_section = 'default'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages $pageheader_content = $logo_html_fragment; // (HTML) // Add the logo $this->_add_image($pageheader_images, 'dummy_path', $identifier, $logo, 'png', 'auto', 'auto', 'data'); $this->_add_pageheader ($pageheader_section, $pageheader_position, $pageheader_content, $pageheader_images, true, false); } private function _generate_pagefooters() { //To position a text within the header or footer, preceed the fragment with //[ELM:<position>] where position can be 'left', 'center' or 'right' //Retrieve customer specific Logo $company_name = $this->get_dossier()->get_gebruiker()->get_klant()->volledige_naam; if (!$company_name || (($this->overriden_data_context != 'arbode') && ($this->overriden_data_context != 'riegitaal') && ($this->overriden_data_context != 'viia') && ($this->overriden_data_context != 'nijha'))) { $company_name = 'BrisToezicht'; } // Define the first page footer fragments $pagefooter_position = 'left'; $pagefooter_section = 'first'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages $pagefooter_content = ' '; $pagefooter_images = array(); // $this->_add_pagefooter ($pagefooter_section, $pagefooter_position, $pagefooter_content, $pagefooter_images, true, false); // Define the page footer fragments $pagefooter_section = 'even'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages if ($this->overriden_data_context == 'viia') { $pagefooter_content = '<p style="border-top-style: solid;font-size:10pt;">[ELM:LEFT][ELM:PAGE][ELM:CENTER]'.$this->revisiedatum. '[ELM:RIGHT]'.$this->kenmerk.' '.$this->omschrijving.'</p>'; } else { $pagefooter_content = '<p style="border-top-style: solid;font-size:10pt;">[ELM:LEFT][ELM:PAGE][ELM:CENTER][ELM:DATE][ELM:RIGHT]Rapport '.$company_name .'</p>'; } $pagefooter_images = array(); // $this->_add_pagefooter ($pagefooter_section, $pagefooter_position, $pagefooter_content, $pagefooter_images, true, false); // Define the page footer fragments $pagefooter_section = 'default'; // 'default'|'fist'|'even' : if 'even' is selected, default will be used for odd pages if ($this->overriden_data_context == 'viia') { $pagefooter_content = '<p style="border-top-style: solid;font-size:10pt;">[ELM:LEFT][ELM:PAGE][ELM:CENTER]'.$this->revisiedatum. '[ELM:RIGHT]'.$this->kenmerk.' '.$this->omschrijving.'</p>'; } else { $pagefooter_content = '<p style="border-top-style: solid;font-size:10pt;">[ELM:LEFT][ELM:PAGE][ELM:CENTER][ELM:DATE][ELM:RIGHT]Rapport '.$company_name .'</p>'; } $pagefooter_images = array(); // $this->_add_pagefooter ($pagefooter_section, $pagefooter_position, $pagefooter_content, $pagefooter_images, true, false); } private function _generate_disclaimer_page() { if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') || ($this->overriden_data_context == 'viia') || ($this->overriden_data_context == 'nijha')) { $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Deze rapportage is automatisch gegenereerd. Het systeem ondersteunt en bevordert professioneel toezicht maar treedt in geen geval in de plaats van de deskundigheid van een toezichthouder. Dit rapport is met de grootste zorg samengesteld. Er kunnen echter geen enkele rechten aan worden ontleend. Wij zijn niet aansprakelijk voor schade die het gevolg is van onjuistheid of onvolledigheid (in de meest ruime zin des woords) van deze applicatie en de gegenereerde rapportages.</p>'; } else { $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Deze rapportage is automatisch gegenereerd door BRIStoezicht. BRIStoezicht ondersteunt en bevordert professioneel toezicht. Het systeem treedt in geen geval in de plaats van de deskundigheid van een toezichthouder. BRIStoezicht is met de grootste zorg samengesteld. BRIS bv aanvaardt echter geen enkele aansprakelijkheid voor schade die het gevolg is van onjuistheid of onvolledigheid (in de meest ruime zin des woords) van deze applicatie en de gegenereerde rapportages.</p>'; } // Add a section for the disclaimer page $section_header = $this->_create_section_header(1, 'Disclaimer'); $this->_add_section($html_fragment, $section_header, array(), 'summary', 'before'); // $this->_add_section($html_fragment, $section_header, array(), 'summary', 'before', 'A4', 'portrait', 'html', false, false); } private function _generate_inleiding_pages_standaard() { if (!@array_key_exists( 'inleiding', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Inleiding...' ); $html_fragment = $this->_generate_style_definitions_block(array('p', 'table', 'td')); /* $html_fragment .= '<p>' . "Toezichtniveau's:<br />" . '<table>' . '<tr><td style="background-color:#05CBFC; text-align: center; vertical-align: middle; width: 50px; height: 50px; white-space:nowrap;">S.</td><td style="background-color:#05CBFC; text-align: left; vertical-align: middle;">Steekproef/td></tr>' . '<tr><td style="background-color:#309A6A; text-align: center; vertical-align: middle; width: 50px; height: 50px;">1.</td><td style="background-color:#309A6A; text-align: left; vertical-align: middle;">Visuele controle</td></tr>' . '<tr><td style="background-color:#FEFF99; text-align: center; vertical-align: middle; width: 50px; height: 50px;">2.</td><td style="background-color:#FEFF99; text-align: left; vertical-align: middle;">Beoordeling van hoofdlijnen</td></tr>' . '<tr><td style="background-color:#F5A000; text-align: center; vertical-align: middle; width: 50px; height: 50px;">3.</td><td style="background-color:#F5A000; text-align: left; vertical-align: middle;">Beoordeling hoofdlijnen en kenmerkende details</td></tr>' . '<tr><td style="background-color:#FE0002; text-align: center; vertical-align: middle; width: 50px; height: 50px;">4.</td><td style="background-color:#FE0002; text-align: left; vertical-align: middle;">Algehele controle van alle onderdelen</td></tr>' . '</table>' . '</p>'; * */ $html_fragment .= '<p>' . "Toezichtniveau's:" . '</p>' . '<p>' . '[IMG:report_legend]' . '</p>'; $steekproef_interval = $this->get_dossier()->get_gebruiker()->get_klant()->steekproef_interval; $html_fragment .= '<p>' . '<u>' . 'Steekproef' . '</u><br />' . '<span style="text-align:justify">Controle vindt steekproefsgewijs plaats. Waarbij een onderdeel 1 op de ' . $steekproef_interval . ' keer wordt meegenomen.</span>' . '</p>' . '<p>' . '<u>' . 'Visuele controle' . '</u><br />' . '<span style="text-align:justify">Een vluchtige beoordeling op het oog op basis van kennis en ervaring zonder projectspecifieke tekeningen of details te raadplegen en of hulpmiddelen (bijvoorbeeld meetlat) te gebruiken.</span>' . '</p>' . '<p>' . '<u>' . 'Beperkte controle' . '</u><br />' . '<span style="text-align:justify">Beoordeling op hoofdlijnen, op het oog en met eenvoudige hulpmiddelen worden elementaire controles uitgevoerd. Er worden alleen algemene projectspecifieke tekeningen geraadpleegd. Bij twijfel vindt raadpleging van detailtekeningen plaats.</span>' . '</p>' . '<p>' . '<u>' . 'Representatieve controle' . '</u><br />' . '<span style="text-align:justify">Beoordeling op hoofdlijnen en kenmerkende details, op het oog en met eenvoudige hulpmiddelen worden elementaire controles uitgevoerd. Daarnaast worden enkele kritische detailleringen in detail beoordeeld. Er worden algemene projectspecifieke tekeningen geraadpleegd en detailtekeningen van kritische detailleringen.</span>' . '</p>' . '<p>' . '<u>' . 'Integrale controle' . '</u><br />' . '<span style="text-align:justify">Beoordeling van alle onderdelen op detailniveau. Op het oog en met de benodigde hulpmiddelen worden controles tot op detailniveau uitgevoerd. Alle projectspecifieke tekeningen, detail-tekeningen, berekeningen, rapporten en certificaten worden geraadpleegd.</span>' . '</p>'; // Add the images that are used in this section $section_images = array(); // Report colours legend, do this as an image, as the HTML table keeps being 'crippled' during the conversion to Word $base_path = $this->images_path_icons; $this->_add_image($section_images, $base_path, 'report_legend', 'report_legend'); // Add a section for this page //$section_header = $this->_create_section_header(1, '2. Legenda'); $section_header = $this->_create_section_header(1, ++$this->section_number.'. Legenda'); //$this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'portrait', 'html', false, true, true); } private function _generate_inleiding_pages_fine_and_kinney() { if (!@array_key_exists( 'inleiding', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Inleiding...' ); $html_fragment = $this->_generate_style_definitions_block(array('p', 'table', 'td')); /* $html_fragment .= '<p>' . "Toezichtniveau's:<br />" . '<table>' . '<tr><td style="background-color:#05CBFC; text-align: center; vertical-align: middle; width: 50px; height: 50px; white-space:nowrap;">S.</td><td style="background-color:#05CBFC; text-align: left; vertical-align: middle;">Steekproef/td></tr>' . '<tr><td style="background-color:#309A6A; text-align: center; vertical-align: middle; width: 50px; height: 50px;">1.</td><td style="background-color:#309A6A; text-align: left; vertical-align: middle;">Visuele controle</td></tr>' . '<tr><td style="background-color:#FEFF99; text-align: center; vertical-align: middle; width: 50px; height: 50px;">2.</td><td style="background-color:#FEFF99; text-align: left; vertical-align: middle;">Beoordeling van hoofdlijnen</td></tr>' . '<tr><td style="background-color:#F5A000; text-align: center; vertical-align: middle; width: 50px; height: 50px;">3.</td><td style="background-color:#F5A000; text-align: left; vertical-align: middle;">Beoordeling hoofdlijnen en kenmerkende details</td></tr>' . '<tr><td style="background-color:#FE0002; text-align: center; vertical-align: middle; width: 50px; height: 50px;">4.</td><td style="background-color:#FE0002; text-align: left; vertical-align: middle;">Algehele controle van alle onderdelen</td></tr>' . '</table>' . '</p>'; * */ $html_fragment .= '<p>' . "Risico's zijn bepaald met toepassing van het Fine&Kinney risicomodel. De risico's zijn vastgesteld vanuit de som uit Kans (waarschijnlijkheid x blootstelling) en Effecten. De vastgestelde risico's zijn in vijf groepen ingedeeld. Hieronder is deze classificatie aangegeven." . '</p>' . '<p>' . "Risico classificatie:" . '</p>' . '<p>' . '[IMG:report_legend]' . '</p>'; // Add the images that are used in this section $section_images = array(); // Report colours legend, do this as an image, as the HTML table keeps being 'crippled' during the conversion to Word $base_path = $this->images_path_icons; $this->_add_image($section_images, $base_path, 'report_legend', 'report_legend_fine_and_kinney'); // Add a section for this page //$section_header = $this->_create_section_header(1, '2. Legenda'); $section_header = $this->_create_section_header(1, ++$this->section_number.'. Legenda'); //$this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'portrait', 'html', false, false, false); } private function check_empty_table($table_headers, $table_rows, $table_options = array()){ if(count($table_rows)!=0){ $table_fragment = $this->_generate_table_fragment($table_headers, $table_rows, $table_options); } else { $table_fragment = $this->_generate_table_fragment(tg('geengegevens'), $table_rows, $table_options); } return $table_fragment; } private function _generate_dossier_gegevens() { if (!@array_key_exists( 'dossiergegevens', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Dossiergegevens...' ); $klant = $this->get_klant(); $dos = $this->get_dossier(); //$html_fragment = $this->_generate_style_definitions_block(array('p')) . _klant // '<p>Dit onderdeel wordt momenteel nog uitgewerkt en de TODO stukjes zullen later ingevuld worden.</p>'; $html_fragment = ''; // Add a section for the main header of this chapter //$section_header = $this->_create_section_header(1, '1. Algemeen'); $section_header = $this->_create_section_header(1, ++$this->section_number.'. Algemeen'); $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); // Define any and all styles that are used for the tables over here $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); // Keep track of the subsection numbers as we go along $subsection_cnt = 0; /* SUBSECTION 1.1 Dossiergegevens */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Dossiergegevens'; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(array('width'=>'134'),array('width'=>'448')); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); $raw_row_data_cell_values[] = array('Dossiernaam', $this->hss( $dos->beschrijving )); $raw_row_data_cell_values[] = array('Identificiatienummer', $this->hss( $dos->kenmerk )); //$raw_row_data_cell_values[] = array('Aanmaakdatum', date( 'd-m-Y', $dos->aanmaak_datum )); $raw_row_data_cell_values[] = array('Adres', $this->hss( $dos->locatie_adres )); //Add postcode if it exists if (!empty($dos->locatie_postcode) && !empty ($dos->locatie_woonplaats)){ $raw_row_data_cell_values[] = array('Postcode en Woonplaats', $this->hss( strtoupper($dos->locatie_postcode) .' ' .$dos->locatie_woonplaats)); } if (!empty($dos->bag_identificatie_nummer)) { $raw_row_data_cell_values[] = array('BAG nummer', $this->hss( $dos->bag_identificatie_nummer )); } if ( !( empty($dos->locatie_kadastraal) && empty($dos->locatie_sectie) && empty($dos->locatie_nummer) ) ) { $raw_row_data_cell_values[] = array('Kadastraal / Sectie / Nummer', $this->hss( $dos->locatie_kadastraal ) . ' / ' . $this->hss( $dos->locatie_sectie ) . ' / ' . $this->hss( $dos->locatie_nummer )); } if (!empty($dos->xy_coordinaten)) { $raw_row_data_cell_values[] = array('X/Y-coördinaten', $this->hss( $dos->xy_coordinaten )); } if (!empty($dos->opmerkingen)) { $raw_row_data_cell_values[] = array('Opmerkingen', $dos->opmerkingen); } if (0) { //$raw_row_data_cell_values[] = array('Kaart', 'TODO'); } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { if(!empty($cell_data[1])) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } } // First create the table fragment and then combine everything into the section. $table_fragment = $this->_generate_table_fragment('',$table_rows, array('class'=>'TableNoHeader', 'style'=>'table-layout:fixed')); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.2 Betrokkenen */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Betrokkenen'; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers $header_data = array('Rol', 'Naam', 'Organisatie', 'Telefoonnr.', 'Email'); //$header_data = array(''); $header_options = $this ->_generate_custom_cell_options (array('85','79','96','96','202')); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Add the betrokkenen. foreach ($this->deelplannen as $deelplan) { foreach ($this->deelplan_subjecten[$deelplan->id] as $deelplan_subject) { $subject = $this->_CI->dossiersubject->get($deelplan_subject->dossier_subject_id); $raw_row_data_cell_values[] = array($this->hss($subject->rol), $this->hss($subject->naam), $this->hss($subject->organisatie), $this->hss($subject->telefoon), $this->hss($subject->email)); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $empty=array_filter($cell_data); if(!empty($empty)){ $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } } // First create the table fragment and then combine everything into the section. $table_options['style'] = 'table-layout:fixed;'; $table_fragment=$this->check_empty_table($table_headers, $table_rows,$table_options); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.3 Deelplangegevens */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Projectgegevens'; } else { // Default report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Deelplangegevens'; } $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(array('width'=>'134'),array('width'=>'448')); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Note: we should only have 1 'deelplan', but just in case... foreach ($this->deelplannen as $deelplan) { // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $raw_row_data_cell_values[] = array('Naam project', $this->hss(trim($deelplan->naam))); $raw_row_data_cell_values[] = array('Identificatienummer', $this->hss(trim($deelplan->kenmerk))); $raw_row_data_cell_values[] = array('Aanvraagdatum', date( 'd-m-Y', strtotime($deelplan->aanvraag_datum) )); } else { // Default report settings. $raw_row_data_cell_values[] = array('Naam deelplan', $this->hss(trim($deelplan->naam))); $raw_row_data_cell_values[] = array('Identificatienummer', $this->hss(trim($deelplan->kenmerk))); $raw_row_data_cell_values[] = array('OLO nummer', $this->hss(trim($deelplan->olo_nummer))); $raw_row_data_cell_values[] = array('Aanvraagdatum', date( 'd-m-Y', strtotime($deelplan->aanvraag_datum) )); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { if(!empty($cell_data[1])) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table('',$table_rows, array('width'=>'100%','class'=>'TableNoHeader', 'style'=>'table-layout:fixed')); $this->_add_section($table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.4 Gebouwdelen */ $have_bouwdelen = false; foreach ($this->deelplannen as $deelplan) foreach ($this->deelplan_bouwdelen[$deelplan->id] as $bouwdeel) { $have_bouwdelen = true; break; } if ($have_bouwdelen) { // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Locatie'; } else { // Default report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Gebouwdelen'; } $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(array('width'=>'134'),array('width'=>'448')); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Check if bouwdelen exist. // Note: we should only get 1 deelplan, but just to be sure, for now at least, loop over the deelplannen. //$this->deelplannen[] = $deelplan; foreach ($this->deelplannen as $deelplan) { $bouwdelen_str = ''; foreach ($this->deelplan_bouwdelen[$deelplan->id] as $bouwdeel) { $bouwdelen_str .= $this->hss($bouwdeel->naam) . '<br />'; } $gebouwdelen_gedefinieerd_str = (empty($bouwdelen_str)) ? 'Nee' : 'Ja'; // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. // Store the data to the 'raw' set. $raw_row_data_cell_values[] = array('Locaties gedefinieerd', $gebouwdelen_gedefinieerd_str); //$raw_row_data_cell_values[] = array('Bevindingen per gebouwdeel', 'TODO'); $raw_row_data_cell_values[] = array('Aanwezige locaties', $bouwdelen_str); } else { // Default report settings. // Store the data to the 'raw' set. $raw_row_data_cell_values[] = array('Gebouwdelen gedefinieerd', $gebouwdelen_gedefinieerd_str); //$raw_row_data_cell_values[] = array('Bevindingen per gebouwdeel', 'TODO'); $raw_row_data_cell_values[] = array('Aanwezige gebouwdelen', $bouwdelen_str); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_options = array('class'=>'TableNoHeader', 'style'=>'table-layout:fixed'); $table_fragment=$this->check_empty_table('', $table_rows, $table_options); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); } /* SUBSECTION 1.5 Checklist(en) */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Checklist(en)'; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers $header_data = ($klant->heeft_toezichtmomenten_licentie == 'ja') ? array('Checklistgroep', 'Bwn', 'Checklist', 'Toezichthouder', 'Datum toewijzing') : array('Checklistgroep', 'Checklist', 'Toezichthouder', 'Datum toewijzing'); $header_options = array(); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Loop over the 'deelplannen', outputting the checklist data as we go along foreach ($this->deelplannen as $deelplan) { $deelplanchecklistgroepen = $this->_CI->deelplanchecklistgroep->get_by_deelplan( $deelplan->id ); foreach ($deelplan->get_checklisten() as $i => $checklist) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($checklist->checklist_id, $this->deelplan_checklists)) { continue; } // get_checklisten() yields irregular data $bouwnummer = $checklist->bouwnummer; $checklist = $this->_CI->checklist->get( $checklist->checklist_id ); $checklist->bouwnummer = $bouwnummer; $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); // get toezichthouder data $toezichthouder = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->gebruiker->get( $deelplanchecklistgroepen[$checklistgroep->id]->toezicht_gebruiker_id ) : null; $toezichthouder_str = (is_null($toezichthouder) || empty($toezichthouder)) ? '' : $toezichthouder->volledige_naam; $datum_toewijzing_str = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? date( 'd-m-Y', strtotime($deelplanchecklistgroepen[$checklistgroep->id]->initiele_datum) ) : ''; $raw_row_data_cell_values[] = ($klant->heeft_toezichtmomenten_licentie == 'ja') ? array($this->hss($checklistgroep->naam), $this->hss($checklist->bouwnummer), $this->hss($checklist->naam), $this->hss($toezichthouder_str), $datum_toewijzing_str) : array($this->hss($checklistgroep->naam), $this->hss($checklist->naam), $this->hss($toezichthouder_str), $datum_toewijzing_str); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.6 Thema's */ // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. // TODO: proper replacement for the "Thema's section.... } else { // Default report settings. // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . "Thema's"; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers $header_data = array('Hoofdthema', 'Thema'); //$header_data = array(''); $header_options = array(array('width'=>'134'),array('width'=>'448')); // An array of arrays (1 per column to use) in case column options should be passed. //$header_options = array(array('colspan' => 2)); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Loop over the 'deelplannen', outputting the 'thema' data as we go along foreach ($this->deelplannen as $deelplan) { // Get the themas that are used in this 'deelplan' and store their names in a two-dimensional array, indexed by the hoofdthema_id. $deelplan_themas = $this->_CI->deelplanthema->get_by_deelplan( $deelplan->id ); $all_themas = array(); foreach ($deelplan_themas as $deelplan_thema) { // First get the thema itself $cur_thema = $this->_CI->thema->get($deelplan_thema->thema_id); // Only display thema's actually in use by the current vragen if (!in_array( $cur_thema->id, $this->deelplan_themas[$deelplan->id] )) continue; // Now index them by hoofdthema_id $cur_hoofdthema_id = $cur_thema->hoofdthema_id; if (!array_key_exists($cur_hoofdthema_id, $all_themas)) { $all_themas["$cur_hoofdthema_id"] = array(); } $all_themas["$cur_hoofdthema_id"][] = $cur_thema->thema; } // Now we have a two-dimensional array with hoofdthema_id => themas. // Proceed to add the data to the raw cell values dataset, performing the look-up on hoofdthema name only once per hoofdthema. foreach($all_themas as $cur_hoofdthema_id => $cur_thema_names) { // Get the name of the 'hoofdthema' $cur_hoofdthema_name = $this->_CI->hoofdthema->get($cur_hoofdthema_id)->naam; // Then proceed to store the data to the data cells set foreach ($cur_thema_names as $cur_thema_name) { $raw_row_data_cell_values[] = array($this->hss($cur_hoofdthema_name), $this->hss($cur_thema_name)); } } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_options = array('style'=>'table-layout:fixed'); $table_fragment=$this->check_empty_table($table_headers, $table_rows, $table_options); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); } /* SUBSECTION 1.7 Deelplan documenten */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Locatie documenten'; } else { // Default report settings. $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Deelplan documenten'; } $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers $header_data = array('#', 'Omschrijving', 'Auteur', 'Versie', 'Datum laatste wijziging'); //$header_data = array(''); $header_options = array(); //$header_options = array(array('colspan' => 2)); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Output the 'deelplan bescheiden'. First get the bescheiden data for the entire document. $dossier_bescheiden = $dos->get_bescheiden(); // Loop over the 'deelplannen', outputting only the 'bescheiden' that are associated with the respective 'deelplannen'. foreach ($this->deelplannen as $deelplan) { // Get the deelplan bescheiden and make a map of their "dossier_bescheiden_id" values $deelplan_bescheiden = $this->deelplan_bescheiden[$deelplan->id]; $deelplan_dossier_bescheiden_ids = array(); foreach ($deelplan_bescheiden as $deelplan_bescheid) { $deelplan_dossier_bescheiden_ids[] = $deelplan_bescheid->dossier_bescheiden_id; } // Now loop over the dossier bescheiden, only outputting those that are associated to the currently processed deelplan $deelplan_bescheiden_cnt = 0; foreach($dossier_bescheiden as $bescheid) { // Only show data of the 'bescheiden' that are associated with the currently processed 'deelplan' if (in_array($bescheid->id, $deelplan_dossier_bescheiden_ids)) { // Store the data for this document to the raw data cells $raw_row_data_cell_values[] = array(++$deelplan_bescheiden_cnt, $this->hss( $bescheid->omschrijving ), $this->hss( $bescheid->auteur ), $this->hss( $bescheid->versienummer ), $this->hss( $bescheid->datum_laatste_wijziging )); } } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.8 Toezichtmomenten */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Toezichtmomenten'; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers // Apply the required overrides for Arbode and Riegitaal. $tm_title = ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) ? 'Checklist' : 'Checklistgroep'; if($klant->heeft_toezichtmomenten_licentie == 'ja'){ $header_data = array('#', $tm_title, 'Bwn', 'Datum', 'Toezichthouder', 'Datum hercontrole', 'Voort- gang'); $opts = array( '25','146', '63', '79', '142', '82', '53'); }else{ $header_data = array('#', $tm_title, 'Datum', 'Toezichthouder', 'Datum hercontrole', 'Voort- gang'); $opts = array('28','148','78','144','96','87'); } $header_options = $this -> _generate_custom_cell_options( $opts ); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Loop over the 'deelplannen', outputting the 'toezichtmomenten' data as we go along foreach ($this->deelplannen as $deelplan) { //Try to output data from superviser_moments_cl DB table $superviser_moments = $deelplan->get_supervision_moments_cl(); $raw_row_data_cell_values_cl = array(); if( count($superviser_moments) ) { //$raw_row_data_cell_values = $this->getMomentsClDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values); $raw_row_data_cell_values_cl = $this->getMomentsClDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values); //continue; } //Try to output data from superviser_moments_clg DB table $superviser_moments = $deelplan->get_supervision_moments_clg(); $raw_row_data_cell_values_clg = array(); if( count($superviser_moments) ) { //$raw_row_data_cell_values = $this->getMomentsClgDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values); $raw_row_data_cell_values_clg = $this->getMomentsClgDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values); //continue; } // The required data should be obtained on a checklist level, so iterate over all checklists $raw_row_data_cell_values_dp = array(); foreach ($deelplan->get_checklisten() as $i => $checklist) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($checklist->checklist_id, $this->deelplan_checklists)) { continue; } // get_checklisten() yields irregular data $checklist = $this->_CI->checklist->get( $checklist->checklist_id );// from bt_checklisten $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); // get toezichthouder data $toezichthouder = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->gebruiker->get( $deelplanchecklistgroepen[$checklistgroep->id]->toezicht_gebruiker_id ) : null; // get matrix data // $matrix = isset( $deelplanchecklistgroepen[$checklistgroep->id] )//TODO: Don't delete (Commented by Kostia on 31-03-2015) // ? $this->_CI->matrix->get( $deelplanchecklistgroepen[$checklistgroep->id]->matrix_id ) // : null; // haal hercontrole data op $hercontrole_datums_tijden = $deelplan->get_hercontrole_data_voor_checklist( $checklist->id ); $hercontrole_data = array(); foreach ($hercontrole_datums_tijden as $hercontrole_datum_tijd) { // Explode the date-times into: date, start time, end time (i.e. index 0 = date). $hercontrole_datum_tijd_parts = explode('|', $hercontrole_datum_tijd); if (!empty($hercontrole_datum_tijd_parts[0])) { $hercontrole_data[] = date( 'd-m-Y', strtotime( $hercontrole_datum_tijd_parts[0] ) ); } } // Calculate the 'voortgang' // $matrix //TODO: Don't delete (Commented by Kostia on 31-03-2015) // ? $deelplan->get_progress_by_checklist( $matrix->id, $checklist->id ) // : 0; $voortgang = $deelplan->get_progress_by_checklist( $checklist->id ); //d($matrix); //d($voortgang); $datums = $deelplan->get_toezichtmomenten_by_checklist( $checklist->id ); $j = 0; foreach ($datums as $datum => $gebruikers) { $last = $j++ == sizeof($datums) - 1; $gebruikerstr = ''; foreach ($gebruikers as $gebruiker_id) { $gebruikerstr .= ($gebruikerstr ? ', ' : '') . (($g = $this->_CI->gebruiker->get( $gebruiker_id )) ? $g->volledige_naam : '(onbekende toezichthouder)'); } // Properly format some of the texts that we need to output $hercontrole_data_str = ($last && !empty( $hercontrole_data )) ? implode( ', ', $hercontrole_data ) : '-'; $voortgang_str = ($last) ? round( 100 * $voortgang ) . '%' : '-'; // Store the data to the raw data cells set //$raw_row_data_cell_values[] = $raw_row_data_cell_values_dp[] = array( $j, $this->hss($checklistgroep->naam), date( 'd-m-Y', strtotime( $datum ) ), $this->hss( $gebruikerstr ), $this->hss($hercontrole_data_str), $this->hss($voortgang_str)); } } // foreach ($deelplan->get_checklisten() as $i => $checklist) } // foreach ($this->deelplannen as $deelplan) // Add (compatible) data sets to the '$input_data_sets' array in order to add them to the compound data table. // Note: add the 'most important'/best data sets as the first one(s), as the code creates the compound set from left to right. $input_data_sets = array($raw_row_data_cell_values_dp, $raw_row_data_cell_values_cl, $raw_row_data_cell_values_clg); $assoc_data_set = array(); foreach($input_data_sets as $input_data_set) { foreach ($input_data_set as $candidate_data_set) { // Use the date as look-up key, and only add the data set if none exists for that date. $assoc_key = $candidate_data_set[2]; //if (!array_key_exists($assoc_key, $assoc_data_set)) //{ $assoc_data_set["$assoc_key"] = $candidate_data_set; //} } } //echo "+++ raw_row_data_cell_values assoc unsorted +++<br />"; //d($assoc_data_set); // Custom sort function for sorting the temporary assocuative array by its key values, using date comparisons. function date_cmp($a, $b) { $a_secs = strtotime($a); $b_secs = strtotime($b); if ($a_secs == $b_secs) { return 0; } return ($a_secs < $b_secs) ? -1 : 1; } // Sort the (temporary) associative data set by key, using a custom date comparison function uksort($assoc_data_set, "date_cmp"); // Extract the values from the sorted associative array, so we end up with precisely a correctly sorted numerically // indexed array with the raw data that we need. $raw_row_data_cell_values = array_values($assoc_data_set); // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_options['style'] = 'table-layout:fixed;'; $table_fragment=$this->check_empty_table($table_headers, $table_rows, $table_options); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); /* SUBSECTION 1.9 Automatische email berichten */ // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Automatische email berichten'; $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $header_data = array('Vraag', 'Toezichthouder', 'Waardeoordeel', 'Toelichting', 'Ontvanger', 'Datum en tijd'); } else { // Default report settings. $header_data = array('Vraag', 'Toezichthouder', 'Waardeoordeel', 'Toelichting', 'Ontvanger', 'Datum en tijd'); } //$header_data = array(''); $header_options = array(); //$header_options = array(array('colspan' => 2)); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Loop over the 'deelplannen', outputting the 'automatic email' data as we go along foreach ($this->deelplannen as $deelplan) { // Retrieve the sent emails (if any) for the currently processed deelplan, and add them to the table data. $sent_deelplan_emails = $this->_CI->deelplanvraagemail->get_all_sent_by_deelplan($deelplan->id); // The required data should be obtained on a checklist level, so iterate over all checklists foreach ($sent_deelplan_emails as $sent_deelplan_email) { // Store the data to the raw data cells set $vraag_text = $this->hss($sent_deelplan_email->get_deelplan_vraag()->get_vraag()->tekst); $toezichthouder_text = $this->hss($sent_deelplan_email->get_gebruiker()->volledige_naam); $waardeoordeel_text = $this->hss($sent_deelplan_email->get_deelplan_vraag()->get_vraag()->get_waardeoordeel(true, $sent_deelplan_email->status)); $toelichting_text = $this->hss($sent_deelplan_email->toelichting); $ontvanger_text = $this->hss($sent_deelplan_email->recipient); $datum_text = $this->hss(date( 'd-m-Y H:i:s', strtotime($sent_deelplan_email->datum_sent))); //$raw_row_data_cell_values[] = array($j, $this->hss($checklistgroep->naam), date( 'd-m-Y', strtotime( $datum ) ), $this->hss( $gebruikerstr ), $this->hss($hercontrole_data_str), $this->hss($voortgang_str)); $raw_row_data_cell_values[] = array($vraag_text, $toezichthouder_text, $waardeoordeel_text, $toelichting_text, $ontvanger_text, $datum_text); } // foreach ($sent_deelplan_emails as $sent_deelplan_email) } // foreach ($this->deelplannen as $deelplan) // Construct the proper table rows data from the raw data set. Note: only add this section if emails were sent (most likely, this will not often be the case). if (!empty($raw_row_data_cell_values)) { foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment = $this->_generate_table_fragment($table_headers, $table_rows, array()); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); } } // private function _generate_dossier_gegevens() private function getMomentsClDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values){ $klant = $this->get_klant(); $j = 0; foreach ($superviser_moments as $date => $moment ){ $last = $j++ == sizeof($superviser_moments) - 1; $checklistgroep = $this->_CI->checklistgroep->get( $moment->checklist_groep_id ); $user_str = ''; foreach ($moment->users as $user_id) { $username = ($g = $this->_CI->gebruiker->get( $user_id )) ? $g->volledige_naam : '(onbekende toezichthouder)'; if (strpos($user_str, $username)=== false) { $user_str .= ($user_str ? ', ' : '') . $username; } } // haal hercontrole data op $hercontrole_datums_tijden = $deelplan->get_hercontrole_data_voor_checklist( $moment->checklist_id ); $hercontrole_data = array(); foreach ($hercontrole_datums_tijden as $hercontrole_datum_tijd){ // Explode the date-times into: date, start time, end time (i.e. index 0 = date). $hercontrole_datum_tijd_parts = explode('|', $hercontrole_datum_tijd); if (!empty($hercontrole_datum_tijd_parts[0])){ $hercontrole_data[] = date( 'd-m-Y', strtotime( $hercontrole_datum_tijd_parts[0] ) ); } } $hercontrole_data_str = ($last && !empty( $hercontrole_data )) ? implode( ', ', $hercontrole_data ) : '-'; $voortgang_str = $moment->progress; $raw_row_data_cell_values[] = ($klant->heeft_toezichtmomenten_licentie == 'ja') ? array( $j, $this->hss($checklistgroep->naam), $this->hss($moment->bouwnummer), date( 'd-m-Y', strtotime( $date ) ), $this->hss( $user_str ), $this->hss($hercontrole_data_str), $this->hss($voortgang_str) ) : array( $j, $this->hss($checklistgroep->naam), date( 'd-m-Y', strtotime( $date ) ), $this->hss( $user_str ), $this->hss($hercontrole_data_str), $this->hss($voortgang_str) ); } return $raw_row_data_cell_values; } private function getMomentsClgDocData( $deelplan, $superviser_moments, $raw_row_data_cell_values){ $j = 0; foreach ($superviser_moments as $date => $moment ){ $last = $j++ == sizeof($superviser_moments) - 1; $checklistgroep = $this->_CI->checklistgroep->get( $moment->checklist_group_id ); $user_str = ''; foreach ($moment->users as $user_id){ $username = ($g = $this->_CI->gebruiker->get( $user_id )) ? $g->volledige_naam : '(onbekende toezichthouder)'; if (strpos ($user_str, $username)===false) { $user_str .= ($user_str ? ', ' : '') . $username; } } // haal hercontrole data op $hercontrole_datums_tijden = $deelplan->get_hercontrole_data_voor_checklistgroep( $moment->checklist_group_id ); $hercontrole_data = array(); foreach ($hercontrole_datums_tijden as $hercontrole_datum_tijd){ // Explode the date-times into: date, start time, end time (i.e. index 0 = date). $hercontrole_datum_tijd_parts = explode('|', $hercontrole_datum_tijd); if (!empty($hercontrole_datum_tijd_parts[0])){ $hercontrole_data[] = date( 'd-m-Y', strtotime( $hercontrole_datum_tijd_parts[0] ) ); } } $hercontrole_data_str = ($last && !empty( $hercontrole_data )) ? implode( ', ', $hercontrole_data ) : '-'; $voortgang_str = $moment->progress; $raw_row_data_cell_values[] = array($j, $this->hss($checklistgroep->naam), date( 'd-m-Y', strtotime( $date ) ), $this->hss( $user_str ), $this->hss($hercontrole_data_str), $this->hss($voortgang_str)); } return $raw_row_data_cell_values; } private function _generate_organisatie_kenmerken() { //if (!@array_key_exists( 'organisatiekenmerken', $this->get_filter( 'onderdeel' ))) // return; $this->_set_progress( 'Organisatiekenmerken...' ); $section_header = $this->_create_section_header(1, ++$this->section_number.'. Organisatiekenmerken'); // Get the dossier object $dossier = $this->get_dossier(); // If we successfully got the dossier object, we proceed if (!is_null($dossier)) { // Use the proper model for getting the values (if any) $this->_CI->load->model('org_kenmerken'); $org_kenmerken = $this->_CI->org_kenmerken->get_by_dossier( $dossier->id ); // If something has been specified, proceed to show the table. if (!is_null($org_kenmerken)) { // indicate the properties that should not be shown $hide_members = array('id', 'dossier_id'); // Specify some nicer texts to use rather than the DB field names for those fields that do not have directly usable names $nice_labels = array( 'productie_en' => 'Productie- en transportmiddelen', //'personen_werkzaam' => '', 'jaar_less_18' => '< 18 jaar', 'jaar_18_20' => '18 - 20 jaar', 'jaar_21_30' => '21 - 30 jaar', 'jaar_31_40' => '31 - 40 jaar', 'jaar_41_50' => '41 - 50 jaar', 'jaar_51_60' => '51 - 60 jaar', 'jaar_61_65' => '61 - 65 jaar', 'aantal_fte' => 'Aantal FTE', //'minder_validen' => '', 'wwb_ers' => 'WWB-ers', //'werktijden_en_overwerk' => '', 'functies_voor' => 'In het bedrijk komen de volgende functies voor', 'wao_wia_toetreding' => 'WAO/WIA-toetreding', //'geconstateerde_beroepsziekten' => '', 'gezondheidskundig_onderzoek' => 'Periodiek ArbeidsGezondheidskundig Onderzoek' ); /* d(array_keys(get_object_vars($org_kenmerken))); exit; array (size=41) 0 => string 'id' (length=2) 1 => string 'dossier_id' (length=10) 2 => string 'bedrijf' (length=7) 3 => string 'bezoekadres' (length=11) 4 => string 'postadres' (length=9) 5 => string 'telefoon' (length=8) 6 => string 'contactpersoon' (length=14) 7 => string 'preventiemedewerker' (length=19) 8 => string 'branche' (length=7) 9 => string 'bedrijfsactiviteiten' (length=20) 10 => string 'productieproces' (length=15) 11 => string 'bedrijfslocatie' (length=15) 12 => string 'projectlocatie' (length=14) 13 => string 'productie_en' (length=12) 14 => string 'personen_werkzaam' (length=17) 15 => string 'jaar_less_18' (length=12) 16 => string 'jaar_18_20' (length=10) 17 => string 'jaar_21_30' (length=10) 18 => string 'jaar_31_40' (length=10) 19 => string 'jaar_41_50' (length=10) 20 => string 'jaar_51_60' (length=10) 21 => string 'jaar_61_65' (length=10) 22 => string 'aantal_fte' (length=10) 23 => string 'minder_validen' (length=14) 24 => string 'zwangeren' (length=9) 25 => string 'jeugdigen' (length=9) 26 => string 'allochtonen' (length=11) 27 => string 'thuiswerkers' (length=12) 28 => string 'inleenkrachten' (length=14) 29 => string 'oproepkrachten' (length=14) 30 => string 'wwb_ers' (length=7) 31 => string 'werktijden_en_overwerk' (length=22) 32 => string 'functies_voor' (length=13) 33 => string 'verzuimpercentage' (length=17) 34 => string 'meldingsfrequentie' (length=18) 35 => string 'verzuimduur' (length=11) 36 => string 'wao_wia_toetreding' (length=18) 37 => string 'ongevallencijfers' (length=17) 38 => string 'geconstateerde_beroepsziekten' (length=29) 39 => string 'ziekteverzuimbegeleiding' (length=24) 40 => string 'gezondheidskundig_onderzoek' (length=27) */ // Define any and all styles that are used for the tables over here $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); $section_images = array(); $table_rows = array(); $header_data = array(); $header_options = array(); //$header_options = array(array('colspan' => 2)); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Now process all of the members, formatting them as required foreach ($org_kenmerken as $kenmerk => $value) { if (!in_array($kenmerk, $hide_members)) { $label = (!empty($nice_labels["$kenmerk"])) ? $nice_labels["$kenmerk"] : ucfirst(str_replace('_', ' ', $kenmerk)); // Store the data to the raw data cells set $raw_row_data_cell_values[] = array($this->hss($label), $this->hss($value)); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal', 'before'); //d($raw_row_data_cell_values); //exit; } // if (!is_null($org_kenmerken)) else { $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Er zijn nog geen organisatiekenmerken opgegeven.</p>'; $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } } // if (!is_null($dossier)) else { $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Het dossier kon niet succesvol opgehaald worden.</p>'; $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); //$html_fragment = ''; } // Add a section for the main header of this chapter //$section_header = $this->_create_section_header(1, ++$this->section_number.'. Organisatiekenmerken'); // $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } private function _generate_toetsing_kerndeskundige() { if (!@array_key_exists( 'toetsing_kerndeskundige', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Toetsing kerndeskundige...' ); // Register the images of this section $section_images = array(); $this->_add_image($section_images, $this->images_path_icons, 'signature_ruud_van_de_laar', 'handtekening_ruud_van_de_laar'); $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p><b>Verklaring Toetsing Arbo Risico- Inventarisatie en -Evaluatie</b></p>' . '<p>Hierbij verklaart ondergetekende dat deze Arbo RI&E is beoordeeld door een kerndeskundige.</p>' . '<p>In het kader van de Arbo-wet is de RI&E getoetst volgens de maatwerkregeling. De RI&E is beoordeeld op onderstaande elementen:' . '<ul>' . '<li>Wettelijk verplichte inventarisaties;</li>' . '<li>Methode van prioriteitstelling;</li>' . '<li>Gevolgde werkwijze;</li>' . '<li>Inhoudelijke adviezen;</li>' . '<li>Indien van toepassing: Bezoek van bedrijfs- en projectlocatie(s);</li>' . '<li>Volledigheid inzake veiligheid, gezondheid en welzijn;</li>' . '<li>Plan van aanpak.</li>' . '</ul>' . '</p>' . '<p><b>Conclusie</b>: Onderhavig RI&E-rapport <b>voldoet</b> aan de in de wet gestelde eisen op voorwaarde dat de acties uit uw plan van aanpak ' . 'en de eventueel aangeduide noodzakelijke verdiepende onderzoeken zijn uitgevoerd.</p>' . '<p>Opmerkingen:' . '<ul>' . '<li>Het plan van aanpak maakt deel uit van de wettelijke verplichting de risico’s te inventariseren en te evalueren;</li>' . '<li>Alle acties ter verbetering van de knelpunten en alle verplichte verdiepende onderzoeken dienen te zijn uitgevoerd voor volledigheid;</li>' . '<li>Een eventuele werknemersvertegenwoordiging moet actief betrokken worden bij het plan van aanpak, geïnformeerd worden over de voortgang van de ' . 'uitvoering van de verbeteracties en worden geïnformeerd over de inhoud van dit rapport.</li>' . '</ul>[IMG:signature_ruud_van_de_laar]<br />' . 'Ir. R.<NAME>ar<br />' . 'Gecertificeerd Arbeidshygiënist (rah)' . '</p>' ; //$html_fragment = ''; // Add a section for the main header of this chapter //$section_header = $this->_create_section_header(1, '1. Algemeen'); $section_header = $this->_create_section_header(1, ++$this->section_number.'. Toetsing kerndeskundige'); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before'); //$this->_add_section($style_fragment.$html_fragment, $section_header, $section_images, 'normal', 'before'); // TODO: fill this with the proper content } private function _generate_documenten_lijst() { if (!@array_key_exists( 'documenten', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Documenten...' ); $this->_output_header1( 'Documenten', false ); $this->_output_bescheiden_table( $this->get_dossier()->get_bescheiden() ); } private function _generate_deelplannen_lijst() { if (!@array_key_exists( 'deelplannen', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Deelplannen...' ); /* $this->_output_header1( 'Deelplannen', false ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<span style="text-align:justify">Een locatie in de fysieke leefomgeving kan in een dossier worden opgenomen. Onder dat dossier kunnen meerdere deelplannen worden opgenomen. '. 'Ieder deelplan kan op zichzelf meerdere aspecten van de fysieke leefomgeving behelsen. '. 'Bijvoorbeeld de realisatiefase (bouwen) en de gebruiksfase (milieu). '. 'Deelplannen kunnen ook toegepast worden bij grote of complexe bouwplaatsen of inrichtingen. '. 'Zo kan ieder bouwblok of ieder onderdeel uit een inrichting in een &quot;eigen&quot; deelplan opgenomen zijn.</span>', true, false, true ); $this->_tcpdf->Ln(); $dos = $this->get_dossier(); $bescheiden = $dos->get_bescheiden(); foreach ($this->deelplannen as $deelplan) { // hoofdkop voor dit deelplan $this->_output_header2( $deelplan->naam, false ); // lijst van betrokkenen bij dit deelplan $this->_output_subheader( $this->hss( 'Betrokkenen ' . $deelplan->naam ) ); foreach ($deelplan->get_subjecten() as $i => $subject) { if ($i) $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td width="200px">Rol</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->rol ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Naam</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Adres</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->adres ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Postcode en woonplaats</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->postcode . ' ' . $subject->woonplaats ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Telefoon</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->telefoon ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">E-mail</td>' . '<td width="25px">:</td>' . '<td width="300px">' . $this->hss( $subject->email ) . '</td>' . '</tr>' . '</table>' , true, false, true ); } $this->_tcpdf->Ln(); // lijst van bescheiden bij dit deelplan $this->_output_subheader( $this->hss( 'Documenten ' . $deelplan->naam ) ); $this->_tcpdf->Ln(); $this->_output_bescheiden_table( $bescheiden ); $this->_tcpdf->Ln(); // lijst van checklists bij dit deelplan $this->_output_subheader( $this->hss( 'Checklisten ' . $deelplan->naam ) ); $this->_tcpdf->Ln(); $deelplanchecklistgroepen = $this->_CI->deelplanchecklistgroep->get_by_deelplan( $deelplan->id ); $deelplan_themas = $this->_CI->deelplanthema->get_by_deelplan( $deelplan->id ); foreach ($deelplan->get_checklisten() as $i => $checklist) { // get_checklisten() yields irregular data $checklist = $this->_CI->checklist->get( $checklist->checklist_id ); $checklistgroep = $this->_CI->checklistgroep->get( $checklist->checklist_groep_id ); // get toezichthouder data $toezichthouder = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->gebruiker->get( $deelplanchecklistgroepen[$checklistgroep->id]->toezicht_gebruiker_id ) : null; // get matrix data $matrix = isset( $deelplanchecklistgroepen[$checklistgroep->id] ) ? $this->_CI->matrix->get( $deelplanchecklistgroepen[$checklistgroep->id]->matrix_id ) : null; // get thema data $checklist_themas = array(); // lijst van alle GESELECTEERDE thema's, met als key hoofdthema id foreach ($this->_CI->thema->get_by_checklist( $checklist->id ) as $thema) // thema geselecteerd voor checklist? if (isset( $deelplan_themas[ $thema->id ] )) { if (!isset( $checklist_themas[$thema->hoofdthema_id] )) $checklist_themas[$thema->hoofdthema_id] = array(); $checklist_themas[$thema->hoofdthema_id][] = $thema; } $checklist_hoofdthemas = array(); // lijst van ALLE hoofdthema's foreach ($this->_CI->hoofdthema->get_by_checklist( $checklist->id, true ) as $hoofdthema) $checklist_hoofdthemas[ $hoofdthema->id ] = $hoofdthema; // build table $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td width="200px">Hoofdgroep / gebouwfase</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $checklist->get_checklistgroep()->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Categorie / activiteiten</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $checklist->naam ) . '</td>' . '</tr>' . '<tr>' . '<td width="200px">Toezichthouder</td>' . '<td width="25px">:</td>' . '<td width="420px">' . $this->hss( $toezichthouder ? $toezichthouder->volledige_naam : '(niet bekend)' ) . '</td>' . '</tr>'; if (empty( $checklist_themas )) { $html .= '<tr>' . '<td width="200px">Thema\'s</td>' . '<td width="25px">:</td>' . '<td width="420px"></td>' . '</tr>'; } else { $eerste = true; foreach ($checklist_themas as $hoofdthema_id => $themas) { $seen_themas = array(); foreach ($themas as $thema) { if (in_array( $thema->thema, $seen_themas )) continue; $seen_themas[] = $thema->thema; } $html .= '<tr>' . '<td width="200px">' . ($eerste ? 'Thema\'s' : '') . '</td>' . '<td width="25px">' . ($eerste ? ':' : '') . '</td>' . '<td width="120px"><b>' . $this->hss( $checklist_hoofdthemas[$hoofdthema_id]->naam ) . '</b></td>' . '<td width="300px">' . implode( ', ', $seen_themas ) . '</td>' . '</tr>'; $eerste = false; } } $html .= '</table>'; // output table $this->_output_subheader( $this->hss( 'Checklist ' . ($i + 1) ) ); $this->_tcpdf->WriteHTML( $html, true, false, true ); $this->_tcpdf->Ln(); // haal hercontrole data op $hercontrole_data = $deelplan->get_hercontrole_data_voor_checklist( $checklist->id ); foreach ($hercontrole_data as $i => $datum) $hercontrole_data[$i] = date( 'd-m-Y', strtotime( $datum ) ); // build toezichtmomenten table $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td style="width:120px; font-weight: bold">Bezoeknummer</td>' . '<td style="width:110px; font-weight: bold">Datum</td>' . '<td style="width:150px; font-weight: bold">Toezichthouder</td>' . '<td style="width:140px; font-weight: bold">Geplande datum hercontrole</td>' . '<td style="width:100px; font-weight: bold">Voortgang</td>' . '</tr>'; $voortgang = $matrix ? $deelplan->get_progress_by_checklist( $matrix->id, $checklist->id ) : 0; $datums = $deelplan->get_toezichtmomenten_by_checklist( $checklist->id ); $j = 0; foreach ($datums as $datum => $gebruikers) { $last = $j++ == sizeof($datums) - 1; $gebruikerstr = ''; foreach ($gebruikers as $gebruiker_id) $gebruikerstr .= ($gebruikerstr ? ', ' : '') . (($g = $this->_CI->gebruiker->get( $gebruiker_id )) ? $g->volledige_naam : '(onbekende toezichthouder)'); $html .= '<tr>' . '<td style="font-style:italic">' . $j . '.</td>' . '<td style="font-style:italic">' . date( 'd-m-Y', strtotime( $datum ) ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $gebruikerstr ) . '</td>' . '<td style="font-style:italic">' . (($last && !empty( $hercontrole_data )) ? implode( ', ', $hercontrole_data ) : '-') . '</td>' . '<td style="font-style:italic">' . ($last ? round( 100 * $voortgang ) . '%' : '-') . '</td>' . '</tr>'; } $html .= '</table>'; // output table $this->_output_subheader( $this->hss( 'Toezichtmomenten' ) ); $this->_tcpdf->Ln(); $this->_tcpdf->WriteHTML( $html, true, false, true ); $this->_tcpdf->Ln(); } } * */ } private function _generate_samenvatting() { if (!@array_key_exists( 'samenvatting', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Samenvatting...' ); /* $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Dit onderdeel wordt momenteel nog uitgewerkt en zal later toegevoegd worden.</p>'; * */ $html_fragment = ''; // Add a section for the main header of this chapter // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $section_title = 'Statusoverzicht'; $header_data = array('Onderwerpen', 'Status'); } else { // Default report settings. $section_title = 'Samenvatting'; $header_data = array('Onderwerp', 'Status'); } //$section_header = $this->_create_section_header(1, '3. Samenvatting'); // Define any and all styles that are used for the tables over here $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); // Initialise the subsection counter $subsection_cnt = 0; // First get the dossier data, then loop over the 'deelplannen'. // Note: we should only have to support a single 'deelplan' but leave the loop in place anyway as we may need to show multiple // 'deelplannen' at a later time. $dos = $this->get_dossier(); if(!empty($this->deelplannen)) { $section_header = $this->_create_section_header(1, ++$this->section_number.". {$section_title}"); //If VIIA, don't add a pagebreak before if($this->overriden_data_context == 'viia') { $this->_add_section("", $section_header, array(), 'normal', 'before'); } else { $this->_add_section("", $section_header, array(), 'normal', 'before'); } $onderwerp_nr = 0; foreach ($this->deelplannen as $j => $deelplan) { // hoofdkop voor dit deelplan //$this->_output_header2( $deelplan->naam, false ); // Now loop over the checklists, outputting the data as required foreach ($this->deelplan_scopes[$deelplan->id] as $i => $scope) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($scope['checklist_id'], $this->deelplan_checklists)) { continue; } $scope_id = $scope['scope_id']; // Initialise the images set, table data rows sets and some other data that is used for this section $subsection_cnt++; //$subsection_header_title = "3.{$subsection_cnt} " . $this->hss($checklist->naam); $subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . $this->hss($scope['naam']); $section_images = array(); $table_rows = array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers //$header_data = array('Onderwerp', 'Status'); // Defined further above, as they are overridden for some contexts. $header_options = array(); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now process the actual data, adding the values to the rows as we go along // maak onderverdeling in vragen naar onderwerp $onderwerp_vragen = array(); foreach ($this->deelplan_onderwerpen[$deelplan->id][$scope_id] as $onderwerp_id => $onderwerp) { foreach ($onderwerp['vragen'] as $vraag) { // voeg vraag toe if (!isset( $onderwerp_vragen[ $onderwerp_id ] )) $onderwerp_vragen[ $onderwerp_id ] = array( 'naam' => $onderwerp['naam'], 'vragen' => array(), 'status' => 4, ); $onderwerp_vragen[ $onderwerp_id ]['vragen'][] = $vraag; // update onderwerp status $vraag_status = $this->_status_to_samenvatting_waarde( $vraag ); if ($onderwerp_vragen[ $onderwerp_id ]['status'] > $vraag_status) $onderwerp_vragen[ $onderwerp_id ]['status'] = $vraag_status; } } // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(array('width' => '100%'), array('width' => '125px')); // An array of arrays (1 per column to use) in case column options should be passed. $raw_row_data_cell_values = array(); // Loop over the onderwerpen and use the data of it as needed // Presently we only need the 'onderwerpen' names and the status so we can show the proper status icon foreach ($onderwerp_vragen as $onderwerp_id => $onderwerp_data){ switch ($onderwerp_data['status']){ case 0: $status_img_identifier = ($this->overriden_data_context == 'viia') ? 'status-rood-viia' : 'status-rood'; break; case 1: $status_img_identifier = 'status-geel'; break; case 2: $status_img_identifier = 'status-groen'; break; case 3: $status_img_identifier = 'status-groen'; break; } //If VIIA, add a counter to onderwerp if($this->overriden_data_context == 'viia'){ $raw_row_data_cell_values[] = array(sprintf('%02d',++$onderwerp_nr).". ".$this->hss($onderwerp_data['naam']), "[IMG:{$status_img_identifier}]"); }else{ $raw_row_data_cell_values[] = array($this->hss($onderwerp_data['naam']), "[IMG:{$status_img_identifier}]"); } } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data){ $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); } // foreach ($deelplan->get_checklisten() as $i => $checklist) } // foreach ($this->deelplannen as $j => $deelplan) /* Leeswijzer -- for now VIIA-only */ if ($this->overriden_data_context == 'viia') { // Initialise the images set, table data rows sets and some other data that is used for this section //$subsection_cnt++; //$subsection_header_title = "{$this->section_number}.{$subsection_cnt} " . 'Leeswijzer'); $subsection_header_title = "Leeswijzer"; $section_images = array(); $table_rows = array(); $raw_row_data_cell_values = array(); $raw_row_data_cell_options=array(); // Add the subsection header $section_header = $this->_create_section_header(2, $subsection_header_title); // Define the table headers $header_data = array('Icoon', 'Betekenis'); $header_options = $this -> _generate_custom_cell_options (array('59','531')); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); //$table_fragment = $this->_generate_table_fragment('',$table_rows, array('class'=>'TableNoHeader', 'style'=>'table-layout:fixed')); // Define any and all styles that are used for the tables over here $style_fragment = ''; // Now add the icons and their descriptions, hard coded. $raw_row_data_cell_values[] = array("[IMG:status-groen]", $this->hss('Voldoet / niet van toepassing')); $raw_row_data_cell_values[] = array("[IMG:status-geel]", $this->hss('Afwijking / aandachtspunt / niet kunnen beoordelen')); $status_img_identifier = ($this->overriden_data_context == 'viia') ? 'status-rood-viia' : 'status-rood'; $raw_row_data_cell_values[] = array("[IMG:{$status_img_identifier}]", $this->hss('Nog niet beoordeeld')); // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers,$table_rows, array('width'=>'100%', 'style'=>'table-layout:fixed')); //$table_fragment=$this->check_empty_table($table_headers, $table_rows, $table_options); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); } // if ($this->overriden_data_context == 'viia') } else { $section_header = $this->_create_section_header(1, ++$this->section_number.". {$section_title}"); $this->_add_section(tg('geengegevens'), $section_header, array(), 'normal', 'before'); } } private function _vraag_weergeven( $deelplan_id, $vraag ) { // check status filter $status = $this->_status_to_description( $vraag ); if ($vraag->get_wizard_veld_recursief( 'vraag_type' ) == 'invulvraag') { if (!$this->waardeoordeel_invulvragen) { //die( 'Neem vraag niet op, want het is een invulvraag en die tonen we niet' ); return false; } } else { if (!isset( $this->waardeoordelen[$status] )) { //die( 'Neem vraag niet op, want ' . $status . ' wordt niet getoond' ); return false; } } // check betrokkene filter if (is_array( $this->betrokkenen )) { $found = false; if (isset( $this->deelplan_vraag_subjecten[ $deelplan_id ] )) { if (isset( $this->deelplan_vraag_subjecten[ $deelplan_id ][ $vraag->id ] )) { foreach ($this->deelplan_vraag_subjecten[ $deelplan_id ][ $vraag->id ] as $subject) { if (isset( $this->betrokkenen[ $subject->dossier_subject_id ] )) { $found = true; break; } } } } if (!$found) { return false; } } // done! mag getoond worden! return true; } private function _generate_bevindingen() { if (!@array_key_exists( 'bevindingen', $this->get_filter( 'onderdeel' ))) return; $this->_set_progress( 'Bevindingen...' ); // Add a section for the main header (and possible introduction text) of this report part //$section_header = $this->_create_section_header(1, '4. Bevindingen'); // Set the maximum dimensions for the snapshots //$max_snapshot_image_width = $max_photo_image_width = 144; $max_snapshot_image_width = $max_photo_image_width = 144; $max_snapshot_image_height = $max_photo_image_height = 'auto'; // Set the maximum dimensions for the overview thumbnails. VIIA-181: changed width 300 to A4 $max_overview_thumb_image_width = 620; $max_overview_thumb_image_height = 529; // Loop over the structure: // -Deelplan(nen) (ought to be only one, but possibly it's handy to support multiple ones) - for now, assume only one // -Checklists (all) // -Hoofdgroepen (all) // -Vragen + grondslagen // -W.O. icon, [revisie], W.O. tekst + datum, toelichting (*), # (?), snapshot(s), foto('s) // // * = The 'toelichting' is compound, consisting of: gebouwdeel, toelichting, hercontroledatum, betrokkenen // First get the dossier $dos = $this->get_dossier(); //echo "<br /><br />"; // Now iterate over the deelplannen. // Note: this only ought to be 1, but in case it isn't, we use a loop anyway. If multiple 'deelplannen' need to be shown, we must accomodate // accordingly by outputting the names or so in a section, and bump the underlying section header levels 1 level. if(!empty($this->deelplannen)){ $section_header = $this->_create_section_header(1, ++$this->section_number.'. Bevindingen'); $this->_add_section('', $section_header, array(), 'normal', 'before', 'A4', 'landscape'); foreach ($this->deelplannen as $j => $deelplan) { // hoofdkop voor dit deelplan //echo "Deelplan: " . $deelplan->naam . "<br />"; // Now iterate over the checklists, creating a section per checklist $scope_cnt = 0; foreach ($this->deelplan_scopes[$deelplan->id] as $i => $scope) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($scope['checklist_id'], $this->deelplan_checklists)) { continue; } $scope_id = $scope['scope_id']; $scope_cnt++; // Changed (26-3-2015): Made the following functionality 'VIIA' specific. if ($this->overriden_data_context == 'viia') { // The first checklist can start directly under the chapter header. For subsequent checklists we make sure to always start on a new page. if ( $scope_cnt > 1) { $sub_section_page_break = 'before'; } else { $sub_section_page_break = 'none'; } } else { // For other clients than 'VIIA' for now we do not insert page breaks before starting a new subsection. $sub_section_page_break = 'none'; } $section_header = $this->_create_section_header(2, "{$this->section_number}.{$scope_cnt} " . $scope['naam']); $this->_add_section('', $section_header, array(), 'normal', $sub_section_page_break, 'A4', 'landscape'); // Initialise the images set here (and NOT further ahead as then the annotations will go missing!). $section_images = array(); // Get the vragen and iterate over them, extracting the various bits of information, and storing them as table rows as required. // page is 650px wide $current_hoofdgroep_id = null; // Generate the snapshots and register them with the images array too. // Note: we only need the annotation images and data in this section, so we get these into a local variable. // The overview images, on the other hand, are processed in a different method, so store the data for those in the global member, // as we have this information available here anyway, hence preventing a further call to generate the same data again. //$section_annotation_data_set = array(); //MJ (27-04-2015): changed value of 50 to 100 to create a larger canvas size //$aap = $this->_CI->annotatieafbeeldingprocessor->create($deelplan->id, $scope['checklist_groep_id'], @ $scope['checklist_id'], 50, false, $this->images_path_snapshots); $aap = $this->_CI->annotatieafbeeldingprocessor->create($deelplan->id, $scope['checklist_groep_id'], @ $scope['checklist_id'], 100, false, $this->images_path_snapshots); //added the option to include hoofdgroep specific annotations. If desired, use true as the second parameter. //the hoofdgroep -specific images are added to the global images set to be used later on. $hoofdgroep_specific = ($this->overriden_data_context == 'viia'); $aap->run(new RapportageAnnotatieAfbeeldingProcessorCallback(), $hoofdgroep_specific); // We can now do with the annotations and overviews what we want. // Register the annotations themselves with the section and register the overviews with the global overview data set (which will be processed later). // Register the annotations themselves with the section. Also store the identifiers and annotation numbers in a handy look-up set, facilitating work further ahead. //$section_annotation_cnt = 0; $vraag_annotations = array(); foreach ($aap->annotation_data_set as $img_idx => $img_data) { //d($img_data); // Get some information from the annotation. We do this outside the check if it's a snapshot, so we can possibly use this // information for other types of annotations too. $cur_annotation_type = $img_data['metadata']->GetannotatieType(); $cur_annotation_object = $img_data['metadata']->GetAnnotatieObject(); $cur_annotation_text = $cur_annotation_photoid = ''; //d($cur_annotation_type); // text, compound if ( ($cur_annotation_type == 'text') || ($cur_annotation_type == 'compound') ) { $cur_annotation_text = $cur_annotation_object->get_text(); //echo 'Annotation text: '; //d($cur_annotation_text); } // photoassignment if ($cur_annotation_type == 'photoassignment') { continue; // do not show "todo things" in the "bevindingen" sectie } // photo, compound if ( ($cur_annotation_type == 'photo') || ($cur_annotation_type == 'compound') ) { $cur_annotation_photoid = $cur_annotation_object->get_photoid(); //echo 'Annotation photo ID: '; //d($cur_annotation_photoid); } if ($img_data['type'] == 'snapshot') { // Create a proper reference //$section_annotation_cnt++; // Usable data for creating the references: // private 'bescheidenId' => string '4850' (length=4) // private 'dossierId' => string '9090' (length=4) // private 'deelplanId' => int 8950 // private 'checklistgroepId' => string '34' (length=2) // private 'checklistId' => string '609' (length=3) // private 'hoofdgroepId' => string '48928' (length=5) // private 'vraagId' => int 250931 // private 'annotatieNummer' => int 1 $cur_img_bescheiden_id = $img_data['metadata']->GetBescheidenId(); $cur_img_bescheiden_orientation= $img_data['metadata']->GetBescheidenOrientation(); $cur_img_dossier_id = $img_data['metadata']->GetDossierId(); $cur_img_deelplan_id = $img_data['metadata']->GetDeelplanId(); $cur_img_checklistgroep_id = $img_data['metadata']->GetChecklistGroepId(); $cur_img_checklist_id = $img_data['metadata']->GetChecklistId(); $cur_img_hoofdgroep_id = $img_data['metadata']->GetHoofdgroepId(); $cur_img_vraag_id = $img_data['metadata']->GetVraagId(); $cur_img_annotatie_nummer = $img_data['metadata']->GetAnnotatieNummer(); $cur_img_pagina_nummer = $img_data['metadata']->GetPaginaNummer(); if ( ($cur_annotation_type == 'photo') || ($cur_annotation_type == 'compound') ) { $photo_identifier = $cur_annotation_photoid.'.jpg_'.$cur_img_deelplan_id.'_'.$cur_img_vraag_id; if (array_key_exists($photo_identifier,$this->photo_annotaties)) { $this->photo_annotaties[$photo_identifier]=$this->photo_annotaties[$photo_identifier]." & ".$cur_img_annotatie_nummer; } else { $this->photo_annotaties[$photo_identifier]=$cur_img_annotatie_nummer; } } //$identifier = 'annotation_' . $section_annotation_cnt; $identifier_parts = array('annotation', $cur_img_dossier_id, $cur_img_deelplan_id, $cur_img_checklistgroep_id, $cur_img_checklist_id, $cur_img_vraag_id, $cur_img_annotatie_nummer); $identifier = implode('_', $identifier_parts); //d($img_data['metadata']); //d($identifier); // Resize the image if necessary $resized_image_data = $this->_force_max_image_dimensions($img_data['png_contents'], $max_snapshot_image_width, $max_snapshot_image_height); // Now use the resized image (if it was successfully resized), or the source one if it was not (successfully) resized. $image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $img_data['png_contents']; // Add the image to the section images. Pass a dummy path name, as we pass the data directly. //$this->_add_image($section_images, 'dummy_path', $identifier, $cur_overview_data['png_contents'], 'png', 'auto', 'auto', 'data'); $this->_add_image($section_images, 'dummy_path', $identifier, $image_data, 'png', 'auto', 'auto', 'data'); // Store the images to the look-up set if (!array_key_exists($cur_img_vraag_id, $vraag_annotations)) { $vraag_annotations["$cur_img_vraag_id"] = array(); } //$vraag_annotations["$cur_img_vraag_id"][] = array('annotation_number' => $cur_img_annotatie_nummer, 'identifier' => $identifier); $vraag_annotations["$cur_img_vraag_id"][] = array ( 'bescheiden_id' => $cur_img_bescheiden_id.'_'.$cur_img_pagina_nummer, 'bescheiden_orientation' => $cur_img_bescheiden_orientation, 'annotation_number' => $cur_img_annotatie_nummer, 'identifier' => $identifier, 'annotation_type' => $cur_annotation_type, 'annotation_text' => $cur_annotation_text, 'annotation_photoid' => $cur_annotation_photoid ); } } // Register the overviews with the global overview data //foreach ($aap->overview_data_set as $img_idx => $img_data) foreach ($aap->overview_data_set as $overview_bescheiden_id => $img_data) { if (!isset($cur_img_pagina_nummer)) { $cur_img_pagina_nummer = '1'; } // Simply add the overview images to the existing set of overview images if (!array_key_exists($overview_bescheiden_id.'_'.$cur_img_pagina_nummer, $this->overview_data_set)) { $this->overview_data_set["$overview_bescheiden_id"."_"."$cur_img_pagina_nummer"] = $img_data; } } if (!isset($aap->overview_thumbs_data_set)) { $aap->overview_thumbs_data_set = array(); } foreach ($aap->overview_thumbs_data_set as $overview_bescheiden_id => $img_data) { // Add a thumbnail for it to a global set too. This is used for adding small thumbnails in a more efficient way than adding them repeatedly. if (!array_key_exists($overview_bescheiden_id, $this->overview_thumbs_data_set)) { // Make a globally registered thumbnail of the overview image $dummy_image_for_dimensions_check = imagecreatefromstring($img_data['png_contents']); if (imagesx($dummy_image_for_dimensions_check) < imagesy($dummy_image_for_dimensions_check) ) { //portrait $overview_width = $max_overview_thumb_image_width; $overview_height = $max_overview_thumb_image_height; } else { //landscape $overview_width = $max_overview_thumb_image_height; $overview_height = $max_overview_thumb_image_width; } $resized_image_data = $this->_force_max_image_dimensions($img_data['png_contents'], $overview_width, $overview_height ); // $resized_image_data = $this->_force_max_image_dimensions($img_data['png_contents'], $max_overview_thumb_image_width, $max_overview_thumb_image_height ); // Now use the resized image (if it was successfully resized), or the source one if it was not (successfully) resized. //$image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $img_data['png_contents']; // To stay on the safe side, we only use the thumbnails if we are sure the resizing went successfully as we otherwise may end up with a very // large original drawing that is undesirable here. if (!empty($resized_image_data['png_contents'])) { $this->overview_thumbs_data_set["$overview_bescheiden_id"][] = $resized_image_data['png_contents']; // Add the image to the global too images. Pass a dummy path name, as we pass the data directly. //$this->_add_image($section_images, 'dummy_path', $identifier, $image_data, 'png', 'auto', 'auto', 'data'); $identifier = "overview_thumb_{$overview_bescheiden_id}"; $this->_add_image($this->document_images, 'dummy_path', $identifier, $resized_image_data['png_contents'], 'png', 'auto', 'auto', 'data'); } } } /* if (!empty($vraag_annotations) || !empty($this->overview_data_set)) { //echo "+++ aap +++<br />\n"; //dump($aap); echo "+++ aap->annotation_data_set +++<br />\n"; d($aap->annotation_data_set); echo "+++ vraag_annotations +++<br />\n"; d($vraag_annotations); echo "+++ aap->overview_data_set +++<br />\n"; d($aap->overview_data_set); echo "+++ this->overview_data_set +++<br />\n"; d($this->overview_data_set); exit; } * */ //echo "Vragen: " . sizeof($vragen) . "<br />"; $onderwerp_cnt = 0; $vraag_cnt = 0; $vragen_fotosvideos = array(); $vragen_fotosvideos_archive = array(); $this->show_revisions = (@array_key_exists( 'show-revisions', $this->get_filter( 'onderdeel' ))); foreach ($this->deelplan_onderwerpen[$deelplan->id][$scope_id] as $onderwerp_id => $onderwerp) { // As we now always start hoofdgroepen in a new table on new page, for 'VIIA' the starting of // the new table etc. has been moved so it takes place when determining a new hoofdgroep ($show_current_hoofdgroep_header) if ($this->overriden_data_context != 'viia') { // Initialise the images set and the table data rows sets that are used for this section //$section_images = array(); $table_rows = array(); // Use the checklist name as a level 2 header (preceded by the chapter-sequence number. $section_header = $this->_create_section_header(3, "{$this->section_number}.{$scope_cnt}.{$onderwerp_cnt} " . $onderwerp['naam']); //If the user has chosen to display revisie history, include the Revisie column if ($this->show_revisions ){ // Add a section with a table that is created using the various helpers $header_data = array('Status', 'Revisie', 'Waardeoordeel', 'Toelichting', '#', 'Snapshot', "Foto's"); $header_options = $this -> _generate_custom_cell_options (array('78','66','260','253','44','182','182'), 'font-size:12pt;'); $num_cols = 7; } else { //If not, combine the first two columns $header_data = array('Status', 'Waardeoordeel', 'Toelichting', '#', 'Snapshot', "Foto's"); // Add a section with a table that is created using the various helpers $header_options = $this -> _generate_custom_cell_options (array('144','260','253','44','182','182'), 'font-size:12pt;'); $num_cols = 6; } $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); } // if ($this->overriden_data_context != 'viia') // Each "onderwerp" starts on a new page, so make sure to initialise the boolean that keeps track of whether the previous question has annotations // is set to 'false'. $previous_question_has_annotations = false; //$table_headers = $this->_generate_table_header_row_fragment($header_data, array()); foreach ($onderwerp['vragen'] as $vraag) { ++$onderwerp_cnt; // Perform the necessary actions if this question has revisions. $vraag_has_revisions = (isset( $this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id] )); if ($vraag_has_revisions) { // Get the current revisions, do so in descending order. $cur_vraag_revisions = array_reverse($this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id]); // Set the current revision number to be 1 higher than the amount of revisions in the history. $revisie_nr_str = sizeof($cur_vraag_revisions) + 1; } else { // Set the current revision number to 1. At present this is not shown but this way it is at least properly set if it should be needed // for something anyway. $cur_vraag_revisions = array(); $revisie_nr_str = '1'; } // kijk of de status(=waardeoordeel) van deze vraag getoond mag worden if (!$this->_vraag_weergeven( $deelplan->id, $vraag )) { continue; } $vraag->toelichting = str_replace( '[GERELATEERDE BEVINDING]', '', str_replace( '[TEKSTBALLON]', '', $vraag->toelichting ) ); // zijn er uploads? $cur_vraag_id = $vraag->id; if (!array_key_exists($cur_vraag_id, $vragen_fotosvideos)) { $vragen_fotosvideos["$cur_vraag_id"] = array(); } $fotosvideos_html = ''; if (isset( $this->deelplan_uploads[$deelplan->id][$vraag->id] )) { foreach ($this->deelplan_uploads[$deelplan->id][$vraag->id] as $q => $upload) { // Define the identifier $identifier = "deelplan_upload_" . $upload->id; // Resize the image if necessary // TODO: if the image is very small and if it's a JPEG the image will not get converted to PNG, add in a 'force' option to the resize // call!!! //$resized_image_data = $this->_force_max_image_dimensions($img_data['png_contents'], $max_snapshot_image_width, $max_snapshot_image_height); //$resized_image_data = $this->_force_max_image_dimensions($upload->get_data()->data, $max_photo_image_width, $max_photo_image_height); $resized_image_data = $this->_force_max_image_dimensions($upload->get_data(), $max_photo_image_width, $max_photo_image_height); // Now use the resized image (if it was successfully resized), or the source one if it was not (successfully) resized. //$image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $img_data['png_contents']; //$image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $upload->get_data()->data; $image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $upload->get_data(); // Add the image to the section images. Pass a dummy path name, as we pass the data directly. //$this->_add_image($section_images, 'dummy_path', $identifier, $cur_overview_data['png_contents'], 'png', 'auto', 'auto', 'data'); $this->_add_image($section_images, 'dummy_path', $identifier, $image_data, 'png', 'auto', 'auto', 'data'); // Store each fragment individually, bound to the filename (this is our link back to any and all associated annotations). $cur_vraag_photo_name = $upload->filename; $fotosvideos_html_fragment = "<p>[IMG:{$identifier}]</p>"; $path_parts = pathinfo($cur_vraag_photo_name); $cur_vraag_photo_name_without_extension = $path_parts['filename']; $vragen_fotosvideos["$cur_vraag_id"]["$cur_vraag_photo_name_without_extension"] = $fotosvideos_html_fragment; // Add the fragment to the current question's total string too, this is handy for the situation where the pictures are not associated // to snapshots, and hence can be shown in one go, without being filtered out. $fotosvideos_html .= $fotosvideos_html_fragment; } } // Increment the questions counter; $vraag_cnt++; // New hoofdgroep? If so show the name and priority level of it $show_current_hoofdgroep_header = ($current_hoofdgroep_id != $vraag->hoofdgroep_id); //if ($current_hoofdgroep_id != $vraag->hoofdgroep_id) if ($show_current_hoofdgroep_header) { //for VIIA, add the hoofdgroep images if ($this->overriden_data_context == 'viia') { //reset the section header or it will repeat it with each new hoofdgroep. //If the user has chosen to display revisie history, include the Revisie column if ($this->show_revisions ){ // Add a section with a table that is created using the various helpers $header_data = array('Status', 'Revisie', 'Waardeoordeel', 'Toelichting', '#', 'Snapshot', "Foto's"); $header_options = $this -> _generate_custom_cell_options (array('78','66','260','253','44','182','182'), 'font-size:12pt;'); $num_cols = 7; } else { //If not, combine the first two columns $header_data = array('Status', 'Waardeoordeel', 'Toelichting', '#', 'Snapshot', "Foto's"); // Add a section with a table that is created using the various helpers $header_options = $this -> _generate_custom_cell_options (array('78','260','319','44','182','182'), 'font-size:12pt;'); $num_cols = 6; } $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); $hoofdgroep_nr = 0; if ($current_hoofdgroep_id) { $hoofdgroep_nr++; $hoofdgroep_page_break = ($hoofdgroep_nr > 1) ? 'before' : 'none'; // First check if the current 'hoofdgroep' has annotations for which bescheiden thumbs need to be added. If so, do so here. // Careful! This array is only filled if the above loop did so, which means that in theory it is possible to reach this point without // it being defined. Therefore, check if it exists and is not empty first. // Close the hoofdgroep table //reset the section header or it will repeat it with each new hoofdgroep. $section_header = null; // First create the table fragment using the header row and the actual table data rows $table_fragment=$this->check_empty_table($table_headers, $table_rows); // Now combine everything into the section. $style_fragment = $this->_generate_style_definitions_block(array("table_bevindingen")); $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal', $hoofdgroep_page_break, 'A4', 'landscape', 'html', false, true, false); // Initialise the images set and the table data rows sets that are used for the new section // $section_images = array(); $table_rows = array(); if (!empty($cur_hoofdgroep_annotations_bescheiden_ids)) { // Add additional rows with the thumbnails of the overview images, first add one row with a header and then another row with the // images.. Use the colspan set earlier $cell_options = array(array('colspan' => $num_cols)); // Add a header in a single row. $section_header = $this->_create_section_header(3, "De bij deze hoofdgroep getoonde annotaties hebben betrekking op de volgende bescheiden. Een grotere versie hiervan is te vinden in de 'Annotaties' bijlage."); // Add the overview images. Does not work well in a table, so use paragraphs instead. $html_fragment = ''; foreach ($cur_hoofdgroep_annotations_bescheiden_ids as $cur_hoofdgroep_annotations_bescheiden_id => $orientation) { $html_fragment = $this->_generate_style_definitions_block(array('p')) . "<p>[IMG:overview_thumb_{$cur_hoofdgroep_annotations_bescheiden_id}_$current_hoofdgroep_id]</p>"; // When we have created the overview image, add it as a section to the document, // using the appropriate orientation $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', $orientation); $section_header = ''; //no need to repeat the header text with every image } //reset annotation array $cur_hoofdgroep_annotations_bescheiden_ids = array(); } } } // if ($this->overriden_data_context == 'viia') // set new hoofdgroep $current_hoofdgroep_id = $vraag->hoofdgroep_id; // get prio for this hoofdgroep $prio = null; if ($this->deelplan_prioriteiten[$deelplan->id][$scope_id]) $prio = $this->deelplan_prioriteiten[$deelplan->id][$scope_id][$vraag->checklist_id]->get_waarde( $current_hoofdgroep_id, $vraag->hoofdthema_id, $deelplan->id ); if (!$prio) $prio = 'zeer_hoog'; switch ($prio) { case 'zeer_laag': $prio_niveau = 'S'; break; case 'laag': $prio_niveau = '1'; break; case 'gemiddeld': $prio_niveau = '2'; break; case 'hoog': $prio_niveau = '3'; break; case 'zeer_hoog': $prio_niveau = '4'; break; default: $prio_niveau = '?'; break; } // Add the hoofdgroep to the table //Added background-color none as style to the text to remedy a bug in PHPDocX $cell_data = array('<span style="background-color:none"><b>'.$vraag->hoofdgroep_naam .' ['.$prio_niveau.']</b></span>'); $cell_options = array(array('colspan' => $num_cols)); $row_options = array('style' => 'background-color:#4f81bd; font-size:12pt;'); $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options, $row_options ); } //echo "Vraag: " . $vraag->tekst . "<br />"; // Get the used grondslagen names $grondslagen = array(); if (isset( $this->checklistgroep_grondslagen[ $scope['checklist_groep_id'] ][ $vraag->id ] )) { foreach ($this->checklistgroep_grondslagen[ $scope['checklist_groep_id'] ][ $vraag->id ] as $grondslag) { $grondslag_artikel = $grondslag->grondslag . ' ' . $grondslag->artikel; $grondslagen[] = $grondslag_artikel; // Store the used grondslagen to the global set too, so we can easily create appendix 2 later if (!array_key_exists($grondslag_artikel, $this->used_grondslagen)) { $this->used_grondslagen["$grondslag_artikel"] = $grondslag; } } } $vraag_grondslagen_artikelen_str = (empty($grondslagen)) ? '' : ' [' . implode(', ', $grondslagen) . ']'; //d($grondslagen); // Add the vraag itself to the table //$cell_data = array('1. Bouwvergunning aanwezig [BB art. 1.23]'); $cell_data = array('<span style="background-color:none"><b>'.$vraag_cnt.'. '.$vraag->tekst.$vraag_grondslagen_artikelen_str.'</b></span>'); $cell_options = array(array('colspan' => $num_cols)); $row_options = array('style' => 'background-color:#dbe5f1;'); $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options, $row_options); // Then, continue to process the rest of the data belonging to this 'vraag', adding it to the table as required as we go along. $cell_options = array(); // It seems we can use the "toelichtingsgeschiedenis" for determining whether multiple rows need to be created or not. $vraag_has_revisions = (isset( $this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id] )); //d($vraag_cnt); //d($vraag_has_revisions); //if (isset( $this->deelplan_toelichtinggeschiedenis[$deelplan->id][$vraag->id] )) // Loop over the history, or over the single row, constructing our dataset as needed // Note: it seems the history is not quite set up as initially expected, so no longer loop over row amounts, but rather, add the revisions // (if any) in reverse order after adding the current revision. $rows_to_show = 1; for ($row_idx = 0 ; $row_idx < $rows_to_show ; $row_idx++) { //Only display revision number in the first row if($row_idx > 0) $revisie_nr_str = ''; // First initialise (and fill) the data that we need regardless of whether the current question has annotations or not. $wo_icon_identifier_str = $waardeoordeel_str = $toelichting_str = $nr_str = $snapshot_str = $fotos_str = ''; // Construct the content for the 'status' (and possibly 'revisie') column(s) $wo_kleur = $vraag->get_waardeoordeel_kleur( true ); //d($wo_kleur); /* switch ($wo_kleur) { case 'groen': $wo_icon_identifier = 'status-voldoet'; break; case 'oranje': $wo_icon_identifier = 'status-in_bewerking'; break; case 'rood': $wo_icon_identifier = 'status-voldoet_niet'; break; default: case 'in_bewerking': $wo_icon_identifier = 'status-in_bewerking'; } * */ switch ($wo_kleur) { case 'groen': $wo_icon_identifier = 'status-groen'; break; case 'oranje': $wo_icon_identifier = 'status-geel'; break; case 'rood': $wo_icon_identifier = ($this->overriden_data_context == 'viia') ? 'status-rood-viia' : 'status-rood'; break; default: case 'in_bewerking': $wo_icon_identifier = 'status-geel'; } $wo_icon_identifier_str = "[IMG:{$wo_icon_identifier}]"; //d($wo_icon_identifier_str); // Construct the content for the 'Waardeoordeel' column //$waardeoordeel_str = $this->_status_to_description( $vraag ); //$waardeoordeel_str = $this->_status_to_description( $vraag ) . ' (' . $wo_kleur . ')'; // If VIIA, don't include the date of the waardeoordel if ($this->overriden_data_context == 'viia') { $waardeoordeel_str = $this->_status_to_description( $vraag ); } else { $waardeoordeel_str = $this->_status_to_description( $vraag ) . '<br />' . date('d-m-Y', strtotime( $vraag->last_updated_at )); } // Construct the content for the 'Toelichting' column //$toelichting_str = '...'; $toelichting_str = $this->hss( $vraag->toelichting ); // Construct the content for the 'Fotos' column $fotos_str = $fotosvideos_html; // As an inner loop, show each snapshot in a row of its own $cur_vraag_annotations = (array_key_exists($vraag->id, $vraag_annotations)) ? $vraag_annotations[$vraag->id] : array(); // Show either 1 row (if there are no annotations, or one row per annotation otherwise. if (empty($cur_vraag_annotations)) { //$cell_data = array($vraag_cnt.'. '.$vraag->tekst.$vraag_grondslagen_artikelen_str); if ($this->show_revisions ) { if (!$vraag_has_revisions) $revisie_nr_str = 1; $cell_data = array($wo_icon_identifier_str, $revisie_nr_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } else { $cell_data = array($wo_icon_identifier_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } // Combine the various parts that together constitute the table row data and store them $cell_options = array(); $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options); } else { // Loop over the images, making sure to always show at least one row $cur_vraag_has_photos = false; //$cur_vraag_annotations[$cur_ann_idx]['annotation_photoid'] //if(!empty($cur_vraag_annotations)){ //for ($i=0;$i<sizeof()) //} if (!empty($vragen_fotosvideos["$cur_vraag_id"])) { // First reset all cell values // Add the pictures $k=0; $annotation_pic_name=array(); for($i=0;$i<sizeof($cur_vraag_annotations);$i++){ $annotation_pic_name[]=$cur_vraag_annotations[$i]['annotation_photoid']; } foreach ($vragen_fotosvideos["$cur_vraag_id"] as $pic_name => $pic_data_str) { $fotos_str = $pic_data_str; $key = array_search($pic_name, $annotation_pic_name) !==false; if($k!=0) $wo_icon_identifier_str = $revisie_nr_str=$waardeoordeel_str=$toelichting_str=$nr_str=''; // Output the pictures in a separate row // Only include the picture row if they are the first one (to include the status etc.) or if they are not also included as annotation if(!$key || $k == 0){ //If the first row contains a pic also used as annotation, remove the pic if ($k == 0 && $key) { $fotos_str = ''; } //Only include revision number on the first row if ($this->show_revisions) { if (!$vraag_has_revisions) $revisie_nr_str = 1; $cell_data = array($wo_icon_identifier_str, $revisie_nr_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } else { $cell_data = array($wo_icon_identifier_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options); $k++; } } } else { if ($this->show_revisions) { $cell_data = array($wo_icon_identifier_str, '', $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } else { $cell_data = array($wo_icon_identifier_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options); } // if (!empty($vragen_fotosvideos["$cur_vraag_id"])) for ($cur_ann_idx = 0 ; $cur_ann_idx < sizeof($cur_vraag_annotations) ; $cur_ann_idx++) { // Register the ID of the bescheiden on which the annotation was made. For 'VIIA' users this is used for adding a small // overview image after each hoofdgroep. $cur_vraag_annotations_bescheiden_id = $cur_vraag_annotations[$cur_ann_idx]['bescheiden_id']; if (!isset($cur_hoofdgroep_annotations_bescheiden_ids)) { $cur_hoofdgroep_annotations_bescheiden_ids = array(); } if (!array_key_exists($cur_vraag_annotations_bescheiden_id, $cur_hoofdgroep_annotations_bescheiden_ids)) { $cur_hoofdgroep_annotations_bescheiden_ids["$cur_vraag_annotations_bescheiden_id"] = $cur_vraag_annotations[$cur_ann_idx]['bescheiden_orientation']; } // If the current question has annotations we always need to reset the 'fotos' string first, and only fill it with the individual // pictures per annotation (if any) and handle any and all not show pictures afterwards. $fotos_str = ''; // Do not repeat the same values in each of the columns. // Note: make particularly sure to reset the fotos_str as otherwise the subsequent code will incorrectly use rowspans! $wo_icon_identifier_str = $waardeoordeel_str = $toelichting_str = ''; // Construct the content for the 'toelichting' column if (!empty($cur_vraag_annotations[$cur_ann_idx]['annotation_text'])) { // prio 7: this is not required (august 2014) $toelichting_str = "<p>Annotatie tekst:<br />" . $cur_vraag_annotations[$cur_ann_idx]['annotation_text'].'</p>'; } if (!empty($cur_vraag_annotations[$cur_ann_idx]['annotation_photoid'])) { $cur_photoid = $cur_vraag_annotations[$cur_ann_idx]['annotation_photoid']; //d($cur_photoid); //d(array_keys($vragen_fotosvideos["$cur_vraag_id"])); $toelichting_str .= "<p>Annotatie foto:\n" . $cur_photoid.'</p>'; if (array_key_exists($cur_photoid, $vragen_fotosvideos["$cur_vraag_id"])) { // Make sure the picture gets shown in this row $fotos_str = $vragen_fotosvideos["$cur_vraag_id"]["$cur_photoid"]; // Also, remove the picture from the set of all pictures, so it will not get shown again in the final row with pictures. // MJ 01-07-2015: rather than removing the photo's,move it to a different aray for now. That way pictures can be reused if necessary // Temporary workaround because of javascript issues (layers being duplicated and removed) $vragen_fotosvideos_archive["$cur_vraag_id"]["$cur_photoid"]=$fotos_str; unset($vragen_fotosvideos["$cur_vraag_id"]["$cur_photoid"]); } elseif (array_key_exists($cur_photoid, $vragen_fotosvideos_archive["$cur_vraag_id"])) { $fotos_str = $vragen_fotosvideos_archive["$cur_vraag_id"]["$cur_photoid"]; } } // Construct the content for the '#' column $nr_str = $cur_vraag_annotations[$cur_ann_idx]['annotation_number']; // Construct the content for the 'Snapshot' column $identifier = $cur_vraag_annotations[$cur_ann_idx]['identifier']; $snapshot_str = "[IMG:{$identifier}]"; // If photos exist for this question, make sure to adapt the last cell such that it uses a rowspan in the last cell // of (only!) the first row. if (!empty($fotos_str)) { // Note: the rowspan mechanism has been disabled for now as the output that resulted from it was deemed to be undesirable. /* // For the first row of a question with multiple annotations and at least 1 photo, signal in the last cell that // a rowspan needs to be used that spans ALL of the rows of the current question. $last_cell_options_cell_idx = (sizeof($cell_options) - 1); $cell_options[$last_cell_options_cell_idx]['rowspan'] = sizeof($cur_vraag_annotations); * */ // Signal that the current question has photos, this is used further ahead for determining whether subsequent rows need // to have 5 or 6 cells. $cur_vraag_has_photos = true; } //$cell_data = array($vraag_cnt.'. '.$vraag->tekst.$vraag_grondslagen_artikelen_str); // Add the right amount of cells (either 5 or 6). Needed due to the rowspan that is used when images are present. // Note: for questions with revisions, we first add the latest revision. //if ($cur_vraag_has_photos && ($cur_ann_idx > 0) ) if (0) { // If the current question has photos, they were shown in the first cell, using a rowspan. Therefore, we must // then NOT output the last data cell as otherwise the table WILL get messed up. if ($vraag_has_revisions) { $cell_data = array($wo_icon_identifier_str, $revisie_nr_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str); } else { $cell_data = array($wo_icon_identifier_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str); } } else { // Either this question has no photos or we are in the first row, so we DO ouput the 'photos' cell too. if ($this->show_revisions) { if(!$vraag_has_revisions) $revisie_nr_str; $cell_data = array($wo_icon_identifier_str, $revisie_nr_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } else { $cell_data = array("", "", $toelichting_str, $nr_str, $snapshot_str, $fotos_str); } } // Combine the various parts that together constitute the table row data and store them $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options); } // for ($cur_ann_idx = 0 ; $cur_ann_idx < sizeof($cur_vraag_annotations) ; $cur_ann_idx++) // If there are still remaining photos, output them here, in a single row. //d($vragen_fotosvideos["$cur_vraag_id"]); } // else of clause: if (empty($cur_vraag_annotations)) } // for ($row_idx = 0 ; $row_idx < $rows_to_show ; $row_idx++) // In case revisions exist, add their data too as separate table rows if ($this->show_revisions) { // Output the revisions in descending order. foreach ($cur_vraag_revisions as $cur_vraag_revision) { // Re-initialise (and fill) the data that we need. $wo_icon_identifier_str = $waardeoordeel_str = $toelichting_str = $nr_str = $snapshot_str = $fotos_str = ''; // Set the new value for the 'Status' column. // public function get_waardeoordeel_kleur( $zet_standaard /* bool */, $use_status=null ) //$wo_kleur = $vraag->get_waardeoordeel_kleur(true, $cur_vraag_revision->status); //$wo_kleur = ($cur_vraag_revision->status == 'in_bewerking') ? $cur_vraag_revision->status : $vraag->get_waardeoordeel_kleur(true, $cur_vraag_revision->status); $wo_kleur = ($cur_vraag_revision->status == 'in_bewerking') ? 'oranje' : $vraag->get_waardeoordeel_kleur(true, $cur_vraag_revision->status); //switch ($cur_vraag_revision->status) switch ($wo_kleur) { case 'groen': $wo_icon_identifier = 'status-groen'; break; case 'oranje': $wo_icon_identifier = 'status-geel'; break; case 'rood': $wo_icon_identifier = ($this->overriden_data_context == 'viia') ? 'status-rood-viia' : 'status-rood'; break; default: case 'in_bewerking': $wo_icon_identifier = 'status-geel'; } $wo_icon_identifier_str = "[IMG:{$wo_icon_identifier}]"; // Set the new value for the 'Revisie' column. $revisie_nr_str--; // Set the new value for the 'Waardeoordeel' column. // public function get_waardeoordeel( $zet_standaard /* bool */, $use_status=null ) //$waardeoordeel_str = $cur_vraag_revision->status . '<br />' . $vraag->get_waardeoordeel(true, $cur_vraag_revision->status) . '<br />' . date('d-m-Y', strtotime( $cur_vraag_revision->datum )); $waardeoordeel_str = $vraag->get_waardeoordeel(true, $cur_vraag_revision->status) . " ({$wo_kleur})<br />" . date('d-m-Y', strtotime( $cur_vraag_revision->datum )); //$waardeoordeel_str = $cur_vraag_revision->status . $vraag->get_waardeoordeel(true, $cur_vraag_revision->status) . "<br />" . date('d-m-Y', strtotime( $cur_vraag_revision->datum )); // Set the new value for the 'Toelichting' column. $toelichting_str = $cur_vraag_revision->toelichting; // Set the new value for the 'Nr' column. //$nr_str = ''; // Set the new value for the 'Snapshot' column. //$snapshot_str = ''; // Set the new value for the 'Foto's' column. //$fotos_str = ''; // Set the raw cell data for this revision. $cell_data = array($wo_icon_identifier_str, $revisie_nr_str, $waardeoordeel_str, $toelichting_str, $nr_str, $snapshot_str, $fotos_str); // Combine the various parts that together constitute the table row data and store them $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $cell_options); } // foreach ($cur_vraag_revisions as $cur_vraag_revision) } //if ($this->show_revisions) } // foreach ($onderwerp['vragen'] as $vraag) // As we now always start hoofdgroepen in a new table on new page for 'VIIA', we already added these individual tables in the loop right above, // instead of doing it only once here for generating a big single table containing all the questions as was previously the case. For non-VIIA users we use // the single big table. if ($this->overriden_data_context != 'viia') { // When we have created the compound section data set for the current checklist, we combine everything and add it as a section // to the document. // First create the table fragment using the header row and the actual table data rows $table_fragment=$this->check_empty_table($table_headers, $table_rows); // Define any and all styles that are used for the tables over here //$style_fragment = $this->_generate_style_definitions_block(array('table_bevindingen')); $style_fragment = $this->_generate_style_definitions_block(array("table_bevindingen")); // Now combine everything into the section. $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal', 'none', 'A4', 'landscape', 'html', false, true, false); } // if ($this->overriden_data_context != 'viia') } // In case of VIIA, the table is written to the document when a new hoofdgroep starts // Therefore, there will be content left to be written at the end of the generation of the bevindingen tabel. if ($this->overriden_data_context == 'viia') { // First create the table fragment using the header row and the actual table data rows $table_fragment=$this->check_empty_table($table_headers, $table_rows); // Define any and all styles that are used for the tables over here //$style_fragment = $this->_generate_style_definitions_block(array('table_bevindingen')); $style_fragment = $this->_generate_style_definitions_block(array("table_bevindingen")); // Now combine everything into the section. $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'landscape', 'html', false, true, false); // Clean up the table content $table_fragment = $table_rows = ''; if (!empty($cur_hoofdgroep_annotations_bescheiden_ids)) { // Add additional rows with the thumbnails of the overview images, first add one row with a header and then another row with the // images.. Use the colspan set earlier $cell_options = array(array('colspan' => $num_cols)); // Add a header in a single row. $section_header = $this->_create_section_header(3, "De bij deze hoofdgroep getoonde annotaties hebben betrekking op de volgende bescheiden. Een grotere versie hiervan is te vinden in de 'Annotaties' bijlage."); // Add the overview images. Does not work well in a table, so use paragraphs instead. $html_fragment = ''; foreach ($cur_hoofdgroep_annotations_bescheiden_ids as $cur_hoofdgroep_annotations_bescheiden_id => $orientation) { $html_fragment = $this->_generate_style_definitions_block(array('p')) . "<p>[IMG:overview_thumb_{$cur_hoofdgroep_annotations_bescheiden_id}_$current_hoofdgroep_id]</p>"; // When we have created the overview image, add it as a section to the document, // using the appropriate orientation $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', $orientation); $section_header = ''; //no need to repeat the header text with every image } //reset all variables $cur_hoofdgroep_annotations_bescheiden_ids = array(); } } } // foreach ($deelplan->get_checklisten() as $i => $checklist) } // foreach ($this->deelplannen as $j => $deelplan) } else { $section_header = $this->_create_section_header(1, ++$this->section_number.'. Bevindingen'); $this->_add_section(tg('geengegevens'), $section_header, array(), 'normal', 'before', 'A4', 'landscape'); } } private function _generate_opdrachten() { //if (!@array_key_exists( 'dossiergegevens', $this->get_filter( 'onderdeel' ))) // return; $this->_set_progress( 'Opdrachten...' ); $dos = $this->get_dossier(); //$html_fragment = $this->_generate_style_definitions_block(array('p')) . // '<p>Dit onderdeel wordt momenteel nog uitgewerkt en zal later toegevoegd worden.</p>'; $html_fragment = ' '; // Add a section for the main header of this chapter // Apply the required overrides for Arbode and Riegitaal. if ( ($this->overriden_data_context == 'arbode') || ($this->overriden_data_context == 'riegitaal') ) { // Arbode report settings. $section_title = 'Plan van aanpak'; $header_data = array('Vraag', 'Actie', 'Gereed datum', 'Verantwoordelijke', 'Status', 'Locatie', 'Foto'); } else { // Default report settings. $section_title = 'Opdrachten'; $header_data = array('Vraag', 'Opdracht', 'Gereed datum', 'Betrokkene', 'Status', 'Locatie', 'Foto'); } //$section_header = $this->_create_section_header(1, '5. Opdrachten'); // $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before', 'A4', 'portrait', 'html', false, false); if(!empty($this->deelplannen)) { $section_header = $this->_create_section_header(1, ++$this->section_number.". {$section_title}"); $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before', 'A4', 'landscape'); // $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before', 'A4', 'portrait', 'html', false, false); foreach ($this->deelplannen as $j => $deelplan) { // Now iterate over the checklists, creating a section per checklist $onderwerp_cnt = 0; foreach ($this->deelplan_scopes[$deelplan->id] as $i => $scope) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($scope['checklist_id'], $this->deelplan_checklists)) { continue; } $scope_id = $scope['scope_id']; $onderwerp_cnt++; // Initialise the images set and the table data rows sets that are used for this section $section_images = array(); $table_rows = array(); // We are outputting a 'straightforward' table, that requires no special (cell) options. $cell_options = array(); // Get the deelplanopdrachten $deelplan_opdrachten = $this->_CI->deelplanopdracht->get_by_deelplan_checklistgroep_checklist( $deelplan->id, $scope['checklist_groep_id'], @ $scope['checklist_id'] ); // Store the 'deelplanopdrachten' per 'vraag' $vraag_opdrachten = array(); foreach ($deelplan_opdrachten as $deelplan_opdracht) { $cur_vraag_id = $deelplan_opdracht->vraag_id; if (!array_key_exists($cur_vraag_id, $vraag_opdrachten)) { $vraag_opdrachten["$cur_vraag_id"] = array(); } $vraag_opdrachten["$cur_vraag_id"][] = $deelplan_opdracht; } // Use the checklist name as a level 2 header (preceded by the chapter-sequence number. $section_header = $this->_create_section_header(2, "{$this->section_number}.{$onderwerp_cnt} " . $scope['naam']); // Add a section with a table that is created using the various helpers $table_headers = $this->_generate_table_header_row_fragment($header_data, array()); //echo "Vragen: " . sizeof($vragen) . "<br />"; $vraag_cnt = 0; foreach ($this->deelplan_onderwerpen[$deelplan->id][$scope_id] as $onderwerp_id => $onderwerp) { foreach ($onderwerp['vragen'] as $vraag) { // kijk of de status(=waardeoordeel) van deze vraag getoond mag worden if (!$this->_vraag_weergeven( $deelplan->id, $vraag )) continue; // Increment the questions counter; $vraag_cnt++; // Only add the vragen that have opdrachten; one opdracht per row $cur_vraag_id = $vraag->id; if (array_key_exists($cur_vraag_id, $vraag_opdrachten)) { // Get the opdrachten for this vraag and add them, one opdracht per row $cur_vraag_opdrachten = $vraag_opdrachten["$cur_vraag_id"]; foreach ($cur_vraag_opdrachten as $cur_vraag_opdracht) { // Make sure all image data is available $cur_vraag_opdracht->load_image_data(); //d($cur_vraag_opdracht); // Add the data to the table $vraag_str = $opdracht_str = $datum_str = $betrokkene_str = $status_str = $locatie_str = $foto_str = ''; // Fill in the various parts that comprise an 'opdracht' $vraag_str = $vraag_cnt.'. '.$this->hss($vraag->tekst); $opdracht_str = $this->hss($cur_vraag_opdracht->opdracht_omschrijving); $datum_str = date( 'd-m-Y', strtotime($cur_vraag_opdracht->gereed_datum) ); $subject = $this->_CI->dossiersubject->get($cur_vraag_opdracht->dossier_subject_id); $betrokkene_str = $this->hss($subject->naam); $status_str = $this->hss($cur_vraag_opdracht->status); // Locatie can be made out of multiple images for historical reasons, loop over them if (!is_null( $cur_vraag_opdracht->snapshot_afbeelding )) { $identifier = 'opdracht_snapshot_' . $cur_vraag_opdracht->id . '_snapshot'; $this->_add_image($section_images, 'dummy_path', $identifier, $cur_vraag_opdracht->snapshot_afbeelding, 'png', '200', '200', 'data'); $locatie_str = "[IMG:{$identifier}]"; } // Add photo's if added after February 2016 (in that case multilple images can be stored separately). // Else use the photo from before Februari 2016 $deelplanuploads = array(); $deelplanuploads = $cur_vraag_opdracht->get_deelplan_uploads(); // Check to see if there is a deelplanupload from the old days (directly in the opdracht if ($cur_vraag_opdracht->deelplan_upload_id) { $deelplanuploads[] = $this->_CI->deelplanupload->get($cur_vraag_opdracht->deelplan_upload_id); } $foto_str = ''; $firstrow = true; if (sizeof($deelplanuploads) > 0) { foreach ($deelplanuploads as $deelplanupload) { // add image $uploaddata = $deelplanupload->get_data(); $identifier = 'opdracht_foto_' . $cur_vraag_opdracht->id . '_' . $deelplanupload->id; try { // get image size $im = new Imagick(); //$im->readImageBlob($uploaddata->data); $im->readImageBlob($uploaddata); $w = $im->getImageWidth(); $h = $im->getImageHeight(); $im->destroy(); unset($im); // calc new size that fits within maxw/maxh, keep aspect ratio $maxw = 200; $maxh = 150; if ($w > $maxw || $h > $maxh) { $ratio = $w / $h; $neww = $maxw; $newh = $neww / $ratio; if ($newh > $maxh) { $newh = $maxh; $neww = $maxh * $ratio; } $w = round($neww); $h = round($newh); } } catch (Exception $e) { $w = $h = 200; } switch ($deelplanupload->mimetype) { case 'image/jpeg': case 'image/jpg': $type = 'jpg'; break; case 'image/png': default: // eeks! $type = 'png'; break; } $this->_add_image($section_images, 'dummy_path', $identifier, $uploaddata, $type, $w, $h, 'data'); $foto_str = "[IMG:{$identifier}]"; // memory cleanup unset( $uploaddata ); // Set the raw cells (only photo if first row was already added) if ($firstrow) { $cell_data = array($vraag_str, $opdracht_str, $datum_str, $betrokkene_str, $status_str, $locatie_str, $foto_str); } else { $cell_data = array('', '', '', '', '', '', $foto_str); } // Combine the various parts that together constitute the table row data and store them $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data); // Memory cleanup $cur_vraag_opdracht->unload_image_data(); $firstrow = false; //set first variable to false to make sure next rows are clean } // foreach ($deelplanuploads as $deelplanupload) } else { // If no deelplanuploads were found, add the opdracht $cell_data = array($vraag_str, $opdracht_str, $datum_str, $betrokkene_str, $status_str, $locatie_str, $foto_str); // Combine the various parts that together constitute the table row data and store them $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data); } } // foreach ($cur_vraag_opdrachten as $cur_vraag_opdracht) } // if (array_key_exists($cur_vraag_id, $vraag_opdrachten)) } } // exit; // First create the table fragment using the header row and the actual table data rows //$table_fragment = _generate_table_fragment($headers = '', $rows = array(), $options = array()); $table_fragment=$this->check_empty_table($table_headers, $table_rows); // Define any and all styles that are used for the tables over here $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); // Now combine everything into the section. $this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal', 'none', 'A4', 'landscape'); } // foreach ($deelplan->get_checklisten() as $i => $checklist) } // foreach ($this->deelplannen as $j => $deelplan) } else { $section_header = $this->_create_section_header(1, ++$this->section_number.". {$section_title}"); $this->_add_section(tg('geengegevens'), $section_header, array(), 'normal', 'before', 'A4', 'landscape'); } } private function _generate_foto_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-fotos', $this->get_filter( 'onderdeel' ))) return; $addendum_title = 'Bijlage '.romanic_number(++$this->addendum_number)." Foto's" ; //$this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Annotaties...' ); $this->_set_progress( $addendum_title . '...' ); // Add the images that are used in this section $section_images = array(); // Get the proper data (if any) for this appendix as a compound data set and add it (if any) as level 2 sections per checklist. //$compound_image_sections = $this->_output_uploads_list( 'foto/video', 2, 325, 240 ); $compound_image_sections = $this->_output_uploads_list( 'foto/video', 2, 234, 174 ); if (empty($compound_image_sections)) { $html_fragment = $this->_generate_style_definitions_block(array('p')) . "<p>Er zijn geen foto's om te tonen.</p>"; // Add a section for the main header of this chapter $section_header = $this->_create_section_header(1, $addendum_title); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'portrait'); } else { // Add a section for the main header of this chapter $html_fragment = ''; $section_header = $this->_create_section_header(1, $addendum_title); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'portrait'); // Now add each of the sections that are returned in the compound data set. foreach ($compound_image_sections as $compound_image_section) { $section_header = $this->_create_section_header(2, $compound_image_section['section_header']); $section_html_fragment = $this->_generate_style_definitions_block(array('table_100pct')) . $compound_image_section['section_html']; $this->_add_section($section_html_fragment, $section_header, $compound_image_section['section_images'], 'normal', 'none', 'A4', 'portrait'); } } } private function _generate_annotaties_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-annotaties', $this->get_filter( 'onderdeel' ))) return; $dossier = $this->get_dossier(); // The report options now also include the possibility to generate the annotations overviews as full-size downloads. // Check if that option is requested over here, and if so, generate them and make them available. $generate_annotaties_download = (@array_key_exists( 'annotaties_download', $this->get_filter( 'onderdeel' ))); $addendum_title = 'Bijlage '.romanic_number(++$this->addendum_number).' Annotaties'; //$this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Annotaties...' ); $this->_set_progress( $addendum_title . '...' ); // Add the images that are used in this section $section_images = array(); // Specify the paper size and orientation to use // When changing these values, also change them in annotatieafbeeldingsprocessorimpl.php!!! $usePaperSize = 'A4'; $usePaperSize = 'A3'; //$usePaperSize = 'A2'; //$usePaperSize = 'A1'; //$useOrientation = 'portrait'; $useOrientation = 'landscape'; // Determine the maximum width and height of each overview image. Base this on the combination of size and orientation. // First work out the sizes based on 'landscape' orientation, and 'A4' paper size. // MJ (21-04-2015): Changed the max. dimensions to fit at 100% // Calculation should be: desired nr of inches * pixels/in (in this case 96). $max_overview_image_width = 932; //1200; $max_overview_image_height = 579; //650; // Now see if we need to override the size. if ($usePaperSize == 'A3') { $max_overview_image_width = 1398; //1850; $max_overview_image_height = 900; //1100; } //MJ (24-04-2015) The below code is likely never used since Word can't handle a page size larger than A3. // If it is, dimensions need to be checked! else if ($usePaperSize == 'A2') { $max_overview_image_width = 1824; //2400; $max_overview_image_height = 988; //1300; } else if ($usePaperSize == 'A1') { $max_overview_image_width = 3600; $max_overview_image_height = 2000; //$max_overview_image_width = 1800; //$max_overview_image_height = 1000; } else if ($usePaperSize == 'A0') { $max_overview_image_width = 4800; $max_overview_image_height = 2600; } /* else if ($usePaperSize == 'custom') { $max_overview_image_width = 12000; $max_overview_image_height = 6500; } * */ // Then check the orientation. If we are requesting 'landscape' orientation, the above determined values are correct, but if // we choose 'portrait' orientation, we flip them. if ($useOrientation == 'portrait') { $dummy_swap_variable = $max_overview_image_width; $max_overview_image_width = $max_overview_image_height; $max_overview_image_height = $dummy_swap_variable; } // If we need to generate the annotated bescheiden as full-size downloads, open a zip file for them here $annotaties_download_successfully_created = false; if ($generate_annotaties_download) { // Create the ZIP archive $zip = new ZipArchive(); $filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "annotaties_full_size_{$dossier->id}.zip"; //$filename = sys_get_temp_dir() . "annotaties_full_size_{$dossier->id}.zip"; //d($filename); // If an older version exists with the same name, remove it first. if (file_exists($filename)) { unlink($filename); } // Now actually create the archive if ($zip->open($filename, ZipArchive::CREATE)===TRUE) { $annotaties_download_successfully_created = true; } } // if ($generate_annotaties_download) //$html_fragment = $this->_generate_style_definitions_block(array('p')) . // '<p>Dit onderdeel wordt momenteel nog uitgewerkt en zal later toegevoegd worden.</p>'; $html_fragment = $this->_generate_style_definitions_block(array('p')).''; // Now simply loop over all of the (previously) globally registered overview images, outputting references to them and registering the data for it too. // 26-3-2015: Note: the array is no longer numerically indexed, but by 'bescheiden_id' values, so the loop has been changed accordingly! //for ($overview_idx = 0 ; $overview_idx < sizeof($this->overview_data_set) ; $overview_idx++) foreach ($this->overview_data_set as $overview_bescheiden_id => $cur_overview_data) { // Extract the overview data //$cur_overview_data = $this->overview_data_set[$overview_idx]; //d($cur_overview_data); // Create an identifier for this image //$identifier = "overview_{$overview_idx}"; $identifier = "overview_{$overview_bescheiden_id}"; // Add the reference to the HTML fragment $html_fragment .= "<p>[IMG:{$identifier}]</p>"; // Resize the image if necessary $resized_image_data = $this->_force_max_image_dimensions($cur_overview_data['png_contents'], $max_overview_image_width, $max_overview_image_height); // Now use the resized image (if it was successfully resized), or the source one if it was not (successfully) resized. $image_data = (!empty($resized_image_data['png_contents'])) ? $resized_image_data['png_contents'] : $cur_overview_data['png_contents']; // Add the image to the section images. Pass a dummy path name, as we pass the data directly. //$this->_add_image($section_images, 'dummy_path', $identifier, $cur_overview_data['png_contents'], 'png', 'auto', 'auto', 'data'); $this->_add_image($section_images, 'dummy_path', $identifier, $image_data, 'png', 'auto', 'auto', 'data'); // Finally, if we need to generate the annotated bescheiden as full-size downloads, do so here if ($generate_annotaties_download && $annotaties_download_successfully_created) { // Get the name of the original 'bescheiden' and use that, with an added '.png' extension. $current_bescheiden = $this->_CI->dossierbescheiden->get($overview_bescheiden_id); $zip->addFromString($current_bescheiden->bestandsnaam.'.png', $cur_overview_data['png_contents']); } } // Finally, if we need to generate the annotated bescheiden as full-size downloads, do so here if ($generate_annotaties_download && $annotaties_download_successfully_created) { // Close the ZIP archive //echo "numfiles: " . $zip->numFiles . "\n"; //echo "status:" . $zip->status . "\n"; $zip->close(); //exit; } //exit; // Add a section for the main header of this chapter $section_header = $this->_create_section_header(1, $addendum_title); if(count($section_images)==0) $html_fragment=tg('geengegevens'); // $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'landscape'); $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', $usePaperSize, $useOrientation); // $this->_add_section($html_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'portrait', 'html', false, false); // $this->_output_uploads_list( 'foto/video', 2, 325, 240 ); $bijlage_nr++; } private function _generate_documenten_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-documenten-tekeningen', $this->get_filter( 'onderdeel' ))) return; // doe documenten en tekeningen in PNG formaat (nu we het nieuwe annotaties systeem hebben zijn die er ws niet meer ;-)) $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Documenten / Tekeningen...' ); //$this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Documenten / Tekeningen' ); $this->_output_bescheiden_list( '/\.(png|jpe?g)$/', 1, 650, 720 ); $bijlage_nr++; // doe annotaties $this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Annotaties...' ); //$this->_tcpdf->AddPage(); $this->_output_header1( 'Bijlage ' . $bijlage_nr . ' Annotaties' ); $this->_output_annotatie_list( 1, 650, 720 ); $bijlage_nr++; } private function _generate_juridische_grondslag_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-juridische-grondslag', $this->get_filter( 'onderdeel' ))) return; $addendum_title = 'Bijlage '.romanic_number(++$this->addendum_number).' Grondslagen'; //$this->_set_progress( 'Bijlage ' . $bijlage_nr . ' Annotaties...' ); $this->_set_progress( $addendum_title . '...' ); $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Dit onderdeel wordt momenteel nog uitgewerkt en zal later toegevoegd worden.</p>'; $html_fragment = $style_fragment = ''; // For this section we use the previously compiled set of actually used 'grondslagen'. // Sort it by the array keys first (which is hopefully good enough as a sorting mechanism). $section_images = array(); $table_rows = array(); // Define the table headers $header_data = array('Afkorting', 'Grondslag', 'Artikel', 'Tekst'); //$header_data = array(''); $header_options = array(array('width'=>'94'),array('width'=>'87'),array('width'=>'70'),array('width'=>'700')); // An array of arrays (1 per column to use) in case column options should be passed. //$header_options = array(array('colspan' => 2)); $table_headers = $this->_generate_table_header_row_fragment($header_data, $header_options); // Now add the table rows using a helper function. Make sure that each row has equally many fields in it! $raw_row_data_cell_options = array(); $raw_row_data_cell_values = array(); // Add the grondslagen. foreach ($this->used_grondslagen as $afkorting => $grondlag) { $use_tekst = $grondlag->tekst; if (empty($use_tekst)) { if (!empty($grondslag->grondslag_tekst_id)) { $gt = $this->_CI->grondslagtekst->get( $grondslag->grondslag_tekst_id ); if ($gt) { $use_tekst = $gt->get_artikel_tekst(); } } } /* if (!isset( $data[$grondslag->grondslag] )) $data[$grondslag->grondslag] = array(); // new way $gt = $this->_CI->grondslagtekst->get( $grondslag->grondslag_tekst_id ); if ($gt) { $data[$grondslag->grondslag][$grondslag->artikel] = $gt->get_artikel_tekst(); } // old way if (!$data[$grondslag->grondslag][$grondslag->artikel] || ($grondslag->tekst && !isset( $data[$grondslag->grondslag][$grondslag->artikel] ))) $data[$grondslag->grondslag][$grondslag->artikel] = $grondslag->tekst; * */ //$raw_row_data_cell_values[] = array($this->hss($afkorting), $this->hss($grondlag->grondslag), $this->hss($grondlag->artikel), $this->hss($use_tekst)); $formatted_tekst = $this->_format_juridische_tekst ($this->hss($use_tekst)); $raw_row_data_cell_values[] = array($this->hss($afkorting), $this->hss($grondlag->grondslag), $this->hss($grondlag->artikel), $formatted_tekst); } // Construct the proper table rows data from the raw data set foreach($raw_row_data_cell_values as $cell_data) { $table_rows[] = $this->_generate_table_normal_row_fragment($cell_data, $raw_row_data_cell_options); } // First create the table fragment and then combine everything into the section. $table_fragment=$this->check_empty_table($table_headers,$table_rows, array('width'=>'100%', 'style'=>'table-layout:fixed')); //$this->_add_section($style_fragment.$table_fragment, $section_header, $section_images, 'normal'); // Add a section for the main header of this chapter $section_header = $this->_create_section_header(1, $addendum_title); $style_fragment = ''; $this->_add_section($style_fragment.$html_fragment.$table_fragment, $section_header, $section_images, 'normal', 'before', 'A4', 'landscape'); $bijlage_nr++; } private function _generate_pago_pmo_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-pago-pmo', $this->get_filter( 'onderdeel' ))) return; $addendum_title = 'Bijlage '.romanic_number(++$this->addendum_number).' PAGO/PMO'; $this->_set_progress( $addendum_title . '...' ); // Add a section for the main header of this chapter $section_header = $this->_create_section_header(1, $addendum_title); // Get the dossier object $dossier = $this->get_dossier(); // If we successfully got the dossier object, we proceed if (!is_null($dossier)){ $this->_CI->load->model('pago_pmo'); $funcs = $this->_CI->pago_pmo->get_funcs( $dossier ); // If we've got function(s). if( count($funcs) > 0 ){ $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); // Construct the proper table header $header_data = array( 'Functie', 'Aantal medewerkers', 'Onderwerp' ); $header_options = array(array('rowspan' => 2, 'width'=>'18.51%'),array('rowspan' => 2, 'width'=>'9.26%'),array('colspan' => 6)); $table_headers = $this->_generate_table_header_row_fragment( $header_data, $header_options ); $header_data = array( 'beeldschermwerk', 'biologische agentia', 'gevaarlijke stoffen', 'schadelijk geluid', 'fysieke belasting', 'Werkdruk en mentale belasting' ); $header_options = array( array('width'=>'12.04%'), array('width'=>'12.04%'), array('width'=>'12.04%'), array('width'=>'12.04%'), array('width'=>'12.04%'), array('width'=>'12.04%') ); $table_headers .= $this->_generate_table_header_row_fragment( $header_data, $header_options ); $table_rows = array(); // Construct the proper table rows data from the raw data set foreach( $funcs as $func ){ $cell_data = array( $func->functie, $func->n_medewerkers, $func->beeldschermwerk, $func->biologische_agentia, $func->gevaarlijke_stoffen, $func->schadelijk_geluid, $func->fysieke_belasting, $func->werkdruk_belasting ); $table_rows[] = $this->_generate_table_normal_row_fragment( $cell_data, array() ); } $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, array(), 'normal', 'before', 'A4', 'landscape' ); }// If no function found else{ $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Er zijn nog geen functiegegevens ingevoerd.</p>'; $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } }// if (is_null($dossier)) else{ $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Het dossier kon niet succesvol opgehaald worden.</p>'; $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } $bijlage_nr++; } private function _generate_pbm_bijlage( &$bijlage_nr ) { if (!@array_key_exists( 'bijlage-pbm', $this->get_filter( 'onderdeel' ))) return; $addendum_title = 'Bijlage '.romanic_number(++$this->addendum_number).' PBM'; $this->_set_progress( $addendum_title . '...' ); // Add a section for the main header of this chapter $section_header = $this->_create_section_header(1, $addendum_title); // Get the dossier object $dossier = $this->get_dossier(); // If we successfully got the dossier object, we proceed if (!is_null($dossier)){ $this->_CI->load->model('pbm'); $tasks = $this->_CI->pbm->get_tasks( $dossier ); // If we've got task(s). if( count($tasks) > 0 ){ $style_fragment = $this->_generate_style_definitions_block(array('table_100pct')); // Construct the proper table header $header_data = array( '<NAME>', 'Risico/blootstelling', 'R=WXBXE', 'Bronmaatregelen', 'PBM' ); $header_options = array( array('rowspan' => 2, 'width'=>'25%'), array('rowspan' => 2, 'width'=>'20%'), array('colspan' => 4, 'width'=>'15%'), array('rowspan' => 2, 'width'=>'20%'), array('rowspan' => 2, 'width'=>'20%') ); $table_headers = $this->_generate_table_header_row_fragment( $header_data, $header_options ); $header_data = array('W', 'B', 'E', 'R'); $header_options = array(); $table_headers .= $this->_generate_table_header_row_fragment( $header_data, $header_options ); // Construct the proper table rows data from the raw data set foreach( $tasks as $task ){ $risks = $task->risks; $count_risks= count( $risks ); if( $count_risks ){// Task has risks info $is_first_risk = TRUE; foreach( $risks as $risk ){ $cell_data = array(); if( $is_first_risk ){ $cell_data[] = $task->pbm_taak_name; $row_options = array( array('rowspan' => $count_risks) ); }else{ $row_options = array(); } $cell_data[] = $risk->risico_blootstelling; $cell_data[] = $risk->w; $cell_data[] = $risk->b; $cell_data[] = $risk->e; $cell_data[] = $risk->r; $cell_data[] = $risk->bronmaatregelen; $cell_data[] = $risk->pbm; $is_first_risk = FALSE; $table_rows[] = $this->_generate_table_normal_row_fragment( $cell_data, $row_options ); } }else{// Task does not have risks info $cell_data = array($task->pbm_taak_name,'','','','','','',''); $table_rows[] = $this->_generate_table_normal_row_fragment( $cell_data, array()); } } $table_fragment=$this->check_empty_table($table_headers, $table_rows); $this->_add_section($style_fragment.$table_fragment, $section_header, array(), 'normal', 'before', 'A4', 'landscape' ); }// If no tasks found else{ $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Er zijn nog geen gegevens ingevuld.</p>';//TODO: Translate to Dutch $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } }// if (is_null($dossier)) else{ $html_fragment = $this->_generate_style_definitions_block(array('p')) . '<p>Het dossier kon niet succesvol opgehaald worden.</p>'; $this->_add_section($html_fragment, $section_header, array(), 'normal', 'before'); } $bijlage_nr++; } private function _generate_toc() { // Add a section with the TOC $section_header = $this->_create_section_header(1, 'Inhoudsopgave'); $this->_add_section('', $section_header, array(), 'TOC', 'before'); } /******************************************************************************** * * * HELPER FUNCTIONS * * * ********************************************************************************/ private function _format_juridische_tekst($juridische_tekst = '') { $patterns = array(); $replacements = array (); //Remove control characters $juridische_tekst = preg_replace('/[\x00-\x1F\x80-\xFF]/',' ',$juridische_tekst); //Artikel & omschrijving $patterns[] = "(([a|A]rtikel\\s+\\d+\\.\\d+(\\.|\\.\\d+|\\.\\d+\\.|))(.+)(Toon leden van .+?)(\\d\\.\\s+|[A-Z])|(([a|A]rtikel\\s+\\d+\\.\\d+(\\.\\d+\\.|\\.\\d+|\\.)?)((.+?)(\\d\\.\\s+)|\\d\\.\\s+|[A-Z])))"; $replacements[] = "$1$7$3$10<br>$5$11"; //Lijsten $patterns[] = "(([\\:|\\;|\\.|\\,](\\s+)(en\s+|of\s+|))(([a-z0-9]\\.)|\\p{Pd})(\\s))"; $replacements[] = '$1<br/>$4'; return preg_replace($patterns, $replacements, $juridische_tekst); } private function _force_max_image_dimensions($image, $max_width = 'auto', $max_height = 'auto', $name_or_data = 'data') { // Initialise the result set $result_set = array( 'png_contents' => '', 'width' => 0, 'height' => 0, ); $contents = ''; if ($name_or_data == 'name') { $contents = @file_get_contents( $image ); if ($contents === false) { //throw new Exception( 'Failed to download from URL: ' . $image ); } } else { $contents = $image; } // Only continue if we have contents if (!empty($contents)) { $im = @imagecreatefromstring( $contents ); if (is_resource( $im )) { $scaling_factor = $x_scaling_factor = $y_scaling_factor = 1; // Get the current dimensions $img_width = imagesx($im); $img_height = imagesy($im); // Work out what X-scaling factor to use if ( ($max_width != 'auto') && ($max_width > 0) ) { # Now we can work out what the scaling factor (if any) needs to be used if ($img_width > $max_width) { $x_scaling_factor = $img_width / $max_width; } } // Work out what Y-scaling factor to use if ( ($max_height != 'auto') && ($max_height > 0) ) { # Now we can work out what the scaling factor (if any) needs to be used if ($img_height > $max_height) { $y_scaling_factor = $img_height / $max_height; } } // Now work out which of the two scaling factors to use as scaling factor for the entire image $scaling_factor = ( $x_scaling_factor > $y_scaling_factor ) ? $x_scaling_factor : $y_scaling_factor; // If a scaling factor was determined, resize the image //if ($scaling_factor != 1) if (1) { // Work out the new dimensions $new_width = floor($img_width / $scaling_factor); $new_height = floor($img_height / $scaling_factor); // Create an empty image that will hold the resized one $dest_img = imagecreatetruecolor($new_width, $new_height); // Resize the source into the new one // imagecopyresized($dest_img, $im, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height); imagecopyresampled($dest_img, $im, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height); // Get the resized image as a PNG into the result set ob_start(); imagepng($dest_img); $result_set['png_contents'] = ob_get_contents(); ob_end_clean(); // Set the new dimension in the result set too $result_set['width'] = $new_width; $result_set['height'] = $new_height; // Destroy the image resource if (!is_null($dest_img)) { imagedestroy($dest_img); } } } // Destroy the image resource if (!is_null($im)) { imagedestroy($im); } } return $result_set; } // Creates a section header that will result in nothing being output in the document. // Use this for special sections like the front page, etc. private function _create_empty_section_header() { return $this->_create_section_header(0, '', ''); } // Creates a section header in the proper data format. private function _create_section_header($level, $text, $style = '') { // [SectionHeader type] $section_header = array( 'level' => $level, // (numeric header level, 1, 2, etc.) 'text' => $text, // The actual text 'style' => $style, // 'auto'|<overriding type - string> ('auto' = use templates heading styles) ); return $section_header; } //clear document attributes private function _clear_attributes() { $this->pageheaders = Array(); $this->pagefooters = Array(); $this->sections = Array(); $this->document_images = Array(); } private function _add_document($type, $template, $title = '', $pageheaders = array(), $pagefooters = array(), $sections = array(), $images = array(), $first = 'false') { $document= array(); $document['type'] = $type; // 'DOCX'|'PDF'|'XLSX' $document['template'] = $template; // template name (optional) $document['title'] = $title; // the document title $document['pageheaders'] = $pageheaders; // the page headers to be used in this document $document['pagefooters'] = $pagefooters; // the page footers to be used in this document $document['sections'] = $sections; // the sections to be used in this document $document['images'] = $images; // the sections to be used in this document $document['first'] = $first; // indicates whether this document comprises the first section of the document $this->documents[] = $document; } // Helper function to add a section to a passed set of sections. // Note: this method directly adds the passed section to the globally registered (total) set of sections, as we presently do not allow sections to be nested. private function _add_section($content, $section_header, $images = array(), $section_type = 'normal', $page_break = 'none', $size = 'A4', $orientation = 'portrait', $content_type = 'html', $perform_cleanup = false, $use_word_styles = true, $ignore_css = true) { // [Section type] $section = array(); $section['section_type'] = $section_type; // 'normal'|'TOC'|'front'|'summary' $section['size'] = $size; // 'A4', 'A3', ... $section['orientation'] = $orientation; // 'portrait'|'landscape' $section['section_header'] = $section_header; // [SectionHeader type] $section['page_break'] = $page_break; // 'none'|'after'|'before' $section['perform_cleanup'] = $perform_cleanup; // 'true' = perform clean-up actions (like 'HTML Tidy', etc.), 'false' = use the content "as-is". Aim for using 'false' as much as possible. $section['use_word_styles'] = $use_word_styles; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $section['ignore_css'] = $ignore_css; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $section['content_type'] = $content_type; // 'text'|'html' //make sure we have UTF-8 encoded content if (mb_detect_encoding($content,'UTF-8', true) == false) { $content = Encoding::toUTF8($content); } $section['content'] = $content; // (text or HTML) $section['images'] = $images; // <array([Image type])> $section['tables'] = array(); // <array([Table type])> - NOT USED FOR NOW - POSSIBLY IMPLEMENTED LATER $this->sections[] = $section; } // Helper function to add a header to the document private function _add_pageheader($section, $position, $content, $images = array(), $use_word_styles = true, $ignore_css = true) { $header = array(); $header['section'] = $section; // 'default'|'first'|'even' : if 'even' is selected, default will be used for odd pages $header['position'] = $position; // 'left'|'center'|'right' $header['content'] = $content; // HTML $header['images'] = $images; // <array([Image type])> $header['use_word_styles'] = $use_word_styles; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $header['ignore_css'] = $ignore_css; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $this->pageheaders[] = $header; } // Helper function to add a footer to the document private function _add_pagefooter($section, $position, $content, $images = array(), $use_word_styles = true, $ignore_css = true) { $footer = array(); $footer['section'] = $section; // 'default'|'first'|'even' : if 'even' is selected, default will be used for odd pages $footer['position'] = $position; // 'left'|'center'|'right' $footer['content'] = $content; // HTML $footer['images'] = $images; // <array([Image type])> $footer['use_word_styles'] = $use_word_styles; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $footer['ignore_css'] = $ignore_css; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = use the passed CSS styles. Aim for using 'true' as much as possible. $this->pagefooters[] = $footer; } // Add one or more images to an images set. // Note: the $image_names array is allowed to either be associative or numerically indexed private function _add_images(&$image_set = array(), $base_path, $image_names = array(), $type = 'png', $width = 'auto', $height = 'auto') { //d($image_names); // Get the array keys (if any) $image_keys = array_keys($image_names); //d(array_keys($image_names)); //d($image_keys); // Add the images one by one to the image set, using the proper helper method for it foreach ($image_keys as $image_key) { /* d($image_key); d(is_int($image_key)); d(is_string($image_key)); d($image_names["{$image_key}"]); * */ $image_name = $image_names["{$image_key}"]; // Work out the identifier to use, being either an explicitly used array key, or just the image name without extension) if the // images were passed in a non-associative array. $image_identifier = (is_string($image_key)) ? $image_key : $image_name; // Add the images. // Note: when making use of the width and/or height parameters, the same (passed) values are applied to ALL images that were passed in the // set! $this->_add_image($image_set, $base_path, $image_identifier, $image_name, $type, $width, $height); } } // Add one image to an images set. // Note: either the filename or the actual data can be passed. private function _add_image(&$image_set = array(), $base_path, $identifier, $image_name, $type = 'png', $width = 'auto', $height = 'auto', $data_or_name = 'name') { // Add the image to the set, using the proper format. // Note: for now we silently skip files that do not exist. We can of course also do other things, like throwing an exception or so. if ($data_or_name == 'name') { $image_file_data = ''; $image_file = $base_path . $image_name . '.' . $type; if (file_exists($image_file)) { $image_file_data = file_get_contents($image_file); } } else { $image_file_data = $image_name; } //if (file_exists($image_file)) if (!empty($image_file_data)) { $image = array( 'identifier' => $identifier, // Used for binding the image to the placeholder identifier, can be a name, a hash, ... 'type' => $type, // 'jpg'|'png'|'gif' 'width' => $width, // 'auto'|<number> (for forcing a specific width) 'height' => $height, // 'auto'|<number> (for forcing a specific height) 'data' => $image_file_data, // the actual file data (this will be base64 encoded when passed via SOAP) ); $image_set[] = $image; } } // Use this for creating a compound set of styles, all in one definition. Returns an array of style definitions. // Call this like e.g. $style_definitions = $this->_generate_style_definitions(array('p', 'table', 'td')); // Make sure to properly implement each of the "_generate_style_definition_<.....>" methods before including them in the call! private function _generate_style_definitions($styles_to_generate = array()) { //MJ (28-04-2015) added the possibility to add parameters. To do so, pass an array //as the second variable containing the parameters to pass to the function $style_definitions = array(); foreach ($styles_to_generate as $style_to_generate) { $method_name = '_generate_style_definition_' . $style_to_generate; $style_definitions[] = call_user_func(array($this, $method_name)); } return $style_definitions; } // Use this for creating a compound set of styles, all in one definition // Call this like e.g. $this->_generate_style_definitions_block(array('p', 'table', 'td')); // Make sure to properly implement each of the "_generate_style_definition_<.....>" methods before including them in the call! private function _generate_style_definitions_block($styles_to_generate = array()) { return $this->_generate_style_block($this->_generate_style_definitions($styles_to_generate)); } // This method expects an array of CSS style definitions and output them in a '<style>' block. private function _generate_style_block($style_parts = array()) { return '<style>' . implode("\n", $style_parts) . '</style>'; } // Return the precise CSS style definition for the 'p' tags. private function _generate_style_definition_p() { //return 'p {text-indent:100px;color:rgb(0,0,255);text-decoration:underline;}'; return 'p {text-indent:0px;}'; } // Return the precise CSS style definition for the 'table' tags. private function _generate_style_definition_table() { return 'table {border-collapse: collapse;border:1px solid #000;border-collapse: collapse; border-spacing: 0px;}'; } private function _generate_style_definition_table_bevindingen() { //the next lines can be used if we want a border around all annotations and snapshots (last two columns) //$this->show_revisions?$cols= 7: $cols = 6; //$tdcols = implode(" + ", array_fill(0, $cols - 1, "td")); //return 'table {border-collapse: collapse; width: 100%; table-layout:fixed; font-size: 10pt;} td {vertical-align:top;} table ' .$tdcols .' img {border:1px solid #000000;}'; return 'table {border-collapse: collapse; width: 100%; table-layout:fixed; font-size: 10pt;} td {vertical-align:top;}'; //The line below would be nicer and would remove the need to pass a column count, but unfortunately phpDOCX doesn't respect it. //return 'table {border-collapse: collapse; width: 100%; table-layout:fixed; font-size: 10pt;} td {vertical-align:top;} table td:nth-last-child(-n+2) img {border: 1px solid #000000;}'; } private function _generate_style_definition_table_100pct() { return 'table {width: 100%;}'; } private function _generate_style_definition_table_header($td_size = '') { if ($td_size){ return 'table {width: 100%; border-bottom: 1pt solid black;} td {width: '.$td_size.';}'; } else { return 'table {width: 100%; border-bottom: 1pt solid black;}'; } } private function _generate_style_definition_table_footer($td_size = '') { if ($td_size){ return 'table {width: 100%; border-top: 1pt solid black;} td {width: '.$td_size.';}'; } else { return 'table {width: 100%; border-top: 1pt solid black;}'; } } // Return the precise CSS style definition for the 'td' tags. private function _generate_style_definition_td() { return 'td {border-collapse: collapse;border:1px solid #000;border-collapse: collapse; border-spacing: 0px; padding: 3px; text-indent:0px;}'; } // Generate an options string for a table cell. This can be used for <th> and <td> tags private function _generate_table_cell_options_string($options = array()) { $options_str_parts = array(); $options_str_parts[] = (!empty($options['colspan']) && is_int($options['colspan'])) ? 'colspan="'.$options['colspan'].'"' : ''; $options_str_parts[] = (!empty($options['rowspan']) && is_int($options['rowspan'])) ? 'rowspan="'.$options['rowspan'].'"' : ''; $options_str_parts[] = (!empty($options['style'])) ? 'style="'.$options['style'].'"' : ''; $options_str_parts[] = (!empty($options['width'])) ? 'width="'.$options['width'].'"' : ''; $options_str_parts[] = (!empty($options['height'])) ? 'height="'.$options['height'].'"' : ''; $options_str = implode(' ', $options_str_parts); return $options_str; } // Generate a single table header cell private function _generate_table_header_cell_fragment($header, $options = array()) { $options_str = $this->_generate_table_cell_options_string($options); $fragment = "<th {$options_str}>" . $header . '</th>'; return $fragment; } // Generate a single table normal cell private function _generate_table_normal_cell_fragment($cell, $options = array()) { $options_str = $this->_generate_table_cell_options_string($options); $fragment = "<td {$options_str}>" . $cell . '</td>'; return $fragment; } // Generate table header cells. // Example usage: $header_cells = $this->_generate_table_header_cells_fragment(array('kol1', 'kol2'), array(array(),array('colspan'=>3)) private function _generate_table_header_cells_fragment($headers = array(), $options = array()) { $fragment = ''; $idx = 0; foreach ($headers as $header) { $options_to_pass = (!empty($options[$idx])) ? $options[$idx] : array(); $fragment .= $this->_generate_table_header_cell_fragment($header, $options_to_pass); $idx++; } return $fragment; } // Generate table normal cells private function _generate_table_normal_cells_fragment($cells = array(), $options = array()) { $fragment = ''; $idx = 0; foreach ($cells as $cell) { $options_to_pass = (!empty($options[$idx])) ? $options[$idx] : array(); $fragment .= $this->_generate_table_normal_cell_fragment($cell, $options_to_pass); $idx++; } return $fragment; } // Generate custom table header options private function _generate_custom_cell_options ($widths = array(), $style = ''){ $content = array(); foreach ($widths as $width){ $content[] = array('width'=>$width, 'style' => $style); } return $content; } // Generate a table row with header cells private function _generate_table_header_row_fragment($headers = array(), $options = array()) { if (empty($headers)) { return ''; } $cells = $this->_generate_table_header_cells_fragment($headers, $options); $fragment = $this->_generate_table_row_fragment($cells, $options); return $fragment; } // Generate a table row with normal cells private function _generate_table_normal_row_fragment($cell_contents = array(), $options = array(), $row_options = array()) { $cells = $this->_generate_table_normal_cells_fragment($cell_contents, $options); $fragment = $this->_generate_table_row_fragment($cells, $row_options); return $fragment; } // Generate a table row with cells or headers private function _generate_table_row_fragment($cells = array(), $row_options = array()) { //$fragment = '<tr>' . implode('', $cells) . '</tr>'; $row_options_str = $this->_generate_row_options_string($row_options); $fragment = "<tr {$row_options_str}>" . $cells . '</tr>'; return $fragment; } // Generate a table. // Note: the $headers parameter expects a single 'tr' row with headers, whereas the $rows parameter expects an array of 'tr' rows // with normal cells. private function _generate_table_fragment($headers = '', $rows = array(), $options = array()) { $options_str = $this->_generate_table_options_string($options); $fragment = "<table {$options_str}>" . $headers .implode('', $rows) . '</table>'; //$fragment .= $this->_generate_table_header_row_fragment($headers, $options); return $fragment; } private function _generate_row_options_string($row_options = array()) { $row_options_str_parts = array(); $row_options_str_parts[] = (!empty($row_options['class'])) ? 'class="'.$row_options['class'].'"' : ''; $row_options_str_parts[] = (!empty($row_options['style'])) ? 'style="'.$row_options['style'].'"' : ''; $row_options_str = implode(' ', $row_options_str_parts); return $row_options_str; } // Generate an options string for a table. This can be used for <table> tag private function _generate_table_options_string($options = array()) { $options_str_parts = array(); $options_str_parts[] = (!empty($options['class'])) ? 'class="'.$options['class'].'"' : ''; $options_str_parts[] = (!empty($options['width'])) ? 'width="'.$options['width'].'"' : ''; $options_str_parts[] = (!empty($options['style'])) ? 'style="'.$options['style'].'"' : ''; $options_str = implode(' ', $options_str_parts); return $options_str; } /* TCPDF specific - no longer needed */ private function _output_header1( $text, $top_of_page=true ) { $this->_output_header( $text, 0, $top_of_page, self::FONTHEADERSIZE ); } private function _output_header2( $text, $top_of_page=true ) { $this->_output_header( $text, 1, $top_of_page, self::FONTHEADERSIZE-1 ); } private function _output_header3( $text, $top_of_page=true ) { $this->_output_header( $text, 2, $top_of_page, self::FONTHEADERSIZE-2 ); } private function _output_subheader( $text ) { /* // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTSIZE+1 ); $this->_tcpdf->SetTextColor( 0, 0, 0 ); $this->_tcpdf->WriteHTML( $this->hss( $text ), true, false, true ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); * */ } private function _output_header( $text, $level, $top_of_page, $fontsize ) { /* // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', $fontsize ); $this->_tcpdf->SetTextColor( 0, 204, 171 ); // #00ccab $this->_tcpdf->WriteHTML( $this->hss( $text ), true, false, true ); $this->_tcpdf->Bookmark( $text, $level, $top_of_page ? 0 : -1 ); // reset color to black $this->_tcpdf->SetTextColor( 0, 0, 0 ); // additional empty line $this->_tcpdf->Ln(); * */ } private function _output_bescheiden_table( array $bescheiden ) { $html = '<table cellspacing="0" cellpadding="0" border="0">' . '<tr>' . '<td style="width:100px; font-weight: bold">Tekening / Stuknummer</td>' . '<td style="width:130px; font-weight: bold">Auteur</td>' . '<td style="width:150px; font-weight: bold">Omschrijving</td>' . '<td style="width:100px; font-weight: bold">Datum laatste wijziging</td>' . '<td style="width:140px; font-weight: bold">Bestandsnaam</td>' . '</tr>' ; foreach ($bescheiden as $bescheid) { $html .= '<tr>' . '<td style="font-style:italic">' . $this->hss( $bescheid->tekening_stuk_nummer ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->auteur ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->omschrijving ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->datum_laatste_wijziging ) . '</td>' . '<td style="font-style:italic">' . $this->hss( $bescheid->bestandsnaam ) . '</td>' . '</tr>'; } $html .= '</table>'; } // Generates a compound data set with HTML fragments with placeholder tags for the images. The actual image data is also returned in the compound data set. private function _output_uploads_list($datatype, $foto_per_row, $max_width, $max_height ) { // Define a local sort function for the upload list if (!function_exists('sort_by_picture_upload_date')) { function sort_by_picture_upload_date ($a, $b) { if ($a[1]->uploaded_at == $b[1]->uploaded_at) { return 0; } return ($a[1]->uploaded_at < $b[1]->uploaded_at) ? -1 : 1; } // function sort_by_picture_upload_date ($a, $b) } // if (!function_exists('sort_by_picture_upload_date')) $compound_return_set = array(); foreach ($this->deelplannen as $j => $deelplan) { $first = true; foreach ($deelplan->get_checklisten() as $i => $checklist) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($checklist->checklist_id, $this->deelplan_checklists)) { continue; } // First determine the "scope_id", which is comprised of the combination of the checklistgroep ID and checklist ID, which is the secondary index // in the deelplan_vragen dataset $scope_id = $checklist->checklist_groep_id . '_' . $checklist->id; // get list of foto/video uploads $upload_list = array(); //$vragen = $this->deelplan_vragen[$deelplan->id][$checklist->id]; $vragen = $this->deelplan_vragen[$deelplan->id]["$scope_id"]; //d($vragen); foreach ($vragen as $vraag) { if (isset( $this->deelplan_uploads[$deelplan->id][$vraag->id] )) { if ($this->_vraag_weergeven( $deelplan->id, $vraag )) { foreach ($this->deelplan_uploads[$deelplan->id][$vraag->id] as $q => $upload) { if ($upload->datatype == $datatype) { //$annotation_id = $this->photo_annotaties [$this->hss( $upload[1]->filename).'_'.$upload[2].'_'.$upload[3]]; //add annotation id to the upload information $annotation_identifier = $upload->filename.'_'.$deelplan->id.'_'.$vraag->id; if ($this->photo_annotaties [$annotation_identifier]){ $upload->annotation_id = $this->photo_annotaties [$annotation_identifier]; } else { $upload->annotation_id = 0; } $sort_key = $upload->annotation_id.'-'.$upload->filename; $upload_list[$sort_key] = array( $vraag, $upload ); } } } } } // something todo? if (!empty( $upload_list )) { /* // Sort the list by the upload dates of the pictures for VIIA if ($this->overriden_data_context == 'viia') { usort($upload_list, 'sort_by_picture_upload_date'); } * */ //sort the upload_list ksort($upload_list); // Initialise the data set for this section /* // if available, then show deelplan header if ($first) { // $this->_output_header2( $deelplan->naam, false ); $first = false; } * */ $section_header = 'Checklist ' . ($i + 1) . ': ' . $this->_CI->checklistgroep->get($checklist->checklist_groep_id)->naam . ' - ' . $checklist->naam; $checklist_images_data_set = array( 'section_header' => $this->hss( $section_header ), 'section_images' => array(), 'section_html' => '' ); // show uploads $images_html = '<table class="TableNoHeader" style="text-align:center" cellspacing="0" cellpadding="3" border="0">'; $foto_index =0; foreach ($upload_list as $q => $upload) { // handle table rows if (!($foto_index % $foto_per_row)) { if ($q) $images_html .= '</tr>'; $images_html .= '<tr>'; } $uploaddata = $upload[1]->get_data(); /* raw image data */ // $uploaddata->data, $this->_process_raw_image_data( /* raw image data */ $uploaddata, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow jpg conversion */ TRUE ); //$this->_CI->deelplanuploaddata->_clear_cache( $uploaddata->id ); //unset( $uploaddata->data ); unset( $uploaddata ); // Work out an identifier that makes sure that identical images only require the filedata once $path_parts = pathinfo($upload[1]->filename); $identifier = sha1('foto_bijlage_' . $path_parts['filename']); $image_already_registered = false; foreach($checklist_images_data_set['section_images'] as $registered_image) { if ($registered_image['identifier'] == $identifier) { $image_already_registered = true; } } // Only register the image if it wasn't already registered previously if (!$image_already_registered) { //$this->_add_image($images_set, 'dummy_path', $identifier, file_get_contents($tempfilename), 'jpg', 'auto', 'auto', 'data'); $this->_add_image($checklist_images_data_set['section_images'], 'dummy_path', $identifier, file_get_contents($tempfilename), 'jpg', round($impixwidth-10 /* margin */), round($impixheight-10 /* margin */), 'data'); } if ($upload[1]->annotation_id == 0) { $annotation_text = ''; } else { $annotation_text = '<br/>annotatie nr: '.$upload[1]->annotation_id; } // add $images_html .= '<td width="' . $max_width . '">' . "[IMG:{$identifier}]" . '<br/><b>Vraag ' . $upload[0]->rapportage_vraag_nummer . ': </b>' . $this->hss( $upload[1]->filename ) .$annotation_text. '</td>'; $foto_index++; } $images_html .= '</tr></table>'; // Store the HTML fragment and register the section $checklist_images_data_set['section_html'] = $images_html; $compound_return_set[] = $checklist_images_data_set; } } } // Return the compound data set return $compound_return_set; } private function _process_raw_image_data( $imagecontents, $max_width, $max_height, &$impixwidth, &$impixheight, &$tempfilename, $allow_convert_to_jpg ) { // calc correct width/height to display image in $imwidth = 640; // default! $imheight = 480; try { $im = new Imagick(); if ($im->readImageBlob( $imagecontents )) { $imwidth = $im->getImageWidth(); $imheight = $im->getImageHeight(); if (!$imwidth || !$imheight) { error_log( 'Failed to determine image dims: ' . $imwidth . 'x' . $imheight ); $imwidth = 640; // default! $imheight = 480; } } $max_width = $max_width == 'auto' ? $imwidth : $max_width; $impixwidth = round( $max_width ); $impixheight = round( ($max_width / $imwidth) * $imheight ); if (($impixheight > $max_height) && $max_height != 'auto') { $impixheight = round( $max_height ); $impixwidth = round( ($max_height / $imheight) * $imwidth ); } // resize image to be of the a small size: twice at what it will be displayed at, so we still have some detail! if ($allow_convert_to_jpg) { $im->resizeImage( 2*$impixwidth, 2*$impixheight, imagick::FILTER_BOX, 0 ); $im->setImageFormat( 'jpeg' ); $im->setImageCompression( Imagick::COMPRESSION_JPEG ); $im->setImageCompressionQuality( 80 ); unset($imagecontents); $imagecontents = $im->getImageBlob(); } } catch (ImagickException $e) { // fail silently, use default error_log( 'ImagickException: ' . $e->getMessage() ); $impixwidth = $imwidth; $impixheight = $imheight; } if ($im) @$im->destroy(); unset($im); // make tempfile from image contents $tempfilename = $this->make_temp_image( $imagecontents, 'jpg' ); unset($imagecontents); } private function _output_bescheiden_list( $regexp_match, $foto_per_row, $max_width, $max_height ) { foreach ($this->deelplannen as $j => $deelplan) { if (!isset( $this->deelplan_bescheiden[$deelplan->id] )) continue; $numfiles = 0; $images_html = '<table cellspacing="0" cellpadding="3" border="0">'; foreach ($this->deelplan_bescheiden[$deelplan->id] as $deelplanbescheiden) { // is er genoeg data in het bescheiden? $dossierbescheiden = $deelplanbescheiden->get_dossier_bescheiden(); if (!$dossierbescheiden->bestandsnaam || !preg_match( $regexp_match, $dossierbescheiden->bestandsnaam )) continue; // is het bescheiden uberhaupt in gebruik door een vraag die momenteel getoond moet/mag worden $gebruik_bescheiden = false; foreach ($deelplan->get_checklisten() as $checklist) { // Apply filtering by checklist, if needed... if (!empty($this->deelplan_checklists) && !in_array($checklist->checklist_id, $this->deelplan_checklists)) { continue; } foreach ($this->deelplan_vragen[$deelplan->id][$checklist->id] as $vraag) { // kijk of de status(=waardeoordeel) van deze vraag getoond mag worden if (!$this->_vraag_weergeven( $deelplan->id, $vraag )) continue; if (isset( $this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] )) { foreach ($this->deelplan_vraag_bescheiden[$deelplan->id][$vraag->id] as $vraagbescheiden) { if ($deelplanbescheiden->dossier_bescheiden_id == $vraagbescheiden->dossier_bescheiden_id) { $gebruik_bescheiden = true; break(3); } } } } } if (!$gebruik_bescheiden) continue; // if available, then show deelplan header if (!$numfiles) $this->_output_header2( $deelplan->naam, false ); ++$numfiles; // handle table rows if (!($numfiles % $foto_per_row)) { if ($numfiles) $images_html .= '</tr>'; $images_html .= '<tr>'; } $dossierbescheiden->laad_inhoud(); $this->_process_raw_image_data( /* raw image data */ $dossierbescheiden->bestand, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow JPG conversion */ FALSE ); $dossierbescheiden->geef_inhoud_vrij(); // add $images_html .= '<td width="' . $max_width . '">' . '<img src="' . $tempfilename . '" width="' . round($impixwidth-10 /* margin */) . '" height="' . round($impixheight-10 /* margin */) . '" />' . '<br/><b>' . $this->hss( $dossierbescheiden->bestandsnaam ) . '</b> ' . '</td>'; } $images_html .= '</tr></table>'; /* if ($numfiles) // output HTML $this->_tcpdf->WriteHTML( $images_html, true, false, true ); * */ } } private function _output_annotatie_list( $foto_per_row, $max_width, $max_height ) { foreach ($this->deelplannen as $j => $deelplan) { if (!isset( $this->deelplan_bescheiden[$deelplan->id] )) continue; $numfiles = 0; $images_html = '<table cellspacing="0" cellpadding="3" border="0">'; foreach ($this->deelplan_bescheiden[$deelplan->id] as $deelplanbescheiden) { // is er genoeg data in het bescheiden? $dossierbescheiden = $deelplanbescheiden->get_dossier_bescheiden(); // get layerdata $layerdata = $this->_CI->deelplanlayer->get_layer_for_deelplan_bescheiden( $deelplan->id, $dossierbescheiden->id ); if (!$layerdata) continue; // get vragen for which there is layer data $vraag_ids = $this->_CI->pdfannotatorlib->get_vraag_ids_in_layer_data( $layerdata->layer_data ); foreach ($vraag_ids as $vraag_id) { if (!$vraag = $this->_CI->vraag->get( $vraag_id )) continue; // if available, then show deelplan header if (!$numfiles) $this->_output_header2( $deelplan->naam, false ); ++$numfiles; // handle table rows if (!($numfiles % $foto_per_row)) { if ($numfiles) $images_html .= '</tr>'; $images_html .= '<tr>'; } // process image in PDF annotator $png = $this->_CI->pdfannotatorlib->bescheiden_naar_png( $deelplan->id, $dossierbescheiden->id, $vraag_id ); // process image for rapportage $this->_process_raw_image_data( /* raw image data */ $png, /* max dimensions for image */ $max_width, $max_height, /* output size to display image in */ $impixwidth, $impixheight, /* temp image filename */ $tempfilename, /* allow JPG conversion */ FALSE ); // add $images_html .= '<td width="' . $max_width . '">' . '<img src="' . $tempfilename . '" width="' . round($impixwidth-10 /* margin */) . '" height="' . round($impixheight-10 /* margin */) . '" />' . '<br/><b>' . $this->hss( $vraag->tekst ) . '</b> ' . '</td>'; } } $images_html .= '</tr></table>'; /* if ($numfiles) // output HTML $this->_tcpdf->WriteHTML( $images_html, true, false, true ); * */ } } private function _status_to_samenvatting_waarde( $vraag ) { // hoofdgroep status: ("magic constants" worden gebruikt voor gemakkelijk vergelijk) // 0 - handhaven // 1 - aandacht // 2 - niet van toepassing // 3 - niet handhaven // 4 - geen enkele vraag nog beantwoord // update thema status $status = $vraag->get_waardeoordeel_kleur( true ); switch( $status ) { case 'rood': return 0; case 'groen': return 2; case 'oranje': return 1; default: case 'in_bewerking': return 4; } } private function _status_to_waarde( $vraag ) { switch ($vraag->get_waardeoordeel_kleur( true )) { case 'groen': return 3; case 'oranje': return 1; case 'rood': return 0; default: case 'in_bewerking': return 2; } } private function _status_to_description( $vraag, $alt_status=null ) { return $vraag->get_waardeoordeel( true, $alt_status ); } private function _set_progress( $action_description ) { $this->set_progress( min( 1, $this->item_count ? $this->item_number / $this->item_count : 0 ), $action_description ); $this->item_number++; } public function get_deelplannen() { return $this->deelplannen; } } <file_sep>DELETE FROM `teksten` WHERE `teksten`.`string` = 'dossiers.rapportage::revisies.tonen.ja'; DELETE FROM `teksten` WHERE `teksten`.`string` = 'dossiers.rapportage::revisies.tonen.nee'; <file_sep>BRISToezicht.OfflineKlaar = { klaar: false, huidigeAantal: 0, opdrachtAantal: 4, // opdrachten (niet in deze volgorde uitgevoerd per se): // 1: images inladen (vanuit specialimage.js) // 2: wetteksten inladen (vanuit toetsdata-js.php) // 3: verantwoordingen inladen (vanuit toetsdata-js.php) // 4: ophalen toezichtsgegevens (vanuit toetsdata-js.php) // // LET OP: telefoon interface gebruikt dit ook, en doet 3 fake calls omdat daar alleen afbeeldingen geladen worden! initialize: function() { // // geen zin om tijdens het toezichtscherm / PDF annotator ontwikkelen te wachten // op die trage Quest server? zet dan "opdrachtAantal" TIJDELIJK (!!) op 3 ipv 4, // en je zult sneller kunnen werken ;) let wel, je hebt geen wetteksten (of beter // gezegd, die komen naar verloop van tijd pas), dus zet em wel degelijk weer terug // naar 4 voordat je releaset! ;-) // this.markeerNietKlaar(); }, markeerKlaar: function( tag ) { $('.status-offline-tag-niet-klaar-' + tag).hide(); $('.status-offline-tag-klaar-' + tag).show(); this.huidigeAantal++; if (this.huidigeAantal == this.opdrachtAantal) this.markeer( true ); }, markeerNietKlaar: function() { this.markeer( false ); }, markeer: function( klaar ) { this.klaar = klaar; if (klaar) { $('.status-offline-niet-klaar').hide(); $('.status-offline-klaar').show(); $('#nlaf_LoadingScreen, #nlaf_LoadingScreenContent').remove(); } else { $('.status-offline-niet-klaar').show(); $('.status-offline-klaar').hide(); } }, isKlaarVoorOffline: function() { return this.klaar; } }; <file_sep><? require_once 'base.php'; class DeelplanVraagGeschiedenisResult extends BaseResult { function DeelplanVraagGeschiedenisResult( $arr ) { parent::BaseResult( 'deelplanvraaggeschiedenis', $arr ); } function get_deelplan() { $this->_CI->load->model( 'deelplan' ); return $this->_CI->deelplan->get( $this->deelplan_id ); } function get_vraag() { $this->_CI->load->model( 'vraag' ); return $this->_CI->vraag->get( $this->vraag_id ); } } class DeelplanVraagGeschiedenis extends BaseModel { function DeelplanVraagGeschiedenis() { parent::BaseModel( 'DeelplanVraagGeschiedenisResult', 'deelplan_vraag_geschiedenis' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); } function get_by_deelplan( $deelplan_id, $bouwnummer='' ) { $args = array( $deelplan_id, $bouwnummer ); if (!$this->dbex->is_prepared( 'get_vraag_geschiedenis_by_deelplan' )) $this->dbex->prepare( 'get_vraag_geschiedenis_by_deelplan', ' SELECT * FROM deelplan_vraag_geschiedenis WHERE deelplan_id = ? AND bouwnummer = ? '. 'ORDER BY datum ' ); $res = $this->dbex->execute( 'get_vraag_geschiedenis_by_deelplan', $args ); $result = array(); foreach ($res->result() as $row) { $vraag_id = $row->vraag_id; if (!isset( $result[$vraag_id] )) $result[$vraag_id] = array(); $result[$vraag_id][] = $this->getr( $row ); } return $result; } function add( $deelplan_id, $vraag_id, $status, $toelichting, $gebruiker_id, $datum=null,$toelichting_id='', $bouwnummer='' ) { if ($datum) $datum = date( 'Y-m-d H:i:s', strtotime( $datum ) ); else $datum = date( 'Y-m-d H:i:s' ); // For some reason the below code was used; this ought to be pretty much exactly what the 'insert' method of the base model does, hence, it has been rewritten to use that instead. // By doing so, Oracle also doesn't give an error due to not being able to determine the last insert ID. /* if (!$this->dbex->is_prepared( 'add_vraag_geschiedenis' )) $this->dbex->prepare( 'add_vraag_geschiedenis', 'INSERT INTO deelplan_vraag_geschiedenis (deelplan_id, vraag_id, status, toelichting, gebruiker_id, datum) VALUES (?, ?, ?, ?, ?, '.get_db_prepared_parameter_for_datetime().')' ); $args = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'status' => $status, 'toelichting' => $toelichting, 'gebruiker_id' => $gebruiker_id, 'datum' => $datum, ); $this->dbex->execute( 'add_vraag_geschiedenis', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( $args ); */ // !!! If no choice has been made for a 'waardeoordeel' (yet) we need to use the standardvalue that was specified for the checklist (otherwise the reports don't show correct statuses, etc.)! if (!$status || $status == 'in_bewerking') { // !!! TBD: make a proper (and Oracle safe!) version of the below query. It may have to take the 'gebruik_wo_standaard' value into account too, but at any // rate the COALESCE needs to be translated correctly. If all is well, the field 'c_wo_standaard' should contain the proper default value. A fall-back // value can also be specified in it... // If a value is found, then use that. The vraag::get_waardeoordeel call doesn't do what we want, as it gets the text, and not the short 'wt??' value. $this->_CI->load->model('vraag'); $vraag = $this->_CI->vraag->get($vraag_id); $standaard_antwoord = $vraag->get_standaard_antwoord(); if (!is_null($standaard_antwoord) && !empty($standaard_antwoord)) { $status = $standaard_antwoord->status; } } // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'status' => $status, 'toelichting' => $toelichting, 'gebruiker_id' => $gebruiker_id, 'datum' => ((get_db_type() == 'oracle') ? array('format_string' => get_db_literal_for_datetime("?"), 'data' => $datum) : $datum), 'toelichting_id' => $toelichting_id, 'bouwnummer' => $bouwnummer ); // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'iiscis' : ''; $result = $this->insert( $data, '', $force_types ); } }<file_sep><? require_once 'base.php'; class DeelplanBouwdeelResult extends BaseResult { function DeelplanBouwdeelResult( &$arr ) { parent::BaseResult( 'deelplanbouwdeel', $arr ); } } class DeelplanBouwdeel extends BaseModel { function DeelplanBouwdeel() { parent::BaseModel( 'DeelplanBouwdeelResult', 'deelplan_bouwdelen', true ); } public function check_access( BaseResult $object ) { // disabled for model } function set_for_deelplan( $deelplan_id, array $nieuwe_bouwdeel_namen ) { // query preparen $stmt_name = 'DeelplanBouwdeel::set_for_deelplan'; if (!$this->dbex->prepare( $stmt_name, 'INSERT INTO deelplan_bouwdelen (deelplan_id, naam) VALUES (?, ?)' )) throw new Exception( 'Fout bij voorbereiden deelplan bouwdeel query.' ); // begin transactie $this->db->trans_start(); // bouw associative array van huidige bouwdelen op $bestaande_bouwdelen = array(); foreach ($this->get_by_deelplan_id( $deelplan_id ) as $bouwdeel) { if (!isset( $bestaande_bouwdelen[$bouwdeel->naam] )) $bestaande_bouwdelen[$bouwdeel->naam] = array(); $bestaande_bouwdelen[$bouwdeel->naam][] = $bouwdeel; } // loop over de nieuwe lijst van bouwdeel namen, als we een bouwdeel al kennen // doen we niks; we halen hem NIET uit de lijst van bestaande bouwdelen, omdat // we anders niet goed met dubbelen om kunnen gaan! // nog niet bekende bouwdelen voegen we toe. let op dat we lege bouwdeel namen // negeren! foreach ($nieuwe_bouwdeel_namen as $i => $nieuwe_naam) { $nieuwe_naam = $nieuwe_bouwdeel_namen[$i] = trim($nieuwe_naam); // verwijder extra whitespace if (!strlen( $nieuwe_naam )) { unset( $nieuwe_bouwdeel_namen[$i] ); continue; } if (isset( $bestaande_bouwdelen[$nieuwe_naam] )) continue; if (!$this->dbex->execute( $stmt_name, array( $deelplan_id, $nieuwe_naam ) )) throw new Exception( 'Fout bij uitvoeren deelplan bouwdeel query.' ); } // nu lopen we nogmaals over de bestaande delen heen en legen we de lijst van // bestaande bouwdelen: alles wat daarna overblijft is oud en mag weg! foreach ($nieuwe_bouwdeel_namen as $nieuwe_naam) unset( $bestaande_bouwdelen[$nieuwe_naam] ); // geen error als ie niet bestaat! foreach ($bestaande_bouwdelen as $bouwdelen) foreach ($bouwdelen as $bouwdeel) $bouwdeel->delete(); // maak transactie af if (!$this->db->trans_complete()) throw new Exception( 'Fout bij opslaan transactie bij opslaan bouwdelen.' ); } function get_by_deelplan_id( $deelplan_id ) { return $this->search( array( 'deelplan_id' => $deelplan_id ), null, false, 'AND', 'naam' ); } function verwijder_voor_deelplan( $deelplan_id ) { $this->db->query( 'DELETE FROM deelplan_bouwdelen WHERE deelplan_id = ' . intval( $deelplan_id ) ); } } <file_sep>function afspraakPopup( datum, start_tijd, eind_tijd, onStore ) { var timePickerConfig = { hourText: 'Uur', minuteText: 'Minuut', amPmText: ['',''], defaultTime: '09:00', minutes: { starts: 0, ends: 45, interval: 15 }, rows: 4, showCloseButton: true, closeButtonText: 'Sluiten', onClose: function() { var popup = getPopup(); var st = popup.find( '[name=start_tijd]' ); var et = popup.find( '[name=eind_tijd]' ); if (st.val() && et.val()) // both set? then do nothing return; var tgt, val, factor; if (st.val() && st[0] == this) tgt = et, val = st.val(), factor = 1; else if (et.val() && et[0] == this) tgt = st, val = et.val(), factor = -1; else return; if (!val.match( /^(\d{2}):(\d{2})$/ )) return; tgt.val( BRISToezicht.Tools.zeroPad( parseInt( RegExp.$1 ) + (1 * factor), 2 ) + ':' + RegExp.$2 ); } }; modalPopup({ width: 340, height: 230, top: 200, html: $('<div>') .css( 'padding', '20px' ) .css( 'font-size', '9pt' ) .append( $('<p>') .append( $('<div>') .text('Datum: ') .css( 'display', 'inline-block' ) .css( 'font-weight', 'bold' ) .css( 'width', '120px' ) ) .append( $('<input>') .attr('type', 'text') .attr( 'readonly', 'readonly' ) .attr( 'name', 'datum' ) .val( datum ) .datepicker({ dateFormat: "dd-mm-yy" }) .css({width:'10em'}) ) ) .append( $('<p>') .append( $('<div>') .text('Start tijd: ') .css( 'display', 'inline-block' ) .css( 'font-weight', 'bold' ) .css( 'width', '120px' ) ) .append( $('<input>') .attr( 'type', 'text' ) .attr( 'readonly', 'readonly' ) .attr( 'name', 'start_tijd' ) .val( start_tijd ) .timepicker(timePickerConfig) .css({width:'10em'}) ) ) .append( $('<p>') .append( $('<div>') .text('Eind tijd: ') .css( 'display', 'inline-block' ) .css( 'font-weight', 'bold' ) .css( 'width', '120px' ) ) .append( $('<input>') .attr( 'type', 'text' ) .attr( 'readonly', 'readonly' ) .attr( 'name', 'eind_tijd' ) .val( eind_tijd ) .timepicker(timePickerConfig) .css({width:'10em'}) ) ) .append( $('<p>') .css('padding-top', '5px') .append( $('<input>') .attr( 'type', 'button' ) .attr( 'value', 'Opslaan' ) .click( function(){ closePopup( 1 ); } ) ) .append( $('<input>') .attr( 'type', 'button' ) .attr( 'value', 'Annuleren' ) .click( function(){ closePopup( 0 ); } ) ) ) .append( $('<span>') .css( 'font-style', 'italic' ) .css( 'color', '#777' ) .css( 'font-size', '8pt' ) .html( 'Agendasynchronisatie kan uitsluitend plaatsvinden wanneer u alle bovenstaande velden volledig invult.' ) ) , onClose: function( ret ) { if (!ret || !parseInt(ret)) // cancel clicked or outside popup return; var popup = getPopup(); var nieuweDatum = popup.find( '[name=datum]' ).val(); var nieuweStartTijd = popup.find( '[name=start_tijd]' ).val(); var nieuweEindTijd = popup.find( '[name=eind_tijd]' ).val(); onStore( nieuweDatum, nieuweStartTijd, nieuweEindTijd ); } }); } <file_sep>ALTER TABLE `bt_checklist_groepen` DROP `standaard_waardeoordeel_tekst_14`, DROP `standaard_waardeoordeel_is_leeg_14`, DROP `standaard_waardeoordeel_kleur_14`, DROP `standaard_waardeoordeel_tekst_24`, DROP `standaard_waardeoordeel_is_leeg_24`, DROP `standaard_waardeoordeel_kleur_24`; ALTER TABLE `bt_checklisten` DROP `standaard_waardeoordeel_tekst_14`, DROP `standaard_waardeoordeel_is_leeg_14`, DROP `standaard_waardeoordeel_kleur_14`, DROP `standaard_waardeoordeel_tekst_24`, DROP `standaard_waardeoordeel_is_leeg_24`, DROP `standaard_waardeoordeel_kleur_24`; ALTER TABLE `bt_hoofdgroepen` DROP `standaard_waardeoordeel_tekst_14`, DROP `standaard_waardeoordeel_is_leeg_14`, DROP `standaard_waardeoordeel_kleur_14`, DROP `standaard_waardeoordeel_tekst_24`, DROP `standaard_waardeoordeel_is_leeg_24`, DROP `standaard_waardeoordeel_kleur_24`; ALTER TABLE `bt_vragen` DROP `waardeoordeel_tekst_14`, DROP `waardeoordeel_is_leeg_14`, DROP `waardeoordeel_kleur_14`, DROP `waardeoordeel_tekst_24`, DROP `waardeoordeel_is_leeg_24`, DROP `waardeoordeel_kleur_24`; <file_sep>ALTER TABLE `webservice_log` DROP FOREIGN KEY `webservice_log_ibfk_1` , ADD FOREIGN KEY ( `webservice_account_id` ) REFERENCES `webservice_accounts` ( `id` ) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `webservice_log` ADD `extra_result` TEXT NULL DEFAULT NULL ;<file_sep>ALTER TABLE `deelplan_checklist_groepen` ADD `voortgang_percentage` INT NOT NULL DEFAULT '0'; -- draai php index.php /cli/calc_voortgangen !!!<file_sep>REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('extern.inloggen::mail', 'e-mailadres', NOW(), 0), ('extern.inloggen::password', '<PASSWORD>', NOW(), 0), ('extern.inloggen::newpassword', '<PASSWORD>', NOW(), 0), ('extern.inloggen::stayloggedin', 'ingelogd blijven', NOW(),0), ('extern.inloggen::login', 'Login', NOW(), 0), ('extern.inloggen::setpassword', 'W<PASSWORD>woord instellen', NOW(), 0), ('extern.inloggen::invalid_token', 'Het token dat u heeft gebruikt is niet (langer) geldig, Neem svp contact op met de helpdesk', NOW(), 0), ('extern..index::afsluiten', 'Afsluiten', NOW(), 0), ('extern..index::deelplannen.header', 'Deelplannen', NOW(), 0), ('extern..index::deelplannen.kies.deelplan', 'Kies een deelplan om de inspectie te starten:', NOW(), 0), ('extern..index::deelplannen.welkom', 'Welkom', NOW(), 0), ('extern..index::dossiers.kies.adres', 'Kies hieronder het adres:', NOW(), 0), ('extern..index::dossiers.welkom', 'Welkom', NOW(), 0), ('extern..index::dossiers.welkom', 'Wilkommen', NOW(), 2), ('extern..index::echt.afsluiten', 'Wilt u werkelijk afsluiten? Eventuele niet gereed gemelde opdrachten zullen niet worden gesynchroniseerd.', NOW(), 0), ('extern..index::er.is.nog.geen.foto.gemaakt', 'Deze opdracht vereist dat u een foto maakt. U kunt deze opdracht daarom nog niet gereed melden.', NOW(), 0), ('extern..index::er.is.nog.geen.waardeoordeel.gegeven', 'Er is nog geen waardeoordeel gegeven of foto gemaakt. U kunt deze opdracht daarom nog niet gereed melden.', NOW(), 0), ('extern..index::even-geduld-aub', 'Even geduld aub...', NOW(), 0), ('extern..index::form.uploaden', 'Gegevens uploaden...', NOW(), 0), ('extern..index::foto', 'Foto', NOW(), 0), ('extern..index::foto.gemaakt', 'Foto gemaakt, nog niet gesynchroniseerd.', NOW(), 0), ('extern..index::foto.locatie', 'Maak een foto op de aangegeven locatie. Klik op de tekening voor een vergroting. Klik op het camera icoon om een foto te maken.', NOW(), 0), ('extern..index::foto.nog.niet.gemaakt', 'Nog geen foto gemaakt.', NOW(), 0), ('extern..index::foto.nog.niet.gemaakt.op.locatie', 'Nog geen foto gemaakt op locatie: $1', NOW(), 0), ('extern..index::foto.uploaden', 'Foto $1/$2 uploaden...', NOW(), 0), ('extern..index::fout-bij-synchroniseren', 'Er is iets fout gegaan bij het synchroniseren. Uw gegevens zijn nog niet veilig verwerkt. Klik op de knop hieronder om het nogmaals te proberen.', NOW(), 0), ('extern..index::gereed', 'Gereed', NOW(), 0), ('extern..index::gereed.datum.tekst', 'Opdracht dient gereed te zijn voor $1.', NOW(), 0), ('extern..index::gereed_datum', 'Gereed datum', NOW(), 0), ('extern..index::kies.een.waardeoordeel', '-- kies een waardeoordeel --', NOW(), 0), ('extern..index::klaar-om-te-synchroniseren', 'Uw gereed gemelde opdrachten staan klaar om gesynchroniseerd te worden. Klik op de knop hieronder zodra u een betrouwbare en bij voorkeur snelle internetverbinding heeft (b.v. WiFi.) U kunt op dit moment deze pagina nog NIET afsluiten, anders gaan uw gegevens verloren!', NOW(), 0), ('extern..index::locatie', 'Locatie', NOW(), 0), ('extern..index::niets-te-synchroniseren', 'U heeft geen opdrachten gereed gemeld, er is daarom niets te synchroniseren. U kunt nu veilig deze pagina afsluiten.', NOW(), 0), ('extern..index::opdracht.echt.opnieuw.uitvoeren', 'Opdracht echt opnieuw uitvoeren? Eventuele gemaakte foto''s zullen ook worden gewist!', NOW(), 0), ('extern..index::opdrachten.header', 'Overzicht', NOW(), 0), ('extern..index::ophalen.afbeeldingen', 'Ophalen afbeeldingen...', NOW(), 0), ('extern..index::opnieuw', 'Opnieuw', NOW(), 0), ('extern..index::overniew.proberen', 'Opnieuw proberen', NOW(), 0), ('extern..index::synchroniseren-afgerond', 'Het synchroniseren is succesvol afgerond. U kunt nu veilig deze pagina afsluiten.', NOW(), 0), ('extern..index::terug', 'Terug', NOW(), 0), ('extern..index::toelichting', 'Toelichting', NOW(), 0), ('extern..index::upload.starten', 'Synchronisatie starten', NOW(), 0), ('extern..index::volgende', 'Volgende', NOW(), 0), ('extern..index::vorige', 'Vorige', NOW(), 0); <file_sep><? require_once 'base.php'; class CategorieResult extends BaseResult { function CategorieResult( &$arr ) { parent::BaseResult( 'categorie', $arr ); } public function get_vragen() { $CI = get_instance(); $CI->load->model( 'vraag' ); return $CI->vraag->get_by_categorie( $this->id ); } public function get_vragen_map( $matrixmapId=0, $artikelId=0 ) { $CI = get_instance(); $CI->load->model( 'vraag' ); $res = $CI->vraag->get_by_categorie_map( $this->id, $matrixmapId, $artikelId ); return $res; } public function rename( $name ) { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'CategorieResult::rename', 'UPDATE bt_categorieen SET naam = ? WHERE id = ?', $db ); $CI->dbex->execute( 'CategorieResult::rename', array( $name, $this->id ), $db ); $this->naam = $name; } public function get_hoofdgroep() { $CI = get_instance(); $CI->load->model( 'hoofdgroep' ); return $CI->hoofdgroep->get( $this->hoofdgroep_id ); } // If $set is not null, the prioriteiten are SET to that value. If it's NULL, nothing is initially done. // If $or is not null, the prioriteiten are OR'd with that value, making it easy to add e.g. "prio 5" to all existing prioriteiten, without changing the rest of the bits // If $clear is not null, the prioriteiten are AND (NOT $clear)'d, making it easy to remove e.g. "prio 3" from all existing prioriteiten, without changing the rest of the bits function verander_prioriteiten( $set=null, $or=null, $clear=null ) { if (is_null( $set ) && is_null( $or ) && is_null( $clear )) return; foreach ($this->get_vragen() as $vraag) $vraag->verander_prioriteiten( $set, $or, $clear ); } /** Kopieert deze categorie. Als er een ander hoofdgroep ID wordt meegegeven, dan * komt de kopie onder die hoofdgroep te hangen. Anders wordt het een identieke * kopie onder dezelfde hoofdgroep. * Als een andere hoofdgroep ID is opgegeven, verandert de sortering verder ook niet. * Wordt een hoofdgroep ID weggelaten, dan wordt de sortering dusdanig aangepast dat * de kopie onderaan de hoofdgroep komt te hangen. * * @return Geeft de kopie terug in object vorm. */ public function kopieer( $ander_hoofdgroep_id=null ) { $categorie = kopieer_object( $this, 'hoofdgroep_id', $ander_hoofdgroep_id ); foreach ($this->get_vragen() as $vraag) $vraag->kopieer( $categorie->id ); return $categorie; } } class Categorie extends BaseModel { function Categorie() { parent::BaseModel( 'CategorieResult', 'bt_categorieen', true ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'hoofdgroep', 'hoofdgroep_id' ); } function get_by_hoofdgroep( $hoofdgroep_id ) { if (!$this->dbex->is_prepared( 'get_by_hoofdgroep' )) $this->dbex->prepare( 'get_by_hoofdgroep', 'SELECT * FROM '.$this->_table.' WHERE hoofdgroep_id = ? ORDER BY sortering', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'get_by_hoofdgroep', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } // CANNOT BE USED INSIDE TRANSACTIONS!!! public function add( $hoofdgroep_id, $name ) { // we use table locks, this autocommits any transactions, so be sure non are active $db = $this->get_db(); // Determine which "null function" should be used $null_func = get_db_null_function(); // prepare statements //$this->dbex->prepare( 'Categorie::add', 'INSERT INTO bt_categorieen (hoofdgroep_id, sortering, naam) VALUES (?, ?, ?)', $db ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'Categorie::search', 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS m FROM bt_categorieen WHERE hoofdgroep_id = ?', $db ); // lock, get max id, create new entries, and be done $res = $this->dbex->execute( 'Categorie::search', array( $hoofdgroep_id ) ); $sortering = intval( reset( $res->result() )->m ); /* $args = array( 'hoofdgroep_id' => $hoofdgroep_id, 'sortering' => $sortering, 'naam' => $name, ); $this->dbex->execute( 'Categorie::add', $args, false, $db ); $id = $this->db->insert_id(); $result = new $this->_model_class( $args ); $result->id = $id; return $result; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'hoofdgroep_id' => $hoofdgroep_id, 'sortering' => $sortering, 'naam' => $name, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } } <file_sep><?php abstract class BRIS_HttpResponse_Abstract { private $_exists = false; /** * @param string $xml_response */ public function __construct($xml_response) { $sxe = new SimpleXMLElement($xml_response); if( isset($sxe->entry->content) ) { $this->_exists = true; $properties = $sxe->entry->content->children('m', true)->children('d', true); foreach($properties as $key => $value) { $this->$key = empty($value) ? null : (string) $value; } } } public function exists() { return $this->_exists; } }<file_sep>CREATE TABLE IF NOT EXISTS `deelplan_checklistgroep_planning` ( `deelplan_id` int(11) NOT NULL, `checklist_groep_id` int(11) DEFAULT NULL, `eerste_hercontrole_datum` date DEFAULT NULL, KEY `deelplan_id` (`deelplan_id`,`checklist_groep_id`), KEY `checklist_groep_id` (`checklist_groep_id`), KEY `eerste_hercontrole_datum` (`eerste_hercontrole_datum`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `deelplan_planning` ( `deelplan_id` int(11) NOT NULL, `gepland_datum` date DEFAULT NULL, KEY `deelplan_id` (`deelplan_id`), KEY `gepland_datum` (`gepland_datum`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `dossier_planning` ( `dossier_id` int(11) NOT NULL, `gepland_datum` date DEFAULT NULL, KEY `dossier_id` (`dossier_id`), KEY `gepland_datum` (`gepland_datum`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `deelplan_checklistgroep_planning` ADD CONSTRAINT `deelplan_checklistgroep_planning_ibfk_2` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_checklistgroep_planning_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `deelplan_planning` ADD CONSTRAINT `deelplan_planning_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `dossier_planning` ADD CONSTRAINT `dossier_planning_ibfk_1` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- -- -- start /cli/planning_updater -- -- -- <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('deelplannen.checklistgroep::status_filter', 'Status', NOW()) ,('deelplannen.checklistgroep::betrokkene_filter', 'Betrokkene', NOW()) ,('deelplannen.checklistgroep::betrokkene_filter_all', 'Alle betrokkenen', NOW()) ,('deelplannen.checklistgroep::kies_een_betrokkene_om_op_te_filteren', 'Kies een betrokkene om op te filteren', NOW()) ,('deelplannen.checklistgroep::datum_filter', 'Hercontrole', NOW()) ,('deelplannen.checklistgroep::datum_filter_all', 'Alle hercontroledata', NOW()) ,('deelplannen.checklistgroep::kies_een_datum_om_op_te_filteren', 'Kies een datum om op te filteren', NOW()) ,('deelplannen.checklistgroep::fase_filter', 'Fase', NOW()) ,('deelplannen.checklistgroep::fase_filter_all', 'Alle fases', NOW()) ,('deelplannen.checklistgroep::kies_een_fase_om_op_te_filteren', 'Kies een fase om op te filteren', NOW()) ,('deelplannen.checklistgroep::toezichtmoment_filter', 'Toezichtmoment', NOW()) ,('deelplannen.checklistgroep::toezichtmoment_filter_all', 'Alle momenten', NOW()) ,('deelplannen.checklistgroep::kies_een_toezichtmoment_om_op_te_filteren', 'Kies een toezichtmoment om op te filteren', NOW()) ; <file_sep>PDFAnnotator.Editable.Compound = PDFAnnotator.Editable.extend({ lines: [], init: function( config ) { this._super( null, true /* fake editable, do not check tool reference! */ ); this.setData( config, { filter: 'geel', waardeoordeel: '-' }, [ 'bgcolor', 'bold', 'bouwdeel_ids', 'font', 'h', 'italic', 'photoid', 'size', 'status', 'text', 'textcolor', 'type', 'underline', 'w', 'x', 'y' ] ); this.line = null; this.origData = config; }, render: function() { var toelichting = this.data.text.replace( /\n/g, '<br/>' ); var margin = 3; var padding = 2; var waardeoordeelWidth = parseInt(this.data.w) - 3*margin - 36; var waardeoordeelHeight = 18; var toelichtingHeight = parseInt(this.data.h) - 3*margin - waardeoordeelHeight; // base object var base = $('<div>') .addClass( 'Rounded10' ) .css( 'left', this.data.x + 'px' ) .css( 'top', this.data.y + 'px' ) .css( 'width', this.data.w + 'px' ) .css( 'height', this.data.h + 'px' ) .css( 'padding', '4px' ) .css( 'position', 'absolute' ) .css( 'background-color', '#e6e6e6' ) .css( 'border', '3px solid #000' ) .css( 'color', '#000' ) .css( 'font-size', this.data.size ); // add divs for elements var filter = this.data.filter; if (!filter) filter = 'geel'; $('<img>') .attr( 'src', '/files/pdf-annotator/images/nlaf/compound-' + filter + '.png' ) .css( 'position', 'absolute' ) .css( 'left', margin + 'px' ) .css( 'top', margin + 'px' ) .css( 'width', '36px' ) .css( 'height', '36px' ) .appendTo( base ); // add waardeoordeel text $('<div>') .text( this.data.waardeoordeel ) .css( 'position', 'absolute' ) .css( 'left', (36 + margin) + 'px' ) .css( 'top', margin + 'px' ) .css( 'width', waardeoordeelWidth + 'px' ) .css( 'height', waardeoordeelHeight + 'px' ) .css( 'font-size', '12pt' ) .appendTo( base ); // add foto image var havePhoto = this.data.photoid ? true : false; $('<img>') .attr( 'src', '/files/pdf-annotator/images/nlaf/compound-have-' + (havePhoto ? '' : 'no-') + 'photo.png' ) .css( 'position', 'absolute' ) .css( 'left', margin + 'px' ) .css( 'top', (36 + 2*margin) + 'px' ) .css( 'width', '36px' ) .css( 'height', '36px' ) .appendTo( base ); // add toelichting text $('<div>') .text( toelichting ) .css( 'position', 'absolute' ) .css( 'border', '1px solid #000' ) .css( 'left', (2*margin + 36) + 'px' ) .css( 'top', (2*margin + waardeoordeelHeight) + 'px' ) .css( 'width', (waardeoordeelWidth - 2*padding) + 'px' ) .css( 'height', (toelichtingHeight - 2*padding) + 'px' ) .css( 'padding', padding + 'px' ) .css( 'font-size', '12pt' ) .css( 'background-color', '#fff' ) .appendTo( base ); this.addVisual( base ); }, /** !!override!! */ getHandle: function( type ) { return null; }, /* !!overide!! */ rawExport: function() { return this.origData; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Compound(data); }, /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { } }); <file_sep>CREATE TABLE IF NOT EXISTS `notificaties` ( `id` int(11) NOT NULL AUTO_INCREMENT, `gebruiker_id` int(11) DEFAULT NULL, `datum` datetime NOT NULL, `bericht` varchar(1024) NOT NULL, `klikbaar` TINYINT NOT NULL DEFAULT '0', `dossier_id` int(11) DEFAULT NULL, `deelplan_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `gebruiker_id` (`gebruiker_id`), KEY `dossier_id` (`dossier_id`), KEY `deelplan_id` (`deelplan_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `notificaties` ADD CONSTRAINT `notificaties_ibfk_3` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `notificaties_ibfk_1` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `notificaties_ibfk_2` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; INSERT INTO `bt_checklist_koppel_voorwaarden` (`id`, `checklist_id`, `veld`, `operator`, `waarde`) VALUES (1, 609, 'aanvraagdatum', '<', '01-04-2012'), (2, 609, 'is integraal', '==', 'ja'), (3, 609, 'bouwsom', '>', '100000'), (15, 610, 'aanvraagdatum', '<', '01-04-2012'), (16, 610, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (17, 610, 'bouwsom', '<=', '100000'), (18, 611, 'aanvraagdatum', '<', '01-04-2012'), (19, 611, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (20, 611, 'bouwsom', '>', '100000'), (21, 611, 'bouwsom', '<=', '1000000'), (22, 612, 'aanvraagdatum', '<', '01-04-2012'), (23, 612, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (24, 612, 'bouwsom', '>', '1000000'), (25, 613, 'aanvraagdatum', '<', '01-04-2012'), (26, 613, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (27, 613, 'bouwsom', '<=', '100000'), (28, 614, 'aanvraagdatum', '<', '01-04-2012'), (29, 614, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (30, 614, 'bouwsom', '<=', '100000'), (31, 614, 'is eenvoudig', '==', 'ja'), (32, 615, 'aanvraagdatum', '<', '01-04-2012'), (33, 615, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (34, 615, 'bouwsom', '>', '100000'), (35, 615, 'bouwsom', '<=', '1000000'), (36, 616, 'aanvraagdatum', '<', '01-04-2012'), (37, 616, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (38, 616, 'bouwsom', '>', '1000000'), (39, 617, 'aanvraagdatum', '<', '01-04-2012'), (40, 617, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (41, 617, 'is dakkapel', '==', 'ja'), (43, 618, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (44, 618, 'bouwsom', '>', '100000'), (45, 618, 'is integraal', '==', 'ja'), (47, 619, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (48, 619, 'bouwsom', '<=', '100000'), (50, 618, 'aanvraagdatum', '>=', '01-04-2012'), (51, 619, 'aanvraagdatum', '>=', '01-04-2012'), (52, 620, 'aanvraagdatum', '>=', '01-04-2012'), (53, 620, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (54, 620, 'bouwsom', '>=', '100000'), (55, 620, 'bouwsom', '<', '1000000'), (56, 621, 'aanvraagdatum', '>=', '01-04-2012'), (57, 621, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (58, 621, 'bouwsom', '>', '1000000'), (59, 632, 'aanvraagdatum', '>=', '01-04-2012'), (60, 632, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (61, 632, 'is dakkapel', '==', 'ja'), (62, 622, 'aanvraagdatum', '>=', '01-04-2012'), (63, 622, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (64, 622, 'bouwsom', '<=', '100000'), (65, 623, 'aanvraagdatum', '>=', '01-04-2012'), (66, 623, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (67, 623, 'bouwsom', '<=', '100000'), (68, 623, 'is eenvoudig', '==', 'ja'), (69, 624, 'aanvraagdatum', '>=', '01-04-2012'), (70, 624, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (71, 624, 'bouwsom', '>', '100000'), (72, 624, 'bouwsom', '<=', '1000000'), (73, 625, 'aanvraagdatum', '>=', '01-04-2012'), (74, 625, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (75, 625, 'bouwsom', '>', '1000000'), (76, 609, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (77, 609, 'is eenvoudig', '==', 'nee'), (78, 609, 'is dakkapel', '==', 'nee'), (79, 609, 'is bestaand', '==', 'nee'), (80, 610, 'is integraal', '==', 'nee'), (81, 610, 'is eenvoudig', '==', 'nee'), (82, 610, 'is dakkapel', '==', 'nee'), (83, 610, 'is bestaand', '==', 'nee'), (84, 611, 'is integraal', '==', 'nee'), (85, 611, 'is eenvoudig', '==', 'nee'), (86, 611, 'is dakkapel', '==', 'nee'), (87, 611, 'is bestaand', '==', 'nee'), (88, 612, 'is integraal', '==', 'nee'), (89, 612, 'is eenvoudig', '==', 'nee'), (90, 612, 'is dakkapel', '==', 'nee'), (91, 612, 'is bestaand', '==', 'nee'), (92, 613, 'is integraal', '==', 'nee'), (93, 613, 'is eenvoudig', '==', 'nee'), (94, 613, 'is dakkapel', '==', 'nee'), (95, 613, 'is bestaand', '==', 'nee'), (96, 614, 'is integraal', '==', 'nee'), (97, 614, 'is dakkapel', '==', 'nee'), (98, 614, 'is bestaand', '==', 'nee'), (99, 615, 'is integraal', '==', 'nee'), (100, 615, 'is eenvoudig', '==', 'nee'), (101, 615, 'is dakkapel', '==', 'nee'), (102, 615, 'is bestaand', '==', 'nee'), (103, 616, 'is integraal', '==', 'nee'), (104, 616, 'is eenvoudig', '==', 'nee'), (105, 616, 'is dakkapel', '==', 'nee'), (106, 616, 'is bestaand', '==', 'nee'), (107, 618, 'is eenvoudig', '==', 'nee'), (108, 618, 'is dakkapel', '==', 'nee'), (109, 618, 'is bestaand', '==', 'nee'), (110, 619, 'is integraal', '==', 'nee'), (111, 619, 'is eenvoudig', '==', 'nee'), (112, 619, 'is dakkapel', '==', 'nee'), (113, 619, 'is bestaand', '==', 'nee'), (114, 620, 'is integraal', '==', 'nee'), (115, 620, 'is eenvoudig', '==', 'nee'), (116, 620, 'is dakkapel', '==', 'nee'), (117, 620, 'is bestaand', '==', 'nee'), (118, 621, 'is integraal', '==', 'nee'), (119, 621, 'is eenvoudig', '==', 'nee'), (120, 621, 'is dakkapel', '==', 'nee'), (121, 621, 'is bestaand', '==', 'nee'), (122, 632, 'is integraal', '==', 'nee'), (123, 632, 'is eenvoudig', '==', 'nee'), (124, 632, 'is bestaand', '==', 'nee'), (125, 622, 'is integraal', '==', 'nee'), (126, 622, 'is eenvoudig', '==', 'nee'), (127, 622, 'is dakkapel', '==', 'nee'), (128, 622, 'is bestaand', '==', 'nee'), (129, 623, 'is integraal', '==', 'nee'), (130, 623, 'is dakkapel', '==', 'nee'), (131, 623, 'is bestaand', '==', 'nee'), (132, 624, 'is integraal', '==', 'nee'), (133, 624, 'is eenvoudig', '==', 'nee'), (134, 624, 'is dakkapel', '==', 'nee'), (135, 624, 'is bestaand', '==', 'nee'), (136, 625, 'is integraal', '==', 'nee'), (137, 625, 'is eenvoudig', '==', 'nee'), (138, 625, 'is dakkapel', '==', 'nee'), (139, 625, 'is bestaand', '==', 'nee'), (141, 1663, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (142, 1663, 'gebruiksfunctie', 'bevat niet', 'bijeenkomstfunctie'), (143, 1663, 'gebruiksfunctie', 'bevat niet', 'celfunctie'), (144, 1663, 'gebruiksfunctie', 'bevat niet', 'gezondheidszorgfunctie'), (145, 1663, 'gebruiksfunctie', 'bevat niet', 'logiesfunctie'), (146, 1663, 'gebruiksfunctie', 'bevat niet', 'onderwijsfunctie'), (147, 1663, 'gebruiksfunctie', 'bevat niet', 'sportfunctie'), (148, 1663, 'gebruiksfunctie', 'bevat niet', 'winkelfunctie'), (149, 1663, 'gebruiksfunctie', 'bevat niet', 'kantoorfunctie'), (150, 1663, 'bouwsom', '>', '1000000'), (151, 1663, 'is bestaand', '==', 'ja'), (153, 1652, 'gebruiksfunctie', 'bevat niet', 'woonfunctie'), (154, 1652, 'is bestaand', '==', 'ja'), (155, 1651, 'gebruiksfunctie', 'bevat', 'woonfunctie'), (156, 1651, 'is bestaand', '==', 'ja'); <file_sep>RENAME TABLE `bt_checklist_aandachtspunten` TO `bt_checklist_ndchtspntn` ; RENAME TABLE `bt_checklist_grondslagen` TO `bt_checklist_grndslgn` ; RENAME TABLE `bt_checklist_richtlijnen` TO `bt_checklist_rchtlnn` ; ALTER TABLE `bt_checklisten` CHANGE `standaard_gebruik_grondslagen` `standaard_gebruik_grndslgn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_richtlijnen` `standaard_gebruik_rchtlnn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_ndchtspntn` `standaard_gebruik_ndchtspntn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_opdrachten` `standaard_gebruik_opdrachten` TINYINT( 4 ) NULL DEFAULT NULL ; RENAME TABLE `bt_hoofdgroep_aandachtspunten` TO `bt_hoofdgroep_ndchtspntn` ; RENAME TABLE `bt_hoofdgroep_grondslagen` TO `bt_hoofdgroep_grndslgn` ; RENAME TABLE `bt_hoofdgroep_richtlijnen` TO `bt_hoofdgroep_rchtlnn` ; ALTER TABLE `bt_hoofdgroepen` CHANGE `standaard_gebruik_grondslagen` `standaard_gebruik_grndslgn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_richtlijnen` `standaard_gebruik_rchtlnn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_ndchtspntn` `standaard_gebruik_ndchtspntn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `standaard_gebruik_opdrachten` `standaard_gebruik_opdrachten` TINYINT( 4 ) NULL DEFAULT NULL ; RENAME TABLE `bt_vraag_aandachtspunten` TO `bt_vraag_ndchtspntn` ; RENAME TABLE `bt_vraag_grondslagen` TO `bt_vraag_grndslgn` ; RENAME TABLE `bt_vraag_richtlijnen` TO `bt_vraag_rchtlnn` ; ALTER TABLE `bt_vragen` CHANGE `gebruik_grondslagen` `gebruik_grndslgn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `gebruik_richtlijnen` `gebruik_rchtlnn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `gebruik_ndchtspntn` `gebruik_ndchtspntn` TINYINT( 4 ) NULL DEFAULT NULL , CHANGE `gebruik_opdrachten` `gebruik_opdrachten` TINYINT( 4 ) NULL DEFAULT NULL ; <file_sep>BRISToezicht.Toets.Verantwoording = { verantwoordingen: {}, // jQuery collection initialize: function() { // toelichting index $('input[type=button][toelichting_index]').live( 'click', function(){ var index = $(this).attr( 'toelichting_index' ); BRISToezicht.Toets.Verantwoording.select( index ); }); // nieuwe toelichting $('#nlaf_NieuweToelichting').click(function(){ BRISToezicht.Toets.Verantwoording.addNieuw(); }); if (BRISToezicht.Toets.readonlyMode) $('#nlaf_NieuweToelichting').attr( 'disabled', 'disabled' ); // preset verantwoordingen button $('#nlaf_KiesToelichting').click(function(){ BRISToezicht.Toets.Verantwoording.popup(); }); // annuleren button $('#nlaf_AnnuleerToelichting').click(function(){ // herstel tekst in textarea var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraagData) $('#nlaf_ToelichtingTextarea').val( vraagData.inputs.toelichting.value ); // sluit popup $('#nlaf_HeaderTerug div').trigger( 'click' ); }); // voeg toe button $('#nlaf_VoegToeToelichting').click(function(){ var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) { BRISToezicht.Toets.data.use_default=1; // wanneer er geen vraag gselecteerd is, handel deze knop anders af if (!BRISToezicht.Toets.Vraag.handleOnderwerpVerantwoordingEnWaardeoordeel()) return; } else // sla toelichting op bij vraag BRISToezicht.Toets.Verantwoording.updateToelichting(); // sluit popup $('#nlaf_HeaderTerug div').trigger( 'click' ); }); }, laatsteActief: function() { return $('#nlaf_ToelichtingTextarea[readonly]').size() == 0; }, updateToelichting: function() { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; if (!this.laatsteActief()) return; if ($('#nlaf_ToelichtingTextarea').val() != vraagData.inputs.toelichting.value) { BRISToezicht.Toets.Vraag.markDirty( true ); vraagData.inputs.toelichting.value = $('#nlaf_ToelichtingTextarea').val(); $('#nlaf_VerantwoordingsTekst .tekst').text( vraagData.inputs.toelichting.value ); } }, updatePresetVerantwoordingen: function() { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData || vraagData.verantwoording_locked) { $('#nlaf_KiesToelichting').hide(); return; } var status = vraagData.inputs.status.value; if (!status || status==vraagData.button_config.standaard) { $('#nlaf_KiesToelichting').hide(); return; } var coord = status ? BRISToezicht.Toets.ButtonConfig.statusNaarPositie( status ) : null; var kleur = vraagData.button_config.kleur[coord.x][coord.y]; // compile list of verantwoordingen that are available for the current vraag/answer combination this.verantwoordingen = []; for (var i in BRISToezicht.Toets.data.verantwoordingen) { var v = BRISToezicht.Toets.data.verantwoordingen[i]; if (typeof(v) != 'object') continue; if (!v.verantwoordingstekst.length) continue; if (v.status && v.status.length) { if (v.status != kleur) { continue; } } if(!BRISToezicht.Toets.is_automatic_accountability_text==true && v.type==1){ continue; } if(BRISToezicht.Toets.is_automatic_accountability_text==true && v.button_naam!=vraagData.inputs.status.defaultValue && v.type==1){ continue; } var text=$('#nlaf_ToelichtingTextarea').val(); var VerantwoordingsTekst=$('#nlaf_VerantwoordingsTekst .tekst').html(); if(v.automatish_generate==1){ $('#nlaf_ToelichtingTextarea').val( text+ " "+v.verantwoordingstekst); $('#nlaf_VoegToeToelichting').click(); } var gebruik = false; switch (vraagData.gebruik_verantwtkstn) { case 'cg': gebruik = (v.checklist_groep_id == BRISToezicht.Toets.data.checklist_groep_id); break; case 'cl': gebruik = (v.checklist_id == vraagData.checklist_id); break; case 'h': gebruik = (v.hoofdgroep_id == vraagData.hoofdgroep_id); break; case 'v': gebruik = (v.vraag_id == vraagData.vraag_id); break; } if(v.type==1 && vraagData.vraag_id!=v.vraag_id) continue; if (!gebruik && v.type!=1) continue; this.verantwoordingen.push( v ); }; // now, show/hide button based on number of available verantwoordingen var button = $('#nlaf_KiesToelichting'); button[ this.verantwoordingen.length == 0 ? 'hide' : 'show' ](); button.attr( 'value', 'Kies een standaard tekst (' + this.verantwoordingen.length + ')' ); }, setVerantwoordingsTekst: function( text ) { var htmlVersie = $('<div>').text( text ).html(); var nl2br = htmlVersie.replace( /\n/g, '<br/>' ); $('#nlaf_VerantwoordingsTekst .tekst').html( nl2br ); /* is een DIV */ $('#nlaf_ToelichtingTextarea').val( text ); /* is een TEXTAREA */ }, addNieuw: function() { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData() ,new_toelichting_id = Math.floor(Date.now() / 1000); if (!vraagData){ $("#nlaf_ToelichtingTextarea").val(""); return; } // als er nu niks is ingevuld, niks doen if (!vraagData.inputs.toelichting.value && !vraagData.inputs.status.value) return; // data voor huidige toelichting, welke we zo meteen in een vraaggeschiedenis entry gaan stoppen var huidigeToelichting = { _command: "vraaggeschiedenis", status: vraagData.inputs.status.value || 'in_bewerking', toelichting: vraagData.inputs.toelichting.value || '', datum: vraagData.last_updated_at || BRISToezicht.Tools.getDateYMDHIS(), vraag_id: BRISToezicht.Toets.Vraag.huidigeVraag, toel_id: vraagData.huidige_toelichting_id, gebruiker_id: vraagData.gebruiker_id }; // voeg vraaggeschiedenis entry toe aan de interne data structuur // dit MOET, anders wordt er geen nette nieuwe knop toegevoegd de volgende keer dat deze // vraag geselecteerd wordt in de HUIDIGE SESSIE! // LET OP: dit object is qua structuur gelijk aan zoals ze worden aangemaakt in toetsdata-js.php! vraagData.vraaggeschiedenis.push({ status: huidigeToelichting.status, gebruiker_id: huidigeToelichting.gebruiker_id, datum: huidigeToelichting.datum, toel_id: huidigeToelichting.toel_id, tekst: huidigeToelichting.toelichting }); // voeg hidden vraaggeschiedenis entry toe aan de form, zodat bij het opslaan de geschiedenis ook daadwerkelijk opgeslagen wordt! BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( huidigeToelichting ) ); // nu alles gezet is, zet de huidige gebruiker_id in de vraag data naar de huidige ingelogde gebruiker! // het kan zo zijn dat een vraag in het verleden is ingevuld door een eerder toegekende toezichthouder, // anders dan de huidige ingelogde gebruiker; om alle nieuwe toelichtingen aan de ingelogde toezichthouder // te koppelen, updaten we de gebruiker id vraagData.gebruiker_id = BRISToezicht.Toets.data.gebruiker_id; // leeg huidige toelichting en status vraagData.inputs.status.value = ''; vraagData.inputs.toelichting.value = ''; vraagData.inputs.toelichting_id.value = new_toelichting_id; vraagData.huidige_toelichting_id = new_toelichting_id; vraagData.last_updated_at = BRISToezicht.Tools.getDateYMDHIS(); vraagData.verantwoording_locked = false; $('#nlaf_VoegToeToelichting').removeAttr( 'disabled' ); // reselect current, to reflect changes visually BRISToezicht.Toets.Vraag.reselect(); }, select: function( toelichting_index ) { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; // check if this is the latest toelichting, i.e. the one that's editable var numToelichtingGeschiedenis = vraagData.vraaggeschiedenis.length; var changeToLatest = numToelichtingGeschiedenis < toelichting_index; // sla nu eerst tekst in de textarea op if (this.laatsteActief()) { this.updateToelichting(); } // now setup toelichting stuff! var toelichtingTextarea = $('#nlaf_ToelichtingTextarea'); if (changeToLatest) { BRISToezicht.Toets.Verantwoording.setVerantwoordingsTekst( vraagData.inputs.toelichting.value ); toelichtingTextarea.css( 'color', 'black' ); toelichtingTextarea.removeAttr( 'readonly' ); } else { // make sure index is correct if (toelichting_index >= 1 && toelichting_index <= numToelichtingGeschiedenis) { var vg = vraagData.vraaggeschiedenis[toelichting_index-1]; var gebruiker = BRISToezicht.Toets.data.gebruikers[ vg.gebruiker_id ]; var status = vg.status; var statusTekst; switch (vraagData.type) { case 'meerkeuzevraag': if (status) { var coord = BRISToezicht.Toets.ButtonConfig.statusNaarPositie( status, true ); statusTekst = vraagData.button_config.tekst[coord.x][coord.y]; } else { statusTekst = 'Niet ingevuld.'; } break; case 'invulvraag': statusTekst = status; break; } var tekst = ''; tekst += 'Verantwoording ' + toelichting_index + '\n'; tekst += 'Door: ' + gebruiker + '\n'; tekst += 'Datum: ' + vg.datum + '\n'; tekst += 'Beoordeling: ' + statusTekst + '\n'; tekst += '\n'; tekst += vg.tekst; BRISToezicht.Toets.Verantwoording.setVerantwoordingsTekst( tekst ); toelichtingTextarea.attr( 'readonly', 'readonly' ); } // display error! else { $('#nlaf_ToelichtingTextarea').val( 'Interne fout, index niet in range: ' + toelichting_index + ' (' + numToelichtingGeschiedenis + ')' ); toelichtingTextarea.attr( 'readonly', 'readonly' ); } } // disable/enable buttons $('input[toelichting_index]').removeAttr( 'disabled' ); $('input[toelichting_index=' + toelichting_index + ']').attr( 'disabled', 'disabled' ); }, popup: function() { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; $('#nlaf_Waardeoordeel .editor').hide(); $('#nlaf_Waardeoordeel .standaardtekst').show(); var tr = null; var table = $('#nlaf_Waardeoordeel .standaardtekst'); table.html(''); for (var i=0; i<BRISToezicht.Toets.Verantwoording.verantwoordingen.length; ++i) { var v = BRISToezicht.Toets.Verantwoording.verantwoordingen[i]; if (!(i % 2)) tr = $('<tr>').appendTo( table ); var td = $('<td>').appendTo( tr ).css('cursor', 'pointer').data( 'verantwoording', v ).click(function(){ $('#nlaf_Waardeoordeel .editor').show(); $('#nlaf_Waardeoordeel .standaardtekst').hide(); var curTekst = '' + $('#nlaf_ToelichtingTextarea').val(); if (curTekst.length) curTekst += '\n\n\n'; curTekst += $(this).data( 'verantwoording' ).verantwoordingstekst; $('#nlaf_ToelichtingTextarea').val( $('<div>').html(curTekst).text() ); }); var lines = v.verantwoordingstekst.split( '\n' ); for (var j=0; j<lines.length; ++j) $('<p style="margin: 2px">').appendTo( td ).html( lines[j] ); } } }; <file_sep>REPLACE INTO teksten(string, tekst , timestamp , lease_configuratie_id) VALUES ('dossiers.rapportage::uitvoer.docxpdf', 'PDF - v1.0.0 - 15-5-2015', '2015-05-15 15:45:00', 0), ('dossiers.rapportage::uitvoer.docxpdf', 'PDF - v1.0.0 - 15-5-2015', '2015-05-15 15:45:00', 1), ('dossiers.rapportage::uitvoer.docx', 'DOCX - v1.0.0 - 15-5-2015', '2015-05-15 15:45:00', 0), ('dossiers.rapportage::uitvoer.docx', 'DOCX - v1.0.0 - 15-5-2015', '2015-05-15 15:45:00', 1) ; <file_sep><?php function thumb( $file ) { exec( 'convert ' . escapeshellarg($file) . ' -resize 40x40 ' . escapeshellarg($file . '.thumb.png') ); } function do_dir( $dir ) { foreach (scandir( $dir ) as $e) if ($e != '.' && $e != '..') if (is_dir( $dir . '/' . $e )) do_dir( $dir . '/' . $e ); else if (is_file( $dir . '/' . $e ) && preg_match( '/\.png$/i', $e ) && !preg_match( '/\.thumb\.png$/i', $e )) thumb( $dir . '/' . $e ); } do_dir( dirname(__FILE__) ); <file_sep><?php class KlantenWebserviceModule extends WebserviceModule { public function GeefKlanten() { // go! $result = array( 'Success' => true, 'Klanten' => array(), ); foreach ($this->CI->klant->all() as $klant) if ($this->_account->mag_bij_klant( $klant->id )) $result['Klanten'][] = array( 'KlantId' => intval( $klant->id ), 'Naam' => $klant->naam, 'VolledigeNaam' => $klant->volledige_naam, ); // output! $this->_output_json( $result ); } public function GeefGebruikers() { // check post variables if ($this->CI->login->logged_in()) $this->_data->KlantId = $this->CI->gebruiker->get_logged_in_gebruiker()->klant_id; else verify_data_members( array( 'KlantId' ), $this->_data ); // check access if (!$this->_account->mag_bij_klant( $this->_data->KlantId )) throw new ServerSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot opgegeven klant.' ); // go! $result = array( 'Success' => true, 'Gebruikers' => array(), ); foreach ($this->CI->gebruiker->get_by_klant( $this->_data->KlantId, true ) as $gebruiker) $result['Gebruikers'][] = array( 'KlantId' => intval( $gebruiker->klant_id ), 'GebruikerId' => intval( $gebruiker->id ), 'VolledigeNaam' => html_entity_decode( $gebruiker->get_status(), ENT_COMPAT, 'UTF-8' ), 'Rol' => ($rol = $gebruiker->get_rol()) ? $rol->naam : '[geen rol]', ); // output! $this->_output_json( $result ); } } WebserviceModule::register_module( WS_COMPONENT_KLANTEN_KOPPELING, new KlantenWebserviceModule() ); <file_sep><?php function htag( $tag, $m=null, $c=null, $style=null, $small=false ) { return get_instance()->helpbutton->tag( $tag, $m, $c, $style, $small ); } function htags( $tag, $m=null, $c=null, $style=null ) { return get_instance()->helpbutton->tag( $tag, $m, $c, $style, true ); } function htagr( $tag, $m=null, $c=null ) { return htag( $tag, $m, $c, "float:right;" ); } class CI_HelpButton { const SESSION_EDIT_MODE = 'helpbutton-editmode'; private $_CI; private $_teksten = array(); private $_edit_mode = false; public function __construct() { $this->_CI = get_instance(); $query = 'SELECT tag, tekst FROM help_buttons WHERE taal = \'nl\''; //d($query); $res = $this->_CI->db->query( $query ); //echo 'HelpButton result: <br />'; //d($res->result()); foreach ($res->result() as $row) $this->_teksten[$row->tag] = $row->tekst; $res->free_result(); if ($this->_CI->session->userdata( self::SESSION_EDIT_MODE )) $this->_edit_mode = true; } public function tag( $tag, $m=null, $c=null, $style='', $small=false ) { global $class, $method; // prepare full tag if (!$c) $c = $class; if (!$m) $m = $method; $full_tag = $c . '.' . $m . '.' . $tag; // build HTML based on whether there's tekst // NOTE: add lots of style directly to element, so CSS styles will not accidentally override $have_tekst = isset( $this->_teksten[$full_tag] ) && strlen(trim($this->_teksten[$full_tag]))>0; $div_style = 'position:absolute;background-color:#505050;border:2pxsolid#303030;color:white;padding:3px;margin:0;min-width:200px;max-width:300px;height:auto;font-weight:normal;font-size:90%;text-align:left;white-space:normal;'; $parent_start = '<div class="helpbutton" style="width:auto;height:auto;border:0;margin:0;padding:0;color:inherit;background-color:transparent;vertical-align:middle;text-align:left;white-space:normal;'.$style.'">'; $parent_end = '</div>'; $filename_extra = $small ? '-s' : ''; if (!$this->_edit_mode) { if ($have_tekst) return $parent_start . '<img src="' . site_url('/files/images/help'.$filename_extra.'.png' ) . '" help_button_tag="' . $full_tag . '" small="' . intval($small) . '" />' . '<div style="' . $div_style . '" class="hidden" help_button_tag="' . $full_tag . '">' . nl2br(htmlentities( $this->_teksten[$full_tag], ENT_COMPAT, 'UTF-8' )) . '</div>' . $parent_end; else return ''; } else { if ($have_tekst) return $parent_start . '<img src="' . site_url('/files/images/help'.$filename_extra.'.png' ) . '" help_button_tag="' . $full_tag . '" class="editable" small="' . intval($small) . '" />' . '<div style="' . $div_style . '" class="hidden" help_button_tag="' . $full_tag . '">' . nl2br(htmlentities( $this->_teksten[$full_tag], ENT_COMPAT, 'UTF-8' )) . '</div>' . $parent_end; else return $parent_start . '<img src="' . site_url('/files/images/help-empty'.$filename_extra.'.png' ) . '" help_button_tag="' . $full_tag . '" class="editable empty" small="' . intval($small) . '" />' . '<div style="' . $div_style . '" class="hidden" help_button_tag="' . $full_tag . '"></div>' . $parent_end; } } public function store( $tag, $tekst ) { $stmt_name = 'CI_HelpButton::store'; if ($tekst) { // !!! Note: check if the Oracle implementation properly updates the 'laast_bijgewerkt_op' column too! //$this->_CI->dbex->prepare( $stmt_name, 'REPLACE INTO help_buttons (tag, tekst, taal) VALUES (?, ?, \'nl\')' ); $this->_CI->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO help_buttons (tag, tekst, taal) VALUES (?, ?, ?)', null, array('tag') ); $this->_CI->dbex->execute( $stmt_name, array( $tag, $tekst, 'nl' ) ); } else { $this->_CI->dbex->prepare( $stmt_name, 'DELETE FROM help_buttons WHERE tag = ?' ); $this->_CI->dbex->execute( $stmt_name, array( $tag ) ); } } public function toggle_edit_mode() { $this->_edit_mode = !$this->_edit_mode; $this->_CI->session->set_userdata( self::SESSION_EDIT_MODE, intval($this->_edit_mode) ); } public function edit_mode() { return $this->_edit_mode; } } <file_sep><?php class ChecklistWizard extends Controller { public function __construct() { parent::__construct(); $this->navigation->push( 'nav.instellingen', '/instellingen' ); $this->navigation->push( 'nav.checklist_wizard', '/checklistwizard' ); $this->navigation->set_active_tab( 'beheer' ); $this->load->helper( 'wizard' ); } /**************************************************************************************************************************************************** * * * I N D E X * * * ****************************************************************************************************************************************************/ public function index() { redirect( '/checklistwizard/checklistgroepen' ); } /**************************************************************************************************************************************************** * * * C H E C K L I S T G R O E P E N * * * ****************************************************************************************************************************************************/ public function checklistgroepen() { $toon_alle_beschikbare_checklistgroepen = $this->session->userdata( 'toon_alle_beschikbare_checklistgroepen' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'image' ); $this->image->all(); // precache all $this->load->view( 'checklistwizard/checklistgroepen', array( 'checklistgroepen' => $this->checklistgroep->get_for_huidige_klant( false /* niet assoc */, !$toon_alle_beschikbare_checklistgroepen ), 'toon_alle_beschikbare_checklistgroepen' => $toon_alle_beschikbare_checklistgroepen, ) ); } public function checklistgroepen_toon_alle_toggle_beschikbare() { $toon_alle_beschikbare_checklistgroepen = $this->session->userdata( 'toon_alle_beschikbare_checklistgroepen' ); $this->session->set_userdata( 'toon_alle_beschikbare_checklistgroepen', !$toon_alle_beschikbare_checklistgroepen ); redirect( '/checklistwizard/checklistgroepen' ); } public function checklistgroep_volgorde() { $this->navigation->push( 'nav.checklist_wizard.checklistgroep_volgorde', '/checklistwizard/checklistgroep_volgorde' ); $this->load->model( 'checklistgroep' ); $checklistgroepen = $this->checklistgroep->get_for_huidige_klant( true /* niet assoc */, true /* alleen eigen */ ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') $this->_update_volgorde_in_objecten( $checklistgroepen, false ); else $this->load->view( 'checklistwizard/checklistgroep_volgorde', array( 'checklistgroepen' => array_values( $checklistgroepen ) ) ); } public function checklistgroep_verwijderen() { $this->_check_post(); $this->_verwijder_object( 'checklistgroep', $_POST['entry_id'], function( $obj ) { return $obj; } ); } public function checklistgroep_kopieren() { $this->_check_post(); $this->_kopieer_object( 'checklistgroep', $_POST['entry_id'], function( $obj ) { return $obj; } ); } public function checklistgroep_toevoegen() { try { $this->_check_post(); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege naam niet toegestaan.' ); $this->load->model( 'checklistgroep' ); if ($this->checklistgroep->find( $naam )) throw new Exception( 'Er bestaat reeds een checklistgroep met de opgegeven naam.' ); $obj = $this->checklistgroep->add( $naam ); // voeg toe met default settings echo json_encode(array( 'success' => true, 'checklist_groep_id' => $obj->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function checklistgroep_uitgebreid_toevoegen( $naam='' ) { $config = array( 'headers' => true, 'modus' => 'nieuw', 'model' => 'checklistgroep', 'context' => null, 'checklistgroep' => null, 'naam' => rawurldecode( $naam ), 'return_url' => '/checklistwizard/checklistgroepen', ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroep_uitgebreid_toevoegen', '/checklistwizard/checklistgroep_uitgebreid_toevoegen' ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } public function checklistgroep_bewerken( $checklist_groep_id ) { $this->load->model( 'checklistgroep' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklistgroep ID opgegeven.' ); $config = array( 'headers' => true, 'modus' => 'defaults', 'model' => 'checklistgroep', 'context' => $checklistgroep, 'checklistgroep' => $checklistgroep, 'return_url' => '/checklistwizard/checklistgroepen', ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroep_uitgebreid_bewerken', '/checklistwizard/checklistgroep_uitgebreid_bewerken', array( $checklistgroep->naam ) ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } /**************************************************************************************************************************************************** * * * C H <NAME> N * * * ****************************************************************************************************************************************************/ public function checklisten( $checklist_groep_id=null ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklist_groep_id ); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklistgroepen', array( $checklistgroep->naam ) ); $this->load->view( 'checklistwizard/checklisten', array( 'checklistgroep' => $checklistgroep, 'checklisten' => $checklistgroep->get_checklisten(), ) ); } public function checklist_volgorde( $checklist_groep_id=null ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklist_groep_id ); if ($checklistgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist groep ID ' . $checklist_groep_id ); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklist_groep_id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklist_volgorde', '/checklistwizard/checklist_volgorde/' . $checklist_groep_id ); $checklisten = $checklistgroep->get_checklisten(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') $this->_update_volgorde_in_objecten( $checklisten, true ); else $this->load->view( 'checklistwizard/checklist_volgorde', array( 'checklistgroep' => $checklistgroep, 'checklisten' => array_values( $checklisten ) ) ); } public function checklist_verwijderen() { $this->_check_post(); $this->_verwijder_object( 'checklist', $_POST['entry_id'], function( $obj ) { return $obj->get_checklistgroep(); } ); } public function checklist_kopieren() { $this->_check_post(); $this->_kopieer_object( 'checklist', $_POST['entry_id'], function( $obj ) { return $obj->get_checklistgroep(); } ); } public function checklist_toevoegen( $checklist_groep_id ) { try { $this->_check_post(); $this->load->model( 'checklistgroep' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklist_groep_id ); if ($checklistgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist groep ID ' . $checklist_groep_id ); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege naam niet toegestaan.' ); if ($checklistgroep->find_checklist( $naam )) throw new Exception( 'Er bestaat reeds een checklist met de opgegeven naam.' ); $obj = $this->checklist->add( $checklistgroep->id, $naam ); // voeg toe met default settings echo json_encode(array( 'success' => true, 'checklist_id' => $obj->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function checklist_uitgebreid_toevoegen( $checklist_groep_id, $naam='' ) { $this->load->model( 'checklistgroep' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklist_groep_id ); if ($checklistgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist groep ID ' . $checklist_groep_id ); $config = array( 'headers' => true, 'modus' => 'nieuw', 'model' => 'checklist', 'context' => $checklistgroep, 'checklistgroep' => $checklistgroep, 'naam' => rawurldecode( $naam ), 'return_url' => '/checklistwizard/checklisten/' . $checklist_groep_id, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklist_uitgebreid_toevoegen', '/checklistwizard/checklist_uitgebreid_toevoegen' ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } public function checklist_bewerken( $checklist_id ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID opgegeven.' ); if ($checklist->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist ID ' . $checklist_id ); $checklistgroep = $checklist->get_checklistgroep(); $config = array( 'headers' => true, 'modus' => 'defaults', 'model' => 'checklist', 'context' => $checklist, 'checklistgroep' => $checklistgroep, 'return_url' => '/checklistwizard/checklisten/' . $checklistgroep->id, // return URL na opslaan 'checklist' => $checklist, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklist_uitgebreid_bewerken', '/checklistwizard/checklist_uitgebreid_bewerken', array( $checklist->naam ) ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } /**************************************************************************************************************************************************** * * * H O O F D G R O E P E N * * * ****************************************************************************************************************************************************/ public function hoofdgroepen( $checklist_id=null ) { $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); $checklistgroep = $checklist->get_checklistgroep(); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->load->view( 'checklistwizard/hoofdgroepen', array( 'checklistgroep' => $checklistgroep, 'checklist' => $checklist, 'hoofdgroepen' => $checklist->get_hoofdgroepen(), ) ); } public function hoofdgroep_volgorde( $checklist_id=null ) { $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); if ($checklist->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist ID ' . $checklist_id ); $checklistgroep = $checklist->get_checklistgroep(); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklist->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist_id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroep_volgorde', '/checklistwizard/hoofdgroep_volgorde/' . $checklist_id ); $hoofdgroepen = $checklist->get_hoofdgroepen(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') $this->_update_volgorde_in_objecten( $hoofdgroepen, true ); else $this->load->view( 'checklistwizard/hoofdgroep_volgorde', array( 'checklistgroep' => $checklistgroep, 'checklist' => $checklist, 'hoofdgroepen' => array_values( $hoofdgroepen ) ) ); } public function hoofdgroep_verwijderen() { $this->_check_post(); $this->_verwijder_object( 'hoofdgroep', $_POST['entry_id'], function( $obj ) { return $obj->get_checklist()->get_checklistgroep(); } ); } public function hoofdgroep_kopieren() { $this->_check_post(); $this->_kopieer_object( 'hoofdgroep', $_POST['entry_id'], function( $obj ) { return $obj->get_checklist()->get_checklistgroep(); } ); } public function hoofdgroep_toevoegen( $checklist_id ) { try { $this->_check_post(); $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); if ($checklist->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist ID ' . $checklist_id ); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege naam niet toegestaan.' ); if ($checklist->find_hoofdgroep( $naam )) throw new Exception( 'Er bestaat reeds een hoofdgroep met de opgegeven naam.' ); $obj = $this->hoofdgroep->add( $checklist->id, $naam ); // voeg toe met default settings echo json_encode(array( 'success' => true, 'checklist_id' => $obj->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function hoofdgroep_uitgebreid_toevoegen( $checklist_id, $naam='' ) { $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); if ($checklist->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot checklist ID ' . $checklist_id ); $checklistgroep = $checklist->get_checklistgroep(); $config = array( 'headers' => true, 'modus' => 'nieuw', 'model' => 'hoofdgroep', 'context' => $checklist, 'checklistgroep' => $checklistgroep, 'naam' => rawurldecode( $naam ), 'return_url' => '/checklistwizard/hoofdgroepen/' . $checklist_id, 'checklist' => $checklist, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist_id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroep_uitgebreid_toevoegen', '/checklistwizard/hoofdgroep_uitgebreid_toevoegen' ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } public function hoofdgroep_bewerken( $hoofdgroep_id ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); if (!($hoofdgroep = $this->hoofdgroep->get( $hoofdgroep_id ))) throw new Exception( 'Ongeldig hoofdgroep ID opgegeven.' ); if ($hoofdgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot hoofdgroep ID ' . $hoofdgroep_id ); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $config = array( 'headers' => true, 'modus' => 'defaults', 'model' => 'hoofdgroep', 'context' => $hoofdgroep, 'checklistgroep' => $checklistgroep, 'return_url' => '/checklistwizard/hoofdgroepen/' . $checklist->id, // return URL na opslaan 'checklist' => $checklist, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroep_uitgebreid_bewerken', '/checklistwizard/hoofdgroep_uitgebreid_bewerken', array( $hoofdgroep->naam ) ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } /**************************************************************************************************************************************************** * * * <NAME> * * * ****************************************************************************************************************************************************/ public function vragen( $hoofdgroep_id=null ) { $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'vraag' ); if (!($hoofdgroep = $this->hoofdgroep->get( $hoofdgroep_id ))) throw new Exception( 'Ongeldig hoofdgroep ID ' . $hoofdgroep_id ); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroepen', '/checklistwizard/vragen/' . $hoofdgroep->id, array( $hoofdgroep->naam ) ); $this->load->view( 'checklistwizard/vragen', array( 'checklistgroep'=> $checklistgroep, 'checklist' => $checklist, 'hoofdgroep' => $hoofdgroep, 'vragen' => $this->_get_hoofdgroep_vragen( $hoofdgroep ), ) ); } public function vraag_volgorde( $hoofdgroep_id=null ) { $this->load->model( 'hoofdgroep' ); $this->load->model( 'vraag' ); if (!($hoofdgroep = $this->hoofdgroep->get( $hoofdgroep_id ))) throw new Exception( 'Ongeldig hoofdgroep ID ' . $hoofdgroep_id ); if ($hoofdgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot hoofdgroep ID ' . $hoofdgroep_id ); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroepen', '/checklistwizard/vragen/' . $hoofdgroep_id, array( $hoofdgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.vraag_volgorde', '/checklistwizard/vraag_volgorde/' . $hoofdgroep_id ); $vragen = $this->_get_hoofdgroep_vragen( $hoofdgroep ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') $this->_update_volgorde_in_objecten( $vragen, true ); else $this->load->view( 'checklistwizard/vraag_volgorde', array( 'checklistgroep' => $checklistgroep, 'hoofdgroep' => $hoofdgroep, 'vragen' => array_values( $vragen ), 'checklist' => $checklist, ) ); } public function vraag_verwijderen() { $this->_check_post(); $this->_verwijder_object( 'vraag', $_POST['entry_id'], function( $obj ) { return $obj->get_categorie()->get_hoofdgroep()->get_checklist()->get_checklistgroep(); } ); } public function vraag_kopieren() { $this->_check_post(); $this->_kopieer_object( 'vraag', $_POST['entry_id'], function( $obj ) { return $obj->get_categorie()->get_hoofdgroep()->get_checklist()->get_checklistgroep(); } ); } public function vraag_toevoegen( $hoofdgroep_id ) { try { $this->_check_post(); $this->load->model( 'hoofdgroep' ); if (!($hoofdgroep = $this->hoofdgroep->get( $hoofdgroep_id ))) throw new Exception( 'Ongeldig hoofdgroep ID ' . $hoofdgroep_id ); if ($hoofdgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot hoofdgroep ID ' . $hoofdgroep_id ); $tekst = trim( $_POST['naam'] ); if (!strlen( $tekst )) throw new Exception( 'Lege vraag tekst niet toegestaan.' ); $categorieen = $hoofdgroep->get_categorieen(); if (empty( $categorieen )) $categorie = $this->categorie->add( $hoofdgroep_id, '...' ); else $categorie = array_pop( $categorieen ); // voeg toe aan laatste $this->load->model( 'vraag' ); $obj = $this->vraag->add( $categorie->id, $tekst, NULL /* defaults thema id */, NULL /* default aanwezigheid */ ); echo json_encode(array( 'success' => true, 'checklist_id' => $obj->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function vraag_uitgebreid_toevoegen( $hoofdgroep_id, $tekst='' ) { $this->load->model( 'hoofdgroep' ); if (!($hoofdgroep = $this->hoofdgroep->get( $hoofdgroep_id ))) throw new Exception( 'Ongeldig hoofdgroep ID ' . $hoofdgroep_id ); if ($hoofdgroep->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot hoofdgroep ID ' . $hoofdgroep_id ); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $config = array( 'headers' => true, 'modus' => 'nieuw', 'model' => 'vraag', 'context' => $hoofdgroep, 'checklistgroep' => $checklistgroep, 'tekst' => rawurldecode( $tekst ), 'return_url' => '/checklistwizard/vragen/' . $hoofdgroep_id, 'checklist' => $checklist, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroepen', '/checklistwizard/vragen/' . $hoofdgroep->id, array( $hoofdgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.vraag_uitgebreid_toevoegen', '/checklistgroepwizard/vraag_uitgebreid_toevoegen' ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } public function vraag_bewerken( $vraag_id ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'vraag' ); if (!($vraag = $this->vraag->get( $vraag_id ))) throw new Exception( 'Ongeldig vraag ID opgegeven.' ); if ($vraag->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot vraag ID ' . $vraag_id ); $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $config = array( 'headers' => true, 'modus' => 'defaults', 'model' => 'vraag', 'context' => $vraag, 'checklistgroep' => $checklistgroep, 'return_url' => '/checklistwizard/vragen/' . $hoofdgroep->id, // return URL na opslaan 'checklist' => $checklist, ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->_process_uitgebreide_editor( $_POST, $config ); } else { $this->navigation->push( 'nav.checklist_wizard.checklistgroepen', '/checklistwizard/checklisten/' . $checklistgroep->id, array( $checklistgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.checklisten', '/checklistwizard/hoofdgroepen/' . $checklist->id, array( $checklist->naam ) ); $this->navigation->push( 'nav.checklist_wizard.hoofdgroepen', '/checklistwizard/vragen/' . $hoofdgroep->id, array( $hoofdgroep->naam ) ); $this->navigation->push( 'nav.checklist_wizard.vraag_uitgebreid_bewerken', '/checklistwizard/vraag_uitgebreid_bewerken', array( $vraag->tekst ) ); $this->load->view( 'checklistwizard/_uitgebreide_editor', $config ); } } /**************************************************************************************************************************************************** * * * P U B L I C H U L P F U N C T I E S * * * ****************************************************************************************************************************************************/ public function hoofdthema_toevoegen() { try { $this->_check_post(); $this->load->model( 'hoofdthema' ); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege hoofdthema naam niet toegestaan.' ); if (!($hoofdthema = $this->hoofdthema->find( $naam ))) $hoofdthema = $this->hoofdthema->add( $naam, 0, 'Eigen' ); echo json_encode(array( 'success' => true, 'hoofdthema_id' => $hoofdthema->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function thema_toevoegen() { try { $this->_check_post(); $this->load->model( 'hoofdthema' ); $this->load->model( 'thema' ); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege thema naam niet toegestaan.' ); $hoofdthema_id = $_POST['hoofdthema_id']; if (!($hoofdthema = $this->hoofdthema->get( $hoofdthema_id ))) throw new Exception( 'Ongeldig hoofdthema opgegeven om nieuw thema aan te koppelen.' ); $thema = resolve_thema( 'new', $naam, $hoofdthema->naam ); echo json_encode(array( 'success' => true, 'thema_id' => $thema->id, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function richtlijn_toevoegen() { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') { $this->load->model( 'richtlijn' ); $this->load->view( 'checklistwizard/richtlijn_toevoegen',array('richtlijn_documents' => $this->richtlijn->get_multi_documents()) ); } else { try { $this->load->model( 'richtlijn' ); switch ($_POST['type']) { case 'upload': if (!isset( $_FILES['upload'] ) || $_FILES['upload']['error'] || !$_FILES['upload']['size'] ) throw new Exception( 'Fout bij uploaden, of geen bestand geselecteerd.' ); if (false === ($contents = @file_get_contents( $_FILES['upload']['tmp_name'] ))) throw new Exception( 'Interne fout bij verwerken van upload, kon bestandsinformatien niet lezen.' ); $filename = $_FILES['upload']['name']; if (!($rl = $this->richtlijn->add( $filename, $contents ))) throw new Exception( 'Fout bij opslaan van upload in de database.' ); break; case 'url': $url = @$_POST['url']; $url_beschrijving = @$_POST['url_beschrijving']; if (!preg_match( '#^([a-z]+)://#i', $url, $matches )) $url = 'http://' . $url; else if (!in_array( strtolower( $matches[1] ), array( 'http', 'https', 'ftp' ))) throw new Exception( 'Ongeldige URL, alleen http, https en ftp zijn toegestaan.' ); if (!($rl = $this->richtlijn->find_url( $url, $url_beschrijving ))) $rl = $this->richtlijn->add_url( $url, $url_beschrijving ); break; case 'exist': if (isset($_POST['exist'])){ $documents=$_POST['exist']; foreach ($documents as $documents_id){ $rl = $this->richtlijn->get_multi_documents($documents_id); $richtlijn_id[] =array($rl[0]->id); $filename[]=array($rl[0]->filename); } } break; default: throw new Exception( 'Ongeldig richtlijn type.' ); } if (!$rl) throw new Exception( 'Algemene fout bij toevoegen richtlijn.' ); if($_POST['type']=="exist"){ echo json_encode(array( 'success' => true, 'richtlijn_id' => $richtlijn_id, 'filename' => $filename, 'url' => @$rl[0]->url, 'url_beschrijving' => @$rl[0]->url_beschrijving, )); } else { echo json_encode(array( 'success' => true, 'richtlijn_id' => $rl->id, 'filename' => @$rl->filename, 'url' => @$rl->url, 'url_beschrijving' => @$rl->url_beschrijving, )); } } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } } public function richtlijn_bewerken( $richtlijn_id ) { $this->load->model( 'richtlijn' ); if (!($rl = $this->richtlijn->get( $richtlijn_id ))) throw new Exception( 'Ongeldige richtlijn.' ); $this->load->view( 'checklistwizard/richtlijn_bewerken', array( 'rl' => $rl, ) ); } public function grondslag_toevoegen() { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') { $this->load->model( 'grondslag' ); $grondslagen = $this->grondslag->search( array('klant_id' => $this->gebruiker->get_logged_in_gebruiker()->klant_id), 'quest_document IS NULL', false, 'AND', 'grondslag' ); $this->load->view( 'checklistwizard/grondslag_toevoegen', array( 'grondslagen' => $grondslagen, ) ); } else { try { $data = @json_decode( @$_POST['data'] ); if (!is_array( $data )) throw new Exception( 'Interne fout, ongeldige data ontvangen, kan geen grondslagen toevoegen.' ); $this->load->model( 'grondslag' ); $this->load->model( 'grondslagtekst' ); $result = array(); $methodes = array(); $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; foreach ($data as $row) { // node is geselecteerd uit briswarenhuis browser if (isset( $row->document_id )) { // kennen we dit quest document al binnen deze klant? $grondslagen = $this->grondslag->search( array( 'klant_id' => $klant_id, 'quest_document' => $row->document_id ) ); if (empty( $grondslagen )) { $grondslag = $this->grondslag->add( $row->document, $klant_id ); $grondslag->quest_document = $row->document_id; $grondslag->save(0,0,0); } else $grondslag = reset($grondslagen ); } // node is zelf toegevoegd else { // !!! Note (OJG - 10-12-2014): oddly enough we ran into the situation where 'grondslag_naam' was completely missing from the POST data, but an // existing one was chosen. This code is now more error proof, and handles that situation correctly. //$grondslag_naam = trim($row->grondslag_naam); if (isset($row->grondslag_naam)) { $grondslag_naam = trim($row->grondslag_naam); if (empty( $grondslag_naam )) throw new Exception( 'Lege grondslag niet toegestaan.' ); $grondslag = $this->grondslag->add_conditional( $grondslag_naam ); if (!$grondslag || !$grondslag->id) throw new Exception( 'Interne database fout bij toevoegen nieuwe grondslag.' ); } else if (isset($row->grondslag_id)) { $grondslag_id = trim($row->grondslag_id); $grondslag = $this->grondslag->get($grondslag_id); if (!$grondslag || !$grondslag->id) throw new Exception( 'Interne database fout bij ophalen bestaande grondslag.' ); } else { throw new Exception( 'Onvoldoende gegevens beschikbaar om een grondslag op te halen of toe te voegen.' ); } } // bepaal wat de artikel tekst wordt waar we op gaan zoeken (dit is ivm de "oude" methode) if ($row->artikel) $artikel = $row->artikel; else if ($row->afdeling) $artikel = 'afdeling ' . $row->afdeling; else if ($row->hoofdstuk) $artikel = 'hoofdstuk ' . $row->hoofdstuk; else $artikel = null; $gt = null; // allereerst, zoek een grondslagtekst in de database op basis van de quest node, mss is hij reeds aanwezig if ($row->quest_node) { $gt = reset( $this->grondslagtekst->search( array( 'klant_id' => $grondslag->klant_id, 'quest_node' => $grondslag->quest_document . '/' . $row->quest_node ), null, null, 'AND', '', 'JOIN bt_grondslagen g ON T1.grondslag_id = g.id' ) ); if ($gt) $methodes[] = 'quest-node'; } // nog niks gevonden? probeer dan te zoeken op de ouderwetse "compound artikel" methode // maar alleen als we wel een "originele grondslag id", niet bij een net nieuw toegevoegde hebben if (!$gt && $artikel) { $gt = reset( $this->grondslagtekst->search( array( 'grondslag_id' => $grondslag->id, 'artikel' => $artikel ) ) ); if ($gt) $methodes[] = 'oude-artikel'; } // nog steeds niks? dan toevoegen if (!$gt) { $gt = $this->grondslagtekst->add_uitgebreid( $grondslag->id, $artikel, $grondslag->quest_document . '/' . $row->quest_node, $row->hoofdstuk, $row->afdeling, $row->paragraaf, $row->artikel, $row->lid, strval( @$row->tekst ) ); if (!$gt) throw new Exception( 'Database fout bij toevoegen nieuwe grondslag.' ); $methodes[] = 'nieuw'; } // done! $result[] = $gt->id; } echo json_encode(array( 'success' => true, 'result' => $result, 'methodes' => $methodes, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } } public function briswarenhuis() { try { $this->_check_post(); $this->load->library( 'quest' ); switch (@$_POST['command']) { case 'list-collectie': //$collectionId = 'bris-mobile'; $collectionId = 'bris-productie'; $parentId = @$_POST['parent_id']; $result = $this->quest->collectionlevel( $collectionId, $parentId ); break; case 'list-node': if (!strlen($document_id = @$_POST['document_id'])) throw new Exception( 'Geen document ID.' ); if (!strlen($node_id = @$_POST['node_id'])) $node_id = ''; $result = $this->quest->toclevel( $document_id, $node_id ); break; } echo json_encode(array( 'success' => true, 'result' => @$result, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function automatic_verantwoordingstekst_popup($vraag_id, $verantwoordingen_id=null){ $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'vraag' ); if (!($vraag = $this->vraag->get( $vraag_id ))) throw new Exception( 'Ongeldig vraag ID opgegeven.' ); if ($vraag->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot vraag ID ' . $vraag_id ); $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); $checklistgroep = $checklist->get_checklistgroep(); $Vkleur = array( array(array('name'=>'wo_kleur_00','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_00' )), array('name'=>'wo_kleur_10','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_10' )),array('name'=>'wo_kleur_20','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_20' ))), array(array('name'=>'wo_kleur_01','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_01' )), array('name'=>'wo_kleur_11','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_11' )),array('name'=>'wo_kleur_21','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_21' ))), array(array('name'=>'wo_kleur_02','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_02' )), array('name'=>'wo_kleur_12','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_12' )),array('name'=>'wo_kleur_22','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_22' ))), array(array('name'=>'wo_kleur_03','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_03' )), array('name'=>'wo_kleur_13','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_13' )),array('name'=>'wo_kleur_23','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_23' ))), array(array('name'=>'wo_kleur_04','value'=>$vraag->get_wizard_veld_recursief( 'wo_kleur_04' )), ), ); $Vtekst = array( array( $vraag->get_wizard_veld_recursief( 'wo_tekst_00' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_10' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_20' ) ), array( $vraag->get_wizard_veld_recursief( 'wo_tekst_01' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_11' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_21' ) ), array( $vraag->get_wizard_veld_recursief( 'wo_tekst_02' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_12' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_22' ) ), array( $vraag->get_wizard_veld_recursief( 'wo_tekst_03' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_13' ), $vraag->get_wizard_veld_recursief( 'wo_tekst_23' ) ), array( $vraag->get_wizard_veld_recursief( 'wo_tekst_04' ), ), ); $j=0; $rood=array(); $groen=array(); $oranje=array(); $this->load->model( 'verantwoording'); $automatic_verantwtkstn = $this->verantwoording->find_automatic_verantwtkstn($vraag_id); if ($verantwoordingen_id){ $data=$this->verantwoording->get_verantwoording_by_id($verantwoordingen_id); $button_name=$data ? $data[0]['button_naam'] : array(); } foreach ($Vkleur as $vkleur_value){ $i=0; foreach ($vkleur_value as $vkleur_result){ if($vkleur_result['value']=="rood"){ $key = isset($button_name) ? array_search(str_replace("wo_kleur_","w",$vkleur_result['name']), $button_name) : false; $rood[]=array('name'=>$vkleur_result['name'],'title'=>$Vtekst[$j][$i],'checked'=>$key || $key===0 ? 1 : 0); } if($vkleur_result['value']=="groen"){ $key = isset($button_name) ? array_search(str_replace("wo_kleur_","w",$vkleur_result['name']), $button_name) : false; $groen[]=array('name'=>$vkleur_result['name'],'title'=>$Vtekst[$j][$i],'checked'=>$key || $key===0 ? 1 : 0); } if($vkleur_result['value']=="oranje"){ $key = isset($button_name) ? array_search(str_replace("wo_kleur_","w",$vkleur_result['name']), $button_name ) : false; $oranje[]=array('name'=>$vkleur_result['name'],'title'=>$Vtekst[$j][$i],'checked'=>$key || $key===0 ? 1 : 0); } $i++; unset($key); } $j++; } $this->load->view( 'checklistwizard/automatic_verantwoordingstekst_popup', array( 'rood' =>$rood, 'groen' =>$groen, 'oranje' => $oranje, 'vraag_id' => $vraag_id, 'checklist' => $checklist, 'checklistgroep' =>$checklistgroep, 'text' => isset($data) ? $data[0]['verantwoordingsteksten'] : '', 'verantwoordingen_id' => isset($verantwoordingen_id) ? $verantwoordingen_id : '', 'automatish_generate' =>isset($data) ? $data[0]['automatish_generate']:'', 'automatic_verantwtkstn' => $automatic_verantwtkstn, ) ); } public function automatic_verantwoordingstekst_save(){ $this->load->model( 'verantwoording'); $this->load->model( 'vraag' ); if (!($vraag = $this->vraag->get( $_POST['vraag_id'] ))) throw new Exception( 'Ongeldig vraag ID opgegeven.' ); if ($vraag->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot vraag ID ' . $_POST['vraag_id'] ); $this->verantwoording->automatic_verantwoordingstekst_save($_POST); $result = wizard_get_automatic_verantwoordingsteksten($vraag); echo json_encode($result); } public function automatic_verantwoordingstekst_delete($vraag_id,$verantwoordingen_id){ $this->load->model( 'verantwoording'); $this->load->model( 'vraag' ); if (!($vraag = $this->vraag->get( $vraag_id))) throw new Exception( 'Ongeldig vraag ID opgegeven.' ); if ($vraag->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot vraag ID ' . $_POST['vraag_id'] ); $this->verantwoording->automatic_verantwoordingstekst_delete($verantwoordingen_id); $result = wizard_get_automatic_verantwoordingsteksten($vraag); echo json_encode($result); } /**************************************************************************************************************************************************** * * * P R I V A T E H U L P F U N C T I E S * * * ****************************************************************************************************************************************************/ private function _update_volgorde_in_objecten( array $objecten, $make_associative ) { // make assoc $_objecten = array(); foreach ($objecten as $object) $_objecten[$object->id] = $object; $objecten = $_objecten; unset( $_objecten ); // store order foreach ($_POST['order'] as $object_id => $order ) { $v = @$objecten[$object_id]; if ($v) { if ($v->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot object' ); $v->sortering = $order; $v->save(0,0,0); } } echo "OK"; } private function _get_hoofdgroep_vragen( $hoofdgroep ) { $vragen = array(); foreach ($hoofdgroep->get_categorieen() as $categorie) $vragen = array_merge( $vragen, $categorie->get_vragen() ); return $vragen; } private function _verwijder_object( $model, $id, $get_checklistgroep ) { $this->load->model( $model ); if (!($object = $this->{$model}->get( $id ))) throw new Exception( 'Ongeldig ID ' . $id ); if ($object->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot object' ); $object->delete(); echo "OK"; } private function _kopieer_object( $model, $id, $get_checklistgroep ) { $this->load->model( $model ); if (!($object = $this->{$model}->get( $id ))) throw new Exception( 'Ongeldig ID ' . $id ); $this->db->trans_start(); try { $object->kopieer(); if (!$this->db->trans_complete()) throw new Exception( 'Database transactie fout bij kopieren.' ); echo "OK"; } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); throw $e; } } private function _check_post() { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'HTTP verzoek is geen POST.' ); } private function _resize_image( $contents, $dWidth, $dHeight ) { $im = new Imagick(); $im->readImageBlob( $contents ); $width = $im->getImageWidth(); $height = $im->getImageHeight(); if( $dWidth == NULL ){ $newheight = $dHeight; $newwidth = ( $width / $height ) * $newheight; }elseif( $dHeight == NULL ){ $newwidth = $dWidth; $newheight = ( $height / $width ) * $newwidth; }elseif( $dHeight == NULL && $dWidth == NULL ){ $newwidth = $width; $newheight = $height; }else{ $newwidth = $dWidth; $newheight = ( $height / $width ) * $newwidth; if( $newheight > $dHeight){ $newheight = $dHeight; $newwidth = ( $width / $height ) * $newheight; } } $im->resizeImage( $newwidth, $newheight, imagick::FILTER_BOX, 0 ); $im->setImageFormat( 'jpeg' ); $im->setImageCompression( Imagick::COMPRESSION_JPEG ); $im->setImageCompressionQuality( 100 ); $contents = $im->getImageBlob(); unset( $im ); return $contents; } private function _process_uitgebreide_editor( array $postdata, array $config ) { $this->db->trans_start(); try { // we hebben ofwel een naam, ofwel een tekst, check voor lege strings if (isset($postdata['naam']) && !strlen($postdata['naam'])) throw new Exception( 'Lege naam niet toegestaan.' ); else if (isset($postdata['tekst']) && !strlen($postdata['tekst'])) throw new Exception( 'Lege tekst niet toegestaan.' ); $this->load->model( $config['model'] ); switch ($config['model']) { case 'checklistgroep': $bestaand = $this->checklistgroep->find( $postdata['naam'] ); break; case 'checklist': $parent = $config['context'] instanceof ChecklistGroepResult ? $config['context'] : $config['context']->get_checklistgroep(); $bestaand = $parent->find_checklist( $postdata['naam'] ); break; case 'hoofdgroep': $parent = $config['context'] instanceof ChecklistResult ? $config['context'] : $config['context']->get_checklist(); $bestaand = $parent->find_hoofdgroep( $postdata['naam'] ); break; case 'vraag': $bestaand = NULL; // dubbele vraag mag best, als mensen dat willen... break; default: throw new Exception( 'Checklistwizard interne configuratie niet correct: model "' . $config['model'] . '" niet ondersteund.' ); } // check of naam al in gebruik, en/of maak nieuw object aan in juiste model if ($config['modus'] == 'nieuw') { if ($bestaand) throw new Exception( 'Opgegeven naam reeds in gebruik.' ); if ($config['model'] == 'checklistgroep') $config['context'] = $this->{$config['model']}->add( $postdata['naam'] ); else if ($config['model'] == 'vraag') { $categorieen = $config['context']->get_categorieen(); if (empty( $categorieen )) $categorie = $this->categorie->add( $config['context']->id, '...' ); else $categorie = array_pop( $categorieen ); // voeg toe aan laatste $config['context'] = $this->{$config['model']}->add( $categorie->id, $postdata['tekst'] ); } else $config['context'] = $this->{$config['model']}->add( $config['context']->id, $postdata['naam'] ); if (!$config['context']) throw new Exception( 'Database fout bij toevoegen.' ); } else if ($config['modus'] == 'defaults') { if ($bestaand && ($bestaand->id != $config['context']->id)) throw new Exception( 'Opgegeven naam reeds in gebruik.' ); } // zet instellingen in het object! $this->_zet_uitgebreide_editor_data_in_object( $postdata, $config ); // rond transactie af! if (!$this->db->trans_complete()) throw new Exception( 'Database fout bij opslaan van de transactie.' ); echo json_encode(array( 'success' => true, )); } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } private function _zet_uitgebreide_editor_data_in_object( array $postdata, array $config ) { $debug = false; //$debug = true; /************************************************************************************************************************ * * * B A S I S D A T A * * * ************************************************************************************************************************/ $object = $config['context']; if ($object->is_wizard_readonly()) throw new Exception( 'Geen schrijf toegang tot object' ); $prefix = $object instanceof VraagResult ? '' : 'standaard_'; $naamveld = $object instanceof VraagResult ? 'tekst' : 'naam'; // !!! NOTE (OJG - 4-3-2016): The 'vraag' model currently adds in a field called 'naam' in the 'get' method. This field, however, // does not exist in the DB, so when the generic code tries to save a 'vraag' here, it errors out because a DB error is returned. // For now the fix is to check if we are editing a vraag, and if so, to unset the 'naam' member if it exists. // A better long-term fix is desirable for this in due time. if ( ($object instanceof VraagResult) && isset($object->naam) ) { if ($debug) echo "+++ Removing 'naam' member from vraag object! +++\n"; unset($object->naam); } // get parents $parent = $object->get_wizard_parent(); $parents = array(); while ($parent) { $parents[] = $parent; $parent = $parent->get_wizard_parent(); } // bewerk data hier en daar voor gebruik in database // stap 1: bewerk aanwezigheid vlaggen tot 1 geheel $aanwezigheid = 0; foreach ($postdata['aanwezigheid'] as $bit) $aanwezigheid |= $bit; $postdata['aanwezigheid'] = $aanwezigheid; // zet velden $velden = array( $naamveld, 'vraag_type', 'aanwezigheid', 'thema_id', 'toezicht_moment', 'fase', 'wo_tekst_00', 'wo_is_leeg_00', 'wo_kleur_00', 'wo_in_gebruik_00', 'wo_tekst_01', 'wo_is_leeg_01', 'wo_kleur_01', 'wo_in_gebruik_01', 'wo_tekst_02', 'wo_is_leeg_02', 'wo_kleur_02', 'wo_in_gebruik_02', 'wo_tekst_03', 'wo_is_leeg_03', 'wo_kleur_03', 'wo_in_gebruik_03', 'wo_tekst_04', 'wo_is_leeg_04', 'wo_kleur_04', 'wo_in_gebruik_04', 'wo_tekst_10', 'wo_is_leeg_10', 'wo_kleur_10', 'wo_in_gebruik_10', 'wo_tekst_11', 'wo_is_leeg_11', 'wo_kleur_11', 'wo_in_gebruik_11', 'wo_tekst_12', 'wo_is_leeg_12', 'wo_kleur_12', 'wo_in_gebruik_12', 'wo_tekst_13', 'wo_is_leeg_13', 'wo_kleur_13', 'wo_in_gebruik_13', 'wo_tekst_20', 'wo_is_leeg_20', 'wo_kleur_20', 'wo_in_gebruik_20', 'wo_tekst_21', 'wo_is_leeg_21', 'wo_kleur_21', 'wo_in_gebruik_21', 'wo_tekst_22', 'wo_is_leeg_22', 'wo_kleur_22', 'wo_in_gebruik_22', 'wo_tekst_23', 'wo_is_leeg_23', 'wo_kleur_23', 'wo_in_gebruik_23', 'wo_standaard', 'wo_steekproef', 'wo_steekproef_tekst' ); $changes = array(); $changesstr = ''; foreach ($velden as $veld) { // bekijk wat mijn nieuwe waarde gaat worden if (!isset( $postdata[$veld] )) throw new Exception( 'Missende formulier waarde: ' . $veld ); $mijn_waarde = $postdata[$veld]; if ($debug) d($veld); if ($debug) d($mijn_waarde); // het naam veld altijd zetten, is niet gerelateerd aan parent verder if ($veld == $naamveld) { if ($debug) echo "+++ 1 +++"; if ($object->$veld != $mijn_waarde) { if ($debug) echo "+++ 2 +++"; $changes[$veld] = $mijn_waarde; } } else if($veld == 'vraag_type' ) { if ($debug) echo "+++ 3 +++"; // This 'else if...' part is needed to be able to reset the standaard_vraag_type to the individually specified value (for the respective object) // regardless of what its parent has specified for the standaard_vraag_type. That effectively solves an ancient bug where in existing checklists it // was not possible to change this, if the object's parent had the same value. // The extra 'property_exists' check is needed here as this same code is used when creating a checklistgroup, checklist, etc. BUT at that time an // incomplete set of members is present in that object (e.g. the standaard_vraag_type does not exist at that time). If we omit the 'property_exists' // check, an error is shown on the screen when trying to create the checklistgroup, etc. despite the system actually having successfully stored it. if ( (property_exists ($object , $prefix.$veld) ) && ($object->{$prefix . $veld} != $mijn_waarde) ) { if ($debug) echo "+++ 4 +++"; $changes[$prefix . $veld] = $mijn_waarde; } } else { if ($debug) echo "+++ 5 +++"; // is dit anders dan mijn parent(s)? zo nee, dan NULL opslaan, zo ja, dan opslaan in dit object! $anders_dan_parent = empty( $parents ); if (!$anders_dan_parent) { if ($debug) echo "+++ 6 +++"; foreach ($parents as $parent) { $zijn_waarde = $parent->get_wizard_veld( $veld ); if (!is_null( $zijn_waarde )) { if ($debug) echo "+++ 7 +++"; if ($mijn_waarde != $zijn_waarde) { if ($debug) echo "+++ 8 +++"; if ($debug) $changesstr .= "VERSCHIL: $veld: mijn=$mijn_waarde, zijn=$zijn_waarde\n"; $anders_dan_parent = true; } break; } } } if (!$anders_dan_parent) { if ($debug) echo "+++ 9 +++"; $mijn_waarde = NULL; // !!! The following assignment was not present! This caused an incorrrect situation where e.g. the parent's value is empty and when at some point in // time the question's value was something other than empty, and the question field is then made empty again, the empty value of the question is // incorrectly 'missed' and the field is never reset! $changes[$prefix . $veld] = $mijn_waarde; if ($debug) $changesstr .= "GELIJK AAN PARENT - ZET WAARDE OP NULL VOOR VELD: $veld\n"; } else { if ($debug) echo "+++ 10 +++"; // zet waarde // if (@$object->{$prefix . $veld} != $mijn_waarde) $changes[$prefix . $veld] = $mijn_waarde; } } } if ($debug) echo "\n\n+-+- CHANGES: -+-+\n"; if ($debug) echo "\n\n" . $changesstr . "\n\n"; if ($debug) d($changes); //exit; // uitzonderingen if ($object instanceof ChecklistGroepResult) { $waarden = array( 'standaard_checklist_status' => $postdata['actief'], 'modus' => $postdata['modus'], 'themas_automatisch_selecteren' => $postdata['themas_automatisch_selecteren'], 'risico_model' => isset($postdata['risico_model']) ? $postdata['risico_model'] : 'generiek', ); if (isset( $_FILES['logo'] ) && $_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { try { $this->load->model( 'image' ); $contents = $this->_resize_image( @file_get_contents( $_FILES['logo']['tmp_name'] ), 32, 16 ); $image = $this->image->find_image_by_data( $contents ); if (!$image) $image = $this->image->add( $_FILES['logo']['name'], $contents, 32, 16 ); $waarden['image_id'] = $image->id; } catch (Exception $e) { throw new Exception( 'Er is iets fout gegaan bij het verwerken van het logo. Checklistgroep is nog niet opgeslagen.' ); } } foreach ($waarden as $k => $v) if (@$object->$k != $v) $changes[$k] = $v; $this->load->model( 'matrix' ); if (@$_POST['matrix_id']) $this->matrix->zet_standaard_matrix_voor_checklist_groep( $object, $_POST['matrix_id'] ); else $this->matrix->geef_standaard_matrix_voor_checklist_groep( $object ); // maakt meteen standaard aan! } else if ($object instanceof ChecklistResult) { $mijn_waarde = ($config['checklistgroep']->standaard_checklist_status != $postdata['actief']) ? $postdata['actief'] : NULL; if ($object->status != $mijn_waarde) $changes['status'] = $mijn_waarde; } // Get all data begins with email_ and create a new array($email_values) with that values. array_walk($_POST, function($val, $key) use(&$email_values) { if( strpos($key, 'email_') !== false ) { $email_values[$key] = $val; } }); // Handle email settings for question level if( !empty($email_values) ) { $json = Vraag::processEmail($email_values); if( $json !== false ) { $changes['email_config'] = $json; } } /************************************************************************************************************************ * * * A C H T E R G R O N D I N F O R M A T I E * * * ************************************************************************************************************************/ $this->_verwerk_achtergrond_informatie( $changes, $prefix, $object, 'grondslagen', 'grondslag_tekst_ids', function( $entry, array $lijst ) { return in_array( $entry->id, $lijst ); } ); $this->_verwerk_achtergrond_informatie( $changes, $prefix, $object, 'richtlijnen', 'richtlijn_ids', function( $entry, array $lijst ) { return in_array( $entry->id, $lijst ); } ); $this->_verwerk_achtergrond_informatie( $changes, $prefix, $object, 'aandachtspunten', 'aandachtspunten', function( $entry, array $lijst ) { return in_array( $entry->aandachtspunt, $lijst ); } ); $this->_verwerk_achtergrond_informatie( $changes, $prefix, $object, 'opdrachten', 'opdrachten', function( $entry, array $lijst ) { return in_array( $entry->opdracht, $lijst ); } ); $this->_verwerk_achtergrond_informatie( $changes, $prefix, $object, 'verantwoordingsteksten', array('verantwoordingstekst', 'status'), function( $entry, array $lijst ) { for ($i=0; $i<sizeof($lijst['verantwoordingstekst']); ++$i) { if ($entry->verantwoordingstekst == $lijst['verantwoordingstekst'][$i]) if ($entry->status == $lijst['status'][$i]) return true; } return false; } ); /************************************************************************************************************************ * * * O P S L A A N * * * ************************************************************************************************************************/ // opslaan! foreach ($changes as $k => $v) { $changesstr .= 'ZET: ' . $k . ', was=' . var_export(@$object->$k,true) . ', wordt=' . var_export($v,true) . "\n"; $object->$k = $v; } // DEBUG: //throw new Exception( "klaar om te saven:\n" . $changesstr ); if (!($object->save( 0, 0, 0 ))) throw new Exception( 'Fout bij opslaan van wijzigingen: ' . $this->db->_error_message() ); /************************************************************************************************************************ * * * Z E T T E N A L S D E F A U L T * * * ************************************************************************************************************************/ if (isset( $_POST['recursief_vraagconfig'] )) { foreach ($object->get_wizard_onderliggenden() as $subobject) $this->_reset_vraagconfiguratie( $subobject ); } if (isset( $_POST['recursief_achtergrondinformatie'] )) { foreach ($object->get_wizard_onderliggenden() as $subobject) $this->_reset_achtergrondinformatie( $subobject ); } if (isset( $_POST['recursief_verantwoordingen'] )) { foreach ($object->get_wizard_onderliggenden() as $subobject) $this->_reset_verantwoordingen( $subobject ); } if (isset( $_POST['recursief_opdrachten'] )) { foreach ($object->get_wizard_onderliggenden() as $subobject) $this->_reset_opdrachten( $subobject ); } } private function _verwerk_achtergrond_informatie( array &$changes, $prefix, $object, $type, $postvar, $aanwezig_test ) { if (@$_POST['gebruik_' . $type] == 'nee') { if (!($object instanceof ChecklistGroepResult)) $changes[$prefix . 'gebruik_' . $type] = NULL; } else { if (!is_array($postvar)) $nieuwe_waarden = isset( $_POST[$postvar] ) ? $_POST[$postvar] : array(); else { $nieuwe_waarden = array(); foreach ($postvar as $key) { $nieuwe_waarden[$key] = isset( $_POST[$key] ) ? $_POST[$key] : array(); } } $update = false; if ($object instanceof ChecklistGroepResult) $update = true; else { // let op: $nieuwe_waarden bevat een lijst van id's of teksten, // maar $huidige_waarden bevat een lijst van objecten! $huidige_waarden = call_user_func( 'wizard_get_' . $type, $object ); if (!is_array($postvar) && sizeof($nieuwe_waarden) != sizeof($huidige_waarden)) { $update = true; } else if (is_array($postvar) && sizeof(reset($nieuwe_waarden)) != sizeof($huidige_waarden)) { $update = true; } else { foreach ($huidige_waarden as $entry) if (!$aanwezig_test( $entry, $nieuwe_waarden )) { $update = true; break; } } } if ($update) { if ($object instanceof ChecklistGroepResult) { $checklist_groep_id = $object->id; $checklist_id = null; } else if ($object instanceof ChecklistResult) { $checklist_groep_id = $object->checklist_groep_id; $checklist_id = $object->id; } else if ($object instanceof HoofdgroepResult) { $checklist = $object->get_checklist(); $checklist_groep_id = $checklist->checklist_groep_id; $checklist_id = null; } else if ($object instanceof VraagResult) { $hoofdgroep = $object->get_categorie()->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); $checklist_groep_id = $checklist->checklist_groep_id; $checklist_id = $checklist->id; } // verwijder huidige grondslagen call_user_func( 'wizard_verwijder_' . $type, $object ); // zet nieuwe call_user_func( 'wizard_zet_' . $type, $object, $nieuwe_waarden, $checklist_groep_id, $checklist_id ); // forceer dat dit object nu z'n eigen grondslagen gebruikt if (!($object instanceof ChecklistGroepResult)) { $changes[$prefix . 'gebruik_' . wizard_cleanup_table_name( $type )] = 1; } } } } private function _reset_vraagconfiguratie( $context ) { $prefix = $context instanceof VraagResult ? '' : 'standaard_'; // zet de juiste velden op NULL $velden = array( 'vraag_type', 'aanwezigheid', 'thema_id', 'toezicht_moment', 'fase', 'wo_tekst_00', 'wo_is_leeg_00', 'wo_kleur_00', 'wo_in_gebruik_00', 'wo_tekst_01', 'wo_is_leeg_01', 'wo_kleur_01', 'wo_in_gebruik_01', 'wo_tekst_02', 'wo_is_leeg_02', 'wo_kleur_02', 'wo_in_gebruik_02', 'wo_tekst_03', 'wo_is_leeg_03', 'wo_kleur_03', 'wo_in_gebruik_03', 'wo_tekst_04', 'wo_is_leeg_04', 'wo_kleur_04', 'wo_in_gebruik_04', 'wo_tekst_10', 'wo_is_leeg_10', 'wo_kleur_10', 'wo_in_gebruik_10', 'wo_tekst_11', 'wo_is_leeg_11', 'wo_kleur_11', 'wo_in_gebruik_11', 'wo_tekst_12', 'wo_is_leeg_12', 'wo_kleur_12', 'wo_in_gebruik_12', 'wo_tekst_13', 'wo_is_leeg_13', 'wo_kleur_13', 'wo_in_gebruik_13', 'wo_tekst_20', 'wo_is_leeg_20', 'wo_kleur_20', 'wo_in_gebruik_20', 'wo_tekst_21', 'wo_is_leeg_21', 'wo_kleur_21', 'wo_in_gebruik_21', 'wo_tekst_22', 'wo_is_leeg_22', 'wo_kleur_22', 'wo_in_gebruik_22', 'wo_tekst_23', 'wo_is_leeg_23', 'wo_kleur_23', 'wo_in_gebruik_23', 'wo_standaard', 'wo_steekproef', 'wo_steekproef_tekst' ); foreach ($velden as $veld) $context->{$prefix . $veld} = NULL; if (!$context->save( 0, 0, 0 )) throw new Exception( 'Fout bij herstellen vraagconfiguratie.' ); // doe dit ook voor alle onderliggende objecten foreach ($context->get_wizard_onderliggenden() as $subobject) $this->_reset_vraagconfiguratie( $subobject ); } private function _reset_achtergrondinformatie( $context ) { $prefix = $context instanceof VraagResult ? '' : 'standaard_'; // verwijder de achtergrondinformatie wizard_verwijder_aandachtspunten( $context ); wizard_verwijder_richtlijnen( $context ); wizard_verwijder_grondslagen( $context ); // markeer de achtergrondinformatie als "niet langer van toepassing" $context->{$prefix . 'gebruik_' . wizard_cleanup_table_name( 'aandachtspunten' )} = NULL; $context->{$prefix . 'gebruik_' . wizard_cleanup_table_name( 'richtlijnen' )} = NULL; $context->{$prefix . 'gebruik_' . wizard_cleanup_table_name( 'grondslagen' )} = NULL; if (!$context->save( 0, 0, 0 )) throw new Exception( 'Fout bij leegmaken achtergrondinformatie.' ); // doe dit ook voor alle onderliggende objecten foreach ($context->get_wizard_onderliggenden() as $subobject) $this->_reset_achtergrondinformatie( $subobject ); } private function _reset_verantwoordingen( $context ) { $prefix = $context instanceof VraagResult ? '' : 'standaard_'; // verwijder de verantwoordingen wizard_verwijder_verantwoordingsteksten( $context ); // markeer de verantwoordingen als "niet langer van toepassing" $context->{$prefix . 'gebruik_' . wizard_cleanup_table_name( 'verantwoordingsteksten' )} = NULL; if (!$context->save( 0, 0, 0 )) throw new Exception( 'Fout bij leegmaken verantwoordingen.' ); // doe dit ook voor alle onderliggende objecten foreach ($context->get_wizard_onderliggenden() as $subobject) $this->_reset_verantwoordingen( $subobject ); } private function _reset_opdrachten( $context ) { $prefix = $context instanceof VraagResult ? '' : 'standaard_'; // verwijder de opdrachten wizard_verwijder_opdrachten( $context ); // markeer de opdrachten als "niet langer van toepassing" $context->{$prefix . 'gebruik_' . wizard_cleanup_table_name( 'opdrachten' )} = NULL; if (!$context->save( 0, 0, 0 )) throw new Exception( 'Fout bij leegmaken achtergrondinformatie.' ); // doe dit ook voor alle onderliggende objecten foreach ($context->get_wizard_onderliggenden() as $subobject) $this->_reset_opdrachten( $subobject ); } } <file_sep>#!/usr/bin/php <?php define( 'COMMAND', 'java -jar ../../docs/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar %s -o %s' ); function compress_js( $path ) { echo "Searching $path\n"; foreach (scandir( $path ) as $file ) { if ($file == '.' || $file == '..') continue; $fullfilename = $path . '/' . $file; if (preg_match( '/\.js/i', $file )) { $js = file_get_contents( $fullfilename ); if (preg_match( '#,(?=\s*[\\)\\}\\]])#ms', $js, $matches, PREG_OFFSET_CAPTURE )) { $offset = $matches[0][1]; $line = 1; for ($i=0; $i<$offset; ++$i) if ($js[$i] == "\n") ++$line; if (!in_array( $fullfilename . ':' . $line, array( './json.js:496', // false hit ) )) { echo( 'Found a trailing , in file ' . $fullfilename . " on line $line: '" . $matches[0][0] . "'!\n" ); } } echo "Compressing $fullfilename ... "; exec( sprintf( COMMAND, $fullfilename, $fullfilename ) ); $jsnew = file_get_contents( $fullfilename ); echo sprintf( 'size reduced to %d%%', round( 100 * (strlen($jsnew) / strlen($js)) ) ); echo "\n"; } else if (is_dir( $fullfilename )) compress_js( $fullfilename ); } } compress_js( '.' ); <file_sep>DROP TABLE IF EXISTS `bt_btz_dossiers`; CREATE TABLE IF NOT EXISTS `bt_btz_dossiers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bt_dossier_id` int(11) NOT NULL, `bt_dossier_hash` varchar(40) NOT NULL, `btz_dossier_id` int(11) NOT NULL, `btz_dossier_hash` varchar(40) NOT NULL, `bt_status` ENUM('open','gestart','bouwfase','afgerond','afgesloten') DEFAULT 'open', `btz_status` ENUM('open','gestart','bouwfase','afgerond','afgesloten') DEFAULT 'open', `project_status` ENUM('open','toets gestart','toets bouwfase','toezicht open','bouwfase','toets afgerond','toezicht afgerond','afgerond','afgesloten') DEFAULT 'open', `kenmerk` varchar(255) DEFAULT NULL, `bouwnummers` varchar(1000) DEFAULT NULL, `aangemaakt_op` datetime DEFAULT NULL, `bijgewerkt_op` datetime DEFAULT NULL, `verwerkt` tinyint(4) NOT NULL DEFAULT '0', `verwerkt_op` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uk__bt_btz_dossiers` (`bt_dossier_id`,`btz_dossier_id`), KEY `bt_dossier_id` (`bt_dossier_id`), KEY `bt_dossier_hash` (`bt_dossier_hash`), KEY `btz_dossier_id` (`btz_dossier_id`), KEY `btz_dossier_hash` (`btz_dossier_hash`), CONSTRAINT `fk__bt_btz_dossiers__dossiers` FOREIGN KEY (`btz_dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS bt_toezichtmoment_performers; DROP TABLE IF EXISTS toezichtmomenten; DROP TABLE IF EXISTS `deelplan_checklist_toezichtmomenten`; CREATE TABLE `deelplan_checklist_toezichtmomenten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bt_toezichtmoment_id` int(11) NOT NULL, `deelplan_checklist_id` int(11) NOT NULL, `naam` varchar(255) DEFAULT NULL, `nummer` varchar(255) DEFAULT NULL, `sub_nummer` varchar(255) DEFAULT NULL, `email_uitvoerende` varchar(255) DEFAULT NULL, `voornaam_uitvoerende` varchar(255) DEFAULT NULL, `achternaam_uitvoerende` varchar(255) DEFAULT NULL, `geslacht_uitvoerende` ENUM('Niet opgegeven', 'Man', 'Vrouw') NOT NULL DEFAULT 'Niet opgegeven', `mobiele_nummer_uitvoerende` varchar(255) DEFAULT NULL, `datum_begin` date DEFAULT NULL, `datum_einde` date DEFAULT NULL, `status_akkoord_woningborg` tinyint(4) NOT NULL DEFAULT '0', `status_gereed_uitvoerende` tinyint(4) NOT NULL DEFAULT '0', `toezichthouder_woningborg_gebruiker_id` int(11) DEFAULT NULL, `bijwoonmoment` tinyint(4) NOT NULL DEFAULT '0', `datum_hercontrole` date DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `FK__toezichtmomenten__bt_toezichtmomenten` FOREIGN KEY (`bt_toezichtmoment_id`) REFERENCES `bt_toezichtmomenten` (`id`), CONSTRAINT `FK__toezichtmomenten__checklist_deelplannen` FOREIGN KEY (`deelplan_checklist_id`) REFERENCES `deelplan_checklisten` (`id`), CONSTRAINT `FK__toezichtmomenten__gebruikers` FOREIGN KEY (`toezichthouder_woningborg_gebruiker_id`) REFERENCES `gebruikers` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <file_sep><? header( 'Content-Type: text/plain' ); ?> (function(){ <? $CI = get_instance(); ?> var grondslagen = BRISToezicht.Toets.data.grondslagen; var updateGrondslag = function( grondslag_tekst_id, bw_url, tekst ) { for (var i=0; i<grondslagen.length; ++i) if (grondslagen[i].grondslag_tekst_id == grondslag_tekst_id) { grondslagen[i].tekst = tekst; grondslagen[i].bw_url = bw_url; } }; <? foreach ($grondslagteksten as $grondslagtekst): /** * NO LONGER FETCH REMOTELY! $tekst = $grondslagtekst->get_artikel_tekst(); */ $tekst = $grondslagtekst->tekst; if (is_null( $tekst ) || !strlen($tekst)) continue; $gs = $grondslagtekst->get_grondslag(); if ($gs && $gs->quest_document && $grondslagtekst->quest_node) $bw_url = sprintf( config_item( 'briswarenhuis_url' ), trim( $grondslagtekst->quest_node, '/' ) ); else $bw_url = ''; $encode_start = microtime(true); ?> updateGrondslag( <?=$grondslagtekst->id?>, '<?=jsstr($bw_url)?>', '<?=jsstr($tekst)?>' ); <? endforeach; ?> //BRISToezicht.Toets.Vraag.reselect(); })(); <file_sep>REPLACE INTO teksten(string, tekst, timestamp, lease_configuratie_id) VALUES ('checklistwizard.section.email', 'E-mail', NOW(), 0), ('email_address', 'E-mailadres', NOW(), 0), ('email_content', 'Begeleidende tekst', NOW(), 0), ('checklistwizard.section.email.email_options', 'Te versturen gegevens', NOW(), 0), ('question_status', 'Waardeoordeel', NOW(), 0), ('date', 'Datum', NOW(), 0), ('supervisor', 'Toezichthouder', NOW(), 0), ('question', 'Vraag', NOW(), 0), ('anwser', 'Toelichting', NOW(), 0), ('checklistwizard.section.email.dossier_data', 'Dossiergegevens', NOW(), 0), ('klant.email_question_notification', 'Email bevestiging bij vragen', NOW(), 0), ('checklistwizard.section.email', 'E-mail', NOW(), 1), ('email_address', 'E-mailadres', NOW(), 1), ('email_content', 'Begeleidende tekst', NOW(), 1), ('checklistwizard.section.email.email_options', 'Te versturen gegevens', NOW(), 1), ('question_status', 'Waardeoordeel', NOW(), 1), ('date', 'Datum', NOW(), 1), ('supervisor', 'Toezichthouder', NOW(), 1), ('question', 'Vraag', NOW(), 1), ('anwser', 'Toelichting', NOW(), 1), ('checklistwizard.section.email.dossier_data', 'Dossiergegevens', NOW(), 1), ('klant.email_question_notification', 'Email bevestiging bij vragen', NOW(), 1); INSERT INTO help_buttons (tag, taal, tekst, laast_bijgewerkt_op) VALUES ('checklistwizard.email.email_address', 'nl', 'Hier kunt u een e-mailadres invoeren, waarnaar u bij beantwoording van deze vraag, altijd automatisch een bericht wilt versturen', '2014-12-04 17:25:44'), ('checklistwizard.email.email_content', 'nl', 'Hier kunt u een tekst invoeren die bij het versturen van het e-mailbericht altijd als begeleidende tekst wordt meegestuurd', '2014-12-04 17:25:44'), ('checklistwizard.email.email_options', 'nl', 'Hier kunt u aangeven welke gegevens u in het automatische e-mailbericht wilt meesturen', '2014-12-04 17:25:44'), ('checklistwizard.email.question_status', 'nl', 'Hier kunt u aangeven bij welke status van de vraag het e-emailbericht automatisch verstuurd dient te worden.', '2014-12-04 17:25:44'); ALTER TABLE bt_vragen ADD email_config text DEFAULT NULL; ALTER TABLE klanten ADD email_question_notification TINYINT UNSIGNED NOT NULL DEFAULT '0';<file_sep>-- Get some IDs in temporary variables SELECT @klant_id_imotep:=id FROM klanten WHERE naam = 'Imotep'; SELECT @klant_id_cebes:=id FROM klanten WHERE naam = 'Cebes'; SELECT @klant_id_vr_ijsselland:=id FROM klanten WHERE naam = 'Ve<NAME>'; SELECT @klant_id_vr_zhz:=id FROM klanten WHERE naam = 'Veiligheids<NAME>'; SELECT @ws_id:=id FROM webservice_applicaties WHERE naam = 'Breed SOAP koppelvlak'; -- Limit some of the webservice accounts to specific 'klant_id' values INSERT INTO webservice_accounts SET webservice_applicatie_id = @ws_id, omschrijving = 'VR Ijsselland', gebruikersnaam = '<EMAIL>', wachtwoord = sha1('ijsselland'), actief = 1, alle_klanten = 1, alle_components = 1, klant_id = @klant_id_vr_ijsselland; INSERT INTO webservice_accounts SET webservice_applicatie_id = @ws_id, omschrijving = 'Veiligheidsregio Z<NAME>', gebruikersnaam = '<EMAIL>', wachtwoord = sha1('vrzhz'), actief = 1, alle_klanten = 1, alle_components = 1, klant_id = @klant_id_vr_zhz; -- Insert the data for VR Ijsselland INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_ijsselland, target_id = @klant_id_imotep; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_ijsselland, target_id = @klant_id_vr_ijsselland; -- Insert the data for VR Zuid-Holland Zuid INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_zhz, target_id = @klant_id_imotep; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_zhz, target_id = @klant_id_vr_zhz; <file_sep>-- create table CREATE TABLE IF NOT EXISTS `bt_grondslag_teksten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `grondslag_id` int(11) NOT NULL, `artikel` int(11) NOT NULL, `tekst` text NOT NULL, PRIMARY KEY (`id`), KEY `grondslag_id` (`grondslag_id`), KEY `artikel` (`artikel`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `bt_grondslag_teksten` ADD CONSTRAINT `bt_grondslag_teksten_ibfk_1` FOREIGN KEY (`grondslag_id`) REFERENCES `bt_grondslagen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- reference table ALTER TABLE `bt_vraag_grondslagen` ADD `grondslag_tekst_id` INT NULL DEFAULT NULL , ADD INDEX ( `grondslag_tekst_id` ) ; ALTER TABLE `bt_vraag_grondslagen` ADD FOREIGN KEY ( `grondslag_tekst_id` ) REFERENCES `bt_grondslag_teksten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>PDFAnnotator.Tool.HandleTool = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine, type ) { /* initialize base class */ this._super( engine, type ); var thiz = this; var showHandles = function( engine ){ if (engine.getActiveTool() != thiz) return; var layer = engine.getActiveLayer(); if (!layer) return; layer.forEachEditable(function( editable ){ var h = editable.getHandle( type ); if (h) h.show(); }); } var hideHandles = function( engine ){ var layer = engine.getActiveLayer(); if (!layer) return; layer.forEachEditable(function( editable ){ var h = editable.getHandle( type ); if (h) h.hide(); }); }; this.on( 'select', function( tool, data ){ showHandles( tool.engine ); }); this.on( 'deselect', function( tool, data ) { hideHandles( tool.engine ); }); engine.on( 'prelayeractivated', function( engine, data ) { hideHandles( engine ); }); engine.on( 'layeractivated', function( engine, data ) { showHandles( engine ); }); engine.on( 'prereboot', function( engine, data ) { hideHandles( engine ); }); } }); <file_sep><? $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); if(isset($color) && $color===TRUE && $group_tag=='deelplannen' && $klant->deelplan_out_of_date_color==1){ $style="style='background:none; background-color:red; border-top:2px solid white;'"; $style_left="style='background:none; background-color:red; border-top-left-radius: 7px;border-top:2px solid white;' "; $style_right="style='background:none; background-color:red; border-top-right-radius: 7px;border-top:2px solid white;' "; } else $style=$style_left=$style_right=""; if (!isset( $width )) $width = '250px'; if (!isset( $group_tag )) $group_tag = 'default'; if (!isset( $panel_outer_class )) $panel_outer_class = 'groupcontent'; if (!isset( $panel_inner_class )) $panel_inner_class = 'groupcontentcontent'; $sub_class=""; if (isset($klant->deelplannen_tab_close)){ if($group_tag=='deelplannen' && $klant->deelplannen_tab_close==1){ $sub_class="hdd"; } } $tag_id = isset($id) ? 'id="'.$id.'"' : ''; ?> <!-- group --> <table <?=$tag_id ?> group_tag="<?=$group_tag?>" border="0" cellspacing="0" cellpadding="0" class="group <?=$sub_class;?> <?=(isset($defunct)&&$defunct) ? 'defunct' : ''?> <?=(isset($expanded)&&$expanded) ? 'expanded' : ''?>" style="width:<?=$width?>" onclick="<?=@$onclick?>"> <tr> <td class="left" <?=$style_left;?>></td> <td class="mid" <?=$style;?>> <?=$header?> </td> <? if (isset( $rightheader ) && $rightheader): ?> <td class="mid" style="text-align:right"> <?=$rightheader?> </td> <? endif; ?> <td class="right" <?=$style_right;?>></td> </tr> </table> <!-- group content --> <? if (!is_null( @$height )): ?> <div class="<?=$panel_outer_class?>" style="width:<?=$width?>; padding:0px; border: 0px; margin: 0px; height: auto;"> <div style="<?=isset( $height ) ? 'height:'.$height.';' : '' ?>;" <?=!empty($panel_inner_class) ? 'class="'.$panel_inner_class.'"' : ''?>> <? else: ?> <div style="height:0;padding:0;margin:0;border:0"> <? endif; ?> <file_sep><? $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); ?> <? $this->load->view('elements/header', array('page_header'=>null)); ?> <? $this->load->view( 'elements/laf-blocks/generic-bar', array( 'header' => tg( 'dossier.header', $dossier->get_omschrijving() ) ) ); ?> <table style="width:100%"> <tr> <td width="125"><?=tgg('dossier.dossiernaam')?>:</td> <td width="25%"><?=$dossier->beschrijving?></td> <td rowspan="7" width="25%" style="vertical-align: top;"><?=tgg('dossier.opmerkingen')?>:<br/><?=htmlentities( $dossier->opmerkingen, ENT_COMPAT, 'UTF-8' )?></td> <? if ( ($klant_id == 202) && !is_null($dossier->get_foto()) ): ?> <td rowspan="7" width="25%" style="vertical-align: top;text-align:center;"><img src="data:image/png;base64,<?=(is_null($dossier->get_foto()) ? '' : base64_encode($dossier->get_foto()->bestand))?>" width="75px"/></td> <? endif; ?> <td rowspan="7" style="vertical-align: top; text-align: right;"> <? if ($dossier_access == 'write'): ?> <input type="button" value="<?=tgng('form.dossier_bewerken')?>" onclick="location.href='<?=site_url('/dossiers/bewerken/'.$dossier->id)?>'" /> <?=htag('dossier_bewerken')?> <? elseif ($dossier_access == 'readonly'): ?> <input type="button" value="<?=tgng('form.dossier_bekijken')?>" onclick="location.href='<?=site_url('/dossiers/bewerken/'.$dossier->id)?>'" /> <?=htag('dossier_bekijken')?> <? endif; ?> <? if (!$dossier->gearchiveerd && $dossier->get_afmelden_access_to_dossier() == 'write') :?> <input type="button" value="<?=tgng('form.dossier_afmelden')?>" onclick="if (confirm('<?=tgn('dit_dossier_werkelijk_afmelden_u_kunt_deze_actie_niet_ongedaan_maken')?>')) location.href='<?=site_url('/dossiers/archiveren/'.$dossier->id.'/confirm')?>'" /> <?=htag('dossier_afmelden')?> <? endif; ?> </td> </tr> <tr> <td width="125"><?=tgg('dossier.identificatienummer')?>:</td> <td width="25%"><?=$dossier->kenmerk?></td> </tr> <tr> <td width="125"><?=tgg('dossier.aanmaakdatum')?>:</td> <td width="25%"><?=date('d-m-Y', $dossier->aanmaak_datum) ?></td> </tr> <? if (!empty($project_status)): ?> <tr> <td width="125"><?=tgg('dossier.bristoetsstatus')?>:</td> <td width="25%"><?=ucfirst($bristoets_status)?></td> </tr> <tr> <td width="125"><?=tgg('dossier.bristoezichtstatus')?>:</td> <td width="25%"><?=ucfirst($bristoezicht_status)?></td> </tr> <tr> <td width="125"><?=tgg('dossier.projectstatus')?>:</td> <td width="25%"><?=ucfirst($project_status)?></td> </tr> <? endif; ?> <tr> <td width="125"><?=tgg('dossier.geplande_datum')?>:</td> <td width="25%"><?=$dossier->gepland_datum ? date( 'd-m-Y', strtotime($dossier->gepland_datum) ) : '-'?></td> </tr> <tr> <td width="125"><?=tgg('dossier.locatie_adres')?>:</td> <td width="25%"><?=$dossier->locatie_adres?>, <?=$dossier->locatie_postcode?>, <?=$dossier->locatie_woonplaats?></td> </tr> <tr> <td width="125"><?=tgg('dossier.deelplan_olo_nummers')?>:</td> <td width="25%"> <? $olo_nummers = array(); foreach ($deelplannen as $deelplan) if ($deelplan->olo_nummer && !in_array( $deelplan->olo_nummer, $olo_nummers )) $olo_nummers[] = $deelplan->olo_nummer; sort( $olo_nummers ); ?> <? if (empty( $olo_nummers )): ?> - <? else: ?> <?=implode( ', ', $olo_nummers )?> <? endif; ?> </td> </tr> </table> <? if ($scope_access != 'none'): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg( 'deelplannen.header' ), 'group_tag' => 'dossier', 'expanded' => true, 'width' => '100%', 'height' => '450px', 'defunct' => false, 'onclick' => '' ) ); ?> <? if ($klant->heeft_toezichtmomenten_licentie == 'nee' && $dossier_access=='write'): ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => null, 'width' => '100%', 'style' => 'margin-top:0px' )); ?> <div style="padding:0;margin:0;border:0;background-color:inherit;height:auto;" class="nieuw_deelplan"> <table style="width:auto"> <tr> <td><input type="button" value="<?=tgn('maak_een_nieuw_deelplan_aan')?>" class="toon_editor" /></td> <td> <div style="padding:0;margin:0;border:0;background-color:inherit;height:auto;" class="hidden"> <form method="POST" action="<?=site_url('/dossiers/deelplan_toevoegen/' . $dossier->id)?>"> Naam: <input type="text" value="" name="nieuw_deelplan" size="40" maxlength="128" placeholder="<?=tgn('laat_leeg_voor_automatische_naam')?>"/> <input type="submit" value="<?=tgng('form.aanmaken')?>" /> </form> </div> </td> <td><?=htag('nieuw_deelplan')?></td> </tr> </table> </div> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <br/> <? endif; $any_expanded = false; $deelplan_expanded = array(); foreach ($deelplannen as $deelplan){ if ($open_deelplan_id == $deelplan->id) $expanded = true; else if (!$open_deelplan_id) $expanded = !$deelplan->afgemeld && !$any_expanded; else $expanded = false; $open_deelplan_id = $expanded?$deelplan->id:$open_deelplan_id; $deelplan_expanded[$deelplan->id] = $expanded; $any_expanded |= $expanded; } if (!$any_expanded){ reset( $deelplan_expanded ); $first_deelplan = key( $deelplan_expanded ); $deelplan_expanded[$first_deelplan] = true; } foreach ($deelplannen as $deelplan): $is_bouwnummer = $klant->heeft_toezichtmomenten_licentie == 'ja' && $deelplan->geintegreerd=='nee'; $expanded = $deelplan_expanded[$deelplan->id]; $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => htmlentities( $deelplan->naam, ENT_COMPAT, 'UTF-8' ) . ($deelplan->afgemeld ? ' [' . tg('afgemeld') . ']' : ''), 'group_tag' => 'deelplannen', 'expanded' => $expanded, 'width' => '100%', 'height' => 'auto', 'onclick' => 'open_deelplan_id='.$deelplan->id.';' ) ); ?> <div style="padding:0;margin:0;border:0;background-color:inherit;height:auto; vertical-align: top; text-align: right; margin-bottom: 10px; "> <? if ($deelplan->olo_nummer): ?> <div style="float:left; height: auto; border: 0; padding: 5px 0px 0px 7px; margin: 0;"> <b>OLO nummer: <?=$deelplan->olo_nummer?></b> </div> <? endif; ?> <? if ( $klant->heeft_toezichtmomenten_licentie == 'ja' && $this->rechten->geef_recht_modus( RECHT_TYPE_MAPPINGEN, $this->gebruiker->get_logged_in_gebruiker()->id ) != RECHT_MODUS_GEEN): ?> <input type="button" value="<?=tgn('mappingmatrix')?>" onclick="location.href='<?=site_url('/deelplannen/project_specifieke_mapping/'.$deelplan->id)?>'" /> <?=htag('mappingmatrix')?> <? endif; ?> <input type="button" value="<?=tgn('opdrachtenoverzicht')?>" onclick="location.href='<?=site_url('/deelplannen/opdrachtenoverzicht/'.$deelplan->id)?>'" /> <?=htag('opdrachtenoverzicht')?> <input type="button" value="<?=tgn('deelplan_bekijken')?>" onclick="location.href='<?=site_url('/deelplannen/bekijken/'.$deelplan->id)?>'" /> <?=htag('deelplan_bekijken')?> <? if ($deelplan_access[$deelplan->id] == 'write'): ?> <? if ( $reg_gegevens_bewerkbare): ?> <input type="button" value="<?=tgn('deelplan_bewerken')?>" onclick="location.href='<?=site_url('/deelplannen/bewerken/'.$deelplan->id)?>'" /> <?=htag('deelplan_bewerken')?> <? endif; ?> <? endif; ?> <? $disabled_str = ($mag_deelplannen_afmelden) ? '' : 'disabled="disabled"'; ?> <input type="button" <?=$disabled_str?> value="<?=tgn('deelplan_afmelden')?>" onclick="if (confirm('Dit deelplan werkelijk afmelden? U kunt deze actie niet ongedaan maken!')) location.href='<?=site_url('/deelplannen/afmelden/'.$deelplan->id)?>'" /> <?=htag('deelplan_bewerken')?> </div> <table class="list2" width="100%"> <thead> <tr> <td class="left" width="16"></td> <? if($is_bouwnummer): ?> <td class="mid" width="<?=$this->is_Mobile?150:210?>"><?=tgg('dossier.scope')?></td> <td class="mid" width="75"><?=tgg('dossier.bouwnr')?></td> <? else: ?> <td class="mid" width="<?=$this->is_Mobile?170:230?>"><?=tgg('dossier.scope')?></td> <? endif; ?> <td class="mid" width="140"><?=tgg('dossier.toezichthouder')?></td> <? if($is_bouwnummer): ?> <td class="mid" width="100"><?=tgg('dossier.matrix')?></td> <td class="mid" width="<?=$this->is_Mobile?110:110?>"><?=tgg('dossier.initiele_datum')?></td> <td class="mid" width="<?=$this->is_Mobile?110:130?>"><?=tgg('dossier.datum_hercontrole')?></td> <td class="mid" width="<?=$this->is_Mobile?50:130?>"><?=tgg('dossier.status_scope')?></td> <? else: ?> <td class="mid" width="140"><?=tgg('dossier.matrix')?></td> <td class="mid" width="<?=$this->is_Mobile?110:120?>"><?=tgg('dossier.initiele_datum')?></td> <td class="mid" width="<?=$this->is_Mobile?110:130?>"><?=tgg('dossier.datum_hercontrole')?></td> <td class="mid" width="<?=$this->is_Mobile?100:200?>"><?=tgg('dossier.status_scope')?></td> <? endif; ?> <? if($klant->heeft_toezichtmomenten_licentie == 'ja'): ?> <td class="mid" style="text-align: right;"> <?=tgg('dossier.integraal_woergeven')?>&nbsp;<input class="geintegreerd" type="checkbox" <?=($deelplan->geintegreerd=='ja'?'checked':'') ?>/> </td> <? else: ?> <td class="mid">&nbsp;</td> <? endif; ?> <td class="right" width="16"></td> </tr> </thead> <tbody> <? $alle_arr = array( 'id' => null, 'gebruikersnaam'=> null, 'volledige_naam'=> tg('alle_gebruikers') ); $alle_entry = new GebruikerResult( $alle_arr ); foreach ($deelplan->get_checklistgroepen() as $checklistgroep){ if ($deelplan->get_toezicht_access_to_deelplan( $checklistgroep ) != 'none'){ // maak lijst van toezichthouders, dit moet per checklistgroep opnieuw! $toezichthouders = array( $alle_entry ); foreach ($gebruikers as $g) { if ( $g->id == $gebruiker_id || (isset( $gebruiker_checklistgroepen[$g->id] ) && in_array( $checklistgroep->id, $gebruiker_checklistgroepen[$g->id] )) ) { $toezichthouders[] = $g; } } // basis data $viewdata = array( 'deelplan' => $deelplan, 'checklistgroep' => $checklistgroep, 'checklist' => null, 'mag_toezichthouder_toekennen' => $mag_gebruiker_toekennen[$deelplan->id], 'mag_matrix_toekennen' => $deelplan_access[$deelplan->id] == 'write', 'mag_initiele_datum_toekennen' => $deelplan_access[$deelplan->id] == 'write', 'toezichthouders' => $toezichthouders, 'matrices' => $matrices[$checklistgroep->id], ); if ($checklistgroep->modus != 'niet-combineerbaar' || $deelplan->geintegreerd=='ja' ){ // dit is het object met instellingen voor de huidige checklistgroep $deelplanchecklistgroep = $deelplanchecklistgroepen[$deelplan->id][ $checklistgroep->id ]; $toezichthouder = @ $gebruikers[ $deelplanchecklistgroep->toezicht_gebruiker_id ]; $toezichthouder_naam = $toezichthouder ? $toezichthouder->get_status() : tg('nog_niet_toegewezen'); if (!$deelplanchecklistgroep->matrix_id) // er kan in theorie nog geen matrix gezet zijn, zet dan altijd de standaard matrix $deelplanchecklistgroep->matrix_id = $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep )->id; $matrix = $matrices[$checklistgroep->id][$deelplanchecklistgroep->matrix_id]; $matrix_naam = $matrix ? $matrix->naam : tg('nog_niet_toegekend'); $initiele_datum = $deelplanchecklistgroep->initiele_datum; $initiele_datum_desc = $deelplanchecklistgroep->initiele_datum ? date('d-m-Y', strtotime($deelplanchecklistgroep->initiele_datum)) : tg('nog_niet_ingepland'); $initiele_start_tijd = $deelplanchecklistgroep->initiele_start_tijd; $initiele_eind_tijd = $deelplanchecklistgroep->initiele_eind_tijd; // load view $viewdata['bouwnummer'] = '';// Fictive value for any case. $viewdata['scope'] = $checklistgroep->naam; $viewdata['toezichthouder'] = $toezichthouder; $viewdata['toezichthouder_naam'] = $toezichthouder_naam; $viewdata['matrix'] = $matrix; $viewdata['matrix_naam'] = $matrix_naam; $viewdata['datum'] = $initiele_datum; $viewdata['datum_desc'] = $initiele_datum_desc; $viewdata['start_tijd'] = $initiele_start_tijd; $viewdata['eind_tijd'] = $initiele_eind_tijd; $viewdata['hercontrole_datum'] = @$deelplan_checklistgroep_planning[$deelplan->id][$checklistgroep->id]; $viewdata['voortgang_percentage'] = $deelplanchecklistgroep->voortgang_percentage; $viewdata['url'] = site_url('/deelplannen/checklistgroep/' . $checklistgroep->id . '/' . $deelplan->id ); $viewdata['project_status'] = (!empty($project_status)) ? $project_status : ''; $this->load->view( 'dossiers/bekijken-scope', $viewdata ); }else{ foreach ($deelplan->get_checklisten() as $checklist){ if ($checklist->checklist_groep_id == $checklistgroep->id){ // dit is het object met instellingen voor de huidige checklistgroep $toezichthouder = ( !(bool)$checklist->toezicht_gebruiker_id ) ? $toezichthouders[0] : @ $gebruikers[ $checklist->toezicht_gebruiker_id ]; $toezichthouder_naam = $toezichthouder ? $toezichthouder->get_status() : tg('nog_niet_toegewezen'); if (!$checklist->matrix_id) // er kan in theorie nog geen matrix gezet zijn, zet dan altijd de standaard matrix $checklist->matrix_id = $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep )->id; $matrix = $matrices[$checklistgroep->id][$checklist->matrix_id]; $matrix_naam = $matrix ? $matrix->naam : tg('nog_niet_toegekend'); $initiele_datum = $checklist->initiele_datum; $initiele_datum_desc = $checklist->initiele_datum ? date('d-m-Y', strtotime($checklist->initiele_datum)) : tg('nog_niet_ingepland'); $initiele_start_tijd = $checklist->initiele_start_tijd; $initiele_eind_tijd = $checklist->initiele_eind_tijd; // // load view $viewdata['checklist'] = $checklist; $viewdata['bouwnummer'] = $checklist->bouwnummer; $viewdata['scope'] = $checklistgroep->naam . '<br/>' . $checklist->naam; $viewdata['toezichthouder'] = $toezichthouder; $viewdata['toezichthouder_naam'] = $toezichthouder_naam; $viewdata['matrix'] = $matrix; $viewdata['matrix_naam'] = $matrix_naam; $viewdata['datum'] = $initiele_datum; $viewdata['datum_desc'] = $initiele_datum_desc; $viewdata['start_tijd'] = $initiele_start_tijd; $viewdata['eind_tijd'] = $initiele_eind_tijd; $viewdata['hercontrole_datum'] = @$deelplan_checklist_planning[$deelplan->id][$checklist->id]; $viewdata['voortgang_percentage'] = $checklist->voortgang_percentage; $viewdata['url'] = site_url('/deelplannen/checklistgroep/'.$checklistgroep->id.'/'.$deelplan->id.'/'.$checklist->id.'/'.urlencode($checklist->bouwnummer)); $viewdata['project_status'] = (!empty($project_status)) ? $project_status : ''; $this->load->view( 'dossiers/bekijken-scope', $viewdata ); } } } } } ?> </tbody> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? if (APPLICATION_HAVE_DOSSIER_RAPPORTAGE): ?> <? $allowed_viia_gebruiker_ids = array(648, 771, 782, 806, 779, 773, 783, 784); $user_is_allowed_to_generate_reports = true; ?> <? if ($dossier->get_rapportage_access_to_dossier() == 'readonly'): ?> <? if ($user_is_allowed_to_generate_reports): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('rapportage.header'), 'group_tag' => 'dossier', 'width' => '100%', 'height' => 'auto', 'defunct' => false, 'onclick' => 'load_rapportage(this);' ) ); ?> <span><?=tg('even.geduld.aub')?></span><br/> <img src="<?=site_url('/files/images/ajax-loader.gif')?>"> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('rapportage-geschiedenis.header'), 'group_tag' => 'dossier', 'width' => '100%', 'height' => 'auto', 'defunct' => false, 'onclick' => 'load_rapportage_geschiedenis(this);' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <? endif; ?> <script type="text/javascript"> var open_deelplan_id="<?=$open_deelplan_id ?>"; $(document).ready(function(){ $(".geintegreerd").click(function(event){ var geintegreerd = $(this).is(':checked') ? "ja" : "nee" ; $.ajax({ "url": "/deelplannen/setintegraalstatus/"+open_deelplan_id, "type": "POST", "async": true, "dataType": "JSON", "data": {"geintegreerd":geintegreerd}, "success": function( data, textStatus, jqXHR ){ if(!data.success){ alert("Error!!!\n"+data.message); } window.location = "/dossiers/bekijken/<?=$dossier->id.'/'?>"+open_deelplan_id; }, "error": function( jqXHR, textStatus, errorThrown ){ alert("System Error!!!\n"+errorThrown); } }); }); // // toezichthouders // $('.toezichthouder_text').click(function(){ if ($(this).siblings( 'select' ).hasClass( 'hidden')) { $(this).siblings( 'select' ).removeClass( 'hidden' ); $(this).siblings( 'span' ).addClass( 'hidden' ); } else { $(this).siblings('select').trigger( 'change' ); } }); $('.toezichthouder_text').siblings('select').change(function(){ $(this).addClass( 'hidden' ); $(this).siblings( 'span' ).removeClass( 'hidden' ); var gebruiker_id = this.value; var gebruiker_naam = this.options[this.selectedIndex].text; var checklist_groep_id = $(this).siblings('img').attr('checklist_groep_id'); var checklist_id = $(this).siblings('img').attr('checklist_id'); var deelplan_id = $(this).attr('deelplan_id'); var bouwnummer = $(this).siblings('img').attr('bouwnummer'); $.ajax({ url: '/deelplannen/store_toezichthouder', type: 'POST', async: true, dataTypeString: 'json', data: { deelplan_id: deelplan_id, checklist_groep_id: checklist_groep_id, checklist_id: checklist_id ? checklist_id : '', gebruiker_id: gebruiker_id, bouwnummer: bouwnummer }, success: function( data, textStatus, jqXHR ) { if (data.match( /^OK$/ )) return; alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + data ); }, error: function( jqXHR, textStatus, errorThrown ) { alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + errorThrown ); } }); $(this).siblings( 'span' ).text( gebruiker_naam ); }); // // planningdatum // $('.planningdatum_text').click(function(){ var context = this; var datum = $(context).siblings( '[name=datum]' ); var start_tijd = $(context).siblings( '[name=start_tijd]' ); var eind_tijd = $(context).siblings( '[name=eind_tijd]' ); afspraakPopup( datum.val(), start_tijd.val(), eind_tijd.val(), function( nieuweDatum, nieuweStartTijd, nieuweEindTijd ) { var checklist_groep_id = $(context).attr('checklist_groep_id'); var checklist_id = $(context).attr('checklist_id'); var deelplan_id = $(context).attr('deelplan_id'); $.ajax({ url: '/deelplannen/store_planningdatum', type: 'POST', async: true, dataTypeString: 'json', data: { deelplan_id: deelplan_id, checklist_groep_id: checklist_groep_id, checklist_id: checklist_id ? checklist_id : '', planningdatum: nieuweDatum, start_tijd: nieuweStartTijd, eind_tijd: nieuweEindTijd }, success: function( data, textStatus, jqXHR ) { if (data.match( /^OK$/ )) { $(context).siblings( 'span' ).text( nieuweDatum ); datum.val( nieuweDatum ); start_tijd.val( nieuweStartTijd ); eind_tijd.val( nieuweEindTijd ); return; } alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + data ); }, error: function( jqXHR, textStatus, errorThrown ) { alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + errorThrown ); } }); }); }); // // matrix // $('.matrix_text').click(function(){ if ($(this).siblings( 'select' ).hasClass( 'hidden' )) { $(this).siblings( 'select' ).removeClass( 'hidden' ); $(this).siblings( 'span' ).addClass( 'hidden' ); } else { $(this).siblings('select').trigger( 'change' ); } }); $('.matrix_text').siblings('select').change(function(){ $(this).addClass( 'hidden' ); $(this).siblings( 'span' ).removeClass( 'hidden' ); var matrix_id = this.value; var matrix_naam = this.options[this.selectedIndex].text; var checklist_groep_id = $(this).siblings('img').attr('checklist_groep_id'); var checklist_id = $(this).siblings('img').attr('checklist_id'); var deelplan_id = $(this).attr('deelplan_id'); $.ajax({ url: '/deelplannen/store_matrix', type: 'POST', async: true, dataTypeString: 'json', data: { deelplan_id: deelplan_id, checklist_groep_id: checklist_groep_id, checklist_id: checklist_id ? checklist_id : '', matrix_id: matrix_id }, success: function( data, textStatus, jqXHR ) { if (data.match( /^OK$/ )) return; alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + data ); }, error: function( jqXHR, textStatus, errorThrown ) { alert( '<?=tgn('fout_bij_opslaan')?>:\n\n' + errorThrown ); } }); $(this).siblings( 'span' ).text( matrix_naam ); }); // // nieuw deelplan // $('div.nieuw_deelplan input[type=button].toon_editor').click(function(){ var tr = $(this).parent().parent(); tr.find('div').show(); tr.find('input[type=text]').focus(); }); $('div.nieuw_deelplan input[type=button].nieuw_deelplan_aanmaken').click(function(){ var input = $(this).parent().parent().find('input[type=text]'); if (input.val()) { this.form.target_state.value = 'nieuw_deelplan'; $('form[name=form] input[type=submit]').click(); } else { input.focus(); alert( '<?=tgn('voer_een_naam_in_voor_het_nieuwe_deelplan')?>' ); } }); }); var loaded_rapportage = false; function load_rapportage(el) { if (loaded_rapportage) return; loaded_rapportage = true; var target = $(el).next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage/' . $dossier->id)?>' ); } function load_rapportage_geschiedenis(el) { var target = $(el).next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_geschiedenis/' . $dossier->id)?>' ); } </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Bewerken', 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> <form method="post" enctype="multipart/form-data"> <table> <? if ($allow_klanten_edit): ?> <tr> <td style="vertical-align:top">Klant</td> <td style="vertical-align:top"> <select name="klant_id"> <option value="">- alle -</option> <? foreach ($klanten as $klant): ?> <option <?=$klant->id==$sjabloon->klant_id?'selected':''?> value="<?=$klant->id?>"><?=$klant->naam?></option> <? endforeach; ?> </select> </td> </tr> <? endif; ?> <tr> <td style="vertical-align:top">Naam</td> <td style="vertical-align:top"> <input name="naam" size="40" value="<?=htmlentities( $sjabloon->naam, ENT_QUOTES, 'UTF-8' )?>" /> </td> </tr> <tr> <td style="vertical-align:top">Checklisten</td> <td style="vertical-align:top"> <ul> <? foreach ($sjabloon->get_checklisten() as $checklist): ?> <li><?=htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8' )?> (<?=htmlentities( $checklist->get_checklistgroep()->naam, ENT_COMPAT, 'UTF-8' )?>)</li> <? endforeach; ?> </ul> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="Opslaan" /> <input type="button" value="Verwijderen" onclick="if (confirm('Sjabloon verwijderen?')) location.href='/instellingen/scopesjabloon_verwijderen/<?=$sjabloon->id?>';" /> <input type="button" value="Terug" onclick="if (confirm('Wijzigingen annuleren?')) location.href='/instellingen/scopesjablonen/';" /> </td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-group-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><? class BaseResult { protected $_CI; protected $_model; function BaseResult( $model, &$row ) { $this->_CI = get_instance(); $this->_model = $model; foreach ($row as $k => $v) $this->$k = $v; $this->get_model()->check_access( $this ); } function get_model() { return $this->_CI->{$this->_model}; } function get_model_name() { return $this->_model; } function dump() { if (!IS_CLI) echo "<pre>"; echo "object (class=".get_class($this).", id=" . spl_object_hash($this) . ") {\n"; foreach ($this as $k=>$v) { $c = substr($k, 0, 1); if (($c>='a' && $c<='z') || ($c>='A' && $c<='Z')) echo " $k = " . (is_null( $v ) ? 'null' : "'$v'") . "\n"; } echo "}"; if (!IS_CLI) echo "</pre>"; echo "\n"; } function dump_str() { $str = "object (class=".get_class($this)."):\n"; foreach ($this as $k=>$v) { $c = substr($k, 0, 1); if (($c>='a' && $c<='z') || ($c>='A' && $c<='Z')) $str .= "$k = '$v'\n"; } return $str; } function get_array_copy() { $data = array(); foreach ($this as $k=>$v) { $c = substr($k, 0, 1); if (($c>='a' && $c<='z') || ($c>='A' && $c<='Z')) $data[$k] = $v; } return $data; } function save( $do_transaction=true, $alias=null, $error_on_no_changes=true ) { $model = $this->_model; $arr = array(); foreach ($this as $k=>$v) { $c = substr($k, 0, 1); if (($c>='a' && $c<='z') || ($c>='A' && $c<='Z')) $arr[$k] = $v; } $class = get_class($this); return $this->_CI->$model->save( (object)$arr, $do_transaction, $alias, $error_on_no_changes ); } function delete() { $model = $this->_model; return $this->_CI->$model->delete( $this ); } static function convert_results( &$active_record, &$query ) { return $active_record->convert_results( $query ); } public function get_edit_fields() { $arr = array(); foreach ($this as $k=>$v) { $c = substr($k, 0, 1); if (($c>='a' && $c<='z') || ($c>='A' && $c<='Z')) { $arr[] = $this->_edit_textfield( $k, $k, $v ); if ($this->_CI->{$this->_model}->get_id_field() == $k) $arr[$k]['flags'][] = 'primary'; } } return $arr; } public function get_edit_name() { return ucfirst($this->_model); } // This method is used for rendering text read only, without any type of control. Note that the same parameters and array contents are used as are used // for the _edit_textfield method. In due time this can perhaps be extended (if necessary) such that the text e.g. is rendered in a DIV with the ID set // to the value that is passed in $fieldname, etc. For that reason, the fields that are not used at this time, have not (yet) been removed. protected function _edit_text_read_only( $name, $fieldname, $value='', $size=40 ) { return array( 'type' => 'text_read_only', 'textsize' => $size, 'name' => $name, 'fieldname' => $fieldname, 'value' => $value, 'flags' => array(), ); } protected function _edit_textfield( $name, $fieldname, $value='', $size=40 ) { return array( 'type' => 'text', 'textsize' => $size, 'name' => $name, 'fieldname' => $fieldname, 'value' => $value, 'flags' => array(), ); } protected function _edit_uploadfield( $name, $fieldname, $curfilename='' ) { return array( 'type' => 'upload', 'name' => $name, 'fieldname' => $fieldname, 'curfilename' => $curfilename, 'flags' => array(), ); } protected function _edit_passwordfield( $name, $fieldname, $value='', $size=40 ) { $field = BaseResult::_edit_textfield( $name, $fieldname, $value, $size ); $field['flags'][] = 'password'; return $field; } protected function _edit_enumfield( $name, $fieldname, $value='', $values=array() ) { return array( 'type' => 'enum', 'name' => $name, 'fieldname' => $fieldname, 'value' => $value, 'values' => $values, 'flags' => array(), ); } protected function _edit_selectfield( $name, $fieldname, $value, $model, $allow_null_value=false, $filter_func=null, $select_func='all' ) { return array( 'type' => 'select', 'name' => $name, 'fieldname' => $fieldname, 'value' => $value, 'model' => $model, 'flags' => ($allow_null_value ? array('select-null-option') : array() ), 'filter_func' => $filter_func, 'select_func' => $select_func, ); } public function get_stuk_naam() { $cl = get_class($this); if (substr( $cl, strlen($cl)-6 )=='Result') $cl = substr( $cl, 0, strlen($cl)-6 ); return $cl; } } class BaseModel extends Model { private $_apc_prefix = 'bb_prefix'; private $_apc_version = 16; private $_cache = array(); protected $_model_class; protected $_id_field = 'id'; protected $_table; protected $_CI; protected $_apc_cache; private $_db; private $_fields = array(); public function BaseModel( $model_class, $table, $use_apc_cache=false, $db=null ) { parent::Model(); $this->_CI = get_instance(); $this->_model_class = $model_class; $this->_table = $table; $this->_apc_cache = function_exists( 'apc_fetch' ) && $use_apc_cache; if (is_null( $db )) $this->_db = $this->_CI->db; else if (is_string( $db )) $this->_db = $this->_CI->load->database( $db, true ); else if (is_object( $db )) { $this->_db = $db; } else throw new Exception( 'BaseModel::BaseModel: unsupported value for $db' ); $this->_load_fields(); } // !!! Note: properly (?) made Oracle <-> MySQL compatible. Note that some mappings cannot be determined reliably, and may not be necessary. // TODO: Improve/implement the mappings if needed and also check ALL of the other methods in this class for Oracle compatibility. This WILL require further effort! private function _load_fields() { if (!$this->_table) // Statistiek model! return; if (get_db_type() == 'oracle') { $query = "SELECT * FROM all_tab_cols WHERE table_name = '" . strtoupper($this->_table) . "'"; } else { $query = "SHOW FIELDS FROM " . $this->_table; } $res = $this->_db->query( $query ); if (!$res) throw new Exception( 'BaseModel::_load_fields: failed to load fields for ' . $this->_table ); $this->_fields = array(); if (get_db_type() == 'oracle') { // Construct a data-set that is EXACTLY compatible with the way the MySQL version looks, so we are sure the data-sets are 100% compatible. foreach ($res->result() as $raw_row) { // Get the column name in lowercase. This is used as the key in the array. //$key = strtolower($raw_row->column_name); // Construct the row object such that is has exactly the same fields and information style as the MySQL version does $row = new stdClass(); $row->Field = strtolower($raw_row->column_name); $row->Type = get_mysql_type_for_oracle_type($raw_row->data_type, $raw_row->data_length); // Not fully implemented (yet)! -- may not be necessary. $row->Null = ($raw_row->nullable == 'N') ? 'NO' : 'YES'; $row->Key = '*** implement if needed ***'; $row->Default = $raw_row->data_default; $row->Extra = '*** implement if needed ***'; // Finally, store the row object to the data set $this->_fields[ $row->Field ] = $row; } } else { foreach ($res->result() as $row) $this->_fields[ $row->Field ] = $row; } } public function get_field( $fieldname ) { $fieldname = strtolower($fieldname); if (!$this->has_field( $fieldname )) return null; return $this->_fields[$fieldname]; } public function has_field( $fieldname ) { $fieldname = strtolower($fieldname); return isset( $this->_fields[ $fieldname ] ); } public function unset_field( $fieldname ) { $fieldname = strtolower($fieldname); unset( $this->{$fieldname} ); } public function unset_fields( $fieldnames = array() ) { foreach ($fieldnames as $fieldname) { $fieldname = strtolower($fieldname); unset( $this->{$fieldname} ); } } public function check_access( BaseResult $object ) { if (!$this->is_object_security_active()) return; // static $klant_id = false; //06-01-2015 MJ: always retrieve kid from userdata rather than checking if klant_id still has information //if ($klant_id===false) $klant_id = $this->session->userdata('kid'); if (!isset($object->klant_id)) { $object->klant_id = ''; } if (!isset($klant_id)) { $klant_id = ''; } $model = $object->get_model(); if (!$model) throw new Exception( 'BaseModel::check_access: failed to fetch model for specified object' ); if (!$model->has_field( 'klant_id' )) throw new Exception( 'BaseModel::check_access: model ' . get_class($model) . ' doesn\'t have a klant id, cannot check access' ); if ($object->klant_id != $klant_id && $object->klant_id != '' ) { $this->throw_no_access_error( $object, $model ); } } protected function throw_no_access_error( $object, $model ) { if (!isset( $_SERVER['HTTP_HOST'] ) || preg_match( '/dev\./', $_SERVER['HTTP_HOST'] )) { if (false) { echo '<pre>'; debug_print_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); echo '</pre>'; } } if (config_item( 'development_version' )) //if (1) { ob_start(); debug_print_backtrace(2); $trace = '<br/><pre>' . ob_get_clean() . '</pre>'; } //$trace .= '<br/>Object:<pre>' . dr($object) . '</pre>'; //d($trace); //d($object); //exit; throw new Exception( 'Geen toegang tot object ' . $object->id . ' van model ' . get_class($model) . ', verkeerde klant id!' . @$trace ); } public function check_relayed_access( BaseResult $object, $model, $field ) { // relay to gebruiker model $CI = get_instance(); if (!isset( $CI->$model )) $CI->load->model( $model ); if (!isset( $object->$field )) show_error( 'Fout bij bepalen van rechten: "' . $field . ' bestaat niet in object".' ); $CI->$model->get( $object->$field ); } public function is_object_security_active() { global $class, $method; if( $class=='admin' || ($class == 'content' && $method == 'logo') || $class == 'telefoon' || ($class == 'dossiers' && $method == 'subject_bewerken') ) { return false; } if ($this->is_post_login() || IS_CLI || (defined( 'IS_WEBSERVICE' ) && IS_WEBSERVICE)) return false; return true; } public function is_post_login() { global $class, $method; return $class == 'gebruikers' && $method == 'postlogin'; } public function get_db() { return $this->_db; } public function get_id_field() { return $this->_id_field; } protected function _get_select_list() { return '*'; } public function get( $id ) { if (!$id) return NULL; $obj = $this->_get_cache( $id ); if ($obj==null) { $this->_db->select( $this->_get_select_list() ); $this->_db->where( $this->_id_field, intval( $id ) ); $query = $this->_db->get( $this->_table ); if ($query->num_rows()!=1) return null; $row = $query->row(); $obj = new $this->_model_class( $row ); $this->_set_cache( $id, $obj ); } return $obj; } public function getr( $array, $use_cache=true ) { if (is_object($array)) $array = (array)$array; else if (!is_array($array)) return null; if (!isset($array[$this->_id_field])) return null; $id = $array[$this->_id_field]; $obj = $use_cache ? $this->_get_cache( $id ) : null; if ($obj==null) { $obj = new $this->_model_class( $array ); $this->_set_cache( $id, $obj ); } return $obj; } public function count() { return $this->_db->count_all( $this->_table ); } public function all( $sort_fields=array(), $assoc=false, $usecache=true ) { $result = array(); if (is_string($sort_fields)) $this->_db->order_by( $sort_fields ); else if (is_array($sort_fields)) foreach ($sort_fields as $field => $order) $this->_db->order_by( $field, $order ); $this->_db->select( $this->_get_select_list() ); $query = $this->_db->get( $this->_table ); $id = $this->_id_field; foreach ($query->result() as $row) { $obj = $usecache ? $this->_get_cache( $row->$id ) : null; if ($obj==null) { $obj = new $this->_model_class( $row ); $this->_set_cache( $row->$id, $obj ); } if ($assoc) $result[$row->$id] = clone $obj; else $result[] = clone $obj; } return $result; } public function save( $object, $do_transaction=true, $alias=null, $error_on_no_changes=true ) { if (!is_object( $object )) return false; $pset = false; $pval = null; foreach ((array)$object as $k => $v) { if ($k == $this->_id_field) { if ($pset) return false; $this->_db->where( $k, $v ); $pset = true; $pval = $v; } else if (substr($k, 0, 1)!='_') { // THIS IS FREAKING UGLY BUT IT WORKS FOR NOW *ashamed* if (!in_array( $k, array( 'laatst_bijgewerkt_op', 'laatste_bestands_wijziging_op' ))) $this->_db->set( $k, $v ); } } if (!$pset) return false; if ($do_transaction) $this->_db->trans_start(); // !!! Note (2014-11-17): Postpone the freeing of the statement. This is needed of the Oracle implemnentation as it requires the statement in order to get the affected_rows value!!!! // TODO: check if we must explicitly free the statement after the affected rows were determined or not. For now this is NOT done. // Copied note from DB_driver.php: // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2014-11-17: DANGER !!!: THE UNCONDITIONAL free_statement WAS DISABLED BECAUSE THE CHAIN OF THE BASE::SAVE -> DB_ACTIVE_REC::UPDATE -> // DB_DRIVER::QUERY CAUSED THE STATEMENT TO GET FREED AT THIS VERY POINT, WHICH IN ORACLE RESULTED IN NUM_AFFECTED_ROWS TO FAIL! THEREFORE, WE EITHER NEED AN // EXTENDED IMPLEMENTATION WHERE WE KEEP TRACK OF THE NUM_ROWS BEFORE FREEING THE STATEMENT, OR WE NEED TO POSTPONE THE FREEING OF THE STATEMENT. // AT THIS MOMENT THE LATTER IS THE CASE HERE AND WE NOW CONDITIONALLY FREE THE STATEMENT HERE. WE NEED TO CHECK IF THIS IS HANDLED CORRECTLY IN ALL LOCATIONS !!!!!!!!! // Note: pass the field types to the 'update' method so that method can make use of this information when needed. //$r = $this->_db->update( $this->_table . ($alias ? ' AS '.$alias : '') ); // Note: on behalf of Oracle compatibility, we skip the automatic freeing of the result in the underlying generic query call! // If we don't do this, in Oracle the subsequent call to $this->_db->affected_rows() fails, as that requires the statement to be active still. // Towards this end the last parameter (i.e. $skip_free_statement) is set to 'true' in the below code. We could make this conditional, by checking if // we're using MySQL or Oracle, but for now it's left as an unconditional value. $skip_free_statement = true; //$r = $this->_db->update( $this->_table . ($alias ? ' AS '.$alias : ''), NULL, NULL, NULL, $this->_fields ); $r = $this->_db->update( $this->_table . ($alias ? ' AS '.$alias : ''), NULL, NULL, NULL, $this->_fields, $skip_free_statement ); /* echo "BaseModel::save: Result: <br />\n"; d($r); echo "BaseModel::save: error_on_no_changes: <br />\n"; d($error_on_no_changes); echo "BaseModel::save: this->_db->affected_rows(): <br />\n"; d($this->_db->affected_rows()); * */ //echo "+++ 1 +++<br />"; if (!$r || ($error_on_no_changes && $this->_db->affected_rows()!=1)) { //echo "+++ 2 +++<br />"; if ($do_transaction) { //echo "+++ 3 +++<br />"; $this->_db->_trans_status = false; $this->_db->trans_complete(); } //exit; return false; } //echo "+++ 4 +++<br />"; //exit; if (get_class($object) != $this->_model_class) { //echo "+++ 5 +++<br />"; $arr = (array)$object; $object = new $this->_model_class( $arr ); } //echo "+++ 6 +++<br />"; $this->_set_cache( $pval, $object ); return $do_transaction ? $this->_db->trans_complete() : true; } public function delete( $object ) { if (!is_object( $object ) || get_class( $object )!=$this->_model_class) return false; $arr = (array)$object; if (!isset( $arr[ $this->_id_field ] )) return false; $this->_db->_trans_status = true; $this->_db->trans_start(); $this->_db->where( $this->_id_field, $arr[ $this->_id_field ] ); // Note: on behalf of Oracle compatibility, we skip the automatic freeing of the result in the underlying generic query call! // If we don't do this, in Oracle the subsequent call to $this->_db->affected_rows() fails, as that requires the statement to be active still. // Towards this end the last parameter (i.e. $skip_free_statement) is set to 'true' in the below code. We could make this conditional, by checking if // we're using MySQL or Oracle, but for now it's left as an unconditional value. $skip_free_statement = true; //$r = $this->_db->delete( $this->_table ); $r = $this->_db->delete( $this->_table, '', null, true, $skip_free_statement ); if (!$r || $this->_db->affected_rows()!=1) { $this->_db->_trans_status = false; $this->_db->trans_complete(); return false; } $this->_clear_cache( $arr[ $this->_id_field ] ); return $this->_db->trans_complete(); } private function _add_cache_stat( $id, $miss ) { if (function_exists('get_stats')) { $stats = get_stats(); $index = $miss ? 'misses' : 'hits'; if ($this->_apc_cache) $stats->cache[$index][] = 'apc:'.$this->_table . ':' . $id; else $stats->cache[$index][] = 'db:'.$this->_table . ':' . $id; } } protected function _get_cache( $id ) { if ($this->_apc_cache) { $key = $this->_get_key( $id ); $value = apc_fetch( $key ); if ($value===FALSE || !is_array($value)) { $this->_add_cache_stat( $id, true ); return null; } if (!isset( $value['version'] ) || $value['version']!=$this->_apc_version) { $this->_add_cache_stat( $id, true ); return null; } if (!is_array( $value['value'] )) { $this->_add_cache_stat( $id, true ); return null; } $obj = (object)$value['value']; $this->_add_cache_stat( $id, false ); return new $this->_model_class( $obj ); } else { if (isset($this->_cache[$id])) { $this->_add_cache_stat( $id, false ); return $this->_cache[$id]; } else { $this->_add_cache_stat( $id, true ); return null; } } } function _set_cache( $id, $object ) { if ($this->_apc_cache) { $key = $this->_get_key( $id ); $data = array(); foreach ($object as $k=>$v) if ($k!='_CI' && $k!='_model') $data[$k] = $v; $value = array( 'version'=>$this->_apc_version, 'value'=>$data ); apc_store( $key, $value ); } else $this->_cache[$id] = $object; } function _clear_cache( $id ) { if ($this->_apc_cache) apc_delete( $this->_get_key( $id ) ); else unset( $this->_cache[$id] ); } private function _get_key( $id ) { return $_SERVER['SERVER_NAME'] . $this->_apc_prefix . '_' . $this->_table . '_' . $id; } function convert_results( $query, $assoc=false ) { if (!$query) { ob_start(); debug_print_backtrace( 2 ); $str = ob_get_clean(); throw new Exception( 'Convert_results called for failed query: <br/>' . str_replace( "\n", '<br/>', $str ) ); } $result = array(); foreach ($query->result() as $row) if ($assoc) $result[ $row->id ] = $this->getr( (array)$row ); else $result[] = $this->getr( (array)$row ); $query->free_result(); return $result; } function get_table() { return $this->_table; } function search( array $fields, $extra_query=null, $assoc=false, $operator='AND', $order_by='', $joins=array() /* each entry must contain JOIN keyword! */ ) { if (!is_array( $joins )) $joins = array( $joins ); // !!! In order to make the below query Oracle compatible we need to change two things: // 1: The first character of the aliases MUST be alphanumeric // 2: The direct value of '1' is not allowed, and MUST be replaced to 'something' that can be evaluated. // $query = 'SELECT _T.* FROM ' . $this->get_table() . ' _T ' . implode( ' ', $joins ) . ' WHERE 1 '; $query = 'SELECT T1.* FROM ' . $this->get_table() . ' T1 ' . implode( ' ', $joins ) . ' WHERE 1=1 '; foreach ($fields as $key => $value) $query .= ' AND (' . $key . ' = ' . $this->db->escape( $value ) . ') '; if ($extra_query) $query .= $operator . ' (' . $extra_query . ') '; if ($order_by) $query .= ' ORDER BY ' . $order_by; if (!($res = $this->db->query( $query ) )) throw new Exception( 'Fout bij uitvoeren query: ' . $query ); return $this->convert_results( $res, $assoc ); } // Note: by allowing an optional $statement_name_suffix parameter, we can re-use ths method for many situations (using different parameters) where we would // otherwise have to duplicate the below code, basically only to use a different prepared statement name. // Also: At least for Oracle it is sometimes desirable to force the types of parameters to a specific type (in particular for LOB handling!). This can be // achieved by passing a type string in the $force_types parameter. function insert( $data, $statement_name_suffix = '', $force_types = '' ) { // build query $query = 'INSERT INTO ' . $this->get_table() . ' ('; $query_values = ''; $c = 0; foreach ($data as $k => $parameter_data) { // In some cases we need to apply special formatting to the prepared parameter. This should not often be needed. In cases where it is, we need to // pass the parameter's value, along with a format string, as an array. An example is when in Oracle one needs to insert a record in which a // literal date-time string needs to be converted to a date. It seems there is no way to just pass the entire formatting function as a string, as // that keeps resulting in DB errors (i.e. "ORA-01858: a non-numeric character was found where a numeric was expected"). Instead, the formatting // needs to be part of the statement itself, and only the value needs to be prepared. $format_string = "%s"; if (is_array($parameter_data)) { // Extract the format string and the parameter data. Note that the format string can contain either a '%s' or just directly a '?' in the location where // the actual parameter value is to appear. $format_string = (!empty($parameter_data['format_string'])) ? $parameter_data['format_string'] : "%s"; $parameter_data = (!empty($parameter_data['data'])) ? $parameter_data['data'] : ''; // Then, write only the data back (at the same position) in the data array, so the normal (generic!) 'execute' call only has the data it expects, // without formatting information. $data[$k] = $parameter_data; } $query .= ($c ? ',' : '') . $k; $query_values .= ($c ? ',' : '') . sprintf($format_string, '?'); // Apply the formatting, if any. Note: the parameter can also directly be passed as a '?' instead of as a '%s' $c++; } $query .= ') VALUES (' . $query_values . ')'; // For Oracle we add a return value, in order to get the last inserted ID value, as the insert_id method is not implemented for Oracle! // Note: this will fail in case the table does not have an 'ID' column! Should this occur in the application, there will probably not be a flexible way to dynamically get the // proper ID column, so the name will then most likely need to be passed to the method, and used down below. /* if ((get_db_type() == 'oracle')) { $query .= ' return ID into :last_insert_id'; } * */ // prepare & execute $stmt_name = get_class($this) . '::insert' . $statement_name_suffix; //if (!$this->dbex->prepare( $stmt_name, $query )) if (!$this->dbex->prepare_with_insert_id( $stmt_name, $query, null, $last_insert_id)) throw new Exception( 'Fout bij preparen van statement voor toevoegen: ' . $query . ', ' . $this->db->_error_message() ); // For Oracle we bind a variable (i.e. $last_insert_id) to the return value, in order to get the last inserted ID value, as the insert_id method is not implemented for Oracle! /* if ((get_db_type() == 'oracle')) { $this->dbex->bind_parameter_with_return_value($stmt_name, ":last_insert_id", $last_insert_id, 10, SQLT_INT); } * */ if (!$this->dbex->execute( $stmt_name, $data, false, null, $force_types )) throw new Exception( 'Fout bij executen van statement voor toevoegen' ); // result if (get_db_type() == 'oracle') { $data['id'] = $last_insert_id; } else { $data['id'] = $this->db->insert_id(); } if (!$data['id']) { throw new Exception( 'Fout bij ophalen insert id' ); } return new $this->_model_class( $data ); } } <file_sep><? require_once 'base.php'; class DeelplanVraagBescheidenResult extends BaseResult { function DeelplanVraagBescheidenResult( $arr ) { parent::BaseResult( 'deelplanvraagbescheiden', $arr ); } } class DeelplanVraagBescheiden extends BaseModel { function DeelplanVraagBescheiden() { parent::BaseModel( 'DeelplanVraagBescheidenResult', 'deelplan_vraag_bescheiden' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); } function get_by_deelplan( $deelplan_id ) { if (!$this->dbex->is_prepared( 'get_vraag_bescheiden_by_deelplan' )) $this->dbex->prepare( 'get_vraag_bescheiden_by_deelplan', ' SELECT lb.*, b.tekening_stuk_nummer, b.auteur, b.omschrijving, b.datum_laatste_wijziging, b.bestandsnaam FROM deelplan_vraag_bescheiden lb JOIN dossier_bescheiden b ON lb.dossier_bescheiden_id = b.id WHERE lb.deelplan_id = ? ORDER BY lb.id ' ); $res = $this->dbex->execute( 'get_vraag_bescheiden_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) { $vraag_id = $row->vraag_id; if (!isset( $result[$vraag_id] )) $result[$vraag_id] = array(); $result[$vraag_id][] = $this->getr( $row ); } $res->free_result(); return $result; } function add( $deelplan_id, $vraag_id, $bescheiden_id ) { /* if (!$this->dbex->is_prepared( 'add_vraag_bescheiden' )) $this->dbex->prepare( 'add_vraag_bescheiden', 'INSERT INTO deelplan_vraag_bescheiden (deelplan_id, vraag_id, dossier_bescheiden_id) VALUES (?, ?, ?)' ); $args = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'bescheiden_id' => $bescheiden_id, ); $this->dbex->execute( 'add_vraag_bescheiden', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'deelplan_id' => $deelplan_id, 'vraag_id' => $vraag_id, 'dossier_bescheiden_id' => $bescheiden_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } }<file_sep><? require_once 'base.php'; class PbmResult extends BaseResult { function PbmResult( $arr ){ foreach ($arr as $k => $v) $this->$k = $v; } //------------------------------------------------------------------------------ }// Class end class Pbm extends BaseModel { private $_cache = array(); function Pbm(){ parent::BaseModel( 'PbmResult', 'cust_rep_data_155_pbm_taak'); } //------------------------------------------------------------------------------ function get_tasks( $dossier ){ //$sql = 'SELECT tasks.* FROM `cust_rep_data_155_pbm_taak` tasks WHERE TRUE AND `dossier_id`=?'; $sql = 'SELECT * FROM cust_rep_data_155_pbm_taak WHERE dossier_id = ?'; $stmt_name = 'pbm::all_tasks'; //$stmt_name .= '_debug_verbose'; //$stmt_name .= '_debug_medium'; $this->_CI->dbex->prepare( $stmt_name, $sql ); $res = $this->_CI->dbex->execute( $stmt_name, array( $dossier->id ), false, null, 'i'); //$res = $this->_CI->dbex->execute_debug(3, $stmt_name, array( $dossier->id ), false, null, 'i'); //d($res); //if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $dossier->id ), false, $this->_CI->db, 'i') )) // if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $dossier->id ), false, null, 'i') )) if (!($res)) { throw new Exception( 'Pbm model exeption by method get_tasks' ); } $this->_CI->load->model('pbm_risk'); $result = array(); foreach( $res->result() as $row ){ unset( $row->dossier_id ); $sub_tasks = $row->risks = $this->_CI->pbm_risk->get_risks( $row->id ); $row = $this->getr( $row ); $result[] = $row; } return $result; } //------------------------------------------------------------------------------ function get_task_by_id( $id ){ $sql = "SELECT * FROM cust_rep_data_155_pbm_taak WHERE id = ?"; $stmt_name = 'pbm::by_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $id ) ))) throw new Exception( 'Pbm model exeption by method get_task_by_id' ); $result = $res->result(); return $this->getr( $result[0] ); } //------------------------------------------------------------------------------ public function save( DossierResult $dossier, array $postdata ){ $postdata['dossier_id'] = $dossier->id; if( $postdata['id'] == '' ){ return $this->insert( $postdata ); }else{ return parent::save( (object)$postdata ); } } }// Class end <file_sep><?php // de 3 modi waarin je een recht_definitie kan hebben define( 'RECHT_MODUS_GEEN', 0x01 ); define( 'RECHT_MODUS_ALLE', 0x02 ); define( 'RECHT_MODUS_EIGEN', 0x04 ); define( 'RECHT_GROUP_ONLY', 0x08 ); define( 'RECHT_MODUS_SYSAD_ONLY', 0x80 );// rechten met deze flag mogen alleen door sysads gegeven worden // de constanten voor de verschillende recht_definities die er zijn in het systeem // // BTW: nooit een getal hergebruiken!!!! // BTW: nooit een getal wijzigen, dan klopt de rol_rechten tabel niet meer!! // define( 'RECHT_TYPE_UT', 1000 ); define( 'RECHT_TYPE_GEBRUIKERS_BEHEREN', 1 ); define( 'RECHT_TYPE_DOSSIER_LEZEN', 2 ); define( 'RECHT_TYPE_DOSSIER_SCHRIJVEN', 3 ); define( 'RECHT_TYPE_DOSSIER_AFMELDEN', 4 ); define( 'RECHT_TYPE_DEELPLAN_LEZEN', 5 ); define( 'RECHT_TYPE_DEELPLAN_SCHRIJVEN', 6 ); define( 'RECHT_TYPE_SCOPE_LEZEN', 7 ); define( 'RECHT_TYPE_SCOPE_SCHRIJVEN', 8 ); define( 'RECHT_TYPE_TOEZICHTBEVINDING_LEZEN', 9 ); define( 'RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN', 10 ); define( 'RECHT_TYPE_MATRICES_BEWERKEN', 11 ); define( 'RECHT_TYPE_TOEWIJZEN_TOEZICHTHOUDERS', 12 ); define( 'RECHT_TYPE_TOEZICHT_AFMELDEN', 13 ); define( 'RECHT_TYPE_DEELPLAN_AFDRUKKEN', 14 ); define( 'RECHT_TYPE_LICENTIES_UITGEVEN', 15 ); define( 'RECHT_TYPE_NIEUWS_BEHEREN', 16 ); define( 'RECHT_TYPE_LOGBOEK_SCHRIJVEN', 17 ); define( 'RECHT_TYPE_DOSSIER_VERANTWOORDELIJKE_ZIJN', 18 ); define( 'RECHT_TYPE_SITEBEHEER', 19 ); define( 'RECHT_TYPE_CHECKLIST_WIZARD', 20 ); define( 'RECHT_TYPE_MANAGEMENT_INFO_BEKIJKEN', 21 ); define( 'RECHT_TYPE_OVERIG_BEHEER', 22 ); define( 'RECHT_TYPE_DOSSIERS_IMPORTEREN', 23 ); define( 'RECHT_TYPE_BACKLOG_BEHEREN', 24 ); define( 'RECHT_TYPE_INLINE_EDIT_BESCHIKBAAR', 25 ); define( 'RECHT_TYPE_PDF_ANNOTATOR', 26 ); define( 'RECHT_TYPE_PHONE_INTERFACE', 27 ); define( 'RECHT_TYPE_ADD_USER_OWN_COMPANY', 28 ); // define( 'RECHT_TYPE_TEKST_MANAGMENT', 29 ); // define( 'RECHT_TYPE_LOGO_MANAGMENT', 30 ); // define( 'RECHT_TYPE_CHECKLIST_GRP_MANAGMENT', 31 ); define( 'RECHT_TYPE_GRP_ADMINISTRATOR', 34 ); define( 'RECHT_TYPE_USER_GROUP_USER', 81 ); define( 'RECHT_TYPE_TOEZICHTMOMENTEN', 82 ); define( 'RECHT_TYPE_MAPPINGEN', 83 ); define( 'RECHT_TYPE_PARENT_KLANT_ADMIN', 84 ); <file_sep> REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('deelplannen.checklistgroep::opdrachten.betrokkene', 'Betrokkene', '2013-12-13 12:29:33', 0), ('deelplannen.checklistgroep::opdrachten.datum', 'Datum', '2013-12-13 12:29:36', 0), ('deelplannen.checklistgroep::opdrachten.gereed', 'Gereed', '2013-12-13 12:29:38', 0), ('deelplannen.checklistgroep::opdrachten.locatie', 'Locatie', '2013-12-13 12:29:30', 0), ('deelplannen.checklistgroep::opdrachten.nieuw', 'Nieuwe opdracht', '2013-12-13 14:01:31', 0), ('deelplannen.checklistgroep::opdrachten.opdracht', 'Opdracht', '2013-12-13 12:29:27', 0), ('dossiers.bekijken::opdrachtenoverzicht', 'Opdrachtenoverzicht', '2013-12-13 19:30:32', 0), ('nav.opdrachtenoverzicht', 'Opdrachtenoverzicht - $1', '2013-12-17 12:32:15', 0), ('nav.opdrachtenoverzicht_pad_element', '$1', '2013-12-13 19:57:24', 0); <file_sep>ALTER TABLE `bt_hoofdgroep_aandachtspunten` ADD `checklist_groep_id` INT NOT NULL AFTER `hoofdgroep_id` ; ALTER TABLE `bt_hoofdgroep_aandachtspunten` ADD INDEX ( `checklist_groep_id` ) ; ALTER TABLE `bt_hoofdgroep_aandachtspunten` ADD FOREIGN KEY ( `checklist_groep_id` ) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `bt_vraag_aandachtspunten` ADD `checklist_groep_id` INT NOT NULL AFTER `vraag_id` , ADD `checklist_id` INT NOT NULL AFTER `checklist_groep_id`, ADD INDEX ( `checklist_groep_id` ), ADD INDEX ( `checklist_id` ); UPDATE bt_vraag_aandachtspunten a SET a.checklist_groep_id = ( SELECT cl.checklist_groep_id FROM bt_checklisten cl JOIN bt_hoofdgroepen h ON cl.id = h.checklist_id JOIN bt_categorieen c ON h.id = c.hoofdgroep_id JOIN bt_vragen v ON c.id = v.categorie_id WHERE v.id = a.vraag_id ), a.checklist_id = ( SELECT h.checklist_id FROM bt_hoofdgroepen h JOIN bt_categorieen c ON h.id = c.hoofdgroep_id JOIN bt_vragen v ON c.id = v.categorie_id WHERE v.id = a.vraag_id ); ALTER TABLE `bt_vraag_aandachtspunten` ADD FOREIGN KEY ( `checklist_groep_id` ) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `bt_vraag_aandachtspunten` ADD FOREIGN KEY ( `checklist_id` ) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Logo\'s verwijderen')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Logo verwijderen', 'width' => '920px' ) ); ?> <form method="post"> <table> <tr> <th id="form_header">Verwijder logo voor:</th> </tr> <tr> <td id="form_value"> <select name="klant_id"> <? foreach ($bestaande_logos as $logo): ?> <option value="<?=$logo->id?>"><?=$logo->volledige_naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form_button"><input type="submit" value="Verwijderen" name="delete" /></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>PDFAnnotator.GUI.Tools = PDFAnnotator.Base.extend({ init: function( gui, toolsconfig ) { this._super(); this.registerEventType( 'beforeselecttool' ); this.registerEventType( 'selecttool' ); /* store tools config */ this.gui = gui; this.toolsconfig = toolsconfig; /* check tools and selected tools dom nodes */ if (this.toolsconfig.tools.size() != this.toolsconfig.selectedTools.size()) throw "different sizes for this.toolsconfig.tools and this.toolsconfig.selectedTools (" + this.toolsconfig.tools.size() + "!=" + this.toolsconfig.selectedTools.size() + ")"; for (var i=0; i<this.toolsconfig.tools.size(); ++i) { $(this.toolsconfig.tools[i]).data( 'selectedTool', $(this.toolsconfig.selectedTools[i]) ); $(this.toolsconfig.selectedTools[i]).data( 'tool', $(this.toolsconfig.tools[i]) ); } /* create instance variables */ this.selectedMenuHeader = null; this.selectedTool = null; /* install resize handler to resize when window resizes */ this.installResizeHandler(); /* install tools item expand/collapse handlers */ this.installOpenCloseEvents(); }, /* initialize as soon as all subsystems are setup */ initialize: function() { /* activate tool now? */ if (this.toolsconfig.activeToolIndex != undefined) this.selectToolByButton( this.toolsconfig.tools[ this.toolsconfig.activeToolIndex ] ); }, getActiveToolName: function() { if (!this.selectedTool) return ''; return this.selectedTool.attr( 'toolname' ); }, getActiveTool: function() { return PDFAnnotator.Tool.prototype.getByName( this.getActiveToolName() ); }, installResizeHandler: function() { var thiz = this; PDFAnnotator.Window.prototype.getInstance().on( 'resize', function( window, data ){ // resize toolbar and handle var cont = thiz.toolsconfig.mainContainer.parent(); cont.css( 'height', data.height + 'px' ); cont.css( 'top', data.top + 'px' ); thiz.toolsconfig.mainContainer.css( 'height', data.height + 'px' ); thiz.toolsconfig.handle.css( 'top', (data.height - (parseInt(thiz.toolsconfig.handle.css( 'height')) + 5)) + 'px' ); // re-position stay-on-top buttons for (var i=0; i<thiz.toolsconfig.tools.size(); ++i) { var btns = [ $(thiz.toolsconfig.selectedTools[i]), $(thiz.toolsconfig.tools[i]) ] for (var j=0; j<btns.length; ++j) { var btn = btns[j]; if (btn.css('top') == 'auto') continue; // store original top once, so we can re-use that value if the window resizes multiple times if (!btn.attr( 'orig-top' )) btn.attr( 'orig-top', btn.css( 'top' ) ); btn.css( 'top', (parseInt(btn.attr( 'orig-top' )) + data.top) + 'px' ); } } }); }, installOpenCloseEvents: function() { var thiz = this; /* toggle entire tools panel opening and closing */ this.toolsconfig.handle.click(function(){ thiz.toggle(); }); /* toggle submenus opening when mousing over */ this.toolsconfig.submenus.each(function(){ var submenu = $(this); var menuitem = submenu.prev(); menuitem.click(function(){ thiz.hideAllSubMenus(); if (!menuitem.hasClass( 'AlwaysOnTop' )) thiz.show(); menuitem.hide(); submenu.show(); }); }); /* relay click events from selected tool nodes to normal nodes */ this.toolsconfig.selectedTools.click(function(){ var toolDom = $($(this).data( 'tool' )); var subMenu = toolDom.parents( '.PanelToolsSubMenu' ); if (subMenu.size()) { thiz.dispatchEvent( 'beforeselecttool', {button:this} ); subMenu.prev().trigger( 'click' ); } else thiz.getActiveTool().dispatchEvent( 'reselect' ); }); /* handle selecting a tool */ this.toolsconfig.tools.click(function(){ thiz.dispatchEvent( 'beforeselecttool', {button:this} ); thiz.dispatchEvent( 'selecttool', {button:this} ); }); /* register event handlers */ this.on( 'beforeselecttool', function( tools, props ){ if (thiz.selectedTool) { thiz.getActiveTool().dispatchEvent( 'deselect' ); $(thiz.selectedTool).hide(); thiz.selectedTool = null; } }); this.on( 'selecttool', function( tools, props ){ thiz.hideAllSubMenus(); }); this.on( 'selecttool', function( tools, props ){ thiz.selectToolByButton( props.button ); }); /* toggle now */ this.toolsconfig.handle.trigger( 'click' ); this.toolsconfig.handle.trigger( 'click' ); }, selectToolByButton: function( btn ) { this.selectedTool = $(btn).data( 'selectedTool' ); this.selectedTool.show(); this.getActiveTool().dispatchEvent( 'select' ); }, hideAllSubMenus: function() { this.toolsconfig.submenus.filter(':visible').each(function(){ var submenu = $(this); var menuitem = submenu.prev(); submenu.hide(); menuitem.show(); }); }, toggle: function() { if (this.toolsconfig.mainContainer.is( ':visible' )) { this.hide(); } else this.show(); }, hide: function() { this.toolsconfig.handle.css( 'right', '0px' ); this.hideAllSubMenus(); this.toolsconfig.mainContainer.hide(); }, show: function() { this.toolsconfig.handle.css( 'right', (1+parseInt(this.toolsconfig.mainContainer.width()) + 'px') ); this.toolsconfig.mainContainer.show(); }, resetTools: function() { var toolmap = PDFAnnotator.Tool.prototype.getToolMap(); for (var i in toolmap) if (typeof( toolmap[i] ) == 'object') { toolmap[i].reset(); } } }); <file_sep><? require_once 'base.php'; class DeelplanSubjectResult extends BaseResult { function DeelplanSubjectResult( &$arr ) { parent::BaseResult( 'deelplansubject', $arr ); } } class DeelplanSubject extends BaseModel { function DeelplanSubject() { parent::BaseModel( 'DeelplanSubjectResult', 'deelplan_subjecten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossiersubject', 'dossier_subject_id' ); } function get_by_deelplan( $deelplan_id ) { if (!$this->dbex->is_prepared( 'get_subjecten_by_deelplan' )) $this->dbex->prepare( 'get_subjecten_by_deelplan', ' SELECT * FROM deelplan_subjecten WHERE deelplan_id = ? ORDER BY id ' ); $res = $this->dbex->execute( 'get_subjecten_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) $result[ $row->dossier_subject_id ] = $this->getr( $row ); return $result; } function set_for_deelplan( $deelplan_id, array $dossier_subject_ids, array $current_subjecten ) { // changes? $change_detected = false; if (sizeof( $current_subjecten ) == sizeof( $dossier_subject_ids )) { foreach ($dossier_subject_ids as $dossier_subject_id) if (!isset( $current_subjecten[$dossier_subject_id] )) { $change_detected = true; break; } if (!$change_detected) return; } // delete current $this->db->from( 'deelplan_subjecten' ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->delete(); // add new $this->dbex->prepare( 'set_deelplan_subject', 'INSERT INTO deelplan_subjecten (deelplan_id, dossier_subject_id) VALUES (?, ?)' ); foreach ($dossier_subject_ids as $dossier_subject_id) { $args = array( 'deelplan_id' => $deelplan_id, 'dossier_subject_id' => $dossier_subject_id, ); $this->dbex->execute( 'set_deelplan_subject', $args ); } // remove any deelplan-subject-vragen that no longer apply if (!empty( $dossier_subject_ids )) $this->db->query( $q = ' DELETE FROM deelplan_subject_vragen WHERE deelplan_id = ' . intval($deelplan_id) . ' AND dossier_subject_id NOT IN (' . implode( ',', array_map( function( $a ) { return intval($a); }, $dossier_subject_ids ) ) . ') '); else $this->db->query( $q = ' DELETE FROM deelplan_subject_vragen WHERE deelplan_id = ' . intval($deelplan_id) . ' '); } } <file_sep><?php class CheckChecklist { private $CI; private $_checklist; private $_checklist_groep; private $_checklist_groep_klant; public function __construct( ChecklistResult $checklist ) { $this->CI = get_instance(); $this->_checklist = $checklist; $this->_checklist_groep = $checklist->get_checklistgroep(); $this->_checklist_groep_klant = $this->_checklist_groep->get_klant(); } public function run( $fix_mistakes ) { echo '-------------------------------------------------------------------------------------' . "\n"; echo 'Checklist: ' . $this->_checklist->naam . "\n"; echo 'Checklist hoort bij groep: ' . $this->_checklist_groep->naam . "\n"; echo 'Checklistgroep is van: ' . $this->_checklist_groep_klant->naam . "\n"; echo '-------------------------------------------------------------------------------------' . "\n"; echo ($fix ? 'Fouten worden gerepareerd' : '!!!! FOUTEN WORDEN NIET GEREPAREERD !!!!') . "\n"; echo '-------------------------------------------------------------------------------------' . "\n"; $seen_themas = $seen_hoofdthemas = $seen_grondslags = array(); foreach ($this->_checklist->get_hoofdgroepen() as $hoofdgroep) foreach ($hoofdgroep->get_categorieen() as $categorie) foreach ($categorie->get_vragen() as $vraag) { if ($thema = $vraag->get_thema()) { $klant = $thema->get_klant(); if (!in_array( $thema->id, $seen_themas )) { $seen_themas[] = $thema->id; echo 'Thema: ' . $thema->thema . str_repeat( ' ', 40 - strlen($thema->thema) ). ' van ' . $klant->naam . "\n"; } if ($klant->id != $this->_checklist_groep_klant->id) { if ($fix_mistakes) { $newthema = $this->CI->thema->find( $thema->thema, $this->_checklist_groep_klant->id ); if ($newthema) { echo 'REPAREREN: verander thema ' . $thema->thema . ' van ' . $thema->id . ' naar ' . $newthema->id . "\n"; $vraag->thema_id = $newthema->id; if (!$vraag->save()) throw new Exception( 'Fout bij opslaan in database.' ); $thema = $newthema; // override reference locally! } else echo 'PROBLEEM: kan fout niet oplossen, kan thema ' . $thema->thema . ' niet vinden voor klant ' . $this->_checklist_groep_klant->naam . "\n"; } } if ($hoofdthema = $thema->get_hoofdthema()) { $klant = $hoofdthema->get_klant(); if (!in_array( $hoofdthema->id, $seen_hoofdthemas )) { $seen_hoofdthemas[] = $hoofdthema->id; echo 'Hoofdthema: ' . $hoofdthema->naam . str_repeat( ' ', 35 - strlen($hoofdthema->naam) ). ' van ' . $klant->naam . "\n"; } if ($klant->id != $this->_checklist_groep_klant->id) { if ($fix_mistakes) { $newhoofdthema = $this->CI->hoofdthema->find( $hoofdthema->naam, $this->_checklist_groep_klant->id ); if ($newhoofdthema) { echo 'REPAREREN: verander hoofdthema ' . $hoofdthema->naam . ' van ' . $hoofdthema->id . ' naar ' . $newhoofdthema->id . "\n"; $thema->hoofdthema_id = $newhoofdthema->id; if (!$thema->save()) throw new Exception( 'Fout bij opslaan in database.' ); $hoofdthema = $newhoofdthema; // override reference locally! } else echo 'PROBLEEM: kan fout niet oplossen, kan hoofdthema ' . $hoofdthema->naam . ' niet vinden voor klant ' . $this->_checklist_groep_klant->naam . "\n"; } } } } foreach ($vraag->get_grondslagen() as $vraaggrondslag) { $grondslag = $vraaggrondslag->get_grondslag(); $klant = $grondslag->get_klant(); if (!in_array( $grondslag->id, $seen_grondslags )) { $seen_grondslags[] = $grondslag->id; echo 'Grondslag: ' . $grondslag->grondslag . str_repeat( ' ', 36 - strlen($grondslag->grondslag) ). ' van ' . $klant->naam . "\n"; } if ($klant->id != $this->_checklist_groep_klant->id) { if ($fix_mistakes) { $newgrondslag = $this->CI->grondslag->find( $grondslag->grondslag, $this->_checklist_groep_klant->id ); if ($newgrondslag) { echo 'REPAREREN: verander grondslag ' . $grondslag->grondslag . ' van ' . $grondslag->id . ' naar ' . $newgrondslag->id . "\n"; $vraaggrondslag->grondslag_id = $newgrondslag->id; if (!$vraaggrondslag->save()) throw new Exception( 'Fout bij opslaan in database.' ); } else echo 'PROBLEEM: kan fout niet oplossen, kan grondslag ' . $grondslag->grondslag . ' niet vinden voor klant ' . $this->_checklist_groep_klant->naam . "\n"; } } } } } } <file_sep><?php class SourceException extends Exception { private $_source; public function __construct( $msg, $source ) { parent::__construct( $msg ); $this->_source = $source; } public function get_source() { return $this->_source; } } class DataSourceException extends SourceException { public function __construct( $msg ) { parent::__construct( $msg, 'data' ); } } class ServerSourceException extends SourceException { public function __construct( $msg ) { parent::__construct( $msg, 'server' ); } } <file_sep><form method="POST" enctype="multipart/form-data"> <table width="100%"> <tr> <td style="vertical-align:top"> <table width="100%"> <tr> <td style="vertical-align:top"><input type="file" name="document[]" accept=".pdf" multiple="true" ></td> </tr> <tr> <td style="text-align: center" width="33%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.toevoegen'), 'blank' => false, 'url' => 'javascript:opslaanDocument();', 'class' => 'greenbutton' ) ); ?> </td> </tr> <table> <table width="100%" class="buttonbar"> </table> <div class="pleasewaitbar hidden" style="text-align:center"> <img src="<?=site_url('/files/images/ajax-loader.gif')?>" /><br/> <i><?=tg('even_geduld_aub_uw_upload_kan_even_duren')?></i> </div> </td> </tr> </table> </form> <script type="text/javascript"> </script><file_sep>/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; DROP TABLE IF EXISTS standard_deelplannen; CREATE TABLE standard_deelplannen ( id INT(11) NOT NULL AUTO_INCREMENT, foreignid INT(11) DEFAULT NULL, klant_id INT(11) NOT NULL, naam VARCHAR(128) NOT NULL, kenmerk VARCHAR(32) DEFAULT NULL, sortering INT(11) NOT NULL, aangemaakt_op TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, afgemeld TINYINT(4) NOT NULL DEFAULT 0, afgemeld_op DATETIME DEFAULT NULL, sjabloon_id INT(11) DEFAULT NULL, sjabloon_naam VARCHAR(256) DEFAULT NULL, olo_nummer VARCHAR(64) DEFAULT NULL, aanvraag_datum DATE DEFAULT NULL, outlook_synchronisatie TINYINT(4) NOT NULL DEFAULT 1, PRIMARY KEY (id), INDEX sjabloon_id (sjabloon_id), CONSTRAINT standard_deelplannen_ibfk_2 FOREIGN KEY (sjabloon_id) REFERENCES sjablonen(id) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; ALTER TABLE `klanten` ADD COLUMN `standaard_deelplannen` tinyint(3) DEFAULT '0' NOT NULL AFTER `standaard_documenten`; REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'klant.standaard_deelplannen', ' Standaard Deelplannen?', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'standaard_deelplannen.headers.standaard_deelplannen', ' Standaard Deelplannen', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'beheer.index::standaard_deelplannen', ' <NAME>', '2015-03-19 15:14:13' ); /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep> DROP TABLE IF EXISTS bijwoonmomenten_map; CREATE TABLE bijwoonmomenten_map ( id int(11) NOT NULL AUTO_INCREMENT, matrix_id int(11) NOT NULL, toezichtmoment_id int(11) NOT NULL, PRIMARY KEY (id), UNIQUE INDEX UK_bijwoonmomenten_map (matrix_id, toezichtmoment_id), CONSTRAINT FK_bijwoonmomenten_map_bt_toezichtmomenten_id FOREIGN KEY (toezichtmoment_id) REFERENCES bt_toezichtmomenten (id) ON DELETE RESTRICT ON UPDATE RESTRICT, CONSTRAINT FK_bijwoonmomenten_map_matrix_mappingen_id FOREIGN KEY (matrix_id) REFERENCES matrix_mappingen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; ALTER TABLE artikel_vraag_mappen ADD COLUMN is_bw BOOLEAN DEFAULT FALSE AFTER is_active;<file_sep><? $this->load->view('elements/header', array('page_header'=>'mappingen.dmmclone','map_view'=>true)); ?> <h1><?=tgg('mappingen.headers.checklistenmap')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list double-list"> <thead> <tr> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoets')?></li> </ul> </th> <th>&nbsp;</th> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoezicht')?></li> </ul> </th> </tr> </thead> <tbody> <tr> <td> <ul id="bt_matrix" class="list mappen"> <? foreach( $bt_matrixen as $i=>$entry): ?> <? $entry_css = 'entry'; ?> <li id="bt_matrix_<?=$entry['id'] ?>" class="<?=$entry_css?> top left right <?=(($i==count($bt_matrixen)-1)?'bottom':'')?>" entry_id="<?=$entry['id'] ?>"> <div class="list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $entry['naam'], ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> </td> <td class="middle">&nbsp;</td> <td> <ul id="checklisten" class="list mappen" style=""> <li class="entry-selected-disabled top left right bottom"> <div class="list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8' )?></div> </li> </ul> </td> </tr> </tbody> </table> </div> <div id="volgende_btn" class="button" style="float:right"> <?=tgg('mappingen.buttons.volgende')?> </div> <br /> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> var checklist_map = { "checklist_id" : <?=$checklist->id ?> ,"bt_matrix_id" : null ,"dmm_naam":"<?=$dmm_naam?>" ,"old_dmm_id":"<?=$old_dmm_id?>" } ; function save_clone_map(){ $.ajax({ url: "<?=site_url('mappingen/save_clone_map/')?>", type: "POST", data: checklist_map, dataType: "json", success: function( data ){ if (data && data.success){ location.href = "<?=site_url('mappingen/finalmapping')?>"+"/"+data.matrixmap_id+"/"+checklist_map.bt_matrix_id+"/"+checklist_map.checklist_id }else{ showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); } }, error: function(erdata) { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen. (save_clone_map)", type: "error", buttons: ["ok"] }); } }); } $(document).ready(function(){ $("#volgende_btn").click(function(){ if(checklist_map.bt_matrix_id==null){ showMessageBox({ message: "You must select bristoets matrix.", type: "error", buttons: ["ok"] }); return; } save_clone_map(); }); $('#bt_matrix li[entry_id]').click(function(){ if(checklist_map.bt_matrix_id!=null){ $("#bt_matrix_"+checklist_map.bt_matrix_id) .removeClass("entry-selected") .addClass("entry"); } $(this) .removeClass("entry") .addClass("entry-selected"); checklist_map.bt_matrix_id = $(this).attr( "entry_id" ); }); //------------------------------------------------------------------------------ }); </script> <file_sep>-- Get some IDs in temporary variables SELECT @klant_id_imotep:=id FROM klanten WHERE naam = 'Imotep'; SELECT @klant_id_bris:=id FROM klanten WHERE naam = 'BRIS'; SELECT @klant_id_cebes:=id FROM klanten WHERE naam = 'Cebes'; SELECT @klant_id_vr_vggm:=id FROM klanten WHERE naam = 'Veiligheids- en gezondheidsregio'; SELECT @klant_id_vr_zhz:=id FROM klanten WHERE naam = 'Veiligheidsregio Zuid-Holland Zu'; SELECT @ws_id:=id FROM webservice_applicaties WHERE naam = 'Breed SOAP koppelvlak'; -- Limit some of the webservice accounts to specific 'klant_id' values INSERT INTO webservice_accounts SET webservice_applicatie_id = @ws_id, omschrijving = 'VR Gelderland-Midden (VGGM)', gebruikersnaam = '<EMAIL>', wachtwoord = sha1('vggm'), actief = 1, alle_klanten = 1, alle_components = 1, klant_id = @klant_id_vr_vggm; -- Insert the data for VGGM INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_vggm, target_id = @klant_id_imotep; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_vggm, target_id = @klant_id_bris; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_vr_vggm, target_id = @klant_id_vr_vggm; <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_beheer')); ?> <? $col_widths = array( 'image' => 40, 'naam' => 200, ); $col_description = array( 'image' => '&nbsp;', 'naam' => 'Naam', ); $col_unsortable = array( 'image', 'naam' ); $rows = array(); foreach ($checklistgroepen as $checklistgroep) { $row = (object)array(); $row->onclick = "location.href='" . site_url('/instellingen/prioriteitstelling_matrix/' . $checklistgroep->id) . "'"; $row->data = array( 'image' => ($checklistgroep->image_id ? '<img src="' . $checklistgroep->get_image()->get_url() . '"> ' : ''), 'naam' => $checklistgroep->naam, ); $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => null, 'url' => '/instellingen/prioriteiten', 'scale_field' => 'naam', 'do_paging' => false, 'disable_search' => true, 'header' => 'Scopes', ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php abstract class WebserviceModule { protected $CI; protected $_data; protected $_account; protected $_log; static private $modules; static public function register_module( $naam, WebserviceModule $object ) { if (empty( $naam )) throw new ServerSourceException( 'Module geregistreerd met lege naam' ); if (isset( self::$modules[$naam] )) throw new ServerSourceException( 'Module "' . $naam . '" reeds geregistreerd' ); self::$modules[$naam] = $object; } static public function get_all_modules() { return self::$modules; } static public function get_module( $naam ) { if (!isset( self::$modules[$naam] )) throw new ServerSourceException( 'Module "' . $naam . '" niet geregistreerd' ); return self::$modules[$naam]; } public function initialize( stdClass $data, WebserviceAccountResult $account, WebserviceLogResult $log ) { $this->CI = get_instance(); $this->_data = $data; $this->_account = $account; $this->_log = $log; $this->locallog( 'initialized' ); } public function has_function( $function ) { return in_array( $function, get_class_methods( $this )); } protected function _output_json( $value ) { $this->CI->_output_json( $value ); } protected function _login( $kid, $uid ) { if ($this->CI->login->logged_in()) $this->CI->login->logout(); $kid = intval( $kid ); $uid = intval( $uid ); if (!$this->CI->login->login( $uid )) throw new ServerSourceException( 'Login mechanisme heeft gefaald (1)' ); if (!$this->CI->login->logged_in()) throw new ServerSourceException( 'Login mechanisme heeft gefaald (2)' ); if ($this->CI->login->get_user_id() != $uid) throw new ServerSourceException( 'Login mechanisme heeft gefaald (3)' ); if (!$this->CI->gebruiker->get_logged_in_gebruiker()) throw new ServerSourceException( 'Login mechanisme heeft gefaald (4)' ); $this->CI->session->set_userdata( 'kid', $kid ); $this->CI->session->set_userdata( 'klant_volledige_naam', 'kvolledige_naam' ); $this->CI->session->set_userdata( 'do_inline_editing', false ); } public function locallog( $s ) { $str = '[' . date('Y-m-d H:i:s') . '] (' . get_class($this) . ') ' . trim($s) . "\n"; $fd = @fopen( "webservice.local.log", "a" ); if (!$fd) return; fwrite( $fd, $str ); fflush( $fd ); fclose( $fd ); } } <file_sep><form name="form" method="post" action="/dossiers/export/<?=$dossier->id?>"> <? $this->dossierexport->output_filter_form( 'standaard', $dossier ); ?> <table> <tr> <th colspan="2" style="text-align:left"><h2><?=tg('uitvoer.formaat')?></h2></th> </tr> <tr> <td colspan="2"> <select name="output_format"> <option value="output_format:docx" selected><?=tgn('uitvoer.docx')?></option> <? if (!$gebruiker->is_riepair_user()): ?> <option value="output_format:docxpdf"><?=tgn('uitvoer.docxpdf')?></option> <? endif; ?> </select> </td> </tr> <tr> <th colspan="2" style="text-align:left"><h2><?=tg('rapportage.versturen')?></h2></th> </tr> <tr> <td colspan="2"> <select name="target"> <option disabled>-- <?=tgn('download.opties')?> --</option> <option selected value="target:download"><?=tgn('rapport.downloaden')?></option> <option disabled></option> <option disabled>-- <?=tgn('email.opties')?> --</option> <? foreach ($subjecten as $subject): ?> <? $have_email = strlen($subject->email) > 0; $email = $have_email ? htmlentities( $subject->email, ENT_COMPAT, 'UTF-8' ) : tgn('geen.email.adres.opgegeven'); if ($subject->organisatie) $tekst = tgn( 'email.naar.met.organisatie', $subject->naam, $subject->organisatie, $email ); else $tekst = tgn( 'email.naar.zonder.organisatie', $subject->naam, $email ); ?> <option <?=$have_email?'':'disabled'?> value="<?=$subject->email?>"><?=$tekst?></option> <? endforeach; ?> <option value="target:email-custom"><?=tgn('naar.onderstaand.email.adres.versturen')?></option> </select> </td> </tr> <tr> <th colspan="2" style="text-align:left"><h2><?=tg('rapportage.file_naam')?></h2></th> </tr> <tr> <td colspan="2"> <input type="text" name="file_naam"> </td> </tr> <tr style="display:none"> <th style="text-align: left; width: 150px;"><?=tg('email.adres')?>:</th> <td><input type="text" name="custom_email" size="40"></td> </tr> <tr style="display:none"> <th style="text-align: left; width: 150px;"><?=tg('email.cc.aan.zelf')?>:</th> <td><input type="checkbox" name="cc_self"></td> </tr> </table> <br/> <input type="hidden" name="download-tag" value="<?=$download_tag?>" /> <input type="submit" id="generate_button" value="<?=tgng('form.aanmaken')?>" /> <?=htag('aanmaken')?> <div class="rapportage-progress" style="display: none; height:auto; border:0; background-color:transparent;"> <? $this->load->view( 'elements/laf-blocks/generic-progress-bar', array( 'extra_class' => 'rapportage', 'width' => '560px', 'proc' => 0, ) ); ?> <span class="rapportage-progress-text">0%</span> <br/> <span class="rapportage-progress-action"></span> </div> </form> <script type="text/javascript"> // // rapportage versturen opties // $('form[name=form]').submit(function(){ var target = $('select[name=target]').val(); var is_download = target == 'target:download'; if (target == 'target:email-custom') { var input = $('input[name=custom_email]'); var customemail = input.val(); if (!customemail) { alert( '<?=tgn('geen.email.adres.ingevoerd')?>' ); input.focus(); return false; } if (!(''+customemail).match( /^(.+)@(.+)\.(.+)$/ )) { alert( '<?=tgn('ongeldig.email.adres.ingevoerd')?>' ); input.focus(); return false; } } // init progress BRISToezicht.Progress.initialize( this, 'dossierexport', '<?=$download_tag?>' ); // als dit een download is, dan submitten, anders ajax call starten if (is_download) { return true; } else { var data = {}; for (var i=0; i<this.elements.length; ++i) { var el = this.elements[i]; if (el.name) { if (el.nodeName.toUpperCase()=='INPUT' && el.type.toUpperCase()=='CHECKBOX') { if (el.checked) data[el.name] = 'on'; } else { data[el.name] = el.value; } } } $.ajax({ url: this.action, type: 'POST', data: data, dataType: 'json', success: function(data) { if (!data.success) alert( '<?=tgn('er.is.een.fout.opgetreden.bij.het.versturen.van.de.email')?>' ); }, error: function() { alert( '<?=tgn('er.is.een.fout.opgetreden.op.de.server')?>' ); } }); return false; } }); $('select[name=target]').change(function(){ // regel custom email veld var input = $('input[name=custom_email]'); var tr = input.parent().parent(); if (this.value == 'target:email-custom') { tr.show(); input.focus(); } else tr.hide(); // regel cc aan jezelf veld var input = $('input[name=cc_self]'); var tr = input.parent().parent(); if (this.value != 'target:download') { tr.show(); input.focus(); } else tr.hide(); }); </script><file_sep>PDFAnnotator.Editable.Quad = PDFAnnotator.Editable.extend({ init: function( config ) { this._super( PDFAnnotator.Tool.prototype.getByName( 'quad' ) ); this.setData( config, { color: '#ff0000' }, [ 'from', 'to' ] ); this.lines = null; }, render: function() { // make sure line object exists, we cannot do this without container, // so we cannot do this inside the constructor! this.conditionallyCreateLines(); var thiz = this; var base = $('<div>') .addClass( 'Rounded10' ) .css( 'padding', '0' ) .css( 'position', 'absolute' ) .click(function(e){ thiz.dispatchEvent( 'click', {event:e} ); }); for (var i=0; i<this.lines.length; ++i) base.append( this.lines[i].dom ); this.addVisual( base ); this.updateInternal(); }, setTo: function( to ) { this.conditionallyCreateLines(); this.data.to = to; this.updateLines(); this.updateInternal(); }, setFrom: function( from ) { this.conditionallyCreateLines(); this.data.from = from; this.updateLines(); this.updateInternal(); }, setFromAndTo: function( from, to ) { this.conditionallyCreateLines(); this.data.to = to; this.data.from = from; this.updateLines(); this.updateInternal(); }, conditionallyCreateLines: function() { if (!this.lines) { if (!this.container) throw 'PDFAnnotator.Editable.Line.conditionallyCreateLines: no container set, cannot continue'; var topleft = this.data.from; var topright = new PDFAnnotator.Math.IntVector2( this.data.to.x, this.data.from.y ); var bottomright = this.data.to; var bottomleft = new PDFAnnotator.Math.IntVector2( this.data.from.x, this.data.to.y ); this.lines = [ new PDFAnnotator.Line( this.container, this.data.color, topleft, topright ), new PDFAnnotator.Line( this.container, this.data.color, topright, bottomright ), new PDFAnnotator.Line( this.container, this.data.color, bottomright, bottomleft ), new PDFAnnotator.Line( this.container, this.data.color, bottomleft, topleft ) ]; } }, finish: function() { this.updateLines( true ); }, updateLines: function( fixPositions ) { var x1 = Math.min( this.data.from.x, this.data.to.x ); var y1 = Math.min( this.data.from.y, this.data.to.y ); var x2 = Math.max( this.data.from.x, this.data.to.x ); var y2 = Math.max( this.data.from.y, this.data.to.y ); if (fixPositions) { this.data.from.x = x1; this.data.from.y = y1; this.data.to.x = x2; this.data.to.y = y2; } else { var topleft = new PDFAnnotator.Math.IntVector2( x1, y1 ); var topright = new PDFAnnotator.Math.IntVector2( x2, y1 ); var bottomright = new PDFAnnotator.Math.IntVector2( x2, y2 ); var bottomleft = new PDFAnnotator.Math.IntVector2( x1, y2 ); this.lines[0].update( topleft, topright ); this.lines[1].update( topright, bottomright ); this.lines[2].update( bottomright, bottomleft ); this.lines[3].update( bottomleft, topleft ); } }, /** Updates the internal state of our DIV and our lines. */ updateInternal: function() { var width = Math.round( Math.abs( this.data.from.x - this.data.to.x ) ); var height = Math.round( Math.abs( this.data.from.y - this.data.to.y ) ); // update div to have position and size of lines, and reset lines to pos 0x0 var base = this.visuals; var x = parseInt( this.lines[0].dom.css( 'left' ) ); var y = parseInt( this.lines[0].dom.css( 'top' ) ); base.css( 'left', x + 'px' ); base.css( 'top', y + 'px' ); base.css( 'width', width + 'px' ); base.css( 'height', height + 'px' ); for (var i=0; i<this.lines.length; ++i) { var d = this.lines[i].dom; d.css( 'left', (parseInt( d.css('left') ) - x) + 'px' ); d.css( 'top', (parseInt( d.css('top') ) - y) + 'px' ); } }, /** !!override!! */ moveRelative: function( relx, rely ) { var vec = new PDFAnnotator.Math.IntVector2( relx, rely ); this.setFromAndTo( this.data.from.added( vec ), this.data.to.added( vec ) ); }, /** !!override!! */ getHandle: function( type ) { // use a bit different handles for lines! switch (type) { case 'resize': if (typeof(this.handles[type]) == 'undefined') this.handles[type] = new PDFAnnotator.Handle.QuadResize( this ); return this.handles[type]; default: return this._super( type ); } }, /* !!overide!! */ rawExport: function() { return { type: 'quad', x1: this.data.from.x, y1: this.data.from.y, x2: this.data.to.x, y2: this.data.to.y, color: this.data.color }; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Quad({ color: data.color, from: new PDFAnnotator.Math.IntVector2( data.x1, data.y1 ), to: new PDFAnnotator.Math.IntVector2( data.x2, data.y2 ) }); }, /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { this.setFromAndTo( this.data.from.multiplied( newlevel / oldlevel ), this.data.to.multiplied( newlevel / oldlevel ) ); this.repositionHandles(); } }); <file_sep>PDFAnnotator.GUI.Menu.Layers = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( menu, config ) { this._super( menu ); // config entries this.list = config.list; this.addLayerWindow = config.addLayerWindow; this.entryClass = config.entryClass; this.invisibleClass = config.invisibleClass; this.activeClass = config.activeClass; this.filters = config.filters; this.filterDepressdClass = config.filterDepressdClass; this.addLayer = config.addLayer; this.removeLayer = config.removeLayer; this.visibleImages = config.visibleImages; this.filterImages = config.filterImages; this.contentClasses = config.contentClasses; this.currentLayerInfo = config.currentLayerInfo; // runtime data this.nextSubjectId = 1; this.nextReferenceId = 1; // runtime data this.layers = []; /* register DOM events */ var thiz = this; this.addLayer.click(function(){ thiz.list.slideUp(); thiz.addLayerWindow.window.slideDown(); thiz.updateReferenceList(); thiz.addLayerWindow.customName.val(''); }); this.addLayerWindow.cancel.click(function(){ thiz.list.slideDown(); thiz.addLayerWindow.window.slideUp(); }); this.addLayerWindow.addCustom.click(function(){ var name = thiz.addLayerWindow.customName.val(); if (name) { // hide add window by fake clicking cancel button thiz.addLayerWindow.cancel.trigger( 'click' ); // add layer with given name thiz.menu.gui.engine.createLayer( name ) .setFilter( 'none' ) .activate(); } }); this.removeLayer.click(function(){ var engine = thiz.menu.gui.engine; var layer = engine.getActiveLayer(); if (layer) { if (confirm( 'De geselecteerde layer met alle annotaties verwijderen?' )) { engine.removeLayer( layer ); } } else alert( 'Selecteer eerst de layer die u wilt verwijderen.' ); }); for (var i in this.filters) { if (this.filters[i] instanceof jQuery) { this.filters[i].attr( 'filter', i ); this.filters[i].click(function(){ var filterBtn = $(this); var filter = $(this).attr( 'filter' ); if (!filterBtn.hasClass( thiz.filterDepressdClass )) { // hide all layers with this filter setting filterBtn.addClass( thiz.filterDepressdClass ); for (var i=0; i<thiz.layers.length; ++i) { if (thiz.layers[i].layer.filter == filter) { thiz.layers[i].hide(); } } } else { // show all layers with this filter setting filterBtn.removeClass( thiz.filterDepressdClass ); for (var i=0; i<thiz.layers.length; ++i) { if (thiz.layers[i].layer.filter == filter) { thiz.layers[i].show(); } } } }); } } /* set handler to deal with resizing of parent window */ this.installResizeHandler(); }, initialize: function() { var thiz = this; /* register engine events (not done in constructor as engine reference is not yet available at that point) */ this.menu.gui.engine.on( 'layeradded', function( engine, data ){ thiz.layers.push( new PDFAnnotator.GUI.Menu.Layers.LayerEntry( thiz.list, data.layer, thiz ) ); }); this.menu.gui.engine.on( 'layerremoved', function( engine, data ){ for (var i=0; i<thiz.layers.length; ++i) { if (thiz.layers[i].layer == data.layer) { thiz.layers[i].remove(); thiz.layers.splice( i, 1 ); } } }); }, updateReferenceList: function() { // for now, always (re)load em var thiz = this; PDFAnnotator.Server.prototype.instance.getAvailableLayerReferenceObjects(function( objects ){ thiz.objects = objects; /* store for later use */ thiz.addLayerWindow.referencesList.html(''); for (var i=0; i<objects.length; ++i) { var subjectDom = thiz.addSubject( objects[i].subject ); for (var j=0; j<objects[i].references.length; ++j) { var reference = objects[i].references[j]; thiz.addReferenceObject( subjectDom, reference ); } } thiz.addLayerWindow.referencesList.find( '[subject-id]' ).click(function(){ var children = thiz.addLayerWindow.referencesList.find( '[parent-subject-id=' + $(this).attr('subject-id') + ']' ); if (children.is(':visible')) children.slideUp(); else children.slideDown(); }); thiz.addLayerWindow.referencesList.find( '[parent-subject-id]' ).click(function(){ // hide add window by fake clicking cancel button thiz.addLayerWindow.cancel.trigger( 'click' ); // see if layer for this object doesn't exist yet, if it exists, activate it var reference = $(this).data( 'reference' ), engine = thiz.menu.gui.engine, layer; if (layer = engine.findLayerByMetaData( 'referenceId', reference.getId() )) { layer.activate(); return; } // create layer, set meta data engine.createLayer( reference.getName() ) .setMetaData( 'referenceId', reference.getId() ) .setFilter( reference.getFilter() ) .activate(); }); }); }, updateLayersByReferences: function() { var engine = this.menu.gui.engine; for (var i=0; i<this.objects.length; ++i) { for (var j=0; j<this.objects[i].references.length; ++j) { var reference = this.objects[i].references[j]; // is there a layer with this object referenced? var layer = engine.findLayerByMetaData( 'referenceId', reference.getId() ); if (layer) layer.setFilter( reference.getFilter() ); } } }, addSubject: function( subjectName ) { return $('<div>') .text( subjectName ) .addClass( this.addLayerWindow.subjectClass ) .attr( 'subject-id', this.nextSubjectId++ ) .appendTo( this.addLayerWindow.referencesList ); }, addReferenceObject: function( subjectDom, referenceObject ) { return $('<div>') .text( referenceObject.getName() ) .addClass( this.addLayerWindow.referenceClass ) .attr( 'parent-subject-id', subjectDom.attr( 'subject-id' ) ) .appendTo( this.addLayerWindow.referencesList ) .data( 'reference', referenceObject ) .hide(); }, installResizeHandler: function() { var thiz = this; // handle resizing dom and tool panels PDFAnnotator.Window.prototype.getInstance().on( 'resize', function( window, data ){ // store original top if not yet done so if (!thiz.currentLayerInfo.attr( 'orig-top' )) thiz.currentLayerInfo.attr( 'orig-top', parseInt( thiz.currentLayerInfo.css( 'top' ) ) ); thiz.currentLayerInfo.css( 'top', (parseInt( thiz.currentLayerInfo.attr( 'orig-top' ) ) + data.top) + 'px' ); }); }, reset: function() { if (PDFAnnotator.Server.prototype.instance) this.updateReferenceList(); } }); <file_sep><? require_once 'base.php'; class ImageResult extends BaseResult { function ImageResult( &$arr ) { parent::BaseResult( 'image', $arr ); } function get_url() { return '/content/images/' . $this->id; } } class Image extends BaseModel { function Image() { parent::BaseModel( 'ImageResult', 'images', true ); } public function check_access( BaseResult $object ) { // disabled for model } function add( $filename, $data, $width, $height ) { /* if (!$this->dbex->is_prepared( 'Image::add' )) $this->dbex->prepare( 'Image::add', 'INSERT INTO images (filename, data, width, height) VALUES (?, ?, ?, ?)' ); $args = array( 'filename' => $filename, 'data' => $data, 'width' => $width, 'height' => $height, ); $this->dbex->execute( 'Image::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'filename' => $filename, 'data' => $data, 'width' => $width, 'height' => $height, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'sbii' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } function find_image_by_data( $data ) { $images = $this->search( array( 'data' => $data ) ); if (empty( $images )) return null; return $images[0]; } } <file_sep>INSERT INTO `lease_configuraties` (`id` ,`naam` ,`achtergrondkleur` ,`voorgrondkleur` ,`eigen_nieuws_berichten` ,`automatisch_collega_zijn` ,`toon_gebruikersforum_knop` ,`login_systeem`) VALUES (NULL , 'mkm', '336EA5', 'ffffff', 'ja', 'nee', 'nee', 'normaal'); ALTER TABLE `lease_configuraties` ADD `login_label` VARCHAR( 128 ) NOT NULL DEFAULT 'Inloggen' AFTER `naam`, ADD `pagina_titel` VARCHAR( 128 ) NOT NULL AFTER `login_label`, ADD `gebruik_matrixbeheer` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja', ADD `gebruik_management_rapportage` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja', ADD `gebruik_instellingen` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja', ADD `gebruik_rollenbeheer` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja', ADD `gebruik_dossier_rapportage` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'ja', ADD `gebruik_deelplan_email` ENUM( 'nee', 'ja' ) NOT NULL DEFAULT 'nee'; UPDATE `lease_configuraties` SET `pagina_titel` = 'M-Kart Mobil', `login_label` = 'M-Kart Mobil', `gebruik_matrixbeheer` = 'nee', `gebruik_management_rapportage` = 'nee',`gebruik_instellingen` = 'nee',`gebruik_rollenbeheer` = 'nee',`gebruik_dossier_rapportage` = 'nee',`gebruik_deelplan_email` = 'ja' WHERE `naam` = 'mkm'; UPDATE `lease_configuraties` SET `pagina_titel` = 'Riepair' WHERE `naam` = 'riepair'; <file_sep><?php // This is really not the way to go normally with Code Igniter, but our Webservices stuff // is setup quite differently. require_once( APPPATH . 'webservices/abstract.php' ); // Load PEAR/SOAP require_once "SOAP/Server.php"; require_once "SOAP/Disco.php"; // Define proxy object, that will handle all requests. Having this inside the controller interferes // with it being a Code Igniter controller here and there. So this got extrapolated into a new class. class SoapProxyObject { var $__typedef = array(); var $__dispatch_map = array(); var $_ws = null; var $_server = null; var $_urn = ''; public function __construct( SOAP_Server $server, AbstractWebservice $ws, $urn ) { // store references $this->_server = $server; $this->_ws = $ws; $this->_urn = $urn; // setup typedef map foreach ($ws->get_types() as $name => $typedef) { if (is_bool( $typedef )) continue; if (is_string( $typedef )) $typedef = array( array( 'item' => $this->_urnify_type( $typedef ) ) ); else if (is_array( $typedef )) foreach ($typedef as $key => &$typename) $typename = $this->_urnify_type( $typename ); else throw new Exception( 'SoapProxyObject::__construct: invalid type definition' ); $this->__typedef[ $name ] = $typedef; } // setup dispatch map foreach ($ws->get_methods() as $methodname => $methoddef) { if (isset( $methoddef['in'] ) && is_array( $methoddef['in'] )) foreach ($methoddef['in'] as $key => &$type) $type = $this->_urnify_type( $type ); if (isset( $methoddef['out'] ) && is_array( $methoddef['out'] )) foreach ($methoddef['out'] as $key => &$type) $type = $this->_urnify_type( $type ); $this->__dispatch_map[ $methodname ] = $methoddef; } // set object map $this->_server->addObjectMap( $this, 'urn:' . $this->_urn ); $this->_server->setCallHandler( array( $this, 'call' ) ); } public function call( $method, $args ) { try { return call_user_func_array( array( $this->_ws, 'call' ), func_get_args() ); } catch (Exception $e) { return $this->_server->_raiseSoapFault( $e->getMessage() ); } } private function _urnify_type( $type ) { if (isset( $this->__typedef[ $type ] )) return '{urn:' . $this->_urn . '}' . $type; return $type; } /** Dispatch function as required by the SOAP server. */ public function __dispatch( $methodname ) { if (isset($this->__dispatch_map[ $methodname ])) return $this->__dispatch_map[ $methodname ]; return NULL; } } /** Soap base controller, with nothing but protected functions to make sure the user can * never call them directly from the URL. */ class SoapBase extends Controller { private $_server = NULL; private $_urn; private $_url; private $_classname; private $_webservice; /** Config finder helper */ private function _get_config_item( $define, $configitem, $default ) { if (defined( $define )) return constant( $define ); else if (config_item( $configitem )) return config_item( $configitem ); else return $default; } /** Constructor. */ protected function __construct() { parent::__construct(); // setup basic parameters $this->_server = new SOAP_Server(); $this->_urn = $this->_get_config_item( 'WEBSERVICE_SOAP_URN', 'webservice_soap_urn', 'btz' ); $this->_url = $this->_get_config_item( 'WEBSERVICE_SOAP_URL', 'webservice_soap_url', '/soap/' ); $this->_classname = $this->_get_config_item( 'WEBSERVICE_SOAP_CLASSNAME', 'webservice_soap_classname', 'Webservice' ); if (!class_exists( $this->_classname )) throw new Exception( 'SoapBase::__construct: invalid webservice classname: ' . $this->_classname . ', class does not exists.' ); // check values $this->_urn = strval( $this->_urn ); if (!$this->_urn) throw new Exception( 'SoapBase::__construct: empty urn not allowed' ); $this->_url = strval( $this->_url ); if (!$this->_url) throw new Exception( 'SoapBase::__construct: empty url not allowed' ); // setup webservice and proxy object $this->_webservice = new $this->_classname(); $this->_proxy = new SoapProxyObject( $this->_server, $this->_webservice, $this->_urn ); } /** Returns SOAP discovery data. * When output is true, the result is not returned, but echoed. * NOTE: in the latter case, the header content type is set to text/xml. */ protected function _discovery( $output=true ) { $disco = '<?xml version="1.0"?>'. '<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/">'. '<scl:contractRef ref="' . site_url( $this->_url . '/wsdl' ). '" />'. '</disco:discovery>'; if (!$output) return $disco; header( 'Content-type: text/xml' ); echo $disco; } /** Returns complete WSDL based on registered methods and types. * When output is true, the result is not returned, but echoed. * NOTE: in the latter case, the header content type is set to text/xml. */ protected function _wsdl( $output=true ) { // create disco object $disco = new SOAP_DISCO_Server( $this->_server, $this->_urn ); // setup PHP_SELF and create wsdl $old_self = $_SERVER['PHP_SELF']; $_SERVER['PHP_SELF'] = preg_replace( '#https?://(.*?)/#', '/', site_url( $this->_url ) ); $wsdl = @ $disco->getWSDL(); $_SERVER['PHP_SELF'] = $old_self; // now either return or output if (!$output) return $wsdl; header( 'Content-Type: text/xml' ); echo $wsdl; } /** Handles soap request. When request is a GET< the discovery data is always sent to the user. * When it's a post, it's handled as an actual request! */ protected function _request() { // if this is not a POST, do discovery if (!isset( $_SERVER['REQUEST_METHOD'] ) || $_SERVER['REQUEST_METHOD']!='POST') $this->_discovery(); // otherwise, handle SOAP call else { $post_data = file_get_contents( 'php://input' ); $this->_server->service( $post_data ); } } } /** Soap controller. */ class Soap extends SoapBase { public function __construct() { parent::__construct(); } public function index() { $this->_request(); } public function wsdl() { $this->_wsdl(); } } <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('checklistwizard.aandachtspunten', 'Aandachtspunten', '2013-08-31 15:33:50', 0), ('checklistwizard.aanwezigheid', 'Controleniveau', '2013-08-31 15:33:50', 0), ('checklistwizard.checklist.actief', 'actief', '2013-09-03 12:10:58', 0), ('checklistwizard.checklist.in-gebruik', 'in gebruik', '2013-09-03 12:10:07', 0), ('checklistwizard.checklist.lang.actief', 'checklist is actief!', '2013-09-03 12:21:26', 0), ('checklistwizard.checklist.lang.in-gebruik', 'checklist is in gebruik!', '2013-09-03 12:21:23', 0), ('checklistwizard.checklist.lang.niet-actief', 'checklist is niet actief', '2013-09-03 12:24:00', 0), ('checklistwizard.checklist.lang.niet-in-gebruik', 'checklist is niet in gebruik', '2013-09-03 12:24:37', 0), ('checklistwizard.checklist.niet-actief', 'niet-actief', '2013-09-03 12:11:13', 0), ('checklistwizard.checklist.niet-in-gebruik', 'niet in gebruik', '2013-09-03 12:10:15', 0), ('checklistwizard.default-afwijkingen', 'wijkt af', '2013-09-03 12:54:07', 0), ('checklistwizard.fase', 'Fase', '2013-08-31 15:33:50', 0), ('checklistwizard.herstel-standaard-set', 'Herstel standaard', '2013-09-03 18:16:31', 0), ('checklistwizard.hoofdthema', 'Hoofdthema', '2013-08-31 15:33:50', 0), ('checklistwizard.integreerbaar', 'Integreerbaarheid', '2013-09-03 13:36:49', 0), ('checklistwizard.logo', 'Logo', '2013-08-31 15:33:50', 0), ('checklistwizard.naam', 'Naam', '2013-08-31 15:33:50', 0), ('checklistwizard.richtlijnen', 'Richtlijnen', '2013-08-31 15:33:50', 0), ('checklistwizard.standaardmatrix', 'Standaard matrix', '2013-09-03 13:37:00', 0), ('checklistwizard.standaardwaardeoordeel', 'Standaard', '2013-08-31 15:33:50', 0), ('checklistwizard.status', 'Checklist status', '2013-09-03 13:36:39', 0), ('checklistwizard.steekproefwaardeoordeel', 'Steekproef', '2013-08-31 15:33:50', 0), ('checklistwizard.steekproefwaardeoordeeltekst', 'Steekproef tekst', '2013-08-31 15:33:50', 0), ('checklistwizard.tekst', 'Tekst', '2013-09-02 19:55:36', 0), ('checklistwizard.thema', 'Thema', '2013-08-31 15:33:50', 0), ('checklistwizard.themas_automatisch_selecteren', 'Thema''s', '2013-09-03 13:36:54', 0), ('checklistwizard.toezicht_moment', 'Toezichtmoment', '2013-08-31 15:33:50', 0), ('checklistwizard.waardeoordelen', 'Waardeoordelen', '2013-08-31 15:33:50', 0), ('checklistwizard.wettelijke_grondslagen', 'Wettelijke grondslagen', '2013-08-31 15:33:50', 0), ('checklistwizard.wis', 'Wis', '2013-08-31 15:33:50', 0), ('checklistwizard.zelf-default-afwijkingen', 'wijkt zelf af', '2013-09-03 12:59:04', 0), ('nav.checklist_wizard', 'Checklist wizard', '2013-04-04 12:03:17', 0), ('nav.checklist_wizard', 'Checklist Wizard', '2013-04-05 15:41:43', 2), ('nav.checklist_wizard.checklisten', '$1', '2013-08-26 16:56:03', 0), ('nav.checklist_wizard.checklistgroepen', '$1', '2013-09-02 20:05:16', 0), ('nav.checklist_wizard.checklistgroep_uitgebreid_bewerken', '$1', '2013-09-02 14:43:54', 0), ('nav.checklist_wizard.checklistgroep_uitgebreid_toevoegen', 'Checklistgroep toevoegen', '2013-08-29 10:42:10', 0), ('nav.checklist_wizard.checklistgroep_volgorde', 'Wijzig checklistgroepen volgorde', '2013-08-26 16:07:22', 0), ('nav.checklist_wizard.checklist_uitgebreid_bewerken', '$1', '2013-09-02 15:00:17', 0), ('nav.checklist_wizard.checklist_uitgebreid_toevoegen', 'Checklist toevoegen', '2013-09-02 19:12:55', 0), ('nav.checklist_wizard.checklist_volgorde', 'Wijzig checklisten volgorde', '2013-08-26 16:25:39', 0), ('nav.checklist_wizard.hoofdgroepen', '$1', '2013-08-26 17:14:53', 0), ('nav.checklist_wizard.hoofdgroep_uitgebreid_bewerken', '$1', '2013-09-02 20:05:45', 0), ('nav.checklist_wizard.hoofdgroep_uitgebreid_toevoegen', 'Hoofdgroep toevoegen', '2013-09-02 20:06:12', 0), ('nav.checklist_wizard.hoofdgroep_volgorde', 'Wijzig hoofdgroep volgorde', '2013-08-26 17:21:09', 0), ('nav.checklist_wizard.vraag_uitgebreid_bewerken', '$1', '2013-09-02 20:05:01', 0), ('nav.checklist_wizard.vraag_uitgebreid_toevoegen', 'Vraag toevoegen', '2013-09-02 19:56:30', 0), ('nav.checklist_wizard.vraag_volgorde', 'Wijzig vraag volgorde', '2013-09-02 20:10:21', 0); <file_sep><?php require_once 'deelplannen.php'; class Mappingen extends Controller{ public function __construct(){ parent::__construct(); $this->navigation->push( 'nav.instellingen', '/instellingen' ); $this->navigation->push( 'nav.mappingen', '/mappingen' ); $this->navigation->set_active_tab( 'beheer' ); } // D E F A U L T M A P P I N G E N public function index(){ redirect( '/mappingen/mappingenlist' ); } public function mappingenlist(){ $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $string = 'mappingen.button.clone'; $btn_clone_title = htmlentities( get_instance()->tekst->get($string , true, true ), ENT_COMPAT, 'UTF-8' ); $this->load->view( 'mappingen/mappingenlist', array( 'list' => $klant->get_mappingen(), 'titles' => array( 'btn_clone_title' => $btn_clone_title ) ) ); } private function _check_post(){ if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'HTTP verzoek is geen POST.' ); } public function savetitle($id=NULL){ try { $this->_check_post(); $naam = trim( $_POST['naam'] ); if (!strlen( $naam )) throw new Exception( 'Lege naam niet toegestaan.' ); $this->load->model( 'matrixmapping' ); $obj = $this->matrixmapping->add( $naam, $this->gebruiker->get_logged_in_gebruiker()->get_klant()->id ); $matrixmapping_id = $obj->id; echo json_encode(array( 'success' => true ,'id' => $matrixmapping_id )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } private function get_matrix_map_checlisten( $matrixmapId ){ $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $checklisten= $klant->get_map_checklisten(); $this->load->model( 'matrixmapchecklisten' ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist($matrixmapId); foreach( $checklisten as &$checklist ){ $checklist->map_period = ''; foreach($matrixmapchecklisten as $mp_checklist ){ if( $is_mapped = $mp_checklist->checklist_id == $checklist->id ){ $checklist->map_period = date( 'd.m.Y', strtotime($mp_checklist->date)).' - '.date( 'd.m.Y', strtotime($mp_checklist->until)); break; } } } return $checklisten; } public function checklistenmap( $matrixmapId, $checklistId=NULL ){ $this->load->model( 'colectivematrix' ); if (!is_array($bt_collective_matrixen = $this->colectivematrix->all(array(), TRUE))) throw new Exception( 'Ongeldig collective matrix '); $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $this->load->model( 'matrixmapping' ); if (!($matrixmapping = $this->matrixmapping->get( $matrixmapId ))) throw new Exception( 'Ongeldig matrixmapping ID ' . $matrixmapId ); $this->load->model( 'matrixmapchecklisten' ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist($matrixmapId); $matrixmappingen = $this->matrixmapping->all(); foreach( $matrixmappingen as $btz_matrix ) { foreach($bt_collective_matrixen as $key=>$bt_matrix ) { if($btz_matrix->id != $matrixmapId && $bt_matrix['id'] == $btz_matrix->bt_matrix_id && $klant->id == $btz_matrix->klant_id ) { unset($bt_collective_matrixen[$key]); break; } } } $this->navigation->push( 'nav.mappingen.checklistenmap', '/mappingen/checklistenmap', array( $matrixmapping->naam )); $this->load->view( 'mappingen/checklistenmap', array( 'bt_matrixen' => $bt_collective_matrixen, 'checklisten' => $this->get_matrix_map_checlisten( $matrixmapId ), 'matrixmap_id' => $matrixmapId, 'checklist_id' => ( $checklistId == NULL && count($matrixmapchecklisten) ) ? $matrixmapchecklisten[0]->checklist_id : $checklistId, 'bt_matrix_id' => $matrixmapping->bt_matrix_id ) ); } public function dmmclonemap( $matrixmapId, $dmmNaam='New DMM Name' ){ $this->load->model( 'colectivematrix' ); $this->load->model( 'checklist' ); if (!is_array($bt_collective_matrixen = $this->colectivematrix->all(array(), true))) throw new Exception( 'Ongeldig collective matrix '); $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $this->load->model( 'matrixmapping' ); if (!($matrixmapping = $this->matrixmapping->get( $matrixmapId ))) throw new Exception( 'Ongeldig matrixmapping ID ' . $matrixmapId ); $matrixmappingen = $this->matrixmapping->all(); foreach( $matrixmappingen as $btz_matrix ) { foreach($bt_collective_matrixen as $key=>$bt_matrix ) { if( $bt_matrix['id'] == $btz_matrix->bt_matrix_id && $klant->id == $btz_matrix->klant_id ) { unset($bt_collective_matrixen[$key]); break; } } } $this->navigation->push( 'nav.mappingen.dmmclonemap', '/mappingen/checklistenmap', array( $matrixmapping->naam )); $checklist = $this->checklist->get($matrixmapping->checklist_id); $this->load->view( 'mappingen/dmmclonemap', array( 'bt_matrixen' => $bt_collective_matrixen, 'checklist' => $checklist, 'dmm_naam' => $dmmNaam, 'old_dmm_id' => $matrixmapId )); } public function save_clone_map(){ try { $this->_check_post(); $checklist_id = $_POST['checklist_id']; $bt_matrix_id = $_POST['bt_matrix_id']; $old_dmm_id = $_POST['old_dmm_id']; $this->load->model( 'matrixmapping' ); $this->load->model( 'bijwoonmomentenmap' ); $this->load->model( 'toezichtmoment' ); $this->load->model( 'colectivematrix' ); $this->load->model( 'artikelvraagmap' ); $matrixmapping = $this->matrixmapping->add( $_POST['dmm_naam'], $this->gebruiker->get_logged_in_gebruiker()->get_klant()->id ); // $matrixmapping->save_matrix_map( $bt_matrix_id, $checklist_id ); //TODO: checklistmap $toezichtmomenten = $this->toezichtmoment->get_by_checklist( $checklist_id ); foreach( $toezichtmomenten as $toezichtmoment ) { $this->bijwoonmomentenmap->add( $matrixmapping->id, $toezichtmoment->id ); } $old_matrixmapping = $this->matrixmapping->get( $old_dmm_id ); $old_map = $old_matrixmapping->getArticelVraagMap(); $new_colectivematrix = $this->colectivematrix->get( $bt_matrix_id ); $old_colectivematrix = $this->colectivematrix->get( $old_matrixmapping->bt_matrix_id ); foreach( $old_map as $old_art_vr_map ){ $old_artikel = $old_colectivematrix->get_artikal( $old_art_vr_map->artikel_id ); foreach( $new_colectivematrix->afdelingen as $afdeling ){ foreach( $afdeling->artikelen as $new_artikel ){ if( $is_found = $new_artikel->naam == $old_artikel->naam ){ foreach($new_artikel->risicoProfielen as $rprofile ){ if($rprofile->risicoProfielId == $old_art_vr_map->bt_riskprofiel_id){ $result = $this->artikelvraagmap->add( $matrixmapping->id, $rprofile->risicoProfielId, $new_artikel->artikelId, $old_art_vr_map->vraag_id ); } } } } if($is_found) break; } } echo json_encode(array( 'success' => true ,'matrixmap_id' => $matrixmapping->id )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function save_checklisten_map( $matrixmappingId ){ try { $this->_check_post(); $this->load->model( 'bijwoonmomentenmap' ); $this->load->model( 'toezichtmoment' ); $this->load->model( 'matrixmapchecklisten' ); $this->load->model( 'matrixmapping' ); $bt_matrix_id = $_POST['bt_matrix_id']; $checklist_id = $_POST['checklist_id']; $matrixmapping = $this->matrixmapping->get( $matrixmappingId ); $matrixmapping->save_btmatrix_map( $bt_matrix_id ); $toezichtmomenten = $this->toezichtmoment->get_by_checklist( $checklist_id ); foreach( $toezichtmomenten as $toezichtmoment ) { $this->bijwoonmomentenmap->add( $matrixmappingId, $toezichtmoment->id ); } echo json_encode(array( 'success' => true )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function cancel_checklisten_map( $matrixmappingId ){ try { $this->load->model( 'matrixmapping' ); $matrixmapping = $this->matrixmapping->get( $matrixmappingId ); $matrixmapping->cancel_map(); echo json_encode(array( 'success' => true )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } private static function _get_hoofdgroep_vragen( $hoofdgroep, $matrixmapId=0, $artikelId=0 ){ $vragen = array(); foreach ($hoofdgroep->get_categorieen() as $categorie){ $nvrn = array(); $nvrn = $categorie->get_vragen_map( $matrixmapId, $artikelId ); $vragen = array_merge( $vragen, $nvrn ); } foreach( $vragen as &$vraag ) $vraag = array( 'id' => $vraag->id ,'naam' => $vraag->naam ,'status'=> $vraag->status ); return $vragen; } private function _get_checklist_hoofdgroepen( $checklist, $matrixmapId ){ $this->load->model( 'toezichtmoment' ); $this->load->model( 'bijwoonmomentenmap' ); $hoofdgroepen = $checklist->get_hoofdgroepen(); $res_hoofdgroepen = array(); foreach( $hoofdgroepen as $hoofdgroep ){ $vragen = self::_get_hoofdgroep_vragen( $hoofdgroep, $matrixmapId ); $is_busy = FALSE; foreach($vragen as $vraag ) if( $is_busy = $vraag['status'] == 'busy' ) break; $tmoment = $this->toezichtmoment->get_by_hoofdgroep( $hoofdgroep->id ); $bw = $this->bijwoonmomentenmap->get_by_toezichtmoment( $tmoment->id, $matrixmapId ); $res_hoofdgroepen[] = array( 'id' => $hoofdgroep->id, 'naam' => $hoofdgroep->naam, 'count'=> count($vragen), 'vragen'=> $vragen, 'is_busy' => $is_busy, 'is_bw' => isset($bw->is_dmm_bw)?$bw->is_dmm_bw:FALSE, 'is_bw_btn' => isset($bw->is_dmm_bw) ); } return $res_hoofdgroepen; } private function normalizeBtCollectivMatrix( $btCollectiveMatrix ) { foreach( $btCollectiveMatrix['afdelingen'] as $afd_key=>&$afdeling ) { foreach( $afdeling['artikelen'] as $art_key=>&$artikel ) { if( count($artikel['risicoprofielen']) < 1 ) { unset($afdeling['artikelen'][$art_key]); } } $afdeling['artikelen'] = array_values($afdeling['artikelen']); if(count($afdeling['artikelen']) < 1) { unset($btCollectiveMatrix['afdelingen'][$afd_key]); } } $btCollectiveMatrix['afdelingen'] = array_values($btCollectiveMatrix['afdelingen']); return $btCollectiveMatrix; } private function isPeriodFit( $matrixmapId, $date, $until ){ $this->load->model( 'matrixmapchecklisten' ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist($matrixmapId); $mk_date = strtotime( $date ); $mk_until = strtotime( $until ); foreach( $matrixmapchecklisten as $mp_checklist ){ $mk_c_date = strtotime($mp_checklist->date); $mk_c_until = strtotime($mp_checklist->until); if( !($mk_until <= $mk_c_date || $mk_date >= $mk_c_until) ){ return FALSE; } } return TRUE; } private function isDatesValid( $matrixmapId, $date, $until ){ if( $date == ''){ echo json_encode( array( 'success' => false, 'message' => 'You should enter date.', 'focus' => 'date' )); return FALSE; }elseif( $until == ''){ echo json_encode( array( 'success' => false, 'message' => 'You should enter date.', 'focus' => 'until' )); return FALSE; }elseif( $until <= $date ){ echo json_encode( array( 'success' => false, 'message' => 'Start date must be greater then end date.', 'focus' => 'until' )); return FALSE; }elseif( !$this->isPeriodFit( $matrixmapId, $date, $until )){ echo json_encode( array( 'success' => false, 'message' => 'This period has been already used.', 'focus' => 'until' )); return FALSE; } return TRUE; } public function save_dmm_checklist_dates($checklistmapId=NULL){ if( !$this->isDatesValid($_POST['matrixmap_id'], $_POST['date'], $_POST['until']) ){ return; } $this->load->model( 'matrixmapchecklisten' ); $data = array( 'date' => date('Y-m-d',strtotime($_POST['date'])), 'until' => date('Y-m-d',strtotime($_POST['until'])), 'matrixmap_id' => $_POST['matrixmap_id'], 'checklist_id' => $_POST['checklist_id'] ); if( $checklistmapId != NULL ){ $data['id'] = $checklistmapId; $matrixmapchecklist = $this->matrixmapchecklisten->save( (object)$data ); }else{ $matrixmapchecklist = $this->matrixmapchecklisten->insert( $data ); } echo json_encode( array( 'success' => true )); } public function finalmapping( $matrixmapId, $btMatrixId, $checklistId ) { $this->load->model( 'colectivematrix' ); if (!$bt_collective_matrix = $this->colectivematrix->get($btMatrixId,true)){ throw new Exception( 'Ongeldig collective matrix '); } $bt_collective_matrix = $this->normalizeBtCollectivMatrix( $bt_collective_matrix ); $this->load->model( 'matrixmapping' ); if (!($matrixmapping = $this->matrixmapping->get( $matrixmapId ))){ throw new Exception( 'Ongeldig matrixmapping ID ' . $matrixmapId ); } $afdelingen = $bt_collective_matrix['afdelingen']; foreach( $afdelingen as &$afdeling ){ $afdeling['count'] = count($afdeling['artikelen']); } $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklistId ))) throw new Exception( 'Ongeldig checklist ID ' . $checklistId ); $this->load->model( 'matrixmapchecklisten' ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist($matrixmapId, $checklistId); if( (bool)count($matrixmapchecklisten) ){ $matrixmapchecklist = $matrixmapchecklisten[0]; $matrixmapchecklist->date = date('d-m-Y',strtotime($matrixmapchecklist->date)); $matrixmapchecklist->until = date('d-m-Y',strtotime($matrixmapchecklist->until)); }else{ $matrixmapchecklist = new stdClass(); $matrixmapchecklist->id = NULL; $matrixmapchecklist->date = ''; $matrixmapchecklist->until = ''; } $hoofdgroepen = $this->_get_checklist_hoofdgroepen( $checklist, $matrixmapId ); $hf_busy_data = array(); foreach( $hoofdgroepen as $key=>$hoofdgroep ){ $hf_busy_data[$hoofdgroep['id']] = $hoofdgroep['is_busy']; } $this->navigation->push( 'nav.mappingen.checklistenmap', '/mappingen/checklistenmap/'.$matrixmapId.($checklistId!=NULL?'/'.$checklistId:''), array( $matrixmapping->naam )); $this->navigation->push( 'nav.mappingen.finalmapping', '/mappingen/finalmapping'); $this->load->view( 'mappingen/finalmapping', array( 'afdelingen' => $afdelingen, 'hoofdgroepen' => $hoofdgroepen, 'matrixmap_id' => $matrixmapId, 'checklist_id' => $checklistId, 'matrixmapchecklist' => $matrixmapchecklist, 'bt_matrix_id' => $btMatrixId, 'hf_busy_data' => $hf_busy_data ) ); }//-- private function _get_checklist_hoofdgroepen_info( $matrixmapId, $artikelId, $checklistId ){ $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklistId ))){ throw new Exception( 'Ongeldig checklist ID ' . $checklistId ); } $hoofdgroepen = $checklist->get_hoofdgroepen(); $hf_vragen = array(); foreach( $hoofdgroepen as $hoofdgroep ){ $vragen = self::_get_hoofdgroep_vragen( $hoofdgroep, $matrixmapId, $artikelId ); $n_free = $n_owner= 0; foreach($vragen as $vraag ){ ( $vraag['status'] == 'free' ) ? $n_free++ : NULL; ( $vraag['status'] == 'owner' ) ? $n_owner++ : NULL; } $hf_vragen[] = array( 'id' => $hoofdgroep->id, 'n_owner' => $n_owner, 'n_free' => $n_free ); } return $hf_vragen; } public function get_opted_vragen( $artikelId, $hfdgrpId, $matrixmapId, $checklistId ){ $this->load->model( 'hoofdgroep' ); $hoofdgroep = $this->hoofdgroep->get($hfdgrpId); $vragen = self::_get_hoofdgroep_vragen( $hoofdgroep, $matrixmapId, $artikelId ); $hf_info = $this->_get_checklist_hoofdgroepen_info( $matrixmapId, $artikelId, $checklistId ); echo json_encode(array( 'success' => true ,'artikel_id' => $artikelId ,'hfdgrp_id' => $hfdgrpId ,'vragen' => $vragen ,'hf_info' => $hf_info )); }//-- private function getArticelRisicoprofielen( $dmmId, $artikelId ){ $this->load->model( 'matrixmapping' ); if (!($dmm= $this->matrixmapping->get( $dmmId ))) throw new Exception( 'Ongeldig DMM id ' . $dmmId ); $this->load->model( 'colectivematrix' ); if (!$bt_collective_matrix = $this->colectivematrix->get( $dmm->bt_matrix_id, true )) throw new Exception( 'Ongeldig collective matrix ID'); foreach($bt_collective_matrix['afdelingen'] as $afdeling ){ $is_found = FALSE; foreach($afdeling['artikelen'] as $artikel ) if( $is_found = $artikel['id'] == $artikelId ) break; if($is_found) break; } return $artikel['risicoprofielen']; }//-- private function isHoofdgroepBusy( $hfId, $dmmId, $artikelId ){ $this->load->model( 'hoofdgroep' ); $hoofdgroep = $this->hoofdgroep->get($hfId); $vragen = self::_get_hoofdgroep_vragen( $hoofdgroep, $dmmId, $artikelId ); $is_busy = FALSE; foreach($vragen as $vraag ) if( $is_busy = $vraag['status'] != 'free' ) break; return $is_busy; } private function _get_checklist_hoofdgroep_info( $matrixmapId, $artikelId, $hfId, $checklistId ){ $hoofdgroepen = $this->_get_checklist_hoofdgroepen_info( $matrixmapId, $artikelId, $checklistId ); foreach( $hoofdgroepen as $hoofdgroep ) if($hoofdgroep['id'] == $hfId ) return $hoofdgroep; } public function set_vraag_assigned( $dmmId, $artikelId, $vraagId, $hfId, $checklistId ){ $this->load->model( 'bijwoonmomentenmap' ); $this->load->model( 'artikelvraagmap' ); $this->load->model( 'matrixmapchecklisten' ); $risicoprofielen = $this->getArticelRisicoprofielen( $dmmId, $artikelId ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist( $dmmId, $checklistId); $matrixmapchecklist = $matrixmapchecklisten[0]; $hf_info= $this->_get_checklist_hoofdgroep_info( $dmmId, $artikelId, $hfId, $checklistId ); foreach( $risicoprofielen as $risicoprofiel ){ $result = $this->artikelvraagmap->add( $matrixmapchecklist->id, $risicoprofiel['id'], $artikelId, $vraagId ); } $hf_info= $this->_get_checklist_hoofdgroep_info( $dmmId, $artikelId, $hfId, $checklistId );//Don't delete this line!!! There were changes!!! echo json_encode(array( 'success' => true ,'is_busy' => $this->isHoofdgroepBusy( $hfId, $dmmId, $artikelId ) // ,'is_busy' => true ,'is_busy' => false ,'hf_id' => $hfId ,'n_owner' => $hf_info['n_owner'] ,'n_free' => $hf_info['n_free'] )); }//-- public function set_vraag_unassigned( $dmmId, $artikelId, $vraagId, $hfId, $checklistId ){ $this->load->model( 'artikelvraagmap' ); $this->load->model( 'matrixmapchecklisten' ); $matrixmapchecklisten = $this->matrixmapchecklisten->get_by_matrixmap_checklist( $dmmId, $checklistId); $matrixmapchecklist = $matrixmapchecklisten[0]; $result = $this->artikelvraagmap->delete_by_artikel_vraag( $matrixmapchecklist->id, $artikelId, $vraagId ); $hf_info = $this->_get_checklist_hoofdgroep_info( $dmmId, $artikelId, $hfId, $checklistId ); echo json_encode(array( 'success' => true, 'is_busy' => $this->isHoofdgroepBusy( $hfId, $dmmId, $artikelId ) ,'hf_id' => $hfId ,'n_owner' => $hf_info['n_owner'] ,'n_free' => $hf_info['n_free'] )); }//-- public function show_project_toezichtpunten( $deelplan_id ){ $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); $this->load->view( 'mappingen/show_project_toezichtpunten', array( 'deelplan_id' => $deelplan_id ,'btz_project_mappen'=>$deelplan->get_project_mappen() ) ); } public function add_project_bristoezicht( $prVraagId ){ $this->load->model( 'projectmap' ); $this->load->model( 'deelplan' ); $this->load->model( 'btbtzdossier'); $this->load->model( 'dossier'); $this->projectmap->save((object)array('id'=>$prVraagId,'is_active'=>TRUE)); $this->projectmap->_set_cache( $prVraagId, null ); $proj_vraag = $this->projectmap->get($prVraagId); $deelplan = $this->deelplan->get($proj_vraag->deelpan_id); $btbtzdossier = $this->btbtzdossier->get_one_by_btz_dossier_id( $deelplan->dossier_id ); $bouwnummers = $btbtzdossier->get_bouwnummers(); $vragen = array(); foreach($bouwnummers as $bouwnummer ) { $vraag = (object)array( 'id' => $proj_vraag->vraag_id, 'automatische_toel_moment' => NULL, 'bouwnummer' => $bouwnummer ); $vragen[] = $vraag; } $this->deelplan->add_vragen( $proj_vraag->deelpan_id, $vragen, array() ); echo json_encode(array( 'success' => true )); } public function change_project_bw( $prVraagId ){ $this->load->model( 'projectmap' ); $this->load->model( 'toezichtmoment' ); $this->load->model( 'deelplan' ); $this->load->model( 'deelplanchecklisttoezichtmoment' ); $pr_vraag = $this->projectmap->get($prVraagId); $toezichtmoment = $this->toezichtmoment->get($pr_vraag->toezichtmoment_id); $deelplan = $this->deelplan->get($pr_vraag->deelpan_id); $dp_checklisten = $deelplan->get_deelplan_checklisten($toezichtmoment->checklist_id); foreach( $dp_checklisten as $dp_checklist ) { $t_momenten = $this->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist( $dp_checklist->id, $toezichtmoment->id ); if(isset($t_momenten[0])) { $t_moment = $t_momenten[0]; } else { continue; } $t_moment->bijwoonmoment = !$t_moment->bijwoonmoment; $t_moment->save(); } echo json_encode(array( 'success' => true )); } public function save_bw( $matrixmapId, $hfId ){ $this->load->model( 'bijwoonmomentenmap' ); $this->load->model( 'toezichtmoment' ); $this->load->model( 'artikelvraagmap' ); $tmoment = $this->toezichtmoment->get_by_hoofdgroep( $hfId ); $bw = $this->bijwoonmomentenmap->get_by_toezichtmoment( $tmoment->id, $matrixmapId ); $bw->is_dmm_bw = $bw->is_drsm_bw = ($_POST['is_bw']=='true'); $bw->save(); $hoofdgroepen = $tmoment->get_hoofdgroepen(); $hf_ids = array(); foreach($hoofdgroepen as $hoofdgroep ) { $hf_ids[] = $hoofdgroep->id; } echo json_encode( array( 'success' => true ,'hf_ids' => $hf_ids )); } }// Class end<file_sep><? $this->load->view('elements/header', array('page_header'=>null)); ?> <? function verplicht_image( $veld, $verplichte_velden ) { if (isset( $verplichte_velden[$veld] )) return '<span style="color:red">*</span>'; return ''; } ?> <script type="text/javascript"> function has_value( component, description, cur_result ) { if ( (''+component.value).length == 0) { $('.group:first').trigger( 'click' ); $(component).addClass( 'inputerror' ); if (cur_result) // only focus first error! component.focus(); return false; } return true; } function on_submit_form() { var result = true; <? foreach ($verplichte_velden as $v => $desc): ?> if (!has_value( document.form.<?=$v?>, '<?=$desc?>', result )) result = false; <? endforeach; ?> return result; } $(document).ready(function(){ $('.inputerror').live('blur', function(){ $(this).removeClass( 'inputerror' ); }); }); </script> <? if ($dossier_access == 'write'): ?> <form name="form" method="post" onsubmit="return on_submit_form();" enctype="multipart/form-data"> <? endif; ?> <input type="hidden" name="target_state" value="" /> <? $this->load->view( 'dossiers/bewerken-registratiegegevens' ); ?> <div style="padding:0;margin:0;border:0;background-color:inherit;height:auto;" class="betrokkenen-container"> <? $this->load->view( 'dossiers/bewerken-betrokkenen' ); ?> </div> <div style="padding:0;margin:0;border:0;background-color:inherit;height:auto;" class="bescheiden-container"> <? $this->load->view( 'dossiers/bewerken-bescheiden' ); ?> </div> <? if ($is_riepair_user): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('rapportage-organisatiekenmerken.header'), 'group_tag' => 'dossier', 'width' => '100%', 'height' => 'auto', 'defunct' => false, 'onclick' => 'load_rapportage_organisatiekenmerken(this);' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('rapportage_pbm.header'), 'group_tag' => 'dossier', 'id'=>'pbm_tab', 'width' => '100%', 'height' => 'auto', 'defunct' => false, 'onclick' => 'load_rapportage_pbm(this);' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('rapportage-pago_pmo.header'), 'group_tag' => 'dossier', 'id'=>'pago_pmo_tab', 'width' => '100%', 'height' => 'auto', 'defunct' => false, 'onclick' => 'load_rapportage_pago_pmo(this);' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <script> function load_rapportage_organisatiekenmerken(el) { var target = $(el).next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_organisatiekenmerken/' . $dossier->id)?>' ); } function load_rapportage_pbm(el) { var target = $(el).next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pbm/' . $dossier->id)?>' ); } function load_rapportage_pago_pmo(el) { var target = $(el).next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pago_pmo/' . $dossier->id)?>' ); } </script> <? endif; ?> <!-- submit button --> <? if ($dossier_access == 'write'): ?> <p align="right"> <input type="submit" value="<?=tgng('form.opslaan')?>" /> </p> <? endif; ?> <? if ($dossier_access == 'write'): ?> </form> <? endif; ?> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class ChecklistGroepKlantResult extends BaseResult { function ChecklistGroepKlantResult( &$arr ) { parent::BaseResult( 'checklistgroepklant', $arr ); } } class ChecklistGroepKlant extends BaseModel { function ChecklistGroepKlant() { parent::BaseModel( 'ChecklistGroepKlantResult', 'bt_checklist_groep_klanten', true ); } public function check_access( BaseResult $object ) { return; } public function all() { $res = get_instance()->db->query( 'SELECT * FROM ' . $this->get_table() ); $result = array(); foreach ($res->result() as $row) { $row = (array)$row; $result[] = new ChecklistGroepKlantResult( $row ); } $res->free_result(); return $result; } public function replace_for_checklistgroep( $checklistgroep_id, array $klant_ids ) { $stmt1 = 'ChecklistGroepKlant::replace_for_checklistgroep::1'; if (!$this->dbex->prepare( $stmt1, 'DELETE FROM ' . $this->get_table() . ' WHERE checklist_groep_id = ?' )) throw new Exception( 'Fout bij opslaan checklistgroep / klant relaties (1).' ); $stmt2 = 'ChecklistGroepKlant::replace_for_checklistgroep::2'; if (!$this->dbex->prepare( $stmt2, 'INSERT INTO ' . $this->get_table() . ' (checklist_groep_id, klant_id) VALUES (?, ?)' )) throw new Exception( 'Fout bij opslaan checklistgroep / klant relaties (2).' ); if (!$this->dbex->execute( $stmt1, array( $checklistgroep_id ) )) throw new Exception( 'Fout bij opslaan checklistgroep / klant relaties (3).' ); foreach ($klant_ids as $klant_id) if (!$this->dbex->execute( $stmt2, array( $checklistgroep_id, $klant_id ) )) throw new Exception( 'Fout bij opslaan checklistgroep / klant relaties (4).' ); } } <file_sep>ALTER TABLE `verantwoordingen` ADD `grondslag` VARCHAR( 32 ) NULL DEFAULT NULL AFTER status , ADD `artikel` VARCHAR( 32 ) NULL DEFAULT NULL AFTER grondslag; <file_sep><?php class Admin extends Controller { const ADMIN_LOGIN_SESSION_KEY = 'admin-login'; function Admin() { parent::Controller(); $this->navigation->push( 'nav.site_beheer', '/admin' ); $this->navigation->set_active_tab( 'admin' ); global $method, $class; if ($method != 'inloggen') { if (!$this->session->userdata( self::ADMIN_LOGIN_SESSION_KEY )) { redirect( '/admin/inloggen' ); } } } private function _load_set( $s ) { if (!isset( $_FILES[$s] )) return FALSE; if ($_FILES[$s]['error']) return FALSE; $f = fopen( $_FILES[$s]['tmp_name'], "rb" ); $lines = array(); while ($line = fgetcsv( $f, 65536 )) { if (sizeof($line)!=4) return FALSE; $lines[] = $line; } return $lines; } private function _sync_set( $set1, $_set2 ) { $taalIndex = 0; $idiomIndex = 1; $tekstIndex = 2; $timeIndex = 3; $set2 = array(); foreach ($_set2 as $entry) $set2[ $entry[$idiomIndex] ] = $entry; $result = "BEGIN;\n"; foreach ($set1 as $entry) if (!isset( $set2[$entry[$idiomIndex]] )) $result .= sprintf( 'INSERT INTO teksten (taal, string, tekst, timestamp) VALUES (\'%s\', \'%s\', \'%s\', %s);'."\n", addcslashes($entry[$taalIndex],"'"), addcslashes($entry[$idiomIndex],"'"), addcslashes(stripslashes($entry[$tekstIndex]),"'"), $entry[$timeIndex] ); else { $time1 = $entry[$timeIndex]; $time2 = $set2[$entry[$idiomIndex]][$timeIndex]; if ($time1 > $time2) $result .= sprintf( 'UPDATE teksten SET tekst = \'%s\', timestamp = %s WHERE taal = \'%s\' AND string = \'%s\';'."\n", addcslashes(stripslashes($entry[$tekstIndex]),"'"), $entry[$timeIndex], addcslashes($entry[$taalIndex],"'"), addcslashes($entry[$idiomIndex],"'") ); } $result .= "ROLLBACK;\n"; return $result; } function index() { $this->db->where( 'status', 'nieuw' ); $res = $this->db->get('klanten'); $this->load->view( 'admin/admin', array( 'aanvragen' => $res->num_rows, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), ), ) ); } function stats_paginas() { $this->navigation->push( 'nav.stats_pagina_statistieken', '/admin/stats_pagina' ); $this->db->orderby( 'aantal', 'desc' ); $this->load->view( 'admin/stats_paginas', array( 'data' => $this->db->get('stats_paginas')->result(), 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/stats_paginas', 'text'=>'Pagina statistieken' ), ), ) ); } function stats_sessies() { $this->navigation->push( 'nav.stats_sessie_statistieken', '/admin/stats_sessies' ); $allow_lease_admin = $this->klant->allow_lease_administratie(); $this->db->orderby( 'aantal', 'desc' ); $this->db->join( 'gebruikers', 'stats_sessies.gebruiker_id = gebruikers.id' ); if ($allow_lease_admin) $this->db->join( 'klanten', 'gebruikers.klant_id = klanten.id' ); else $this->db->join( 'klanten', 'gebruikers.klant_id = klanten.id AND klanten.lease_configuratie_id IS NULL' ); $this->db->select( 'gebruikers.volledige_naam, gebruikers.gebruikersnaam, stats_sessies.aantal, stats_sessies.laatste_inlog, klanten.volledigE_naam AS klant_naam' ); $data = $this->db->get('stats_sessies')->result(); $this->load->view( 'admin/stats_sessies', array( 'data' => $data, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/stats_sessies', 'text'=>'Sessie statistieken' ), ), ) ); } function stats_uris( $mode='ip' ) { $this->navigation->push( 'nav.stats_uri_statistieken', '/admin/stats_uris' ); $this->db->orderby( 'timestamp', 'desc' ); $data = $this->db->get('stats_uris')->result(); $hostnames = array(); if ($mode!='ip') foreach ($data as $row) { if (!isset( $hostnames[ $row->ip ] )) $hostnames[ $row->ip ] = gethostbyaddr( $row->ip ); } $this->load->view( 'admin/stats_uris', array( 'data' => &$data, 'hostnames' => &$hostnames, 'mode' => $mode, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/stats_uris', 'text'=>'Laatste opgevraagde URI\'s' ), ), ) ); } function stats_gebruiker_activiteit() { $this->navigation->push( 'nav.stats_gebruiker_activiteit', '/admin/stats_gebruiker_activiteit' ); $allow_lease_admin = $this->klant->allow_lease_administratie(); $res = $this->db->query(' SELECT g.volledige_naam, g.laatste_request, k.naam AS klant FROM gebruikers g JOIN klanten k ON g.klant_id = k.id WHERE laatste_request IS NOT NULL ' . ($allow_lease_admin ? '' : 'AND k.lease_configuratie_id IS NULL') . ' ORDER BY g.volledige_naam '); $laatste_5mins = $laatste_dag = $laatste_week = $laatste_maand = array(); foreach ($res->result() as $row) { $n = time(); $t = strtotime( $row->laatste_request ); if ( ($n - $t) <= 5*60 ) $laatste_5mins[] = $row; if ( ($n - $t) <= 60*60*24 ) $laatste_dag[] = $row; if ( ($n - $t) <= 60*60*24*7 ) $laatste_week[] = $row; if ( ($n - $t) <= 60*60*24*30 ) $laatste_maand[] = $row; } $res->free_result(); $this->load->view( 'admin/stats_gebruiker_activiteit', array( 'laatste_5mins' => $laatste_5mins, 'laatste_dag' => $laatste_dag, 'laatste_week' => $laatste_week, 'laatste_maand' => $laatste_maand, ) ); } function account_beheer() { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->db->orderby( 'volledige_naam' ); $this->db->where( 'status', 'geaccepteerd' ); $klanten = $this->klant->all(); $klanten = $this->_filter_klanten( $klanten, true ); $this->load->view( 'admin/account_beheer', array( 'data' => $klanten, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_beheer', 'text'=>'Accountbeheer' ), ), 'last_requests' => $this->klant->get_last_requests(), ) ); } function account_list_users( $klant_id ) { $klant = $this->klant->get($klant_id); if(!$klant) { throw new Exception( 'Ongeldig klant ID ' . $klant_id ); } if( $klant->lease_configuratie_id ) { if($this->klant->allow_lease_administratie()) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $gebruikers = $klant->get_gebruikers(); } else { $gebruikers = $klant->get_gebruikers(false, true, true); } } else { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $gebruikers = $klant->get_gebruikers(); } $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $klant_id ); usort( $gebruikers, function( $a, $b ){ return strnatcasecmp( $a->volledige_naam, $b->volledige_naam ); }); $this->load->view( 'admin/account_list_users', array( 'klant' => $klant, 'gebruikers' => $gebruikers, ) ); } function account_list_active_users( $klant_id ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_active_users/' . $klant_id ); $klant = $this->klant->get( $klant_id ); if (!$klant) throw new Exception( 'Ongeldig klant ID ' . $klant_id ); if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant_id ); $gebruikers = $klant->get_gebruikers(); usort( $gebruikers, function( $a, $b ){ return strnatcasecmp( $a->volledige_naam, $b->volledige_naam ); }); $this->load->view( 'admin/account_list_active_users', array( 'klant' => $klant, 'gebruikers' => $gebruikers, 'use_year' => date("Y"), ) ); } function account_toevoegen() { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->navigation->push( 'nav.account_toevoegen', '/admin/account_toevoegen/' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['klantnaam']) && strlen(trim($_POST['klantnaam'])) && isset($_POST['contactpersoon_naam']) && strlen(trim($_POST['contactpersoon_naam'])) && isset($_POST['gebruikersnaam']) && strlen(trim($_POST['gebruikersnaam'])) && isset($_POST['wachtwoord1']) && strlen(trim($_POST['wachtwoord1'])) && isset($_POST['wachtwoord2']) && strlen(trim($_POST['wachtwoord2']))) { $this->load->model( 'gebruiker' ); switch ($this->klant->add_localdb( $_POST['klantnaam'], $_POST['contactpersoon_naam'], $_POST['contactpersoon_email'], $_POST['contactpersoon_telefoon'], $_POST['gebruikersnaam'], $_POST['wachtwoord1'], $_POST['wachtwoord2'], $_POST['volledige_naam'] )) { case 0: redirect( '/admin/account_beheer' ); break; case 1: $errors[] = 'De ingevulde wachtwoorden zijn niet gelijk!'; break; case 2: $errors[] = 'De ingegeven klantnaam is reeds in gebruik'; break; case 3: $errors[] = 'Het toevoegen van de gebruiker is gefaald!'; break; case 4: $errors[] = 'Een onbekende database fout is opgetreden.'; break; case 5: $errors[] = 'De ingevoerde klantnaam bevat ongeldige karakters, uitsluitend (hoofd)letters, cijfers, - en _ zijn toegestaan.'; break; case 6: $errors[] = 'De ingevoerde gebruikersnaam bevat ongeldige karakters, uitsluitend (hoofd)letters, cijfers, - en _ zijn toegestaan.'; break; // oops! default: $errors[] = 'Een onbekende fout is opgetreden.'; break; } } else $errors[] = 'Alle velden met * zijn verplicht!'; } $this->load->view( 'admin/account_toevoegen', array( 'errors' => $errors, 'klantnaam' => @$_POST['klantnaam'], 'contactpersoon_naam' => @$_POST['contactpersoon_naam'], 'contactpersoon_email' => @$_POST['contactpersoon_email'], 'contactpersoon_telefoon' => @$_POST['contactpersoon_telefoon'], 'gebruikersnaam' => @$_POST['gebruikersnaam'], 'volledige_naam' => @$_POST['volledige_naam'], ) ); } function account_gebruiker_toevoegen( $klant_id ) { $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); if( $klant->lease_configuratie_id && $klant->allow_lease_administratie() ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $rols =$this->rol->all(); } else { $rols = $this->rol->get_toekenbare_rollen_for_huidige_klant(); } $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $klant_id ); $this->navigation->push( 'nav.account_gebruiker_toevoegen', '/admin/account_gebruiker_toevoegen/' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['gebruikersnaam']) && strlen(trim($_POST['gebruikersnaam'])) && isset($_POST['wachtwoord']) && strlen(trim($_POST['wachtwoord'])) && isset($_POST['volledige_naam']) && strlen(trim($_POST['volledige_naam']))) { $this->load->model( 'gebruiker' ); $gebruiker = $this->gebruiker->add_localdb( $klant_id, trim($_POST['gebruikersnaam']), $_POST['wachtwoord'], trim($_POST['volledige_naam']), $_POST['rol_id'], trim($_POST['email']) ); if (!$gebruiker) $errors[] = 'Fout bij toevoegen van gebruiker aan database.'; else redirect( '/admin/account_list_users/' . $klant_id ); } else $errors[] = 'Alle velden met * zijn verplicht!'; } $this->load->model( 'rol' ); $this->load->view( 'admin/account_gebruiker_toevoegen', array( 'errors' => $errors, 'gebruikersnaam' => @$_POST['gebruikersnaam'], 'volledige_naam' => @$_POST['volledige_naam'], 'email' => @$_POST['email'], 'rol_id' => @$_POST['rol_id'], 'rollen' => $rols, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_beheer', 'text'=>'Accountbeheer' ), array( 'url'=>'/admin/account_gebruiker_toevoegen', 'text'=>'Gebruiker toevoegen' ), ) ) ); } function account_user_edit( $gebruiker_id ) { $gebruiker = $this->gebruiker->get( $gebruiker_id ); if (!$gebruiker) { throw new Exception( 'Ongeldig gebruiker ID ' . $gebruiker_id ); } $user_logged_in = $this->gebruiker->get_logged_in_gebruiker(); $klant = $user_logged_in->get_klant(); if( $klant->lease_configuratie_id ) { if( !$gebruiker->hasLeaseRol() ) { Throw new Exception('Action not Allowed'); } if( $klant->allow_lease_administratie() ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); } } else { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); } $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $gebruiker->klant_id ); $this->navigation->push( 'nav.gebruiker_bewerken', '/admin/account_user_edit/' . $gebruiker_id ); $this->load->helper( 'editor' ); editor( $gebruiker, 'Site beheer - Gebruiker bewerken', array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_beheer', 'text'=>'Accountbeheer' ), array( 'url'=>'/admin/account_list_users/'.$gebruiker_id, 'text'=>'Gebruiker bewerken' ), ) ); } function account_edit( $id ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $klant = $this->klant->get( $id ); if ($klant==null) redirect( '/admin' ); else { if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant->id ); $this->navigation->push( 'nav.account_bewerken', '/admin/account_edit/'.$id, array( $klant->naam ) ); $this->load->helper( 'editor' ); editor( $klant, 'Site beheer - Klant bewerken', array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_beheer', 'text'=>'Accountbeheer' ), array( 'url'=>'/admin/account_edit/'.$id, 'text'=>'Account bewerken' ), ) ); } } function account_verwijderen( $status=null, $id=null ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->navigation->push( 'nav.account_verwijderen', '/admin/account_verwijderen/'.$id ); $klant = $this->klant->get( $id ); if ($klant==null) redirect( '/admin' ); else { if ($klant->status != $status) redirect( '/admin' ); if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant->id ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['delete'])) $klant->delete(); if (isset( $_POST['referer'] )) redirect( $_POST['referer'] ); else redirect( '/admin' ); } $this->load->view( 'admin/account_verwijderen', array( 'klant' => $klant, 'referer' => isset($_POST['referer']) ? $_POST['referer'] : $_SERVER['HTTP_REFERER'], 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_beheer', 'text'=>'Accountbeheer' ), array( 'url'=>'/admin/account_verwijderen', 'text'=>'Account verwijderen' ), ) ) ); } } function account_logo() { $this->navigation->push( 'nav.logobeheer', '/admin/account_logo' ); $this->load->view( 'admin/account_logo', array( 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_logo', 'text'=>'Logo\'s' ), ) ) ); } function account_logo_nieuw() { $this->navigation->push( 'nav.logobeheer', '/admin/account_logo' ); $this->navigation->push( 'nav.nieuw_logo_toevoegen', '/admin/account_logo_nieuw' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $klant = $this->klant->get( $_POST['klant_id'] ); if ($klant==null) $errors[] = 'Niet bestaande klant'; else { $im = null; $res = false; // weblogo? if ($_POST['weblogo'] && $_POST['weblogo']!='http://') { $im = new Imagick(); $f = fopen( $_POST['weblogo'], "rb" ); if ($f) { try { $res = $im->readImageFile( $f ); } catch (ImagickException $e) {} fclose($f); } else $res = false; if (!$res) { $im->destroy(); $im = null; $errors[] = 'De afbeelding op het door u opgegeven webadres kon niet worden geopend!'; } } // uploaded file? else if (isset($_FILES['logo'])) { $im = new Imagick(); if ($_FILES['logo']['tmp_name']) try { $res = $im->readImage( $_FILES['logo']['tmp_name'] ); } catch (ImagickException $e) {} if (!$res) { $errors[] = 'Het door u geuploade bestand kon niet worden ingelezen!'; $im->destroy(); $im = null; } // huh? } else $errors[] = 'U dient een bestand te uploaden of een webadres op te geven!'; // continue? if ($im!=null) { // check if size is okay $imW = $im->getImageWidth(); $imH = $im->getImageHeight(); $imR = (float)$imW / (float)$imH; $logoW = $this->config->item('logo_width'); $logoH = $this->config->item('logo_height'); $logoR = (float)$logoW / (float)$logoH; if ($imW != $logoW || $imH != $logoH) { if (!isset($_POST['resize']) || $_POST['resize']!='on') { $errors[] = 'Het door u opgegeven bestand is niet van de juiste grootte, en mag niet worden geschaald!'; $im->destroy(); $im = null; } else { // is the relation between height and width like we want it to be? if ($imR==$logoR) { // woohoo, easy scale! $im->resizeImage( $logoW, $logoH, imagick::FILTER_BOX, 0 ); } else { // what to scale? if ($imR < $logoR) { // scale by height $im->resizeImage( null, $logoH, imagick::FILTER_BOX, 0 ); $x = ($logoW - $im->getImageWidth()) / 2; $y = 0; } else { // scale by width $im->resizeImage( $logoW, null, imagick::FILTER_BOX, 0 ); $x = 0; $y = ($logoH - $im->getImageHeight()) / 2; } $whiteCol = new ImagickPixel( "rgb(255,255,255)" ); $im2 = new Imagick(); $im2->newImage( $logoW, $logoH, $whiteCol, 'png' ); $im2->setImageDepth( $im->getImageDepth() ); $im2->compositeImage( $im, imagick::COMPOSITE_DEFAULT, $x, $y ); $whiteCol->destroy(); $im->destroy(); $im = $im2; } } } if ($im!=null) { // set to 24 bits color png $im->setImageDepth( 24 ); $im->setImageFormat( 'png' ); // draw border if required if (isset($_POST['border']) && $_POST['border']=='on') { // assemble commands to draw border $blackCol = new ImagickPixel( "rgb(0,0,0)" ); $imDraw = new ImagickDraw(); $imDraw->setStrokeColor($blackCol); $imDraw->setFillOpacity(0); $imDraw->rectangle(0,0,$logoW-1,$logoH-1); // execute commands onto image $im->drawImage( $imDraw ); // cleanup $blackCol->destroy(); $imDraw->destroy(); } // get big logo string $klant->logo = $im->getImageBlob(); // get small logo string $im->thumbnailImage( $this->config->item( 'logo_display_width' ), $this->config->item( 'logo_display_height' ) ); $klant->logo_klein = $im->getImageBlob(); // save & cleanup $klant->save(); $im->destroy(); redirect( '/admin/account_logo_bekijken/'.$klant->id ); } } } } $this->db->orderby( 'volledige_naam' ); $this->db->where( 'status', 'geaccepteerd' ); $klanten = $this->klant->all(); $klanten = $this->_filter_klanten( $klanten ); $this->load->view( 'admin/account_logo_nieuw', array( 'klanten' => $klanten, 'errors' => $errors, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_logo', 'text'=>'Logo\'s' ), array( 'url'=>'/admin/account_logo_nieuw', 'text'=>'Logo\'s uploaden' ), ) ) ); } function account_logo_delete() { $this->navigation->push( 'nav.logobeheer', '/admin/account_logo' ); $this->navigation->push( 'nav.logo_verwijderen', '/admin/account_logo_delete' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['klant_id'])) { $klant = $this->klant->get( $_POST['klant_id'] ); if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant->id ); if ($klant==null) $errors[] = 'Niet bestaande klant!'; else { $klant->logo = null; $klant->logo_klein = null; $klant->save(); } } } $this->db->where( 'CHAR_LENGTH(logo) !=', '0' ); $bestaande_logos = $this->db->get('klanten')->result(); $this->load->view( 'admin/account_logo_delete', array( 'bestaande_logos' => $bestaande_logos, 'errors' => $errors, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_logo', 'text'=>'Logo\'s' ), array( 'url'=>'/admin/account_logo_delete', 'text'=>'Logo\'s verwijderen' ), ) ) ); } function account_logo_bekijken( $klant_id=null ) { $this->navigation->push( 'nav.logobeheer', '/admin/account_logo' ); $this->navigation->push( 'nav.logo_bekijken', '/admin/account_logo_bekijken' ); if ($klant_id) { $klant = $this->klant->get($klant_id); if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant->id ); } $klanten = $this->klant->search( array(), 'CHAR_LENGTH(logo) != 0' ); $klanten = $this->_filter_klanten( $klanten ); $this->load->view( 'admin/account_logo_bekijken', array( 'bestaande_logos' => $klanten, 'klant_id' => $klant_id, 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/account_logo', 'text'=>'Logo\'s' ), array( 'url'=>'/admin/account_logo_bekijken', 'text'=>'Logo\'s bekijken' ), ) ) ); } function inline_edit( $string=null ) { if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset( $_POST['tekst'] )) $this->tekst->set( $string, $_POST['tekst'] ); echo( '1' ); exit; } $tekst = $this->tekst->get( $string, true, false ); $this->load->view( 'admin/inline_edit', array( 'string' => $string, 'tekst' => $tekst, ) ); } function toggle_inline_edit() { $this->tekst->toggle_inline_edit(); if (isset( $_SERVER['HTTP_REFERER'] )) redirect( $_SERVER['HTTP_REFERER'] ); else redirect(); } function tekst_sync() { $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $set1 = $this->_load_set( 'set1' ); if ($set1===FALSE) $errors[] = 'Er is iets fout gegaan bij het uploaden van set 1'; else { $set2 = $this->_load_set( 'set2' ); if ($set2===FALSE) $errors[] = 'Er is iets fout gegaan bij het uploaden van set 2'; else { $set1to2 = $this->_sync_set( $set1, $set2 ); $set2to1 = $this->_sync_set( $set2, $set1 ); } } } $this->load->view( 'admin/tekst_sync', array ( 'errors' => $errors, 'set1to2' => isset($set1to2) ? $set1to2 : false, 'set2to1' => isset($set2to1) ? $set2to1 : false, ) ); } function apc_info() { echo '<pre>'; var_dump( apc_sma_info( false ) ); echo '</pre>'; } function nieuws( $mode=null, $id=null ) { $this->navigation->push( 'nav.nieuws_items', '/admin/nieuws' ); $this->load->model( 'nieuws' ); $leaseconfiguratie = $this->gebruiker->get_logged_in_gebruiker()->get_klant()->get_lease_configuratie(); // iets te doen? switch ($mode) { case 'toggle': $nieuws = $this->nieuws->get( $id ); if ($nieuws->lease_configuratie_id !== ($leaseconfiguratie ? $leaseconfiguratie->id : null)) break; if ($nieuws!=null) { $nieuws->zichtbaar = $nieuws->is_zichtbaar() ? 'nee' : 'ja'; $nieuws->save(); redirect( '/admin/nieuws' ); } break; case 'add': $titel = isset( $_POST['titel'] ) ? trim( $_POST['titel'] ) : null; $tekst = isset( $_POST['tekst'] ) ? trim( $_POST['tekst'] ) : null; if ($titel && $tekst) { $this->nieuws->add( $titel, $tekst, $leaseconfiguratie ? $leaseconfiguratie->id : null ); redirect( '/admin/nieuws' ); } break; } $this->load->view( 'admin/nieuws', array( 'nav' => array( array( 'url'=>'/admin', 'text'=>'Site beheer' ), array( 'url'=>'/admin/nieuws', 'text'=>'Nieuws editor' ), ), 'nieuws' => $this->nieuws->get_alle_nieuwsitems( $leaseconfiguratie ), 'titel' => isset( $_POST['titel'] ) ? $_POST['titel'] : '', 'tekst' => isset( $_POST['tekst'] ) ? $_POST['tekst'] : '', ) ); } private function _get_aantal_deelplannen_per_jaar( $jaar ) { $deelplannen_dit_jaar = array_pad( array(), 12, 0 ); $this->_get_jaar_start_end_unixtimes( $jaar, $from, $to ); $res = $this->db->query( $query = ' SELECT COUNT(*) AS aantal, MONTH(FROM_UNIXTIME(aanmaak_datum)) AS maand FROM deelplannen WHERE aanmaak_datum BETWEEN ' . $from . ' AND ' . $to . ' GROUP BY maand ' ); foreach ($res->result() as $row) $deelplannen_dit_jaar[ $row->maand - 1 ] = intval( $row->aantal ); foreach (array('Jan','Feb','Mrt','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec') as $index => $maand) { $deelplannen_dit_jaar[ $maand ] = $deelplannen_dit_jaar[ $index ]; unset( $deelplannen_dit_jaar[ $index] ); } return $deelplannen_dit_jaar; } private function _get_actievste_klanten_per_jaar( $jaar ) { $this->_get_jaar_start_end_unixtimes( $jaar, $from, $to ); $res = $this->db->query( $query = ' SELECT COUNT(*) AS aantal, klanten.volledige_naam FROM deelplannen JOIN gebruikers ON gebruikers.id = deelplannen.gebruiker_id JOIN klanten ON klanten.id = gebruikers.klant_id WHERE aanmaak_datum BETWEEN ' . $from . ' AND ' . $to . ' GROUP BY klanten.volledige_naam ORDER BY aantal DESC ' ); $deelplannen_dit_jaar = array(); foreach ($res->result() as $row) { if (sizeof($deelplannen_dit_jaar)<5) $deelplannen_dit_jaar[ $row->volledige_naam ] = intval( $row->aantal ); else { if (!isset( $deelplannen_dit_jaar[ 'Overig' ] )) $deelplannen_dit_jaar[ 'Overig' ] = 0; $deelplannen_dit_jaar[ 'Overig' ] += intval( $row->aantal ); } } foreach ($deelplannen_dit_jaar as $naam => $aantal) { unset( $deelplannen_dit_jaar[$naam] ); $deelplannen_dit_jaar[$naam . ' (' . $aantal . ')' ] = $aantal; } return $deelplannen_dit_jaar; } private function _get_aantal_deelplannen_per_dag_per_jaar( $jaar ) { $deelplannen_dit_jaar = array_pad( array(), 7, 0 ); $this->_get_jaar_start_end_unixtimes( $jaar, $from, $to ); $res = $this->db->query( $query = ' SELECT COUNT(*) AS aantal, DAYOFWEEK(FROM_UNIXTIME(aanmaak_datum)) AS dayofweek FROM deelplannen WHERE aanmaak_datum BETWEEN ' . $from . ' AND ' . $to . ' GROUP BY dayofweek ' ); foreach ($res->result() as $row) $deelplannen_dit_jaar[ $row->dayofweek - 1 ] = intval( $row->aantal ); foreach (array('Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag') as $index => $dayofweek) { $deelplannen_dit_jaar[ $dayofweek ] = $deelplannen_dit_jaar[ $index ]; unset( $deelplannen_dit_jaar[ $index] ); } return $deelplannen_dit_jaar; } private function _get_aantal_deelplannen_met_soort_per_jaar( $jaar ) { $deelplannen_dit_jaar = array(); $this->_get_jaar_start_end_unixtimes( $jaar, $from, $to ); $res = $this->db->query( $query = ' SELECT COUNT(*) AS aantal, soort FROM deelplannen WHERE aanmaak_datum BETWEEN ' . $from . ' AND ' . $to . ' GROUP BY soort ' ); foreach ($res->result() as $row) { if (!$row->soort) $row->soort = 'onbekend'; $deelplannen_dit_jaar[ $row->soort . ' (' . $row->aantal . ')' ] = intval( $row->aantal ); } return $deelplannen_dit_jaar; } private function _get_aantal_deelplannen_met_vergunning_type_per_jaar( $jaar ) { $deelplannen_dit_jaar = array(); $this->_get_jaar_start_end_unixtimes( $jaar, $from, $to ); $res = $this->db->query( $query = ' SELECT COUNT(*) AS aantal, vergunning_type FROM deelplannen WHERE aanmaak_datum BETWEEN ' . $from . ' AND ' . $to . ' GROUP BY vergunning_type ' ); foreach ($res->result() as $row) { if (!$row->vergunning_type) $row->vergunning_type = 'onbekend'; $deelplannen_dit_jaar[ $row->vergunning_type . ' (' . $row->aantal . ')' ] = intval( $row->aantal ); } return $deelplannen_dit_jaar; } private function _get_jaar_start_end_unixtimes( $jaar, &$from, &$to ) { $from = strtotime( $jaar . '-01-01' ); $to = strtotime( ($jaar+1) . '-01-01' )-1; } public function piegraph( $data, $width=800, $height=400 ) { $this->load->helper( 'jpgraph' ); // fetch data $data = unserialize( base64_decode( $data ) ); $values = array_values( $data['values'] ); $keys = array_keys( $data['values'] ); // new graph $graph = new PieGraph($width,$height); $graph->SetShadow(); $graph->title->Set($data['title']); $graph->title->SetFont(FF_FONT1,FS_BOLD); // add plot $p1 = new PiePlot3D($values); $p1->SetCenter(0.3, 0.6); $p1->SetSize( 0.45 ); $p1->SetLegends($keys); $graph->Add($p1); // stroke! $graph->Stroke(); } public function bargraph( $data, $width=800, $height=400 ) { $this->load->helper( 'jpgraph' ); // fetch data $data = unserialize( base64_decode( $data ) ); $databary = $data['values']; $months = array_keys( reset( $data['values'] ) ); $legend = $data['legend']; // New graph with a drop shadow $graph = new Graph($width, $height, 'auto'); $graph->SetShadow(); $graph->SetScale( "textlin" ); $graph->yaxis->scale->SetGrace( 20 ); $graph->xaxis->SetTickLabels($months); $graph->title->Set( $data['title'] ); $graph->title->SetFont(FF_FONT1,FS_BOLD); $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD); $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD); // Create the bar plots $colors = array( 'orange', 'blue', 'green', 'brown' ); $bars = array(); foreach ($databary as $i => $row) { $b1 = new BarPlot( array_values( $row ) ); $b1->SetShadow(); $b1->value->Show(); $b1->value->SetFormat('%d'); $b1->SetFillColor(array_pop( $colors )); $b1->SetLegend( $legend[$i] ); $bars[] = $b1; } // Add as group, or single if (sizeof($bars)>1) $graph->Add(new GroupBarPlot($bars)); else $graph->Add(reset($bars)); // Stroke! $graph->Stroke(); } public function login_als( $gebruiker_id ) { $gebruiker = $this->gebruiker->get( $gebruiker_id ); if (!$gebruiker) { throw new Exception( 'Gebruiker met ID ' . $gebruiker_id . ' bestaat niet.' ); } $klant = $gebruiker->get_klant(); if (!$klant) { throw new Exception( 'Kan klant niet ophalen uit database.' ); } $user_logged_in = $this->gebruiker->get_logged_in_gebruiker(); $klant_logged_in = $user_logged_in->get_klant(); if( $klant_logged_in->lease_configuratie_id ) { if( !$gebruiker->hasLeaseRol() ) { Throw new Exception('Action not Allowed'); } } // ZIE OOK: gebruikers::inloggen if (!$this->login->login_as( $gebruiker->id )) throw new Exception( 'Login fout: login_as() gaf FALSE terug.' ); $this->session->set_userdata( 'kid', $klant->id ); $this->session->set_userdata( 'is_std_doc', $klant->standaard_documenten ); $this->session->set_userdata( 'is_std_deelpl', $klant->standaard_deelplannen ); $this->session->set_userdata( 'klant_volledige_naam', $gebruiker->volledige_naam ); $this->session->set_userdata( 'do_inline_editing', false ); if (!$this->login->logged_in()) throw new Exception( "Na 'inloggen als' is gebruiker niet ingelogd volgens login systeem." ); redirect(); } private function _filter_parent_klanten( $klanten, $childrenOnly=true ){ $CI = get_instance(); $has_children_orgs = $CI->session->userdata( 'has_children_organisations' ); if( !$has_children_orgs ) return $klanten; $kid = $CI->session->userdata( 'kid' ); $parent_admin = $this->login->verify( 'admin', 'parentadmin' ); if( !$parent_admin ) return $klanten; foreach ($klanten as $i => $klant){ if ( $klant->parent_id != $kid && ($klant->id != $kid||$childrenOnly) ){ unset($klanten[$i]); } } return $klanten; } public function checklistgroep_beheer() { $this->navigation->push( 'nav.checklistgroepbeheer', '/admin/checklistgroep_beheer' ); $this->load->model( 'checklistgroep' ); $klanten = $this->klant->all( 'naam' ); $klanten = $this->_filter_parent_klanten( $klanten, false ); $checklistgroepen = array(); foreach ($klanten as $klant){ $checklistgroepen[ $klant->id ] = $klant->get_checklist_groepen(); } $this->load->view( 'admin/checklistgroep_beheer', array( 'klanten' => $klanten, 'checklistgroepen' => $checklistgroepen, ) ); } public function checklistgroep_detail_beheer($klant_id){ $this->navigation->push( 'nav.checklistgroepbeheer', '/admin/checklistgroep_beheer' ); //$this->navigation->push( 'nav.checklistgroepbeheer_bewerk', '/admin/checklistgroep_beheer' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'checklistgroepklant' ); $this->load->model( 'image' ); $this->load->model( 'gebruikerchecklistgroep' ); $klant = $this->klant->get($klant_id); $checklistgroepen[$klant_id] = $klant->get_checklist_groepen(); $checklistgroep_klanten = array(); $all_klanten = $this->klant->all( 'naam' ); $unavailable_klanten = $this->_get_unavailable_klanten( $all_klanten ); foreach ($this->checklistgroepklant->all() as $row) { if (!isset( $checklistgroep_klanten[ $row->checklist_groep_id ] )) $checklistgroep_klanten[ $row->checklist_groep_id ] = array(); $checklistgroep_klanten[ $row->checklist_groep_id ][] = $row->klant_id; } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){ foreach ($checklistgroepen as $klant_id => $cgs) { foreach ($cgs as $cg) { if (!isset( $checklistgroep_klanten[$cg->id] )) $checklistgroep_klanten[$cg->id] = array(); $changed = false; $nieuwe_publ = $_POST['checklistgroepen'][$cg->id]; $nieuwe_img = @$_POST['images'][$cg->id]; if ($cg->beschikbaarheid != $nieuwe_publ || $nieuwe_img != $cg->image_id) { $cg->beschikbaarheid = $nieuwe_publ; $cg->image_id = $nieuwe_img ? $nieuwe_img : NULL; $cg->save(); $changed = true; } if ($cg->beschikbaarheid == 'publiek-voor-beperkt') { $nieuwe_klant = $andere_klant = false; $klant_ids = array(); foreach (isset( $_POST['checklistgroepklant'][$cg->id] ) ? $_POST['checklistgroepklant'][$cg->id] : array() as $klant_id => $unused) { if (!in_array( $klant_id, @$checklistgroep_klanten[$cg->id] )) { $nieuwe_klant = true; $klant = $this->klant->get( $klant_id ); if ($klant) foreach ($klant->get_gebruikers( true ) as $gebruiker) $this->gebruikerchecklistgroep->add( $gebruiker->id, $cg->id ); } $klant_ids[] = $klant_id; } if (!$nieuwe_klant && sizeof($klant_ids) != sizeof( @$checklistgroep_klanten[$cg->id] )) $andere_klant = true; // echo "{$cg->id} " . intval($nieuwe_klant) . " " . intval($andere_klant) . "<br/>\n"; if ($nieuwe_klant || $andere_klant) $this->checklistgroepklant->replace_for_checklistgroep( $cg->id, $klant_ids ); } else if ($changed) { $this->checklistgroepklant->replace_for_checklistgroep( $cg->id, array() ); } } } redirect( 'admin/checklistgroep_detail_beheer/'.$klant_id ); } $this->load->view( 'admin/checklistgroep_beheer_detail', array( 'klanten' => $klant, 'all_klanten' => $all_klanten, 'checklistgroepen' => $checklistgroepen, 'unavailable_klanten' => $unavailable_klanten, 'checklistgroep_klanten' => $checklistgroep_klanten, 'images' =>$this->image->all( 'filename', true ), ) ); } public function image_beheer( $uploaded=0 ) { $this->navigation->push( 'nav.checklistgroepbeheer', '/admin/checklistgroep_beheer' ); $this->navigation->push( 'nav.afbeeldingbeheer', '/admin/image_beheer' ); $this->load->model( 'image' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // something uploaded? if (!isset( $_FILES['image'] ) || $_FILES['image']['error'] || !$_FILES['image']['size']) $errors[] = 'Er is iets fout gegaan bij het uploaden, of er was geen bestand geselecteerd.'; else { if (false === ($data = file_get_contents( $_FILES['image']['tmp_name'] ))) $errors[] = 'Interne fout bij het inlezen van het bestand. Probeer het opnieuw.'; else { $imagedata = getimagesize( $_FILES['image']['tmp_name'] ); if (!is_array( $imagedata ) || sizeof($imagedata) < 2) $errors[] = 'Interne fout bij het bepalen van de breedte en hoogte van de afbeelding.'; else { list( $width, $height ) = $imagedata; if ($_POST['mode'] == 'new') { if (!$this->image->add( $_FILES['image']['name'], $data, $width, $height )) $errors[] = 'Interne fout bij het opslaan van de afbeelding in de database.'; else redirect( '/admin/image_beheer/1' ); } } } } } $this->load->view( 'admin/image_beheer', array( 'images' => $this->image->all( 'filename', true ), 'errors' => $errors, 'uploaded' => $uploaded, ) ); } public function image_delete( $id ) { $this->load->model( 'image' ); if ($image = $this->image->get( $id )) { $image->delete(); } redirect( '/admin/image_beheer' ); } public function toggle_help_button_edit_mode() { $this->helpbutton->toggle_edit_mode(); if (isset( $_SERVER['HTTP_REFERER'] )) redirect( $_SERVER['HTTP_REFERER'] ); else redirect(); } public function help_button_store_text() { $tag = $_POST['tag']; $text = $_POST['text']; $this->helpbutton->store( $tag, $text ); echo "OK"; } public function itpimport() { $this->load->library( 'itpimport' ); $this->navigation->push( 'nav.itp_import', '/admin/itpimport' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { try { // fetch input $is_testrun = @$_POST['testrun'] == 'on'; if (!($naam = trim($_POST['checklistgroepnaam']))) throw new Exception( 'Lege checklistgroepnaam opgegeven.' ); $filenames = array(); switch ($_POST['type']) { case 'csv': foreach ($this->itpimport->get_tabellen() as $nummer => $description) { $upload = @$_FILES['tabel' . $nummer]; if (!$upload || $upload['error'] || !$upload['size']) throw new Exception( 'Niks geselecteerd voor, of upload fout bij, tabel "' . $description . '"' ); if (strtolower( $upload['name'] ) != strtolower( $description . 'Tabel.csv' )) throw new Exception( 'Voor tabel "' . $description . '" werd de file ' . $description . 'Tabel.csv verwacht, niet ' . $upload['name'] ); $filenames[ $nummer ] = $upload['tmp_name']; } break; case 'zip': $this->load->helper( 'export' ); // for self-cleaning temp files $zip = new ZipArchive(); $upload = @$_FILES['zip']; if (!$upload || $upload['error'] || !$upload['size']) throw new Exception( 'Niks geselecteerd voor, of upload fout bij, ZIP bestand' ); if (!$zip->open( $upload['tmp_name'] )) throw new Exception( 'Fout bij inlezen van ZIP bestand, is er een geldig ZIP bestand geupload?' ); $zip_files = array(); for ($i=0; ($res = $zip->statIndex( $i ))!==false; ++$i) if (preg_match( '#/([a-zA-Z]+)Tabel\.csv$#', $res['name'], $matches )) $zip_files[$matches[1]] = $i; foreach ($this->itpimport->get_tabellen() as $nummer => $description) { // extract from ZIP if (!isset( $zip_files[$description] )) throw new Exception( 'Het bestand ' . $filename . 'Tabel.csv is niet aanwezig in het ZIP bestand.' ); $contents = $zip->getFromIndex( $zip_files[$description] ); if ($contents === FALSE) throw new Exception( 'Fout bij opvragen inhoud van bestand ' . $description . 'Tabel.csv.' ); // store temp file to disk and register it in filenames array $tempfile = new ExportTempImage( $contents, 'csv' ); $filenames[ $nummer ] = $tempfile->get_filename(); } $zip->close(); break; } // initializeer itp import! $itpimport = $this->itpimport->create( $filenames, $naam ); // run it! $this->db->trans_start(); $itpimport->run(); if ($is_testrun) { $this->db->_trans_status = false; $this->db->trans_complete(); // will fail! but that's the intention } else if (!$this->db->trans_complete()) throw new Exception( 'Database fout bij opslaan (transactie mislukt).' ); $this->session->set_userdata( 'itpimport-resultaat', array( 'is_testrun' => $is_testrun, 'nieuwe_objecten' => $itpimport->get_num_created_objects() ) ); redirect( '/admin/itpimport_resultaat' ); } catch (Exception $e) { // make sure transaction is rolled back while ($this->db->_trans_depth > 0) { $this->db->_trans_status = false; $this->db->trans_complete(); } $errors[] = $e->getMessage(); } } $this->load->view( 'admin/itpimport', array( 'errors' => $errors, 'tabellen' => $this->itpimport->get_tabellen(), 'checklistgroepnaam' => @$naam, 'is_testrun' => !isset( $is_testrun ) ? true : $is_testrun, ) ); } function itpimport_resultaat() { $this->navigation->push( 'nav.itp_import', '/admin/itpimport' ); $this->navigation->push( 'nav.resultaten', '/admin/itpimport_resultaat' ); $this->load->view( 'admin/itpimport_resultaat', $this->session->userdata( 'itpimport-resultaat' ) ); } function koppelvoorwaarden_beheer( $checklist_id=null ) { $this->navigation->push( 'nav.bristoets_koppeling_checklistbeheer', '/admin/koppelvoorwaarden_beheer' ); $this->load->model( 'checklistkoppelvoorwaarde' ); $this->load->model( 'checklist' ); $this->load->model( 'checklistgroep' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { switch ($_POST['veld']) { case 'aanvraagdatum': $waarde = $_POST['aanvraagdatum']; break; case 'gebruiksfunctie': $waarde = $_POST['gebruiksfunctie']; break; case 'bouwsom': $waarde = $_POST['bouwsom']; break; case 'is integraal': $waarde = $_POST['is']; break; case 'is eenvoudig': $waarde = $_POST['is']; break; case 'is dakkapel': $waarde = $_POST['is']; break; case 'is bestaand': $waarde = $_POST['is']; break; default: $errors[] = 'Veld type nog niet ondersteund.'; } if (empty( $errors )) { if (!$waarde) $errors[] = 'Lege waarde niet toegestaan.'; else { $this->checklistkoppelvoorwaarde->add( $checklist_id, $_POST['veld'], $_POST['operator'], $waarde ); redirect( '/admin/koppelvoorwaarden_beheer/' . $checklist_id ); } } } $alleen_met_regels = $this->session->userdata( 'koppelvoorwaarden_set_alleen_met_regels' ); $list_of_checklist_ids_with_voorwaarden = $this->checklistkoppelvoorwaarde->get_list_of_checklist_ids_with_voorwaarden(); $this->load->view( 'admin/koppelvoorwaarden_beheer', array( 'checklist' => $checklist_id ? $this->checklist->get( intval( $checklist_id ) ) : null, 'checklisten' => $this->checklist->all( 'checklist_groep_id, naam' ), 'checklistgroepen' => $this->checklistgroep->all( 'naam', true ), 'voorwaarden' => $checklist_id ? $this->checklistkoppelvoorwaarde->get_by_checklist_id( $checklist_id ) : null, 'errors' => $errors, 'alleen_met_regels' => $alleen_met_regels, 'list_of_checklist_ids_with_voorwaarden' => $list_of_checklist_ids_with_voorwaarden, ) ); } function koppelvoorwaarden_set_alleen_met_regels( $aan, $checklist_id=null ) { $this->session->set_userdata( 'koppelvoorwaarden_set_alleen_met_regels', intval( $aan ) ); redirect( '/admin/koppelvoorwaarden_beheer/' . $checklist_id ); } function koppelvoorwaarde_verwijderen( $checklist_id=null, $voorwaarde_id=null ) { $this->load->model( 'checklistkoppelvoorwaarde' ); if ($voorwaarde = $this->checklistkoppelvoorwaarde->get( $voorwaarde_id )) $voorwaarde->delete(); redirect( '/admin/koppelvoorwaarden_beheer/' . $checklist_id ); } public function webservice_beheer() { $this->navigation->push( 'nav.webservice_beheer', '/admin/webservice_beheer' ); $this->load->model( 'webserviceaccount' ); $this->load->model( 'webserviceapplicatie' ); // laad webservice code define( 'IS_WEBSERVICE', false ); require_once( dirname(__FILE__) . '/webservice.php' ); // haal alle data op $alle_modules = WebserviceModule::get_all_modules(); $alle_accounts = $this->webserviceaccount->all(); $alle_applicaties = $this->webserviceapplicatie->all(); $alle_klanten = $this->klant->all('naam'); $alle_klanten = $this->_filter_klanten( $alle_klanten ); // laad view $this->load->view( 'admin/webservice_beheer', array( 'alle_modules' => $alle_modules, 'alle_accounts' => $alle_accounts, 'alle_applicaties' => $alle_applicaties, 'alle_klanten' => $alle_klanten, ) ); } public function webservice_account_toggle() { try { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'Geen POST request.' ); $this->load->model( 'webserviceaccount' ); if (!($account = $this->webserviceaccount->get( $_POST['account_id'] ))) throw new Exception( 'Geen geldig account ID.' ); if (!in_array( $_POST['mode'], array( 'actief', 'alle_klanten', 'alle_components' ))) throw new Exception( 'Geen geldige mode.' ); $checked = @$_POST['checked']; $account->{$_POST['mode']} = $checked; $account->save(); echo json_encode((object)array( 'success' => true ) ); } catch (Exception $e) { echo json_encode((object)array( 'success' => false, 'error' => $e->getMessage(), ) ); } } public function webservice_component_toggle() { try { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'Geen POST request.' ); $this->load->model( 'webserviceaccount' ); $this->load->model( 'webservicecomponent' ); if (!($account = $this->webserviceaccount->get( $_POST['account_id'] ))) throw new Exception( 'Geen geldig account ID.' ); if (!($module = reset( $this->webservicecomponent->search( array( 'naam' => @$_POST['module'] ) ) ))) throw new Exception( 'Geen geldige module naam.' ); $checked = @$_POST['checked']; $this->db->trans_start(); $this->db->query( 'DELETE FROM webservice_account_rechten WHERE webservice_account_id = ' . $account->id . ' AND webservice_component_id = ' . $module->id ); if ($checked) $this->db->query( 'INSERT INTO webservice_account_rechten (webservice_account_id, webservice_component_id) VALUES (' . $account->id . ', ' . $module->id . ')' ); if (!$this->db->trans_complete()) throw new Exception( 'Fout bij transactie commit.' ); echo json_encode((object)array( 'success' => true ) ); } catch (Exception $e) { // rollback $this->db->_trans_status = false; $this->db->trans_complete(); // output echo json_encode((object)array( 'success' => false, 'error' => $e->getMessage(), ) ); } } public function webservice_klant_toggle() { try { if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!='POST') throw new Exception( 'Geen POST request.' ); $this->load->model( 'webserviceaccount' ); if (!($account = $this->webserviceaccount->get( $_POST['account_id'] ))) throw new Exception( 'Geen geldig account ID.' ); if (!($klant = $this->klant->get( $_POST['klant_id'] ))) throw new Exception( 'Geen geldig klant ID.' ); if ($klant->lease_configuratie_id && !$this->klant->allow_lease_administratie()) throw new Exception( 'Geen toegang tot klant ID ' . $klant->id ); $checked = @$_POST['checked']; $this->db->trans_start(); $this->db->query( 'DELETE FROM webservice_account_klanten WHERE webservice_account_id = ' . $account->id . ' AND klant_id = ' . $klant->id ); if ($checked) $this->db->query( 'INSERT INTO webservice_account_klanten (webservice_account_id, klant_id) VALUES (' . $account->id . ', ' . $klant->id . ')' ); if (!$this->db->trans_complete()) throw new Exception( 'Fout bij transactie commit.' ); echo json_encode((object)array( 'success' => true ) ); } catch (Exception $e) { // rollback $this->db->_trans_status = false; $this->db->trans_complete(); // output echo json_encode((object)array( 'success' => false, 'error' => $e->getMessage(), ) ); } } public function checklist_import() { $this->load->library( 'checklistimport' ); $this->navigation->push( 'nav.checklist_import', '/admin/checklist_import' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { try { // fetch input $encoding = $_POST['encoding']; $klant_id = @$_POST['klant_id']; $is_testrun = @ $_POST['testrun'] == 'on'; if (!$klant_id) throw new Exception( 'Selecteer een klant.' ); // fetch upload $upload = @ $_FILES['upload']; if (!$upload || $upload['error'] || !$upload['size']) throw new Exception( 'Niks geselecteerd voor, of upload fout.' ); $filename = $upload['tmp_name']; // initializeer itp import! $checklistimport = $this->checklistimport->create( $filename, $klant_id, $encoding ); // run it! $this->db->trans_start(); $checklistimport->run(); if ($is_testrun) { $this->db->_trans_status = false; $this->db->trans_complete(); // will rollback! but that's the intention } else if (!$this->db->trans_complete()) throw new Exception( 'Database fout bij opslaan (transactie mislukt).' ); $this->session->set_userdata( 'checklist-resultaat', array( 'is_testrun' => $is_testrun, 'queries' => $checklistimport->get_queries(), 'counts' => $checklistimport->get_counts(), 'speciale_tekens_teksten' => $checklistimport->get_speciale_tekens_teksten(), ) ); redirect( '/admin/checklist_import_resultaat' ); } catch (Exception $e) { // make sure transaction is rolled back while ($this->db->_trans_depth > 0) { $this->db->_trans_status = false; $this->db->trans_complete(); } $errors[] = $e->getMessage(); } } $klanten = $this->_filter_klanten( $this->klant->all( 'naam' ) ); $this->load->view( 'admin/checklist_import', array( 'errors' => $errors, 'is_testrun' => !isset( $is_testrun ) ? true : $is_testrun, 'klant_id' => !isset( $klant_id ) ? null : $klant_id, 'encoding' => !isset( $encoding ) ? 'Windows-1252' : $encoding, 'klanten' => $klanten, ) ); } function checklist_import_resultaat() { $this->navigation->push( 'nav.checklist_import', '/admin/checklist_import' ); $this->navigation->push( 'nav.resultaten', '/admin/checklist_import_resultaat' ); $this->load->view( 'admin/checklist_import_resultaat', $this->session->userdata( 'checklist-resultaat' ) ); } public function checklist_export() { $this->load->model( 'checklistgroep' ); $this->load->library( 'checklistexport' ); $this->navigation->push( 'nav.checklist_export', '/admin/checklist_export' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { try { // fetch input //$encoding = $_POST['encoding']; $encoding = 'UTF-8'; $checklistgroep_id = @$_POST['checklistgroep_id']; $is_testrun = @ $_POST['testrun'] == 'on'; if (!$checklistgroep_id) throw new Exception( 'Selecteer een checklistgroep.' ); $checklistexport = $this->checklistexport->create( $checklistgroep_id, $encoding ); // run it! $checklistexport->run(); /* $this->session->set_userdata( 'checklistgroep-export-resultaat', array( 'data_for_csv_file' => $checklistexport->get_data_for_csv_file(), 'file_name' => $checklistexport->get_file_name(), )); * */ $this->session->set_userdata( 'checklistgroep-export-resultaat', array( 'file_name' => $checklistexport->get_file_name(), )); redirect( '/admin/checklist_export_resultaat' ); } catch (Exception $e) { //d($e); $errors[] = $e->getMessage(); } } //$klanten = $this->_filter_klanten( $this->klant->all( 'naam' ) ); $checklistgroepen = $this->checklistgroep->all( 'naam' ); $this->load->view( 'admin/checklist_export', array( 'errors' => $errors, 'encoding' => !isset( $encoding ) ? 'Windows-1252' : $encoding, 'checklistgroep_id' => !isset( $checklistgroep_id ) ? null : $checklistgroep_id, 'checklistgroepen' => $checklistgroepen, ) ); } function checklist_export_resultaat() { $this->navigation->push( 'nav.checklist_export', '/admin/checklist_export' ); $this->navigation->push( 'nav.resultaten', '/admin/checklist_export_resultaat' ); $this->load->view( 'admin/checklist_export_resultaat', $this->session->userdata( 'checklistgroep-export-resultaat' ) ); } function tekst_beheer( $sort=0 ) { $this->navigation->push( 'nav.tekstbeheer', '/admin/tekst_beheer' ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { foreach ($this->tekst->get_all() as $string => $tekst) if (isset( $_POST['text'][$string] )) if ($_POST['text'][$string] != $tekst) $this->tekst->set( $string, $_POST['text'][$string] ); redirect( '/admin/tekst_beheer' ); } $count = 0; $groepen = array(); if (!$sort) { $teksten = $this->tekst->get_all(); foreach ($teksten as $string => $tekst) { if (!strlen($tekst)) $groep = '!Nog niet ingevuld!'; else if (preg_match( '/^([a-z0-9_]+)\.([a-z0-9_]+)\:\:/i', $string, $matches )) $groep = 'Pagina ' . $matches[1] . '/' . $matches[2]; else if (preg_match( '/^form\./', $string )) $groep = 'Formulier elementen'; else if (preg_match( '/^nav\./', $string )) $groep = 'Kruimelpad elementen'; else if (preg_match( '/^php\./', $string )) $groep = 'Programmeercode elementen'; else if (preg_match( '/^waardeoordeel\./', $string )) $groep = 'Waardeoordelen'; else $groep = 'Overig'; if (!isset( $groepen[$groep] )) $groepen[$groep] = array(); $groepen[$groep][ $string ] = $tekst; ++$count; } ksort( $groepen ); } else { foreach ($this->tekst->get_all_by_date() as $string => $tekst) { $datum = date( 'd-m-Y', strtotime( $tekst['datum'] ) ); if (!isset( $groepen[$datum] )) $groepen[$datum] = array(); $groepen[$datum][ $string ] = $tekst['tekst']; ++$count; } } $this->load->view( 'admin/tekst_beheer', array( 'groepen' => $groepen, 'count' => $count, 'sort' => $sort, ) ); } public function bag_koppeling_beheer() { $this->navigation->push( 'nav.bag_koppeling_beheer', '/admin/bag_koppeling_beheer' ); $this->load->model( 'bagkoppelinginstelling' ); $this->load->model( 'checklist' ); // get and check checklist id $checklisten = $this->checklist->all(); $checklist_id = $this->bagkoppelinginstelling->get( 'CHECKLIST_ID' ); if (!($checklist = $this->checklist->get( $checklist_id ))) $checklist_id = 0; usort( $checklisten, function( $a, $b ){ $res = strcmp( $a->get_checklistgroep()->naam, $b->get_checklistgroep()->naam ); if ($res) return $res; return strcmp( $a->naam, $b->naam ); }); // get klanten settings $klanten = $this->klant->all('naam'); $klanten = $this->_filter_klanten( $klanten ); $klant_instellingen = array(); foreach ($klanten as $klant) $klant_instellingen[ $klant->id ] = intval( $this->bagkoppelinginstelling->get( 'KLANT' . $klant->id, 0 ) ); // handle POST now if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->bagkoppelinginstelling->set( 'CHECKLIST_ID', $_POST['checklist_id'] ); foreach ($klanten as $klant) $this->bagkoppelinginstelling->set( 'KLANT' . $klant->id, isset( $_POST['klanten'][$klant->id] ) ? 1 : 0 ); redirect( '/admin/bag_koppeling_beheer' ); } // show $this->load->view( 'admin/bag_koppeling_beheer', array( 'checklisten' => $checklisten, 'checklist_id' => $checklist_id, 'klanten' => $klanten, 'klant_instellingen' => $klant_instellingen, ) ); } public function backlog( $mode=null, $wens=null, $alleen_mijn=null, $sortfield=null, $sortorder=null, $search=null ) { $this->navigation->push( 'nav.backlog', '/admin/backlog' ); $this->load->model( 'backlog' ); // beheer zoekinstellingen $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'backlog' ); if (!is_array( $viewdata )) $viewdata = array( 'search' => '', 'sortfield' => 'id', 'sortorder' => 'asc', 'mode' => 'actief', 'wens' => 'alle', 'alleen_mijn' => 'nee', ); if (!is_null( $mode )) $viewdata['mode'] = $mode; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $wens )) $viewdata['wens'] = $wens; if (!is_null( $alleen_mijn )) $viewdata['alleen_mijn'] = $alleen_mijn; if (!is_null( $search )) $viewdata['search'] = $search; // check input $realsortfields = array( 'id', 'verbeterpunt', 'actie', 'prioriteit', 'ureninschatting', 'status', 'afgerond', 'programmeur', 'actie_voor' ); if (!in_array( $viewdata['sortfield'], $realsortfields )) $viewdata['sortfield'] = 'id'; $viewdata['sortorder'] = strtolower($viewdata['sortorder']); if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!in_array( @$viewdata['wens'], array( 'nee', 'alleen-wensen', 'alleen-opdrachten' ))) $viewdata['wens'] = 'alle'; if (!in_array( @$viewdata['alleen_mijn'], array( 'nee', 'ja' ))) $viewdata['alleen_mijn'] = 'alle'; // fetch data $data = $this->backlog->search_backlog( $viewdata['search'], $viewdata['mode'] == 'actief', $viewdata['wens'], $viewdata['alleen_mijn'] != 'nee' ); // sort $factor = $viewdata['sortorder']=='asc' ? 1 : -1; $actualsortfield = $viewdata['sortfield'] == 'actie_voor' ? 'actie_voor_gebruiker_id' : $viewdata['sortfield']; usort($data, function( $a, $b ) use ($actualsortfield, $factor){ return $factor * strnatcasecmp( trim( $a->$actualsortfield ), trim( $b->$actualsortfield ) ); }); // sla zoekinstellingen op $this->zoekinstelling->set( 'backlog', $viewdata ); // show $this->load->model( 'backlogupload' ); $this->load->view( 'admin/backlog', array( 'data' => $data, 'viewdata' => $viewdata, 'backloguploads' => $this->backlogupload->get_aantallen_per_back_log(), 'gebruiker' => $this->gebruiker->get_logged_in_gebruiker(), 'are_special_fields_visible' => $this->_are_special_fields_visible(), 'gebruikers' => $this->_get_backlog_gebruiker_namen(), ) ); } private function _get_backlog_gebruiker_namen() { return array( "1" =>'Marc', "347" =>'Olaf', "2" =>'Raoul', "164" =>'Remco', "213" =>'Richard', "251" =>'Sanne', ); } function backlog_edit( $id=null ) { $this->navigation->push( 'nav.backlog', '/admin/backlog' ); $this->navigation->push( 'nav.backlog_edit', '/admin/backlog_edit/'.$id ); $this->load->model( 'backlog' ); if (!($backlog = $this->backlog->get( $id ))) redirect( '/admin/backlog_edit' ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $are_special_fields_visible = $this->_are_special_fields_visible(); $gebruikers = $this->_get_backlog_gebruiker_namen(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $backlog->verbeterpunt = $_POST['verbeterpunt']; $backlog->actie = $_POST['actie']; $backlog->prioriteit = $_POST['prioriteit']; $backlog->ureninschatting = $_POST['ureninschatting']; $backlog->status = $_POST['status']; $backlog->testresultaten = $_POST['testresultaten']; $backlog->afgerond = isset( $_POST['afgerond'] ) ? 1 : 0; $backlog->actie_voor_gebruiker_id = in_array( @$_POST['actie_voor_gebruiker_id'], array_keys( $gebruikers ) ) ? $_POST['actie_voor_gebruiker_id'] : null; $backlog->is_wens = intval(isset( $_POST['is_wens'] ) && $_POST['is_wens']=='on'); if ($gebruiker->is_super_admin() && $are_special_fields_visible) { $backlog->prio_nr_imotep = $_POST['prio_nr_imotep']; $backlog->prio_nr_bris = $_POST['prio_nr_bris']; $backlog->ureninschatting_intern = $_POST['ureninschatting_intern']; $backlog->programmeur = $_POST['programmeur']; } if (!$backlog->save( false, null, false )) throw new Exception( 'Fout bij opslaan backlog in database.' ); redirect( '/admin/backlog' ); } $this->load->view( 'admin/backlog_edit', array( 'backlog' => $backlog, 'gebruiker' => $gebruiker, 'are_special_fields_visible' => $are_special_fields_visible, 'gebruikers' => $gebruikers, ) ); } public function backlog_verwijderen( $id=null ) { $this->load->model( 'backlog' ); if (($backlog = $this->backlog->get( $id ))) $backlog->delete(); redirect( '/admin/backlog' ); } public function backlog_nieuw() { $this->load->model( 'backlog' ); $backlog = $this->backlog->add(); redirect( '/admin/backlog_edit/' . $backlog->id ); } public function backlog_uploads( $id=null ) { $this->navigation->push( 'nav.backlog', '/admin/backlog' ); $this->navigation->push( 'nav.backlog_uploads', '/admin/backlog_uploads/'.$id ); $this->load->model( 'backlog' ); if (!($backlog = $this->backlog->get( $id ))) redirect( '/admin/backlog' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset( $_FILES['file'] ) && !$_FILES['file']['error'] && $_FILES['file']['size']) { if (false !== ($contents = file_get_contents( $_FILES['file']['tmp_name'] ))) { $this->load->model( 'backlogupload' ); if ($upload = $this->backlogupload->add( $id, $_FILES['file']['name'], $contents )) { redirect( '/admin/backlog_uploads/' . $id ); } else $errors[] = 'Kon upload niet toevoegen aan de database, serverfout.'; } else $errors[] = 'Kon upload niet inladen, serverfout.'; } else $errors[] = 'Geen bestand geselecteerd, of fout bij uploaden.'; } $this->load->view( 'admin/backlog_uploads', array( 'errors' => $errors, 'backlog' => $backlog, 'uploads' => $backlog->get_uploads(), ) ); } public function backlog_uploads_download( $id=null ) { $this->load->model( 'backlogupload' ); if (!($backlog = $this->backlogupload->get( $id ))) redirect( '/admin/backlog' ); $backlog->laad_inhoud(); $this->load->helper( 'user_download' ); user_download( $backlog->bestand, $backlog->bestandsnaam, true, $backlog->content_type ); } public function backlog_uploads_delete( $id=null ) { $this->load->model( 'backlogupload' ); if (!($backlog = $this->backlogupload->get( $id ))) redirect( '/admin/backlog' ); $backlog_id = $backlog->back_log_id; $backlog->delete(); redirect( '/admin/backlog_uploads/' . $backlog_id ); } private function _are_special_fields_visible() { $val = $this->session->userdata( 'backlog::special_fields' ); if (!$this->session->userdata( 'backlog::special_fields' )) return true; return $val != 'nee'; } public function backlog_toggle_special_fields() { if ($this->_are_special_fields_visible()) { $this->session->set_userdata( 'backlog::special_fields', 'nee' ); } else { $this->session->set_userdata( 'backlog::special_fields', 'ja' ); } redirect( '/admin/backlog' ); } public function quest_beheer() { $this->navigation->push( 'nav.quest_beheer', '/admin/quest_beheer' ); $this->load->model( 'grondslag' ); $grondslagen = $this->grondslag->get_gebruikte_grondslagen(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { foreach ($grondslagen as $grondslag) { if (isset( $_POST['documentid'][$grondslag->id] )) { $grondslag->quest_document = $_POST['documentid'][$grondslag->id]; if (!$grondslag->save( false, null, false )) throw new Exception( 'Fout bij opslaan grondslag in database.' ); } } redirect( '/admin/quest_beheer' ); } $this->load->view( 'admin/quest_beheer', array( 'grondslagen' => $grondslagen, ) ); } public function lease_beheer() { if (!$this->klant->allow_lease_administratie()) redirect( '/admin' ); $this->navigation->push( 'nav.lease_beheer', '/admin/lease_beheer' ); $this->load->model( 'leaseconfiguratie' ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $ips = explode( "\n", $_POST['ips'] ); foreach ($ips as $i => $ip) if (!$ip) unset( $ips[$i] ); $klant = $this->klant->get(1); $klant->lease_administratie_ips = implode( ';', $ips ); $klant->save(); redirect( '/admin/lease_beheer' ); } $alle_configuraties = $this->leaseconfiguratie->all( 'naam' ); $this->load->view( 'admin/lease_beheer', array( 'alle_configuraties' => $alle_configuraties, ) ); } public function lease_bewerken( $id ) { if (!$this->klant->allow_lease_administratie()) redirect( '/admin' ); $this->navigation->push( 'nav.lease_beheer', '/admin/lease_beheer' ); $this->navigation->push( 'nav.lease_bewerken', '/admin/lease_bewerken/' . $id ); $this->load->model( 'leaseconfiguratie' ); if (!($configuratie = $this->leaseconfiguratie->get( $id ))) throw new Exception( 'Onbekend lease configuratie id ' . $id ); $geselecteerd = $configuratie->get_klanten(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->db->trans_start(); $this->db->_trans_status = true; try { // save config $configuratie->pagina_titel = $_POST['pagina_titel']; $configuratie->login_systeem = $_POST['login_systeem']; $configuratie->login_label = $_POST['login_label']; $configuratie->achtergrondkleur = $_POST['achtergrondkleur']; $configuratie->voorgrondkleur = $_POST['voorgrondkleur']; $configuratie->url = $_POST['url']; $configuratie->email_sender = $_POST['email_sender']; $configuratie->eigen_nieuws_berichten = (@$_POST['eigen_nieuws_berichten'] == 'on') ? 'ja' : 'nee'; $configuratie->automatisch_collega_zijn = (@$_POST['automatisch_collega_zijn'] == 'on') ? 'ja' : 'nee'; $configuratie->toon_gebruikersforum_knop = (@$_POST['toon_gebruikersforum_knop'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_matrixbeheer = (@$_POST['gebruik_matrixbeheer'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_management_rapportage = (@$_POST['gebruik_management_rapportage'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_instellingen = (@$_POST['gebruik_instellingen'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_rollenbeheer = (@$_POST['gebruik_rollenbeheer'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_dossier_rapportage = (@$_POST['gebruik_dossier_rapportage'] == 'on') ? 'ja' : 'nee'; $configuratie->gebruik_deelplan_email = (@$_POST['gebruik_deelplan_email'] == 'on') ? 'ja' : 'nee'; $configuratie->speciaal_veld_gebruiken = (@$_POST['speciaal_veld_gebruiken'] == 'on') ? 1 : 0; $configuratie->has_children_organisations = (@$_POST['has_children_organisations'] == 'on') ? 1 : 0; $configuratie->save(0,0,0); // save klanten $_POST['klanten'] = array_flip( $_POST['klanten'] ); foreach ($geselecteerd as $klant) { if (!isset( $_POST['klanten'][$klant->id] )) { $klant->lease_configuratie_id = NULL; if (!$klant->save( false, null, false )) throw new Exception( 'Fout bij verwijderen van lease configuratie / klant koppeling voor klant ' . $klant->id ); } else unset( $_POST['klanten'][$klant->id] ); } foreach ($_POST['klanten'] as $klant_id => $unused) { $klant = $this->klant->get( $klant_id ); $klant->lease_configuratie_id = $configuratie->id; if (!$klant->save( false, null, false )) throw new Exception( 'Fout bij aanbrengen van lease configuratie / klant koppeling voor klant ' . $klant->id ); } // commit if (!$this->db->trans_complete()) throw new Exception( 'Fout bij opslaan in database.' ); // done! redirect( '/admin/lease_beheer' ); } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); throw $e; } } $this->load->view( 'admin/lease_bewerken', array( 'geselecteerd' => $geselecteerd, 'klanten' => $this->klant->all('naam'), 'configuratie' => $configuratie, ) ); } private function _filter_klanten( array $klanten, $childrenOnly=false ) { $CI = get_instance(); $has_children_orgs = $CI->session->userdata( 'has_children_organisations' ); $kid = $CI->session->userdata( 'kid' ); $logged_in_gebruiker = $CI->gebruiker->get_logged_in_gebruiker(); $parent_admin = $this->login->verify( 'admin', 'parentadmin' ); // if( APPLICATION_LOGIN_SYSTEM == 'LocalDB' && $is_children_klanten_only ) if( APPLICATION_LOGIN_SYSTEM == 'LocalDB' && $parent_admin ) { $klanten = $this->_filter_parent_klanten($klanten,$childrenOnly); $klanten = array_values( $klanten ); return $klanten; } if (!$this->klant->allow_lease_administratie() ) { foreach ($klanten as $i => $klant){ if ($klant->lease_configuratie_id){ unset($klanten[$i]); } } $klanten = array_values( $klanten ); } return $klanten; } private function _get_unavailable_klanten( array $klanten ) { $gefilterde_klanten = $this->_filter_klanten( $klanten, true ); $unavailable_klanten = array(); foreach ($klanten as $klant) { if (!in_array( $klant, $gefilterde_klanten )) $unavailable_klanten[] = $klant; } return $unavailable_klanten; } function inloggen() { global $__local_debug; if( (isset($__local_debug)&&$__local_debug )){// Debug log in. $this->session->set_userdata( self::ADMIN_LOGIN_SESSION_KEY, 1 ); redirect( '/admin' ); } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { //$passsha1 = '<PASSWORD>'; // ACCEPTATIE en TEST $passsha1 = '<PASSWORD>'; // PRODUCTIE if ( sha1($_POST['wachtwoord']) == $passsha1 ) { $this->session->set_userdata( self::ADMIN_LOGIN_SESSION_KEY, 1 ); redirect( '/admin' ); } } $this->load->view( 'admin/inloggen' ); } public function gebruiks_overzicht() { if( $this->gebruiker->get_logged_in_gebruiker()->get_klant()->naam != CLIENT_NAME_IMOTEP ) { throw new Exception('Access not granted'); } $years = range(date('Y'), 1970); $data = array( 'years' => $years, 'clients' => $this->klant->getAllPairs(), 'selected_year' => null, 'selected_client' => null, ); if($_POST) { $info = $this->klant->getDataforOverview($_POST['client_id'], $_POST['year']); $months = array(1 => 'jan', 2 => 'feb', 3 => 'mar', 4 => 'apr', 5 => 'may', 6 => 'june', 7 => 'july', 8 => 'aug', 9 => 'sep', 10 => 'oct', 11 => 'nov', 12 => 'dec'); $data = array( 'years' => $years, 'clients' => $this->klant->getAllPairs(), 'selected_year' => $_POST['year'], 'selected_client' => $_POST['client_id'], 'months' => $months, 'info' => $info ); } $this->navigation->push( 'nav.usage_overview', '/admin/geubriks_overzicht'); $this->load->view('admin/gebruiks_overzicht', $data); } function user_groups_relationship_list( $id ) { $gebruiker = $this->gebruiker->get( $id ); if (!$gebruiker) { throw new Exception( 'Ongeldig gebruiker ID ' . $id ); } $user_logged_in = $this->gebruiker->get_logged_in_gebruiker(); $klant = $user_logged_in->get_klant(); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; if( $klant->lease_configuratie_id ) { if( !$gebruiker->hasLeaseRol() ) { Throw new Exception('Action not Allowed'); } if( $klant->allow_lease_administratie() ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); } } else { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); } $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $klant_id ); $this->load->model("usergroupsrelation"); $data=$this->usergroupsrelation->get_group_by_uid($id, $klant_id); $this->navigation->push( 'nav.groups_relationship', '/admin/user_groups_relationship_list/' . $id ); $this->load->view("admin/user_groups_form",array('data'=> $data, 'id'=>$id)); } function distributeurs_relationship_save($id){ $gebruiker = $this->gebruiker->get( $id ); if (!$gebruiker) { throw new Exception( 'Ongeldig gebruiker ID ' . $id ); } $user_logged_in = $this->gebruiker->get_logged_in_gebruiker(); $klant = $user_logged_in->get_klant(); if( $klant->lease_configuratie_id ) { if( !$gebruiker->hasLeaseRol() ) { Throw new Exception('Action not Allowed'); } if( $klant->allow_lease_administratie() ) { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $klant_id ); } } else { $this->navigation->push( 'nav.accountbeheer', '/admin/account_beheer' ); $this->navigation->push( 'nav.gebruikerslijst', '/admin/account_list_users/' . $klant_id ); } $this->load->model("usergroupsrelation"); $this->usergroupsrelation->delete($id); foreach ($_POST as $key=>$value){ // $this->usergroupsrelation->save(array('id'=>'','users_group_id'=>$key,'user_id'=>$id)); $this->usergroupsrelation->insert(array('id'=>'','users_group_id'=>$key,'user_id'=>$id)); } redirect('/admin/user_groups_relationship_list/'.$id); } }<file_sep>DROP TABLE dossier_bescheiden_publickeys; <file_sep><?php class BRIS_HttpResponse_Organization extends BRIS_HttpResponse_Abstract {}<file_sep>PDFAnnotator.Tool.Move = PDFAnnotator.Tool.HandleTool.extend({ /* constructor */ init: function( engine ) { this._super( engine, 'move' ); } }); <file_sep>UPDATE zoek_instellingen SET instellingen = REPLACE(instellingen, 'ie-css3.htc', ''); <file_sep>/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; DROP TABLE IF EXISTS standard_documents; CREATE TABLE standard_documents ( id int(11) NOT NULL AUTO_INCREMENT, klant_id int(11) NOT NULL, tekening_stuk_nummer varchar(256) NOT NULL, auteur varchar(256) NOT NULL, omschrijving varchar(512) NOT NULL, zaaknummer_registratie varchar(256) NOT NULL, versienummer varchar(32) NOT NULL, datum_laatste_wijziging varchar(64) NOT NULL, bestandsnaam varchar(256) DEFAULT NULL, png_status enum ('onbekend', 'aangemaakt', 'fout') NOT NULL DEFAULT 'onbekend', has_pdfa_copy tinyint(4) NOT NULL DEFAULT 0, laatste_bestands_wijziging_op timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), INDEX bestandsnaam_ind (bestandsnaam), CONSTRAINT FK_standard_documents_klanten FOREIGN KEY (klant_id) REFERENCES klanten (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'form.verwijder_alles', ' Verwijder alles', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'klant.standaard_documenten', ' Standaard Documemten?', '2015-03-19 15:14:13' ); /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep><? $this->load->view('elements/header', array('page_header'=>'webservice_beheer')); ?> <p> <span style="color:red"><b>LET OP!</b> Alles wat hier aan instellingen gewijzigd wordt is meteen van kracht! Als hier verkeerde wijzigingen worden gedaan, kunnen de koppelingen met andere applicaties ernstig gehinderd worden!</span> </p> <script type="text/javascript"> function webserviceAjaxCall( url, postdata, onsuccess, onerror ) { $.ajax({ url: url, type: 'POST', data: postdata, dataType: 'json', success: function( data, jqXHR, textStatus ){ if (data.success) { if (onsuccess) onsuccess(); } else { if (onerror) onerror(); if (data.error) alert( data.error ); else alert( 'Onbekende fout opgetrouden.' ); } }, error: function() { if (onerror) onerror(); alert( 'Fout bij verwerking.' ); } }); } </script> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Webserviceaccount beheer', 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => false ) ); ?> <? $col_widths = array( 'account' => 200, 'applicatie' => 150, 'gebruikersnaam' => 120, 'actief' => 75, 'alle_klanten' => 150, 'alle_components' => 150, 'opties' => 150, ); $col_description = array( 'account' => 'Account', 'applicatie' => 'Applicatie', 'gebruikersnaam' => 'Gebruikersnaam', 'actief' => 'Actief', 'alle_klanten' => 'Alle klanten', 'alle_components' => 'Alle componenten', 'opties' => 'Opties', ); $col_unsortable = array_keys( $col_widths ); $col_centered = array( 'actief', 'alle_klanten', 'alle_components' ); $rows = array(); foreach ($alle_accounts as $account) { $row = (object)array(); $row->onclick = null; $row->data = array(); $row->data['account'] = $account->omschrijving; $row->data['applicatie'] = $account->get_applicatie()->naam; $row->data['gebruikersnaam'] = $account->gebruikersnaam; $row->data['actief'] = '<input type="checkbox" name="actief" account_id="' . $account->id . '" ' . ($account->actief ? 'checked' : '') . ' />'; $row->data['alle_klanten'] = '<input type="checkbox" name="alle_klanten" account_id="' . $account->id . '" ' . ($account->alle_klanten ? 'checked' : '') . ' />'; $row->data['alle_components'] = '<input type="checkbox" name="alle_components" account_id="' . $account->id . '" ' . ($account->alle_components ? 'checked' : '') . ' />'; $row->data['opties'] = '&nbsp;'; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => null, 'url' => '/admin/webservice_beheer', 'scale_field' => 'opties', 'do_paging' => false, 'header' => null, 'disable_search' => true, 'center_headers' => $col_centered, ) ); ?> <script type="text/javascript"> $(document).ready(function(){ $('[name=actief], [name=alle_klanten], [name=alle_components]').click(function(){ var thiz = this; webserviceAjaxCall( '/admin/webservice_account_toggle', { account_id: $(this).attr('account_id'), checked: thiz.checked ? 1 : 0, mode: $(this).attr('name') }, function() { location.href = location.href; }, function() { thiz.checked = !thiz.checked; } ); }); }); </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Webserviceaccount componententoegang', 'expanded' => false, 'width' => '100%', 'height' => 'auto', 'defunct' => false ) ); ?> <? $col_widths = array( 'module' => 200, ); $col_description = array( 'module' => 'Component', ); $col_unsortable = array( 'module', 'opties' ); $col_centered = array(); foreach ($alle_accounts as $account) { $sname = htmlentities( $account->omschrijving, ENT_COMPAT, 'UTF-8' ); $key = 'account_' . $account->id; $col_widths[$key] = 120; $col_description[$key] = '<span>' . $sname . '</span>'; $col_unsortable[] = $key; $col_centered[] = $key; } $col_widths['opties'] = 150; $col_description['opties'] = 'Opties'; $rows = array(); foreach ($alle_modules as $module => $module_obj) { $row = (object)array(); $row->onclick = null; $row->data = array(); $row->data['module'] = $module; foreach ($alle_accounts as $account) { $checked = $account->actief && $account->mag_bij_component( $module ); $disabled = !$account->actief || $account->alle_components; $title = 'Mag account ' . $account->gebruikersnaam . ' gebruik maken van functies uit ' . $module . '?'; $title = htmlentities( $title, ENT_COMPAT, 'UTF-8' ); $row->data['account_' . $account->id] = '<input type="checkbox" account_id="' . $account->id . '" module="' . $module . '" onclick="eventStopPropagation(event);" ' . ($checked ? 'checked' : '') . ' ' . ($disabled ? 'disabled' : '') . ' title="' . $title. '" />'; } $row->data['opties'] = '&nbsp;'; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => null, 'url' => '/admin/webservice_beheer', 'scale_field' => 'opties', 'do_paging' => false, 'header' => null, 'disable_search' => true, 'center_headers' => $col_centered, ) ); ?> <script type="text/javascript"> $(document).ready(function(){ $('[account_id][module]').click(function(){ var thiz = this; webserviceAjaxCall( '/admin/webservice_component_toggle', { account_id: $(this).attr('account_id'), checked: thiz.checked ? 1 : 0, module: $(this).attr('module') }, null, function() { thiz.checked = !thiz.checked; } ); }); }); </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Webserviceaccount klantentoegang', 'expanded' => false, 'width' => '100%', 'height' => 'auto', 'defunct' => false ) ); ?> <? $col_widths = array( 'klant' => 200, ); $col_description = array( 'klant' => 'Klant', ); $col_unsortable = array( 'module', 'opties' ); $col_centered = array(); foreach ($alle_accounts as $account) { $sname = htmlentities( $account->omschrijving, ENT_COMPAT, 'UTF-8' ); $key = 'account_' . $account->id; $col_widths[$key] = 120; $col_description[$key] = '<span>' . $sname . '</span>'; $col_unsortable[] = $key; $col_centered[] = $key; } $col_widths['opties'] = 150; $col_description['opties'] = 'Opties'; $rows = array(); foreach ($alle_klanten as $klant) { $row = (object)array(); $row->onclick = null; $row->data = array(); $row->data['klant'] = $klant->naam; foreach ($alle_accounts as $account) { $checked = $account->actief && $account->mag_bij_klant( $klant->id ); $disabled = !$account->actief || $account->alle_klanten; $title = 'Mag account ' . $account->gebruikersnaam . ' bij gegevens van klant ' . $klant->naam . '?'; $title = htmlentities( $title, ENT_COMPAT, 'UTF-8' ); $row->data['account_' . $account->id] = '<input type="checkbox" account_id="' . $account->id . '" klant_id="' . $klant->id . '" onclick="eventStopPropagation(event);" ' . ($checked ? 'checked' : '') . ' ' . ($disabled ? 'disabled' : '') . ' title="' . $title. '" />'; } $row->data['opties'] = '&nbsp;'; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => null, 'url' => '/admin/webservice_beheer', 'scale_field' => 'opties', 'do_paging' => false, 'header' => null, 'disable_search' => true, 'center_headers' => $col_centered, ) ); ?> <script type="text/javascript"> $(document).ready(function(){ $('[account_id][klant_id]').click(function(){ var thiz = this; webserviceAjaxCall( '/admin/webservice_klant_toggle', { account_id: $(this).attr('account_id'), checked: thiz.checked ? 1 : 0, klant_id: $(this).attr('klant_id') }, null, function() { thiz.checked = !thiz.checked; } ); }); }); </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>-- -- Add foto column to `dossiers` table -- -- ALTER TABLE `dossiers` ADD `foto` LONGBLOB NULL AFTER `opmerkingen`; DROP TABLE IF EXISTS `dossier_fotos`; CREATE TABLE IF NOT EXISTS `dossier_fotos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dossier_id` int(11) NOT NULL, `bestandsnaam` varchar(256) DEFAULT NULL, `laatste_bestands_wijziging_op` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `dossier_id` (`dossier_id`), CONSTRAINT `fk__dossier_fotos__dossier` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.bewerken::dossierfoto', 'Dossierfoto', 0, ''); INSERT INTO `help_buttons` (`tag`, `taal`, `tekst`, `laast_bijgewerkt_op`) VALUES ('dossiers.bewerken.dossierfoto', 'nl', 'U kunt hier een foto opgeven specifiek voor dit dossier.', '2015-08-09 18:00:00'); <file_sep><?php function user_download( $contents, $filename, $exit=true, $type='application/x-download' ) { // output! header( "Pragma: public" ); header( "Expires: 0" ); header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); header( "Content-Type: $type" ); header( "Content-Disposition: attachment; filename=\"$filename\"" ); header( "Content-Transfer-Encoding: binary" ); header( "Content-Length: " . strlen($contents) ); echo $contents; if ($exit) exit; } <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.vragen')?></h1> <? $this->load->view( 'checklistwizard/_lijst', array( 'placeholder' => 'Vraagtekst', 'entries' => $vragen, 'get_id' => function( $v ) { return $v->id; }, 'get_image' => function( $v ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $v ) { return $v->tekst; }, 'delete_url' => '/checklistwizard/vraag_verwijderen', 'add_url' => '/checklistwizard/vraag_toevoegen/' . $hoofdgroep->id, 'add_uitgebreid_url' => '/checklistwizard/vraag_uitgebreid_toevoegen/' . $hoofdgroep->id, 'copy_url' => '/checklistwizard/vraag_kopieren', 'defaults_url' => '/checklistwizard/vraag_bewerken', ) ); ?> <div class="button"> <a href="<?=site_url('/checklistwizard/vraag_volgorde/' . $hoofdgroep->id)?>">Wijzig volgorde</a> </div> <?=htag('wijzig-volgorde')?> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]:not(.readonly)').click(function(){ location.href = '<?=site_url('/checklistwizard/vraag_bewerken/')?>/' + $(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE project_mappen DROP COLUMN is_bw; ALTER TABLE artikel_vraag_mappen DROP COLUMN is_bw; ALTER TABLE bijwoonmomenten_map ADD COLUMN is_dmm_bw BOOL NOT NULL DEFAULT 0; ALTER TABLE bijwoonmomenten_map ADD COLUMN is_drsm_bw BOOL NOT NULL DEFAULT 0; DELIMITER // DROP PROCEDURE IF EXISTS set_bijwoonmomenten_map// CREATE PROCEDURE set_bijwoonmomenten_map() BEGIN DECLARE dmm_id, tm_id INT; DECLARE no_more_bws BOOLEAN; DECLARE bws_cursor CURSOR FOR SELECT `dmms`.`id`, `tms`.`id` FROM `matrix_mappingen` `dmms` LEFT JOIN `bt_toezichtmomenten` `tms` ON `tms`.`checklist_id`=`dmms`.`checklist_id` ; DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_bws = TRUE; OPEN bws_cursor; bw_loop: LOOP FETCH bws_cursor INTO dmm_id,tm_id; IF ( no_more_bws ) THEN CLOSE bws_cursor; LEAVE bw_loop; END IF; IF (tm_id IS NOT NULL AND dmm_id IS NOT NULL ) THEN REPLACE INTO `bijwoonmomenten_map` SET `matrix_id`=dmm_id, `toezichtmoment_id`=tm_id; END IF; END LOOP bw_loop; END // CALL set_bijwoonmomenten_map()// DROP PROCEDURE IF EXISTS set_bijwoonmomenten_map// DELIMITER ;<file_sep><? $number = 1; $process_dir = function( $is_btz, StempelDirectory $dir, $indent, $belongsto=null ) use (&$process_dir, &$number) { // dir! $id = 'dir' . $number; $str = '<div id="' . $id . '" belongsto="' . $belongsto . '" style="padding-left: ' . (5 + 10*$indent) . 'px;" class="ImageDirDepth' . $indent . ' Directory Collapsed ' . ($indent?'Hidden':'') . '">'; $str .= basename( $dir->get_directory() ); $str .= '</div>'; echo $str; ++$number; // subdirs! foreach ($dir->get_entries() as $entry) if ($entry instanceof StempelDirectory) $process_dir( $is_btz, $entry, $indent+1, $id ); // files foreach ($dir->get_entries() as $entry) if ($entry instanceof StempelFile) { // dir! $str = '<div image="/' . $entry->get_filename() . '" image_width="' . $entry->get_width() . '" image_height="' . $entry->get_height() . '" belongsto="' . $id . '" style="padding-left: ' . (5+10*($indent+1)) . 'px; display:none" class="Image">'; if ($is_btz) { $str .= '<img src="/files/images/s.gif" target_url="/' . $entry->get_filename() . '.thumb.png" style="vertical-align:middle" width="50" height="17" /> '; $str .= '<img src="/files/images/s.gif" target_url="/' . $entry->get_filename() . '" style="vertical-align:middle; position:absolute; left:-9999px; top:-9999px; " /> '; } else $str .= '<img width="50" height="17" src="/' . $entry->get_filename() . '.thumb.png" style="vertical-align:middle" /> '; $str .= preg_replace( '/\.png$/i', '', basename( $entry->get_filename() ) ); $str .= '</div>'; echo $str; } }; foreach (StempelLibrary::instance()->get_directory()->get_entries() as $dir) if (is_dir( $dir->get_directory() )) $process_dir( $is_btz, $dir, 0 ); ?> <file_sep><? function jsstr( $s, $safeents=true ) { $t = str_replace( "\n", '\n', str_replace( "\r", '', addcslashes($s, "'" ) )); if ($safeents) $t = htmlentities( $t, ENT_COMPAT, 'UTF-8' ); return $t; }; /** Searches 'd' object/array recursively for CI references. If found, the * value can NOT be safely json_encode'd. If not found, it probably can! */ function search_for_CI_object( $data, $path ) { if (is_object($data) || is_array($data)) { foreach ($data as $k => $v) search_for_CI_object( $v, $path . '.' . $k ); } else if ($data instanceof Controller) { echo "CI instance found in $path<br/>\n"; } } /** Recursively Converts all strings to UTF-8 if not yet done so. */ function convert_utf8_recursive( $data, $path='' ) { if (is_array($data)) { foreach ($data as $k => $v) $data[$k] = convert_utf8_recursive( $v, $path ? $path . '.' . $k : $k ); return $data; } else if (is_object($data)) { foreach ($data as $k => $v) $data->$k = convert_utf8_recursive( $v, $path ? $path . '.' . $k : $k ); return $data; } else { $encoding = mb_detect_encoding( $data ); if ($encoding != 'ASCII' && $encoding != 'UTF-8') { $s = @iconv( $encoding, 'UTF-8', $data ); if ($s === false) { $s = iconv( 'CP437', 'UTF-8', $data ); return $s; } else return $s; } else return $data; } } // Calculates the size of a directory in 1024 bytes blocks function calculate_directory_size($dirName) { $dirExists = (file_exists($dirName) && is_dir($dirName)); if ($dirExists) { $io = @popen ( '/usr/bin/du -sk ' . $dirName, 'r' ); $size = fgets ( $io, 4096); $size = substr ( $size, 0, strpos ( $size, "\t" ) ); pclose ( $io ); } else { $size = 0; } //echo 'Directory (bestaat ' . ($dirExists ? 'wel' : 'niet') . '): ' . $dirName . ' => Size: ' . $size . " 1024 bytes blocks\n"; return $size; } // Outputs a formatted string of the size of the directory contents. // Note: the default size is in 1024 bytes blocks! function show_directory_size_formatted ($size, $label = '', $blockSize = 1024) { //$kbSize = $size*$blockSize; $kbSize = $size; $mbSize = $kbSize/1024; $gbSize = $mbSize/1024; echo ((empty($label)) ? 'Directory size' : $label) . ": ". sprintf("%.02f",$kbSize) ." KB - ". sprintf("%.02f",$mbSize) ." MB - ". sprintf("%.02f",$gbSize) ." GB\n"; } // function show_directory_size_formatted ($size, $label = '', $blockSize = 1024) // A helper function to convert integer numbers to Roman numerals function romanic_number($integer, $upcase = true) { $table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1); $return = ''; while($integer > 0) { foreach($table as $rom=>$arb) { if($integer >= $arb) { $integer -= $arb; $return .= $rom; break; } } } return $return; } # A nice debug function: gives a nicely formatted debug dump of the passed structure. The result is echoed directly to the screen. # Note: this is the 'DebugComplete' functionality, that doesn't filter out the _CI object function dc($mixed = null) { echo '<pre>'; var_dump($mixed); echo '</pre>'; return null; } // function dc($mixed = null) # A nice debug function: gives a nicely formatted debug dump of the passed structure. The result is echoed directly to the screen. # Note: this is the filtered 'Debug' functionality, that does filters out the _CI object function d($mixed = null) { if (is_a($mixed, 'BaseModel')) { // Make a local copy, from which we remove some members that we do not want to show in the output $mixed_temp = clone $mixed; //$mixed_temp->unset_field('_CI'); $fields_to_unset = array('_CI', '_db', 'config', 'input', 'benchmark', 'db', 'dbex', 'tekst', 'teksten', 'settings', 'gebruiker', 'log', 'logger', 'kennisid', 'kmxlicensesystem'); $mixed_temp->unset_fields($fields_to_unset); } else { $mixed_temp = $mixed; } // Show the filtered output echo '<pre>'; var_dump($mixed_temp); echo '</pre>'; return null; } // function d($mixed = null) # A nice debug function: gives a nicely formatted debug dump of the passed structure. The result is returned as a string. function dr($mixed = null) { ob_start(); var_dump($mixed); $content = ob_get_contents(); ob_end_clean(); return $content; } // function dr($mixed = null) // Creates a debug print backtrace with <cr><lf> per entry and returns it as a string. function dpbr($options = 2) { ob_start(); debug_print_backtrace($options); $content = ob_get_contents(); ob_end_clean(); $content = str_replace(']', "]<br />\n", $content); return $content; } // Gets a debug print backtrace with <cr><lf> per entry and prints it to the screen. function dpb($options = 2) { $content = dpbr($options); echo $content; } // Returns either 'oracle' or 'mysql'. Can be extended to accomodate other DB types too. Defaults to 'mysql' function get_db_type() { $CI = get_instance(); return ($CI->db->dbdriver == 'oci8') ? 'oracle' : 'mysql'; } // Returns the proper function for the currently used DB for selecting the first non-null value // Note: both 'NVL' and 'IFNULL' expect EXACTLY 2 parameters! We could also use 'COALESCE' for an unlimited amount of parameters! function get_db_null_function() { return (get_db_type() == 'oracle') ? 'NVL' : 'IFNULL'; } // Returns a properly formatted string concatenation representation. // Note: all parts must be added in as strings! This means that literals should have DOUBLE quotation, vs. column names! // The $concat_parts array should therefore look something like $concat_parts = array("'A literal'", '<column1>', "'another literal'",'<column2>') function get_db_concat_string($concat_parts) { return (get_db_type() == 'oracle') ? '('.implode('||',$concat_parts).')' : 'CONCAT('.implode(',',$concat_parts).')'; } // Returns the proper function for the currently used DB for selecting the current date/time function get_db_now_function() { return (get_db_type() == 'oracle') ? 'SYSDATE' : 'NOW()'; } // Returns the proper function for the currently used DB for selecting the current date function get_db_date_now_function() { return (get_db_type() == 'oracle') ? 'TO_DATE(SYSDATE)' : 'DATE(NOW())'; } // Returns the proper syntax for being able to use a prepared parameter for a MySQL 'datetime' and Oracle 'date', using a string in 'YYYY-MM-DD HH:MM:SS' notation. function get_db_prepared_parameter_for_datetime() { return (get_db_type() == 'oracle') ? "to_date(?, 'YYYY-MM-DD HH24:MI:SS')" : '?'; } // Returns the proper syntax for being able to use a prepared parameter for a MySQL 'date' and Oracle 'date', using a string in 'YYYY-MM-DD' notation. function get_db_prepared_parameter_for_date() { return (get_db_type() == 'oracle') ? "to_date(?, 'YYYY-MM-DD')" : '?'; } // Returns the proper syntax for being able to use a literal value for a MySQL 'datetime' and Oracle 'date', using a literal string in 'YYYY-MM-DD HH:MM:SS' notation. function get_db_literal_for_datetime($literal_value) { return (get_db_type() == 'oracle') ? "to_date({$literal_value}, 'YYYY-MM-DD HH24:MI:SS')" : $literal_value; } // Returns the proper syntax for being able to use a literal value for a MySQL 'date' and Oracle 'date', using a literal string in 'YYYY-MM-DD' notation. function get_db_literal_for_date($literal_value) { return (get_db_type() == 'oracle') ? "to_date({$literal_value}, 'YYYY-MM-DD')" : $literal_value; } // Returns the proper version for the currently used DB for the "...ORDER BY ... IS NULL" syntax function get_db_order_by_null_clause($nulls_first = true) { if ($nulls_first) { return (get_db_type() == 'oracle') ? ' NULLS FIRST ' : ' IS NULL '; } else { return (get_db_type() == 'oracle') ? ' NULLS LAST ' : ''; // !!! Check what the proper MySQL syntax is in this case! } } // Returns the proper syntax for converting a UNIX timestamp value (i.e. seconds since January 1st, 1970) to a date // MySQL note: use this for TIMESTAMP fields. function get_db_date_from_unix_timestamp( $date_expr ) { return (get_db_type() == 'oracle') ? "(date '1970-01-01' + {$date_expr}/60/60/24)" : 'FROM_UNIXTIME('.$date_expr.')'; } // Returns the proper syntax for converting a timestamp/date field to the "date-only" part // MySQL note: use this for TIMESTAMP fields. function get_db_date_field_from_timestamp_for_literal_comparison( $date_expr ) { return (get_db_type() == 'oracle') ? 'TO_CHAR(' . $date_expr . ', \'YYYY-MM-DD\')' : 'DATE('.$date_expr.')'; } // Returns the proper syntax for being able to do direct literal date comparisons. // MySQL note: use this for DATE and DATETIME fields. function get_db_date_field_from_datetime_for_literal_comparison( $date_expr ) { return (get_db_type() == 'oracle') ? 'TO_CHAR(' . $date_expr . ', \'YYYY-MM-DD\')' : $date_expr; } function get_db_between( $db_expr, $from, $until ) { if (get_db_type() == 'oracle') { return get_oracle_between($db_expr, $from, $until); } else { return get_mysql_between($db_expr, $from, $until); } } function get_mysql_between( $mysql_expr, $from, $until ) { return '(' . $mysql_expr . ') BETWEEN \'' . $from . '\' AND \'' . $until . '\''; } function get_oracle_between( $oracle_expr, $from, $until ) { return get_db_date_field_from_datetime_for_literal_comparison($oracle_expr) . ' BETWEEN \'' . $from . '\' AND \'' . $until . '\''; } // The following function should be used with some care. It is an attempt to 'automagically' purify data for usage with Oracle DBs. // It can be used a.o. in direct INSERT/UPDATE queries that are generated by generic code and that only get passed name-value pairs (without datatype hints) // such as is the case in the base oci8_driver.php file. The main issue is that this code does not take the end result column into account, which is dangerous, as // the column could actually be expecting a number or varchar, instead of a date. function purify_literal_data_for_oracle($raw_data, $expected_datatype = '') { // Extract the base type from the passed complete datatype, so as to (intentionally) lose the length part. $expected_datatype_base = preg_replace("|\(.+\)|", '', $expected_datatype); //echo "+-+ Checking value: *{$raw_data}* +-+<br />"; //echo "+-+ Expected type: ".((!empty($expected_datatype) ? $expected_datatype . " ({$expected_datatype_base})" : 'not specified'))." +-+<br />"; // Try to detect dates first. For now we only manipulate the return value for dates, and leave all other values alone. //if ($timestap = strtotime($raw_data)) if ($expected_datatype_base == 'datetime') { // The value appears to be a datetime, try to figure out what it is exactly and provide the proper format for it for Oracle. // Check for a date in 'YYYY-MM-DD HH:MM:SS', 'YYYY-MM-DD' or 'DD-MON-YY' notation //if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/',$raw_data)) if (preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$raw_data)) { // We found a date in 'YYYY-MM-DD HH:MM:SS' notation, process it //echo "+-+ Date-time in YYYY-MM-DD HH:MM:SS notation +-+<br />"; return "to_date({$raw_data}, 'YYYY-MM-DD HH24:MI:SS')"; } //else if (preg_match('/^\d{4}-\d{2}-\d{2}$/',$date)) else if (preg_match('/\d{4}-\d{2}-\d{2}/',$raw_data)) { // We found a date in 'YYYY-MM-DD' notation, process it //echo "+-+ Date in YYYY-MM-DD notation +-+<br />"; return "to_date({$raw_data}, 'YYYY-MM-DD')"; } else { // We found something else (possibly a valid Oracle format 'DD-MON-YY' date!), for now just return the value "as-is" //echo "+-+ Date in different notation +-+<br />"; return $raw_data; } } else { // If we reached this point, we assume the value to not need any conversion/manipulation and therefore we return the value without changes. //echo "+-+ Not a date-time type +-+<br />"; return $raw_data; } } // Look-up helper for mapping Oracle data types to MySQL ones. // Not fully implemented (yet)! -- may not be necessary. // NOTE: It can by definition not easily be made 100% correct! function get_mysql_type_for_oracle_type($oracle_type, $oracle_length = null) { $oracle_to_mysql_data_type_mappings = array( 'number' => 'int', 'varchar2' => 'varchar', 'float' => 'float', 'date' => 'datetime', // could also be 'date'.... ); $return_value_key = strtolower($oracle_type); $return_value = (array_key_exists($return_value_key, $oracle_to_mysql_data_type_mappings)) ? $oracle_to_mysql_data_type_mappings[$return_value_key] : $return_value_key; if (!is_null($oracle_length)) { $return_value .= '(' . $oracle_length . ')'; } return $return_value; } define('_R_BOUWNUMMER_SPACE','spaceFiLLeRHash000iwTm9Yrea'); define('_R_BOUWNUMMER_DQUOTE','dquoteFiLLeRHash000iwTm9Yrea'); define('_R_BOUWNUMMER_LT','lTLTltFiLLLLeRHash000iwTm9Yrea'); define('_R_BOUWNUMMER_GT','gTTGGtgtFiLLeRHash000iwTm9Yrea'); define('_R_BOUWNUMMER_SHARP','sHARpPpRHash020iwTm9Yrea'); define('_R_BOUWNUMMER_PROC','prOCCpHash020iwTm9Yrea'); define('_R_BOUWNUMMER_LBRACE','lBrACEHash020iwTm9Yrea'); define('_R_BOUWNUMMER_RBRACE','rBrACeHash020iwTm9Yrea'); define('_R_BOUWNUMMER_PIPE','ppiPeppHash020iwTm9Yrea'); // define('_R_BOUWNUMMER_BKSLASH','bkSlaSHHash020iwTm9Yrea'); //TODO: Does not work. define('_R_BOUWNUMMER_CARET','caRteTtHash9920iwTm9Yrea'); define('_R_BOUWNUMMER_TILDE','tIlD7eHash9920iwTm9Yrea'); define('_R_BOUWNUMMER_LSBRACKET','lSbrAcketHash9920iwTm9Yrea'); define('_R_BOUWNUMMER_RSBRACKET','rrSbrAcketHash942iwTm9Yrea'); define('_R_BOUWNUMMER_PLUS','PlaSSHash942iwTm9Yrea'); define('_R_BOUWNUMMER_DOLLAR','DoLlaRRHash942iwTm9Yrea'); define('_R_BOUWNUMMER_AMP','aMPPersHash802iwTm2Yrea'); // define('_R_BOUWNUMMER_COMMA','cOmmMAHash342iwTm2Yrea'); //TODO: Does not work. This simbol is used as delimiter. // define('_R_BOUWNUMMER_SLASH','SslashHash802iwTm2Yrea'); //TODO: Does not work. define('_R_BOUWNUMMER_COLON','coLonNsHash802iwTm2Yrea'); define('_R_BOUWNUMMER_SEMICOLON','SeMICoLonNsHash802iwTm2Yrea'); define('_R_BOUWNUMMER_EQUAL','eqQuUalHash802iwTm2Yrea'); define('_R_BOUWNUMMER_QUESTION','QueStioNlHash802iwTm2Yrea'); define('_R_BOUWNUMMER_AT','AtaTAATHash802iwTm2Yrea'); function encode_bouwnummer($bouwnummer){ $bouwnummer = str_replace(' ', _R_BOUWNUMMER_SPACE,$bouwnummer); $bouwnummer = str_replace('"', _R_BOUWNUMMER_DQUOTE,$bouwnummer); $bouwnummer = str_replace('<', _R_BOUWNUMMER_LT,$bouwnummer); $bouwnummer = str_replace('>', _R_BOUWNUMMER_GT,$bouwnummer); $bouwnummer = str_replace('#', _R_BOUWNUMMER_SHARP,$bouwnummer); $bouwnummer = str_replace('%', _R_BOUWNUMMER_PROC,$bouwnummer); $bouwnummer = str_replace('{', _R_BOUWNUMMER_LBRACE,$bouwnummer); $bouwnummer = str_replace('}', _R_BOUWNUMMER_RBRACE,$bouwnummer); $bouwnummer = str_replace('|', _R_BOUWNUMMER_PIPE,$bouwnummer); // $bouwnummer = str_replace("\\", _R_BOUWNUMMER_BKSLASH,$bouwnummer); //TODO: Does not work. $bouwnummer = str_replace('^', _R_BOUWNUMMER_CARET,$bouwnummer); $bouwnummer = str_replace('~', _R_BOUWNUMMER_TILDE,$bouwnummer); $bouwnummer = str_replace('[', _R_BOUWNUMMER_LSBRACKET,$bouwnummer); $bouwnummer = str_replace(']', _R_BOUWNUMMER_RSBRACKET,$bouwnummer); $bouwnummer = str_replace('+', _R_BOUWNUMMER_PLUS,$bouwnummer); $bouwnummer = str_replace('$', _R_BOUWNUMMER_DOLLAR,$bouwnummer); $bouwnummer = str_replace('&', _R_BOUWNUMMER_AMP,$bouwnummer); // $bouwnummer = str_replace(',', _R_BOUWNUMMER_COMMA,$bouwnummer); //TODO: Does not work. This simbol is used as delimiter. // $bouwnummer = str_replace('/', _R_BOUWNUMMER_SLASH,$bouwnummer); //TODO: Does not work. $bouwnummer = str_replace(':', _R_BOUWNUMMER_COLON,$bouwnummer); $bouwnummer = str_replace(';', _R_BOUWNUMMER_SEMICOLON,$bouwnummer); $bouwnummer = str_replace('=', _R_BOUWNUMMER_EQUAL,$bouwnummer); $bouwnummer = str_replace('?', _R_BOUWNUMMER_QUESTION,$bouwnummer); $bouwnummer = str_replace('@', _R_BOUWNUMMER_AT,$bouwnummer); return $bouwnummer; } function decode_bouwnummer($bouwnummer){ $bouwnummer = str_replace(_R_BOUWNUMMER_SPACE, ' ',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_DQUOTE, '"',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_LT, '<',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_GT, '>',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_SHARP, '#',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_PROC, '%',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_LBRACE, '{',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_RBRACE, '}',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_PIPE, '|',$bouwnummer); // $bouwnummer = str_replace(_R_BOUWNUMMER_BKSLASH, "\\",$bouwnummer); //TODO: Does not work. $bouwnummer = str_replace(_R_BOUWNUMMER_CARET, '^',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_TILDE, '~',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_LSBRACKET, '[',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_RSBRACKET, ']',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_PLUS, '+',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_DOLLAR, '$',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_AMP, '&',$bouwnummer); // $bouwnummer = str_replace(_R_BOUWNUMMER_COMMA, ',',$bouwnummer); //TODO: Does not work. This simbol is used as delimiter. // $bouwnummer = str_replace(_R_BOUWNUMMER_SLASH, '/',$bouwnummer); //TODO: Does not work. $bouwnummer = str_replace(_R_BOUWNUMMER_COLON, ':',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_SEMICOLON, ';',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_EQUAL, '=',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_QUESTION, '?',$bouwnummer); $bouwnummer = str_replace(_R_BOUWNUMMER_AT, '@',$bouwnummer); return $bouwnummer; }<file_sep>ALTER TABLE `bt_grondslagen` ADD `quest_document` VARCHAR( 64 ) NULL DEFAULT NULL; ALTER TABLE `bt_grondslag_teksten` ADD `quest_node` VARCHAR( 128 ) NULL DEFAULT NULL; ALTER TABLE `bt_grondslag_teksten` ADD `quest_node_opgehaald` TINYINT NOT NULL DEFAULT '0'; ALTER TABLE `bt_grondslag_teksten` ADD `quest_node_alternatief_gebruikt` TINYINT NOT NULL DEFAULT '0'; <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_beheer')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('pdf-converter'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <form enctype="multipart/form-data" method="POST"> <p> <?=tg('pdf-converter.helptekst')?> </p> <input type="file" name="pdf_file"><input type="submit" value="<?=tgng('form.converteren')?>"> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>PDFAnnotator.Editable.Line = PDFAnnotator.Editable.extend({ init: function( config, tool ) { this._super( tool || PDFAnnotator.Tool.prototype.getByName( 'singleline' ) ); this.setData( config, { color: '#ff0000' }, [ 'from', 'to' ] ); this.line = null; }, render: function() { // make sure line object exists, we cannot do this without container, // so we cannot do this inside the constructor! this.conditionallyCreateLine(); var thiz = this; var base = $('<div>') .css( 'padding', '0' ) .css( 'position', 'absolute' ) .click(function(e){ thiz.dispatchEvent( 'click', {event:e} ); }); base.append( this.line.dom ); this.addVisual( base ); this.updateInternal(); }, setTo: function( to ) { this.conditionallyCreateLine(); this.data.to = to; this.line.update( this.data.from, this.data.to ); this.updateInternal(); }, setFrom: function( from ) { this.conditionallyCreateLine(); this.data.from = from; this.line.update( this.data.from, this.data.to ); this.updateInternal(); }, setFromAndTo: function( from, to ) { this.conditionallyCreateLine(); this.data.to = to; this.data.from = from; this.line.update( this.data.from, this.data.to ); this.updateInternal(); }, conditionallyCreateLine: function() { if (!this.line) { if (!this.container) throw 'PDFAnnotator.Editable.Line.conditionallyCreateLine: no container set, cannot continue'; this.line = new PDFAnnotator.Line( this.container, this.data.color, this.data.from, this.data.to ); } }, /** Updates the internal state of our DIV and our line. */ updateInternal: function() { // update div to have position and size of line, and reset line to pos 0x0 var base = this.visuals; base.css( 'top', this.line.dom.css( 'top' ) ); base.css( 'left', this.line.dom.css( 'left' ) ); base.css( 'width', this.line.dom.css( 'width' ) ); base.css( 'height', this.line.dom.css( 'height' ) ); this.line.dom.css( 'top', '0px' ); this.line.dom.css( 'left', '0px' ); }, /** Returns either "up" or "down", indicating the direction of the line. */ getDirection: function() { this.conditionallyCreateLine(); return this.line.dir; }, /** !!override!! */ getHandle: function( type ) { // use a bit different handles for lines! switch (type) { case 'resize': return null; case 'move': if (typeof(this.handles[type]) == 'undefined') this.handles[type] = new PDFAnnotator.Handle.LineMove( this ); return this.handles[type]; case 'delete': if (typeof(this.handles[type]) == 'undefined') this.handles[type] = new PDFAnnotator.Handle.LineDelete( this ); return this.handles[type]; default: return this._super( type ); } }, /* !!overide!! */ rawExport: function() { return { type: 'line', x1: this.data.from.x, y1: this.data.from.y, x2: this.data.to.x, y2: this.data.to.y, color: this.data.color }; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Line({ color: data.color, from: new PDFAnnotator.Math.IntVector2( data.x1, data.y1 ), to: new PDFAnnotator.Math.IntVector2( data.x2, data.y2 ) }); }, /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { this.setFromAndTo( this.data.from.multiplied( newlevel / oldlevel ), this.data.to.multiplied( newlevel / oldlevel ) ); this.repositionHandles(); } }); <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_upload_data` ( `id` int(11) NOT NULL, `data` longblob NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `deelplan_upload_data` CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT; ALTER TABLE `deelplan_uploads` ADD `deelplan_upload_data_id` INT NULL DEFAULT NULL AFTER `data` , ADD INDEX ( `deelplan_upload_data_id` ); ALTER TABLE `deelplan_uploads` ADD FOREIGN KEY ( `deelplan_upload_data_id` ) REFERENCES `deelplan_upload_data` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep>DELETE FROM bt_categorieen; DELETE FROM bt_checklist_groepen; DELETE FROM bt_checklisten; DELETE FROM bt_gebruiker_beperkingen; DELETE FROM bt_grondslagen; DELETE FROM bt_hoofdgroepen; DELETE FROM bt_hoofdthemas; DELETE FROM bt_prioriteitstelling_waarden; DELETE FROM bt_prioriteitstellingen; DELETE FROM bt_richtlijnen; DELETE FROM bt_risicoanalyse_effecten; DELETE FROM bt_risicoanalyse_kansen; DELETE FROM bt_risicoanalyse_waardes; DELETE FROM bt_risicoanalyses; DELETE FROM bt_themas; DELETE FROM bt_vraag_grondslagen; DELETE FROM bt_vraag_richtlijnen; DELETE FROM bt_vragen; ALTER TABLE bt_categorieen AUTO_INCREMENT = 1; ALTER TABLE bt_checklist_groepen AUTO_INCREMENT = 1; ALTER TABLE bt_checklisten AUTO_INCREMENT = 1; ALTER TABLE bt_gebruiker_beperkingen AUTO_INCREMENT = 1; ALTER TABLE bt_grondslagen AUTO_INCREMENT = 1; ALTER TABLE bt_hoofdgroepen AUTO_INCREMENT = 1; ALTER TABLE bt_hoofdthemas AUTO_INCREMENT = 1; ALTER TABLE bt_prioriteitstelling_waarden AUTO_INCREMENT = 1; ALTER TABLE bt_prioriteitstellingen AUTO_INCREMENT = 1; ALTER TABLE bt_richtlijnen AUTO_INCREMENT = 1; ALTER TABLE bt_risicoanalyse_effecten AUTO_INCREMENT = 1; ALTER TABLE bt_risicoanalyse_kansen AUTO_INCREMENT = 1; ALTER TABLE bt_risicoanalyse_waardes AUTO_INCREMENT = 1; ALTER TABLE bt_risicoanalyses AUTO_INCREMENT = 1; ALTER TABLE bt_themas AUTO_INCREMENT = 1; ALTER TABLE bt_vraag_grondslagen AUTO_INCREMENT = 1; ALTER TABLE bt_vraag_richtlijnen AUTO_INCREMENT = 1; ALTER TABLE bt_vragen AUTO_INCREMENT = 1; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Gebruikers van klant ' . $klant->naam, 'width' => '920px' ) ); ?> <p> <input type="button" value="Gebruiker toevoegen" onclick="location.href='<?=site_url('/admin/account_gebruiker_toevoegen/' . $klant->id)?>';"> </p> <table class="admintable" width="100%" cellpadding="3" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Gebruiker</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Rol</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Actief?</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;" width="100">Acties</th> </tr> <? foreach ($gebruikers as $i => $gebruiker): ?> <tr class="<?=($i % 2)?'':'zebra'?>"> <td style="" valign="top"><h5><?=$gebruiker->get_status()?></h5></td> <td style="" valign="top"><?=($r = $gebruiker->get_rol()) ? $r->naam : '- geen rol -'?></td> <td style="" valign="top"><?=$gebruiker->status=='actief' ? 'Ja' : 'Nee'?></td> <td style="" valign="top"> <a href="javascript:void(0);" onclick="if (confirm( 'U staat op het punt om gebruiker <?=$gebruiker->get_status()?> van <?=htmlentities($klant->volledige_naam)?> te bewerken. Weet u zeker dat u dit wilt?' )) location.href='<?=site_url('/admin/account_user_edit/'.$gebruiker->id)?>';"><img src="<?=site_url('/content/png/edit')?>" title="Bewerken" alt="Bewerken" /></a> <? if( $gebruiker->status=='actief' && $r): ?> <a href="javascript:void(0);" onclick="if (confirm( 'U staat op het punt om ingelogd te worden als gebruiker <?=$gebruiker->get_status()?> van <?=jsstr($klant->volledige_naam)?> bent. Weet u zeker dat u dit wilt?' )) location.href='<?=site_url('/admin/login_als/'.$gebruiker->id)?>';"><img src="<?=site_url('/content/png/login_as')?>" title="Inloggen als" alt="Inloggen als" /></a> <? else: ?> <? endif; ?> <? if($this->gebruiker->get_logged_in_gebruiker()->get_klant()->usergroup_activate == 1):?> <a href="javascript:void(0);" onclick="if (confirm( 'U staat op het punt om gebruiker <?=$gebruiker->get_status()?> van <?=htmlentities($klant->volledige_naam)?> te bewerken. Weet u zeker dat u dit wilt?' )) location.href='<?=site_url('/admin/user_groups_relationship_list/'.$gebruiker->id)?>';"><img src="<?=site_url('/content/png/edit')?>" title="Bewerken" alt="Bewerken" /></a> <?endif;?> </td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE klanten ADD COLUMN deelplan_out_of_date_color INT(11) DEFAULT 0 AFTER deelplannen_tab_close; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('klant.deelplan_out_of_date_color', 'Deelplan out of date red color?', NOW(), 0);<file_sep><?php get_instance()->load->helper( 'tcpdf' ); get_instance()->load->helper( 'export' ); get_instance()->load->helper( 'soapclient' ); abstract class DossierExportBase extends ExportBase { protected $_CI; private $_dossier; private $_klant; private $_filter_data; private $_output_format; public function __construct( DossierResult $dossier, array $filter_data, $output_format = 'pdf' ) { $this->_CI = get_instance(); $this->_dossier = $dossier; $this->_klant = $dossier->get_gebruiker()->get_klant(); $this->_filter_data = $filter_data; $this->_output_format = $output_format; } public function get_output_format() { return $this->_output_format; } public function get_dossier() { return $this->_dossier; } public function get_klant() { return $this->_klant; } public function get_filter( $key ) { return @$this->_filter_data[$key]; } public function set_progress( $progress /* tussen 0 en 1 */, $action_description ) { $download_tag = $this->get_filter( 'download-tag' ); if (!$download_tag) return; $this->_CI->dossierexport->set_progress( $download_tag, $progress, $action_description ); } abstract public function get_deelplannen(); } abstract class DossierExportPDFBase extends DossierExportBase { protected $_tcpdf; public function __construct( DossierResult $dossier, array $filter_data ) { parent::__construct( $dossier, $filter_data, 'pdf' ); // create instance $classname = $this->get_tcpdf_classname(); $tcpdf = new $classname; $this->_tcpdf = $tcpdf; } public function get_tcpdf_classname() { return 'TCPDF'; } public function get_filename() { return sprintf( '(%s) %s.pdf', date('d-m-Y'), preg_replace( '/\W/', '-', $this->get_dossier()->get_omschrijving() ) ); } public function get_content_type() { return 'application/pdf'; } public function get_contents() { return $this->_tcpdf->Output('unused.pdf', 'S'); } function generate() { // by default disable header/footer stuff by TCPDF, which adds unwanted stripes to header and footer $this->_tcpdf->SetPrintHeader(false); $this->_tcpdf->SetPrintFooter(false); // let rest be handled by parent return parent::generate(); } } abstract class DossierExportDocxBase extends DossierExportBase { //protected $_tcpdf; public function __construct( DossierResult $dossier, array $filter_data, $output_format = 'docx' ) { parent::__construct( $dossier, $filter_data, $output_format ); } public function get_filename() { if (parent::get_output_format() == 'pdf') { return sprintf( '(%s) %s.pdf', date('d-m-Y'), preg_replace( '/\W/', '-', $this->get_dossier()->get_omschrijving() ) ); } else { return sprintf( '(%s) %s.docx', date('d-m-Y'), preg_replace( '/\W/', '-', $this->get_dossier()->get_omschrijving() ) ); } } public function get_content_type() { if (parent::get_output_format() == 'pdf') { return 'application/pdf'; } else { return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; } } public function get_contents() { return $this->get_docx_content(); } function generate() { // let rest be handled by parent return parent::generate(); } } <file_sep><div class="scrolldiv hidden" id="TelefoonPaginaAfsluiten"> <div class="hidden afsluiten notice niets-te-synchroniseren"> <span><?=tg('niets-te-synchroniseren')?></span> </div> <div class="hidden afsluiten warning klaar-om-te-synchroniseren"> <span><?=tg('klaar-om-te-synchroniseren')?></span><br/> <br/> <input class="start" type="button" value="<?=tgn('upload.starten')?>"><br/> <br/> <span class="hidden voortgang"></span> </div> <div class="hidden afsluiten error fout-bij-synchroniseren"> <span><?=tg('fout-bij-synchroniseren')?></span><br/> <br/> <span style="font-style: italic" class="error"></span><br/> <br/> <input class="opnieuw" type="button" value="<?=tgn('overniew.proberen')?>"><br/> </div> <div class="hidden afsluiten notice synchroniseren-afgerond"> <span><?=tg('synchroniseren-afgerond')?></span> </div> </div> <file_sep><? if (!isset( $minwidth )) $minwidth = '600px'; if (!isset( $headers ) || !is_array( $headers )) $headers = array( array( 'text' => 'Missende', 'width' => '200px', 'align' => 'left' ), array( 'text' => 'header', 'width' => '200px', 'align' => 'center' ), array( 'text' => 'informatie', 'width' => '200px', 'align' => 'right' ), ); else foreach ($headers as &$header) { if (!isset( $header['width'] )) $header['width'] = '150px'; if (!isset( $header['align'] )) $header['align'] = 'left'; } if (!isset( $rows ) || !is_array( $rows )) $rows = array(); if (!isset( $flat )) $flat = false; if (!isset( $listclasses ) || !is_array( $listclasses )) $listclasses = array(); if (!function_exists( '_output_headers' )) { function _output_headers( array &$headers, $flat ) { $c=0; foreach ($headers as &$header) { // set properties $first = (!$flat && $c==0) ? 'first' : ''; $text = trim( @$header['text'] ) ? $header['text'] : '&nbsp;'; // output! echo '<div class="item adjust' . $header['align'] . ' ' . $first . '" style="width:' . $header['width'] . '">' . $text . '</div>' . "\n"; ++$c; } } function _output_rows( array $rows, array $headers, $parent, $indent, $flat ) { static $nextid = 0; foreach ($rows as $row) { // set properties $haschildren = (is_array( @$row['children'] ) && sizeof( $row['children'] ) > 0) ? 'haschildren' : ''; $id = isset( $row['id'] ) ? $row['id'] : ('row' . ($nextid++)); $values = isset( $row['values'] ) ? $row['values'] : array(); $onclick = isset( $row['onclick'] ) ? 'onclick="' . $row['onclick'] . '"' : ''; $parentstr = $parent ? 'parent="' . $parent . '"' : ''; $indentstr = $indent > 0 ? 'indent' . $indent : ''; $collapsedstr = @$row['collapsed'] ? 'collapsed' : ''; if (empty($row['style'])) $row['style'] = ''; $style = strlen( @$row['style'] ) ? 'style="' . $row['style'] . '"' : ''; // output! echo '<div class="row ' . $haschildren . ' ' . $indentstr . ' ' . $collapsedstr . '" ' . $style . ' ' . $onclick . ' ' . $parentstr . ' id="' . $id . '">' . "\n"; $c = 0; foreach ($values as $index => $value) { // set properties, some come from header array! $first = (!$flat && $c==0) ? 'first' : ''; $width = $headers[$index]['width']; $align = $headers[$index]['align']; $text = $value; // output! echo "\t" . '<div class="item adjust' . $align . ' ' . $first . ' " style="width: ' . $width . '"><div class="text" style="overflow-x: hidden;">' . $text . '</div></div>' . "\n"; ++$c; } echo '</div>' . "\n"; if ($haschildren) _output_rows( $row['children'], $headers, $id, $indent+1, $flat ); } } } ?> <div class="list <?=implode( ' ', $listclasses )?>" style="min-width: <?=$minwidth?>;"> <div class="header" style="padding: 0px;"> <? _output_headers( $headers, $flat ); ?> </div> <div class="rows" style="padding: 0px; min-width: <?=$minwidth?>; <? if (@$height): ?> height: <?=$height?>; <? endif;?>"> <? _output_rows( $rows, $headers, null, 0, $flat ); ?> </div> </div> <file_sep>ALTER TABLE `gebruikers` DROP `laatste_login`; <file_sep>BRISToezicht.DirtyStatus = { div: null, // null, or jQuery collection of divs that contain the status (might be more than one) initialize: function() { this.div = $('div.store-status'); if (this.div.size() == 0) return; }, updateState: function() { this.setState( this.getState() ); }, getState: function() { var a = BRISToezicht.Toets.Form.haveStoreOnceData(); var b = BRISToezicht.Toets.Form.haveUploads(); var c = BRISToezicht.Toets.Vraag.isDirty(); return a || b || c; }, getStateExceptUploads: function() { var a = BRISToezicht.Toets.Form.haveStoreOnceData(); var b = false; var c = BRISToezicht.Toets.Vraag.isDirty(); return a || b || c; }, setState: function( unstored_data ) { // update all visual indicators this.div.removeClass( 'stored unstored storing-now' ); this.div.addClass( unstored_data ? 'unstored' : 'stored' ); if (unstored_data) { this.div.find( '.stored' ).hide(); this.div.find( '.unstored' ).show(); } else { this.div.find( '.stored' ).show(); this.div.find( '.unstored' ).hide(); } this.div.find( '.storing-now' ).hide(); this.div.show(); BRISToezicht.Toets.Form.updateSyncOverview(); }, setStateStoringNow: function() { // clear previous this.div.removeClass( 'stored unstored' ); this.div.find( '.stored' ).hide(); this.div.find( '.unstored' ).hide(); // show special elements this.div.addClass( 'storing-now' ); this.div.find( '.storing-now' ).show(); } }; <file_sep>ALTER TABLE deelplan_opdrachten ADD COLUMN datum_begin DATE DEFAULT NULL; ALTER TABLE deelplan_opdrachten ADD COLUMN datum_einde DATE DEFAULT NULL; ALTER TABLE deelplan_opdrachten ADD COLUMN deelplan_checklist_id int(11) DEFAULT NULL; ALTER TABLE deelplan_opdrachten ADD CONSTRAINT FK_deelplan_opdrachten_deelplan_checklisten_id FOREIGN KEY (deelplan_checklist_id) REFERENCES deelplan_checklisten(id) ON DELETE CASCADE ON UPDATE CASCADE;<file_sep>-- remove foreign keys on hoofdthema_id fields ALTER TABLE `bt_vragen` DROP FOREIGN KEY `bt_vragen_ibfk_2` ; ALTER TABLE `bt_hoofdgroepen` DROP FOREIGN KEY `bt_hoofdgroepen_ibfk_2` ; ALTER TABLE `bt_checklisten` DROP FOREIGN KEY `bt_checklisten_ibfk_2` ; ALTER TABLE `bt_checklist_groepen` DROP FOREIGN KEY `bt_checklist_groepen_ibfk_3` ; -- remove fields ALTER TABLE bt_vragen DROP `hoofdthema_id`; ALTER TABLE bt_hoofdgroepen DROP `standaard_hoofdthema_id`; ALTER TABLE bt_checklisten DROP `standaard_hoofdthema_id`; ALTER TABLE bt_checklist_groepen DROP `standaard_hoofdthema_id`;<file_sep>ALTER TABLE klanten ADD COLUMN deelplannen_tab_close INT(11) DEFAULT 0 AFTER parent_id; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('klant.deelplannen_tab_close', 'Sluit alle tabbladen met deelplannen?', NOW(), 0);<file_sep><? $this->load->view('elements/header', array('page_header'=>'dossiers')); ?> <? if($klant->heeft_toezichtmomenten_licentie == 'nee'): ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => null, 'width' => '100%' )); ?> <form name="form" method="post" action="/dossiers/dossieroverzicht_genereren/"> <input type="button" value="<?=tgn('maak_een_nieuw_dossier_aan')?>" onclick="location.href='<?=site_url('/dossiers/nieuw')?>'"/> <?=htag('nieuw_dossier')?> <? if ($viewdata['mode']!='archief' && $do_bel_import && $import_access!=RECHT_MODUS_GEEN): ?> <input type="button" value="<?=tgn('importeren_starten')?>" onclick="location.href='/dossiers/importeren';" /> <?=htag('importeren')?> <? endif; ?> <? if($klant->kan_dossieroverzichten_genereren == 'ja'): ?> <input type="hidden" name="download-tag" value="<?=$download_tag?>" /> <input type="submit" id="generate_button" value="<?=tgng('form.dossieroverzicht_genereren')?>" /> <?=htag('dossieroverzicht_genereren')?> <div style="height: 15px;"></div> <div id="dossieroverzicht-progress" class="dossieroverzicht-progress" style="display: none; height:auto; border:0; background-color:transparent;"> <span id="dossieroverzicht-progress-image"><img src="/files/images/loading.gif"></span> <span class="dossieroverzicht-progress-action"></span> </div> <? endif; ?> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? endif; ?> <div style="height: 5px;"></div> <? if (get_instance()->is_Mobile) { $col_widths = array( 'id_nummer' => 140, 'beschrijving' => 200, 'gepland_datum' => 110, 'locatie' => 280, 'gebruiker' => 120, 'opties' => 40, 'pdf_status' =>100, ); } else { $col_widths = array( 'herkomst' => 150, 'id_nummer' => 150, 'beschrijving' => 200, 'gepland_datum' => 110, 'locatie' => 300, 'gebruiker' => 150, 'opties' => 100, 'pdf_status' => 100, ); } $col_description = array( 'herkomst' => tg('herkomst'), 'id_nummer' => tg('id-nummer'), 'beschrijving' => tg('projectomschrijving'), 'gepland_datum' => tg('gepland_op'), 'locatie' => tg('locatie'), 'gebruiker' => tg('verantwoordelijke'), 'opties' => $viewdata['mode']!='archief' ? '<input type="checkbox" class="dossier" onclick="eventStopPropagation(event);" /> ' . htag('verantwoordelijke_hoofd_selectie') : '', 'pdf_status' => tg('pdf_status'), ); if (get_instance()->is_Mobile) unset( $col_description['herkomst'] ); $rows = array(); $today = date('Y-m-d'); foreach ($dossiers as $i => $dossier) { $row = (object)array(); $row->onclick = "location.href='" . site_url('/dossiers/bekijken/' . $dossier->id) . "'"; $row->data = array(); if (!get_instance()->is_Mobile) $row->data['herkomst'] = ucfirst($dossier->herkomst); $row->data['id_nummer'] = @htmlentities( $dossier->kenmerk, ENT_COMPAT, 'UTF-8' ); $row->data['beschrijving'] = @htmlentities( $dossier->beschrijving, ENT_COMPAT, 'UTF-8' ); $row->data['gepland_datum'] = $dossier->gepland_datum ? date('d-m-Y', strtotime( $dossier->gepland_datum ) ) : '-'; $row->data['locatie'] = @htmlentities( $dossier->locatie_adres . ($dossier->locatie_adres ? ', ' : '') . $dossier->locatie_woonplaats, ENT_COMPAT, 'UTF-8' ) . ($dossier->geo_locatie_id ? ' <img style="vertical-align:top;" src="/files/images/earth.png">' : ''); $row->data['gebruiker'] = @htmlentities( $dossier->get_gebruiker()->volledige_naam, ENT_COMPAT, 'UTF-8' ); $row->data['opties'] = ''; if($dossier->pdf_status!="no_ico"){ $ico_name=$dossier->pdf_status=="green" ? "messagebox-notice" : $dossier->pdf_status=="green" ? "messagebox-error" :""; switch ($dossier->pdf_status) { case "green": $ico_name="messagebox-notice"; break; case "red": $ico_name="messagebox-error"; break; case "yellow": $ico_name= "messagebox-warning"; break; } $row->data['pdf_status']='<img src="/files/images/'.$ico_name.'.png">'; } else $row->data['pdf_status']=''; if ($dossier->gepland_datum && $today > $dossier->gepland_datum && $klant->dossierregels_rood_kleuren==1) { foreach ($row->data as $k => $v) $row->data[$k] = '<span style="color:red">' . $v . '</span>'; } if ($viewdata['mode']!='archief') { $row->data['opties'] .= '<input type="checkbox" style="margin-left: 7px;" dossier_id="' . $dossier->id . '" onclick="eventStopPropagation(event);" /> '; } if ($dossier->get_afmelden_access_to_dossier() == 'write') { if ($dossier->gearchiveerd) $row->data['opties'] .= '<a href="#" style="margin-left:5px; vertical-align: top;" onclick="eventStopPropagation( event ); verwijder_dossier(' . $dossier->id . '); return false;">'. '<img alt="' . tgn('dossier_verwijderen') . '" title="' . tgn('dossier_verwijderen') . '" src="' . site_url('/content/png/delete') . '" />'. '</a>'; if ($dossier->gearchiveerd) $row->data['opties'] .= '<a href="#" style="margin-left:5px; vertical-align: top;" onclick="eventStopPropagation( event ); terugzetten_dossier(' . $dossier->id . '); return false;">'. '<img alt="' . tgn('dossier_terugzetten') .'" title="' . tgn('dossier_terugzetten') . '" src="' . site_url('/content/png/terugzetten') . '" />'. '</a>'; } $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => array( 'opties','pdf_status'), 'rows' => $rows, 'config' => array( 'mode' => $viewdata['mode'], ), 'new_button_js' => null, // no new button :) 'url' => '/dossiers/index', 'scale_field' => '', 'do_paging' => true, 'post_table_html' => $viewdata['mode']!='archief' ? '<div style="height: 5px;"></div><table width="100%"><tr><td style="text-align:right">' . htag('archiveren') . '<input type="button" class="archiveer" value="' . tgn('archiveer_geselecteerde_dossiers') . '" /></td></tr></table>' : '', 'header' => ' <input type="radio" ' . ($viewdata['mode']=='mijn' ? 'checked' : '') . ' name="filter" value="mijn" /> ' . tg('toon_mijn_dossiers') . ' <input type="radio" ' . ($viewdata['mode']=='alle' ? 'checked' : '') . ' name="filter" value="alle" /> ' . tg('toon_alle_dossiers') . ' <input type="radio" ' . ($viewdata['mode']=='archief' ? 'checked' : '') . ' name="filter" value="archief" /> ' . tg('toon_gearchiveerde_dossiers' ) . ' <label><input type="checkbox" style="margin-left: 20px;" id="ViewModeToggle" /> <span>' . tg('kaartweergave') . '</span></label> ' . htag('dossier_eigenaar_filter') . ' ', ) ); ?> <script type="text/javascript"> // // overzicht genereren // $('form[name=form]').submit(function(){ // init progress BRISToezicht.Progress.initialize( this, 'dossieroverzicht', '<?=$download_tag?>' ); // submit return true; }); $(document).ready(function(){ // handle global select/deselect $('input.dossier').click(function(){ var selected = this.checked; if (selected) $('input[type=checkbox][dossier_id]').attr( 'checked', 'checked' ); else $('input[type=checkbox][dossier_id]').removeAttr( 'checked' ); }); // handle dossier filter by type/state $('input[type=radio][name=filter]').click(function(){ var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'mode', this.value ); }); // handle archiveer button $('input[type].archiveer').click(function(){ var ids = ''; $('input[type=checkbox][dossier_id]:checked').each(function(){ if (ids.length) ids += ','; ids += $(this).attr('dossier_id'); }); if (ids.length) if (confirm( '<?=tgn('weet_u_zeker_dat_u_de_geselecteerde_dossiers_wilt_archiveren')?>' )) { var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) { var urlParams = BRISToezicht.SearchableList.getUrlParams( listDiv ); location.href = '/dossiers/archiveren_multi/' + ids + urlParams; } } }); }); /* Kaartweergave */ $(document).ready(function(){ var showingKaartWeergave = false; var lijstElementen = $() .add( '.searchable-list .list2' ) .add( $('.archiveer').parent().parent().parent().parent() ); var kaartElementen = null; $('#ViewModeToggle').click(function(){ // flip the switch op de weergave boolean showingKaartWeergave = !showingKaartWeergave; // show/hide de juiste elementen op basis van de nieuwe huidige weergave if (showingKaartWeergave) { // KAART WEERGAVE lijstElementen.hide(); if (!kaartElementen) { // genereert addressen array <? $this->load->view( 'elements/nokiamaps-addressen-array' ); ?> // creeert div met nokia maps erin en met markers op de aangegeven adressen kaartElementen = NokiaMapsHelper.initialize( $('.searchable-list .list2'), adressen ); } else kaartElementen.show(); } else { // LIJST WEERGAVE lijstElementen.show(); kaartElementen.hide(); } }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('intro.index::release_version_value', 'v4.0.0', NOW(), 0), ('intro.index::release_date_value', '4 april 2016', NOW(), 0) ; <file_sep>PDFAnnotator.Engine = PDFAnnotator.Base.extend({ init: function( containerDomObjects, server, gui, initial_layer_name, load_annotations ) { /* vreselijke ipad hack: ipads verneuken position:fixed elementen bij het focussen van text inputs (als keyb. verschijnt) * ga dit tegen door bij het selecteren van een text input of textarea de position op absolute te zetten. bij verliezen * van de focus weer terugzetten. * als je denkt: zet die krengen dan permanent op position:absolute: dat geeft weer andere rariteiten bij keyboard focus, * op deze manier werkt het! */ var isiPad = navigator.userAgent.match(/iPad/i) != null; if (isiPad) { $('input[type=text], textarea').live( 'focus', function() { $('#PanelLayerInfo, #PanelToolsContainer').css( 'position', 'absolute' ); $('#PanelLayerInfo, #PanelToolsContainer').css( 'top', '0px' ); }); $('input[type=text], textarea').live( 'blur', function() { setTimeout( function() { $('#PanelLayerInfo, #PanelToolsContainer').show(); $('#PanelLayerInfo, #PanelToolsContainer').css( 'position', 'fixed' ); $('#PanelLayerInfo, #PanelToolsContainer').css( 'top', '66px' ); }, 1 ); }); } /* initialize base class */ this._super(); this.registerEventType( 'layeradded' ); this.registerEventType( 'layerremoved' ); this.registerEventType( 'prelayeractivated' ); this.registerEventType( 'layeractivated' ); this.registerEventType( 'pagetransformchanged' ); this.registerEventType( 'prereboot' ); /* init state vars */ this.layers = []; this.pageTransform = { flipH: false, flipV: false, rotation: 0, zoomLevel: 1 }; this.metadata = {}; /* init tools */ PDFAnnotator.Tool.prototype.initialize( this ); /* setup platform info */ this.platform = new PDFAnnotator.Engine.Platform(); /* setup server */ this.server = PDFAnnotator.Server.prototype.instance = server; /* setup gui */ this.gui = gui; this.gui.setEngine( this ); this.gui.menu.resetPanels(); /* layers */ this.installContainerDomObjects( containerDomObjects ); this.initialLayerName = initial_layer_name; if (containerDomObjects.editableContainers.length) this.createLayer( this.initialLayerName ); /* initialize overview window */ this.overviewWindow = new PDFAnnotator.OverviewWindow( this, { width: 'auto', height: 'auto', top: '300px', left: '300px', container: this.gui.rootContainer }); /* trigger window resize now */ PDFAnnotator.Window.prototype.triggerNow(); /* the very last action we take is: load annotations from server */ if (load_annotations) PDFAnnotator.Server.prototype.instance.loadAnnotations( this ); }, reboot: function( containerDomObjects ) { this.dispatchEvent( 'prereboot' ); /* destroy all layers */ this.removeAllLayers(); /* set new container objects */ this.installContainerDomObjects( containerDomObjects ); /* create new default layer */ this.createLayer( this.initialLayerName ); /* reset menu state */ this.gui.resetPanels(); /* reset meta data */ this.metadata = {}; /* reset page transform */ this.pageTransform = { flipH: false, flipV: false, rotation: 0, zoomLevel: 1 }; this.applyPageTransform(); /* show overview window */ this.showOverviewWindow(); }, installContainerDomObjects: function( containerDomObjects ) { this.containerDomObjects = containerDomObjects; this.containerDomObjects.drawings.each(function(){ var thiz = $(this); if (thiz.attr( 'original-width' )) return; thiz .attr( 'original-width', thiz.width() ) .attr( 'original-height', thiz.height() ); }); }, showOverviewWindow: function() { if (!this.overviewWindow) return; /* update image */ if (this.getPageCount() > 0) { this.updateOverviewWindow(); /* show window */ this.overviewWindow.show(); } else { /* hide window */ this.overviewWindow.hide(); } }, updateOverviewWindow: function() { /* set image */ if (this.getPageCount() > 0) { var page = $(this.getPage(0)); var document_id = page.parent().attr( 'document_id' ); var overview_url = $('img.Overview[document_id=' + document_id + ']').attr('src'); var thiz = this; this.overviewWindow.setupImage( overview_url, // url page.width(), // original width page.height(), // original height function( w, h ) { // function to fetch transform based on custom size return thiz.getCSSTransform( w, h ); } ); } }, getPlatform: function() { return this.platform; }, getGUI: function() { return this.gui; }, getBaseUrl: function() { return PDFAnnotator.Server.prototype.instance.getBaseUrl(); }, getActiveTool: function() { return this.gui.tools.getActiveTool(); }, getPageCount: function() { return this.containerDomObjects.drawings.size(); }, getPage: function( index ) { if (index < 0 || index >= this.containerDomObjects.drawings.size()) throw 'PDFAnnotator.Engine.getPage: invalid page index ' + index; return this.containerDomObjects.drawings[index]; }, isPageTransformLocked: function() { for (var i=0; i<this.layers.length; ++i) if (this.layers[i].hasObjects()) return true; return false; }, getPageTransform: function() { return this.pageTransform; }, setPageTransform: function( pageTransform ) { // when this is the first page transform, the annotation data will already be in the // correct zoom level, so make sure nothing happens by setting the old zoom level the // the new zoom level this.oldZoomLevel = pageTransform.initial ? pageTransform.zoomLevel : this.pageTransform.zoomLevel; if (typeof( pageTransform.rotation ) != 'undefined') this.pageTransform.rotation = pageTransform.rotation; if (typeof( pageTransform.flipH ) != 'undefined') this.pageTransform.flipH = pageTransform.flipH; if (typeof( pageTransform.flipV ) != 'undefined') this.pageTransform.flipV = pageTransform.flipV; if (typeof( pageTransform.zoomLevel ) != 'undefined') this.pageTransform.zoomLevel = pageTransform.zoomLevel; else if (pageTransform.initial) this.pageTransform.zoomLevel = 1; this.applyPageTransform(); if (pageTransform.initial) this.gui.zoom.setZoomLevelText( this.pageTransform.zoomLevel ); }, getCSSTransform: function( w, h ) { // build CSS string var transformString = '', transformOriginString = '50% 50%'; if (this.pageTransform.rotation == 90 || this.pageTransform.rotation == 270) { var cx = w/2, cy = h/2, x, y; x = -(cx - h/2); y = -(cy - w/2); transformString += ' translate(' + Math.round(x) + 'px,' + Math.round(y) + 'px)'; } if (this.pageTransform.flipH) transformString += ' scaleX(-1)'; if (this.pageTransform.flipV) transformString += ' scaleY(-1)'; if (this.pageTransform.rotation) transformString += ' rotate(' + this.pageTransform.rotation + 'deg)'; transformString = transformString.trim(); return { transform: transformString, origin: transformOriginString, swapwh: this.pageTransform.rotation == 90 || this.pageTransform.rotation == 270 }; }, applyPageTransform: function() { // // NOTE: We don't do "real" zooming! In stead, we just set a new image size relative to its // original dimensions, and scale the positions of the annotations. We could // have used scale transformations to do a REAL zoom function (i.e. don't change // positions (the model), just change the view.) However, the customer does NOT want // this! He wants annotations to be rendered always in exactly the same way, and // just change the picture background. // var oldZoomLevel = this.oldZoomLevel || 1; for (var i=0; i<this.getPageCount(); ++i) { var page = $(this.getPage(i)); var w = Math.round( parseInt( page.attr( 'original-width' ) ) * this.pageTransform.zoomLevel ); var h = Math.round( parseInt( page.attr( 'original-height' ) ) * this.pageTransform.zoomLevel ); page.css( 'width', w + 'px' ); page.css( 'height', h + 'px' ); } for (var i=0; i<this.layers.length; ++i) this.layers[i].setZoomLevel( oldZoomLevel, this.pageTransform.zoomLevel ); // set rest of page transform for (var i=0; i<this.getPageCount(); ++i) { var page = $(this.getPage(i)); var w = parseInt( page.css( 'width' ) ), h = parseInt( page.css( 'height' ) ); // get CSS transform & origin based on our size var transform = this.getCSSTransform( w, h ); // set transform page.css( 'transform', transform.transform ); page.css( '-ms-transform', transform.transform ); page.css( '-moz-transform', transform.transform ); page.css( '-webkit-transform', transform.transform ); page.css( '-o-transform', transform.transform ); // set origin page.css( 'transform-origin', transform.origin ); page.css( '-ms-transform-origin', transform.origin ); page.css( '-webkit-transform-origin', transform.origin ); // set image dimensions before swapping page.css( 'width', w + 'px' ); page.css( 'height', h + 'px' ); // fetch width/height (swap in certain cases) if (transform.swapwh) { var swap = w; w = h; h = swap; } // set width/height for layer divs and parent editor div var layerParent = page.parent(); var layers = page.siblings('.lcc').children( 'div' ); var divs = layers .add( layerParent ) // add img parent, .add( layerParent.parent() ); // and its parent, so that everything is sized properly divs.css( 'width', w + 'px' ); divs.css( 'height', h + 'px' ); } this.updateOverviewWindow(); this.dispatchEvent( 'pagetransformchanged', this.getPageTransform() ); }, setPageRotation: function( degrees ) { if (degrees != 0 && degrees != 90 && degrees != 180 && degrees != 270) degrees = 0; this.pageTransform.rotation = degrees; this.applyPageTransform(); }, togglePageHorizontalFlip: function() { this.pageTransform.flipH = !this.pageTransform.flipH; this.applyPageTransform(); }, togglePageVerticalFlip: function() { this.pageTransform.flipV = !this.pageTransform.flipV; this.applyPageTransform(); }, /* sets meta data */ setMetaData: function( k, v ) { this.metadata[k+''] = v + ''; return this; }, /* reads meta data */ getMetaData: function( k, dflt ) { if (typeof(this.metadata[k + '']) == 'undefined') return dflt; return this.metadata[k + '']; }, /** Changes transparency of the containers background (i.e. the drawing being annotated) * the opacity value must be 0 <= x <= 1, where 0 is fully transparent (invisible), and * 1 is fully opaque (no transparency). */ setPageTransparency: function( transparency ) { this.containerDomObjects.drawings.css( 'opacity', transparency ); this.containerDomObjects.drawings.css( 'filter', 'alpha(opacity=' + Math.round( 100 * transparency ) + ')' ); /* For IE8 and earlier */ }, createLayer: function( name ) { /* create array of containers for the dom objects */ var containers = []; var engine = this; for (var i=0; i<this.containerDomObjects.editableContainers.size(); ++i) { var originalContainer = $(this.containerDomObjects.editableContainers[i]); var layerContainerContainer = originalContainer.find( 'div.lcc' ); if (layerContainerContainer.size() == 0) { layerContainerContainer = $('<div>'); layerContainerContainer.css( 'position', 'relative' ) layerContainerContainer.css( 'left', '0px' ) layerContainerContainer.css( 'top', '0px' ) layerContainerContainer.addClass( 'lcc' ) layerContainerContainer.prependTo( originalContainer ); } var layerContainer = $('<div>') .css( 'position', 'absolute' ) .css( 'left', '0px' ) .css( 'top', '0px' ) .css( 'width', originalContainer.css( 'width' ) ) .css( 'height', originalContainer.css( 'height' ) ) .css( 'background-image', 'url(\'/files/pdf-annotator/images/s.gif\')' ) /* filthy hack to get IE working, raw URL is ugly */ .css( 'background-repeat', 'repeat' ) .attr( 'original-name', name ) .appendTo( layerContainerContainer ); containers.push( new PDFAnnotator.EditableContainer( engine, i+1 /* pagenum */, layerContainer, this.containerDomObjects.drawings[i] ) ); } /* create layer */ var layer = new PDFAnnotator.Layer( this, containers, name ); this.layers.push( layer ); this.dispatchEvent( 'layeradded', {layer:layer} ); /* no layer active? then set newly created layer as active */ if (!this.activeLayer) layer.activate(); return layer; }, removeLayer: function( layer ) { // remove from internal array var index = indexOfArray( this.layers, layer ); if (index == -1) throw 'PDFAnnotator.Engine.removeLayer: specified layer is not in this engine'; this.layers[index].remove(); this.layers.splice( index, 1 ); this.dispatchEvent( 'layerremoved', {layer:layer} ); // if this array was active, make another one active if (this.activeLayer == layer) this.setActiveLayer( this.layers.length ? this.layers[0] : null ); }, setActiveLayer: function( layer ) { if (this.activeLayer == layer) return; this.dispatchEvent( 'prelayeractivated', {layer:layer} ); if (this.activeLayer) this.activeLayer.deactivate(); this.activeLayer = layer; this.dispatchEvent( 'layeractivated', {layer:layer} ); }, getActiveLayer: function() { /* may return null */ return this.activeLayer; }, getVisibleLayers: function() { var layers = []; for (var i=0; i<this.layers.length; ++i) if (this.layers[i].getVisibility()) layers.push( this.layers[i] ); return layers; }, findLayerByMetaData: function( k, v ) { for (var i=0; i<this.layers.length; ++i) if (this.layers[i].getMetaData( k ) == v) return this.layers[i]; return null; }, removeAllLayers: function() { while (this.layers.length) this.removeLayer( this.layers[0] ); }, setZoomLevel: function( level /* value e.g. 0.25 to indicate 25% (zoomout) */ ) { this.setPageTransform({ flipH: this.pageTransform.flipH, flipV: this.pageTransform.flipV, rotation: this.pageTransform.rotation, zoomLevel: level }); }, getZoomLevel: function() { return this.pageTransform.zoomLevel; } }); <file_sep>PDFAnnotator.Handle.QuadResize = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* !!overide!! */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/edit-handle-resize.png', 32, 32, 'drag', this.execute, 'topleft', 0, 0 ); this.addNodeRelative( 1, 1, baseurl + 'images/nlaf/edit-handle-resize.png', 32, 32, 'drag', this.execute, 'bottomright', 0, 0 ); this.updateState(); }, execute: function( relx, rely, side ) { var changeVector = new PDFAnnotator.Math.IntVector2( relx, rely ); if (side == 'topleft') this.editable.setFrom( this.editable.data.from.added( changeVector ) ); else if (side == 'bottomright') this.editable.setTo( this.editable.data.to.added( changeVector ) ); else if (side == 'topright') { var fromChange = new PDFAnnotator.Math.IntVector2( 0, changeVector.y ); var toChange = new PDFAnnotator.Math.IntVector2( changeVector.x, 0 ); this.editable.setFromAndTo( this.editable.data.from.added( fromChange ), this.editable.data.to.added( toChange ) ); } else if (side == 'bottomleft') { var fromChange = new PDFAnnotator.Math.IntVector2( changeVector.x, 0 ); var toChange = new PDFAnnotator.Math.IntVector2( 0, changeVector.y ); this.editable.setFromAndTo( this.editable.data.from.added( fromChange ), this.editable.data.to.added( toChange ) ); } this.updateState(); this.show(); }, updateState: function() { var flipX = this.editable.data.from.x > this.editable.data.to.x; var flipY = this.editable.data.from.y > this.editable.data.to.y; if (flipX && flipY) { this.nodes[0].userdata = 'bottomright'; this.nodes[0].relx = 1; this.nodes[0].rely = 1; this.nodes[1].userdata = 'topleft'; this.nodes[1].relx = 0; this.nodes[1].rely = 0; } else if (flipX) { this.nodes[0].userdata = 'topright'; this.nodes[0].relx = 1; this.nodes[0].rely = 0; this.nodes[1].userdata = 'bottomleft'; this.nodes[1].relx = 0; this.nodes[1].rely = 1; } else if (flipY) { this.nodes[0].userdata = 'bottomleft'; this.nodes[0].relx = 0; this.nodes[0].rely = 1; this.nodes[1].userdata = 'topright'; this.nodes[1].relx = 1; this.nodes[1].rely = 0; } else { this.nodes[0].userdata = 'topleft'; this.nodes[0].relx = 0; this.nodes[0].rely = 0; this.nodes[1].userdata = 'bottomright'; this.nodes[1].relx = 1; this.nodes[1].rely = 1; } } }); <file_sep>ALTER TABLE `bt_checklist_groepen` CHANGE `standaard_waardeoordeel_standaard` `standaard_waardeoordeel_standaard` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , CHANGE `standaard_waardeoordeel_steekproef` `standaard_waardeoordeel_steekproef` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ; ALTER TABLE `bt_checklisten` CHANGE `standaard_waardeoordeel_standaard` `standaard_waardeoordeel_standaard` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , CHANGE `standaard_waardeoordeel_steekproef` `standaard_waardeoordeel_steekproef` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ; ALTER TABLE `bt_hoofdgroepen` CHANGE `standaard_waardeoordeel_standaard` `standaard_waardeoordeel_standaard` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , CHANGE `standaard_waardeoordeel_steekproef` `standaard_waardeoordeel_steekproef` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ; ALTER TABLE `bt_vragen` CHANGE `waardeoordeel_standaard` `waardeoordeel_standaard` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , CHANGE `waardeoordeel_steekproef` `waardeoordeel_steekproef` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ; UPDATE bt_checklist_groepen SET standaard_waardeoordeel_standaard = 'w00', standaard_waardeoordeel_steekproef = 'w04'; <file_sep><? require_once 'base.php'; class ChecklistKoppelVoorwaardeResult extends BaseResult { function ChecklistKoppelVoorwaardeResult( &$arr ) { parent::BaseResult( 'checklistkoppelvoorwaarde', $arr ); } private function _converteer_waarde( $w ) { if (is_array( $w )) return $w; if (preg_match( '/^\d+$/', $w )) $w = intval( $w ); else if (preg_match( '/^\d{2}\-\d{2}\-\d{4}$/', trim($w))) $w = date('Y-m-d', strtotime( $w ) ); return $w; } function voldoet( ChecklistKoppelVoorwaardeData $data ) { $veldnaam = str_replace( ' ', '_', $this->veld ); if (!in_array( 'get_' . $veldnaam, get_class_methods( $data ))) throw new Exception( 'Koppelvoorwaarde veld "' . $veldnaam . '" ongeldig' ); $waarde = $data->{'get_' . $veldnaam}(); $controle_waarde = $this->waarde; $waarde = $this->_converteer_waarde( $waarde ); $controle_waarde = $this->_converteer_waarde( $controle_waarde ); switch ($this->operator) { case 'bevat': case 'bevat niet': if (!is_array( $waarde )) throw new Exception( 'Verwachtte array waarde voor operator "' . $this->operator . '"' ); $resultaat = in_array( $controle_waarde, $waarde ); if ($this->operator == 'bevat niet') $resultaat = !$resultaat; return $resultaat; case 'bevat iets anders dan': if (!is_array( $waarde )) throw new Exception( 'Verwachtte array waarde voor operator "' . $this->operator . '"' ); $resultaat = in_array( $controle_waarde, $waarde ); if (!$resultaat) return true; return sizeof( $waarde ) > 1; case '==': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde == $controle_waarde; case '!=': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde != $controle_waarde; case '>': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde > $controle_waarde; case '<': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde < $controle_waarde; case '>=': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde >= $controle_waarde; case '<=': if (is_array( $waarde )) throw new Exception( 'Verwachtte geen array waarde voor operator "' . $this->operator . '"' ); return $waarde <= $controle_waarde; default: throw new Exception( 'Onbekende operator "' . $this->operator . '"' ); } } } class ChecklistKoppelVoorwaarde extends BaseModel { function ChecklistKoppelVoorwaarde() { parent::BaseModel( 'ChecklistKoppelVoorwaardeResult', 'bt_checklist_koppel_vrwrdn', true ); } public function check_access( BaseResult $object ) { // disabled for model } function add( $checklist_id, $veld, $operator, $waarde ) { /* if (!$this->dbex->is_prepared( 'ChecklistKoppelVoorwaarde::add' )) $this->dbex->prepare( 'ChecklistKoppelVoorwaarde::add', 'INSERT INTO bt_checklist_koppel_vrwrdn (checklist_id, veld, operator, waarde) VALUES (?, ?, ?, ?)' ); $args = array( 'checklist_id' => $checklist_id, 'veld' => $veld, 'operator' => $operator, 'waarde' => $waarde, ); $this->dbex->execute( 'ChecklistKoppelVoorwaarde::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'checklist_id' => $checklist_id, 'veld' => $veld, 'operator' => $operator, 'waarde' => $waarde, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function get_by_checklist_id( $checklist_id ) { return $this->search( array( 'checklist_id' => $checklist_id ), null, false, 'AND', 'veld' ); } function get_list_of_checklist_ids_with_voorwaarden() { $res = $this->db->query( 'SELECT DISTINCT(checklist_id) AS checklist_id FROM bt_checklist_koppel_vrwrdn' ); $result = array(); foreach ($res->result() as $row) $result[] = $row->checklist_id; $res->free_result(); return $result; } } class ChecklistKoppelVoorwaardeData { private $_aanvraagdatum; private $_gebruiksfunctie = array(); private $_bouwsom; private $_is_integraal; private $_is_eenvoudig; private $_is_dakkapel; private $_is_bestaand; public function __construct( $aanvraagdatum, array $gebruiksfunctie, $bouwsom, $is_integraal, $is_eenvoudig, $is_dakkapel, $is_bestaand ) { $this->_aanvraagdatum = date( 'd-m-Y', strtotime( $aanvraagdatum ) ); $this->_gebruiksfunctie = $gebruiksfunctie; $this->_bouwsom = intval( $bouwsom ); $this->_is_integraal = $is_integraal ? 'ja' : 'nee'; $this->_is_eenvoudig = $is_eenvoudig ? 'ja' : 'nee'; $this->_is_dakkapel = $is_dakkapel ? 'ja' : 'nee'; $this->_is_bestaand = $is_bestaand ? 'ja' : 'nee'; } public function get_aanvraagdatum() { return $this->_aanvraagdatum; } public function get_gebruiksfunctie() { return $this->_gebruiksfunctie; } public function get_bouwsom() { return $this->_bouwsom; } public function get_is_integraal() { return $this->_is_integraal; } public function get_is_eenvoudig() { return $this->_is_eenvoudig; } public function get_is_dakkapel() { return $this->_is_dakkapel; } public function get_is_bestaand() { return $this->_is_bestaand; } } <file_sep><?php class BRIS_SupervisionCheckListGroup extends BRIS_AbstractSupervisionMoments { const CLG_SESSION = 'clg_moment_id'; protected $_checklist_group_id; protected static $_model_name = 'supervisionmomentsclg'; public function setChecklistGroupId($checklist_group_id) { $this->_checklist_group_id = $checklist_group_id; return $this; } public function saveMoment() { $this->_checkValues(); if( isset($_SESSION[self::CLG_SESSION]) ) { // Update entry // The fields has to be in order of precedence because the library don't take into account the keys $fields = array( 'progress_end' => $this->_progress, 'supervision_end' => $this->_current_time, 'id' => $_SESSION[self::CLG_SESSION], ); if( !$this->_model->dbex->is_prepared('supervisionmomentsclg::save') ) { $this->_model->dbex->prepare('supervisionmomentsclg::save', 'UPDATE supervision_moments_clg SET progress_end = ?, supervision_end = ? ' . 'WHERE id = ?'); } $this->_model->dbex->execute('supervisionmomentsclg::save', $fields); } else { // Create a new entry $fields = array( 'deelplan_id' => $this->_deelplan_id, 'checklist_group_id' => $this->_checklist_group_id, 'supervisor_user_id' => $this->_supervisor_user_id, 'supervision_start' => $this->_current_time, 'progress_start' => $this->_progress ); $res = $this->_model->insert($fields); $_SESSION[self::CLG_SESSION] = $res->id; } } }<file_sep><? $CI = get_instance(); $test_niveaus = $risico_handler->get_risico_shortnames(); // voordat we iets gaan outputten, moeten we eerst weten welke hoofdgroep namen // we uberhaupt gaan tonen. $my_hoofdgroepen = array(); $my_checklisten = $checklisten; foreach ($unieke_hoofdgroepen as $hoofdgroep_naam => $hoofdgroep_data) { foreach ($my_checklisten as $i => $checklist) { if ($hoofdgroep = @$hoofdgroep_data['checklist_map'][$checklist->id]) { if ($hoofdgroep->bevat_hoofdthema( $hoofdthema->id )) { $my_hoofdgroepen[$hoofdgroep_naam] = $hoofdgroep_data; break; } } } } foreach ($my_checklisten as $i => $checklist) { foreach ($my_hoofdgroepen as $hoofdgroep_naam => $hoofdgroep_data) if ( ($hoofdgroep = @$hoofdgroep_data['checklist_map'][$checklist->id]) && $hoofdgroep->bevat_hoofdthema( $hoofdthema->id )) continue(2); unset( $my_checklisten[$i] ); } ?> <div tag="<?=$tag?>" class="hoofdthema" style="display:none"> <h2>AMBTELIJKE MATRIX - <?=$hoofdthema->naam?></h2> <h2>MATRIX: <?=htmlentities($matrix->naam, ENT_COMPAT, 'UTF-8')?></h2> <table style="width:100%;" cellspacing="0" cellpadding="0" class="prioriteitmatrix"> <tr> <th style="border:0"></th> <? foreach ($my_hoofdgroepen as $hoofdgroep_naam => $unused): ?> <th rowspan="2"><img src="<?=site_url( '/content/verttext/' . rawurlencode( rawurlencode( rawurlencode( $hoofdgroep_naam ) ) ) . '/10/000000/f3f4f6/300' )?>" title="<?=htmlentities($hoofdgroep_naam, ENT_COMPAT, 'UTF-8')?>" /></th> <? endforeach; ?> </tr> <tr> <th class="first">Checklist</th> </tr> <? $last_checklist_index = array_pop( array_keys( $my_checklisten ) ); ?> <? foreach ($my_checklisten as $i => $checklist): ?> <? $cl_editbaar = $editbaar[$checklist->id]; ?> <tr> <td class="first <?=$i==$last_checklist_index?'last':''?>"> <?=htmlentities($checklist->naam, ENT_COMPAT, 'UTF-8')?> <? if (!$cl_editbaar): ?> <img src="<?=site_url('/files/images/letop.png')?>" title="Deze prioriteitstelling is op een risico analyse gebaseerd." style="float:right; margin-right:5px;"> <? endif; ?> </td> <? foreach ($my_hoofdgroepen as $hoofdgroep_naam => $hoofdgroep_data): $hoofdgroep = @$hoofdgroep_data['checklist_map'][$checklist->id]; ?> <td class="<?=$i==$last_checklist_index?'last':''?>"> <? if ($hoofdgroep && $hoofdgroep->bevat_hoofdthema( $hoofdthema->id )): ?> <? $p = $prioriteitstellingen[$checklist->id]->get_waarde( $hoofdgroep->id, $hoofdthema->id ); if (!array_key_exists( $p, $test_niveaus )) $p = 'zeer_hoog'; ?> <div style="min-width: 10px; height: 15px;" class="prio_<?=$p?> hoofdgroep"><?=$test_niveaus[$p]?></div> <select <?=$cl_editbaar?'':'disabled'?> style="display:none" name="checklist[<?=$checklist->id?>][<?=$hoofdgroep->id?>][<?=$hoofdthema->id?>]" <?=$cl_editbaar?'':'disabled="disabled"'?>> <option <?=$p=='zeer_laag'?'selected':''?> value="zeer_laag"><?=$test_niveaus['zeer_laag']?></option> <option <?=$p=='laag' ?'selected':''?> value="laag"><?=$test_niveaus['laag']?></option> <option <?=$p=='gemiddeld'?'selected':''?> value="gemiddeld"><?=$test_niveaus['gemiddeld']?></option> <option <?=$p=='hoog' ?'selected':''?> value="hoog"><?=$test_niveaus['hoog']?></option> <option <?=$p=='zeer_hoog'?'selected':''?> value="zeer_hoog"><?=$test_niveaus['zeer_hoog']?></option> </select> <? else: ?> - <? endif; ?> </td> <? endforeach;?> </tr> <? endforeach; ?> </table> </div> <file_sep>var popupOnClose = function(){}; function modalPopup(props) { var defaults = { align:'center', top:100, width:500, height:500, padding:10, disableColor:'#666666', disableOpacity:40, backgroundColor:'#ffffff', borderColor:'#000000', borderWeight:4, borderRadius:5, fadeOutTime:300, url:null, html:null, loadingImage:'/files/images/loading.gif', onClose: function(){}, onOpen: function(){} }; for (var k in defaults) if (!props[k] && defaults[k]) props[k] = defaults[k]; popupOnClose = props.onClose; $('body').append( '<div id="outerModalPopupDiv" class="outerModalPopupDiv" style="display:block; border-width:0px; position:absolute; z-index:100; "></div>'+ '<div id="blockModalPopupDiv" class="blockModalPopupDiv" style="width:100%; border:0px; padding:0px; margin:0px; z-index:99; position:fixed; top:0px; left:0px; "></div>' ); $('#blockModalPopupDiv').click(function() { var return_value = $('#blockModalPopupDiv').attr( 'return-value' ); if (typeof(popupOnClose) == 'function') if (popupOnClose( return_value )===false) return; $('#outerModalPopupDiv').fadeOut(props.fadeOutTime, function(){ $('#outerModalPopupDiv').remove(); }); $('#blockModalPopupDiv').fadeOut(props.fadeOutTime, function(){ $('#blockModalPopupDiv').remove(); }); }); var OUTER = $('#outerModalPopupDiv') .append('<div id="innerModalPopupDiv" class="innerModalPopupDiv"><div id="contentModalPopupDiv" style="overflow:auto; "></div></div>') .css({ top: $(document).scrollTop()+props.top, width: props.width + 'px', padding: props.borderWeight, background: props.borderColor, borderRadius: props.borderRadius, MozBorderRadius: props.borderRadius, WebkitBorderRadius: props.borderRadius }); $('#innerModalPopupDiv').css({ padding: props.padding, background: props.backgroundColor, borderRadius: props.borderRadius - 3, MozBorderRadius: props.borderRadius - 3, WebkitBorderRadius: props.borderRadius - 3 }); var CONT = $('#contentModalPopupDiv').css({ height: props.height + 'px' }); $('#blockModalPopupDiv').css({ background: props.disableColor, opacity: props.disableOpacity / 100, filter: 'alpha(Opacity=' + props.disableOpacity + ')' }); if(props.align=="center") { OUTER.css({ marginLeft: (-1 * (props.width / 2)) + 'px', left: '50%' }); } else if(props.align=="left") { OUTER.css({ marginLeft: '0px', left: '10px' }); } else if(props.align=="right") { OUTER.css({ marginRight: '0px', right: '10px' }); } else { OUTER.css({ marginLeft: (-1 * (props.width / 2)) + 'px', left: '50%' }); } $('#blockModalPopupDiv').css({ height: screen.height+'px', display: 'block' }); if (props.html) { CONT.html( props.html ); } else if (props.url.search(/\.(jpg|jpeg|gif|png|bmp)/i) != -1) { CONT.html('<div align="center"><img src="' + url + '" border="0" /></div>'); } else { CONT.html('<div align="center"><img src="' + props.loadingImage + '" border="0" /></div>'); $.get(props.url, function(R,stat){ while (match = /<script.*?>(.*?)<\/script>/.exec(R)) { if (match[1]) eval( match[1] ); } CONT.html(R); }, 'html'); } if (typeof( props.onOpen ) == 'function') props.onOpen(); return CONT; } function getPopup() { return $('#outerModalPopupDiv'); } function closePopup( option_return_value ) { // NOTE: option_return_value can only be a string or int value! $('#blockModalPopupDiv').attr( 'return-value', option_return_value ); $('#blockModalPopupDiv').trigger( 'click' ); } <file_sep><?php class CI_BelImport { function create( $filename, $on_invalid_code ) { return new BELImport( $filename, $on_invalid_code ); } } class BELImport { private $CI; private $filename; private $lines = array(); private $on_invalid_code; private $count = 0; private $num_cols = 11; private $users_mapping = array(); public function __construct( $filename, $on_invalid_code='fail' ) { $this->CI = get_instance(); $success = false; $messages = array(); foreach (array( "\t", ';', ',' ) as $separator ) { try { $this->_try_read( $filename, $separator ); $success = true; break; } catch (Exception $e) { // fail, try other separator $messages[] = 'Separator: ' . $separator . ' msg: ' . $e->getMessage(); //throw new Exception('Separator: ' . $separator . ' msg: ' . $e->getMessage()); } } if (!$success) { $messages_str = implode("<br />", $messages); //d($messages); exit; throw new Exception( 'Kon CSV bestand niet importeren als bestand met '.$this->num_cols.' kolommen. Geprobeerd met punt komma, komma en TAB als scheidingsteken.' . '<br /><b>Details</b> <i>(N.B. de laatste regel geeft doorgaans de precieze oorzaak)</i>:<br />' . $messages_str); } // remove top line (header) array_shift( $this->lines ); // deal with invalid code handler switch ($on_invalid_code) { case 'fail': case 'ignore': $this->on_invalid_code = $on_invalid_code; break; default: throw new Exception( 'Ongeldige waarde voor $on_invalid_code' ); } } private function _try_read( $filename, $separator ) { $this->filename = $filename; // In order to be able to properly handle files that were created under Windows, Mac, Unix, etc., make sure each and every file contains the same // line separator $nl = "\n"; $fileAsString = file_get_contents($this->filename); $fileAsString = str_replace("\r\n", $nl, $fileAsString); $fileAsString = str_replace("\n\r", $nl, $fileAsString); $fileAsString = str_replace("\r", $nl, $fileAsString); $fileAsString = str_replace("\n", $nl, $fileAsString); file_put_contents($this->filename, $fileAsString); // Now open the file 'for real' and process it. $f = fopen( $this->filename, "rb" ); if (!$f) throw new Exception( 'Interne fout bij het inlezen van het bestand: ' . $filename ); $line = 0; while (($row = fgetcsv( $f, 0, $separator )) !== false) { ++$line; // Note: if fgetscsv reads an empty line, it doesn't result in FALSE, nor in an empty array, but rather, in an array of which the first element is null! // That particular situation is not trapped by merely checking using the 'empty' function; hence the extention with the 'is_null' check on the first element! if (empty($row) || is_null($row[0])) continue; if (sizeof( $row ) < $this->num_cols) throw new Exception( 'Regel ' .$line . ' is niet leeg en bevat geen '.$this->num_cols.' kolommen, maar ' . sizeof($row) . '!' ); foreach ($row as $k => &$v) $v = trim($v); $this->lines[] = $row; } // Create (and register) the users mapping array. For now all 'foreign_id' values are unique, so we use that as key. // At a later stage we may need something more fancy (possibly limited by import source, etc.). Implement that if the need to do so occurs. $res = $this->CI->db->query( 'SELECT * FROM gebruikers_import_mapping' ); foreach ($res->result() as $row) { $cur_key = $row->foreign_id; $this->users_mapping["$cur_key"] = $row->btz_gebruiker_id; } } public function run() { // Check if the currently logged in user belongs to a community that allows existing dossiers to be overwritten. $this->CI->load->model( 'gebruiker' ); $klant_ids_to_allow_existing_dossier_updates = array(1, 131); $user_klant_id = $this->CI->gebruiker->get_logged_in_gebruiker()->klant_id; $allow_update_of_existing_dossiers = in_array($user_klant_id, $klant_ids_to_allow_existing_dossier_updates); $this->CI->load->model( 'dossier' ); $this->count = 0; foreach ($this->lines as $i => $line) { if (empty( $line ) || !$line[0]) continue; foreach ($line as &$col) { $new = @iconv( "Windows 1252", "UTF-8", $col ); if ($new === false) { $new = @iconv( "CP437", "UTF-8", $col ); if ($new === false) { $new = @iconv( "ISO-8859-1", "UTF-8", $col ); if ($new === false) $new = @iconv( "ISO-8859-1", "UTF-8//IGNORE", $col ); } } $col = $new; } $kenmerk = trim( $line[0] ); $beschrijving = $line[5]; // Dossiernaam //$aanmaak_datum = strtotime( $line[4] ); $aanmaak_datum = strtotime( str_replace('/', '-', $line[6]) ); $locatie_adres = $line[2]; //$locatie_postcode = ''; $locatie_postcode = str_replace(' ', '', $line[3]); $locatie_woonplaats = $line[4]; $locatie_kadastraal = ''; $locatie_sectie = ''; $locatie_nummer = ''; // Try to perform a look-up to determine the proper 'dossier verantwoordelijke', and if none could be determined, use the ID of the currently // logged in user. $foreign_id = $line[9]; $user_id_to_use = (empty($foreign_id) || empty($this->users_mapping["$foreign_id"])) ? $this->CI->gebruiker->login->get_user_id() : $this->users_mapping["$foreign_id"]; //d($user_id_to_use); continue; $code_to_use = (!empty($line[1])) ? $line[1] : 600; // If the 'code' column was left empty, set it to '600' $opmerkingen = $this->_convert_code( $code_to_use ) . "\n" . $line[8]; if ($opmerkingen === false) continue; $gepland_datum = date( 'Y-m-d', strtotime( str_replace('/', '-', $line[7]) ) ); // niet langer gebruikt!!! $herkomst = 'handmatig'; // This column is not really used, but it is used as a marker column, to enforce programs to created a correct amount of columns even if the // (previously) last real column doesn't contain a value. $end_column = $line[10]; // see if dossier with this kenmerk already exists $dossier = $this->CI->dossier->get_by_kenmerk( $kenmerk ); if ($dossier) { // We no longer allow ALL users to overwrite existing dossier data. Instead, only those of specific communities that // have explicitly asked for this (<NAME>, Imotep, ...) get this functionality. if ($allow_update_of_existing_dossiers) { // save returns false when there is no change, so check before we do anything if (substr( $dossier->beschrijving, 0, 256 ) != substr( $beschrijving, 0, 256 ) || $dossier->aanmaak_datum != $aanmaak_datum || $dossier->locatie_adres != $locatie_adres || $dossier->locatie_postcode != $locatie_postcode || $dossier->locatie_woonplaats != $locatie_woonplaats || $dossier->gebruiker_id != $user_id_to_use || $dossier->opmerkingen != $opmerkingen) { $dossier->beschrijving = $beschrijving; $dossier->aanmaak_datum = $aanmaak_datum; $dossier->locatie_adres = $locatie_adres; $dossier->locatie_postcode = $locatie_postcode; $dossier->locatie_woonplaats = $locatie_woonplaats; $dossier->gebruiker_id = $user_id_to_use; $dossier->opmerkingen = $opmerkingen; if (!$dossier->save()) throw new Exception( 'Interne databasefout bij het bijwerken van dossier ' . $kenmerk ); unset( $dossier ); } } // if ($allow_update_of_existing_dossiers) } else { $this->CI->dossier->add( $kenmerk, $beschrijving, $aanmaak_datum, $locatie_adres, $locatie_postcode, $locatie_woonplaats, $locatie_kadastraal, $locatie_sectie, $locatie_nummer, $opmerkingen, '', $herkomst, $user_id_to_use ); $this->count++; } } //exit; } public function get_import_count() { return $this->count; } private function _convert_code( $code ) { switch ($code) { case 100: return 'Omgevingsvergunning regulier'; case 110: return 'Lichte bouwvergunning'; case 120: return 'Reguliere bouwvergunning'; case 130: return '1e fase bouwvergunning'; case 131: return '2de fase bouwvergunning'; case 132: return 'Herziening 1e fase'; case 200: return 'Omgevingsvergunning uitgebreid'; case 300: return 'Sloopvergunning'; case 400: return 'Sloopmelding'; case 500: return 'Gemeentelijk monument'; case 510: return 'Rijksmonument'; case 600: return 'Overige vergunningen'; case 900: return 'Handhaving'; default: if ($this->on_invalid_code == 'fail') throw new Exception( 'Ongeldige opmerkingen code ' . $code . ' gevonden ' ); else return false; } } }<file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.hoofdgroep_volgorde')?></h1> <? $this->load->view( 'checklistwizard/_volgorde', array( 'entries' => $hoofdgroepen, 'get_id' => function( $hg ) { return $hg->id; }, 'get_image' => function( $hg ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $hg ) { return $hg->naam; }, 'store_url' => '/checklistwizard/hoofdgroep_volgorde/' . $checklist->id, 'return_url' => '/checklistwizard/hoofdgroepen/' . $checklist->id, ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>PDFAnnotator.GUI.Zoom = PDFAnnotator.Base.extend({ init: function( gui, zoomconfig ) { this._super(); this.registerEventType( 'zoom' ); /* store tools config */ this.gui = gui; this.zoomconfig = zoomconfig; /* install show list handler. */ this.installListHandler(); /* install zoom level clicks so that zoom actually changes */ this.installZoomSelectHandler(); /* install resize handler to resize when window resizes */ this.installResizeHandler(); }, /* initialize as soon as all subsystems are setup */ initialize: function() { }, installResizeHandler: function() { var thiz = this; PDFAnnotator.Window.prototype.getInstance().on( 'resize', function( window, data ){ var main = thiz.zoomconfig.mainContainer; main.css( 'top', ((data.top + data.height) - (main.outerHeight() + 1)) + 'px' ); }); }, installListHandler: function() { var thiz = this; this.zoomconfig.mainContainer.click(function(){ if (thiz.zoomconfig.current.is(':visible')) { thiz.zoomconfig.current.fadeOut( 'fast' ); thiz.zoomconfig.list.fadeIn( 'fast' ); } else { thiz.zoomconfig.current.fadeIn( 'fast' ); thiz.zoomconfig.list.fadeOut( 'fast' ); } }); }, installZoomSelectHandler: function() { var thiz = this; this.zoomconfig.list.find('[zoom]').click(function(){ var zoom = parseInt( $(this).attr( 'zoom' ) ); thiz.setZoomLevel( zoom / 100 ); }); }, /** Changes the zoom level in the engine and the GUI. */ setZoomLevel: function( level ) { this.setZoomLevelText( level ); this.gui.engine.setZoomLevel( level ); this.dispatchEvent( 'zoom', {level:level} ); }, /** Changes the zoom level the GUI ONLY. */ setZoomLevelText: function( level ) { this.zoomconfig.current.text( Math.round( level * 100 ) + '%' ); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <form method="POST" enctype="multipart/form-data"> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'CSV bestanden', 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'onclick' => '$(this).next().find(\'[type=radio]\').attr(\'checked\',\'checked\');' ) ); ?> <label style="font-size:140%; font-weight: bold"> <input type="radio" name="type" value="csv" checked>CSV bestanden gebruiken </label> <p> Via deze pagina kan een set ITP csv bestanden worden geimporteerd als nieuwe checklistgroep.<br/> <b>LET OP!</b> De CSV bestanden moeten een header regel bevatten, zodat het systeem de kolommen kan herkennen! </p> <table cellpadding="3" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 150px;">Tabel</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 150px;">Upload</th> </tr> <? foreach ($tabellen as $nummer => $omschrijving): ?> <tr> <td><?=$omschrijving?></td> <td><input type="file" name="tabel<?=$nummer?>" /></td> </tr> <? endforeach; ?> <tr> <td colspan="2" style="height: 32px;"></td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'ZIP bestand', 'expanded' => true, 'width' => '100%', 'height' => 'auto' ) ); ?> <label style="font-size:140%; font-weight: bold"> <input type="radio" name="type" value="zip">ZIP bestand gebruiken </label> <p> Via deze pagina kan een set ITP csv bestanden worden geimporteerd die zijn ingepakt in een ZIP bestand.<br/> <b>LET OP!</b> De CSV bestanden moeten een header regel bevatten, zodat het systeem de kolommen kan herkennen! </p> <table cellpadding="3" cellspacing="0"> <tr> <td>ZIP bestand:</td> <td><input type="file" name="zip" /></td> </tr> <tr> <td colspan="2" style="height: 32px;"></td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <br/> <table> <tr> <th style="text-align:left">Naam nieuwe checklistgroep:</th> <td><input type="text" name="checklistgroepnaam" value="<?=$checklistgroepnaam?>" size="32" maxlength="128" /></td> </tr> <tr> <th style="text-align:left">Testrun:</th> <td><input type="checkbox" name="testrun" <?=$is_testrun?'checked':''?> /></td> </tr> </table> <p> <input type="submit" value="Opsturen" /> <span style="font-style:italic; display: none">Even geduld a.u.b....</span> </p> </form> <script type="text/javascript"> $(document).ready(function(){ $('form').submit(function(){ $('[type=submit]').attr( 'disabled', 'disabled' ); $('[type=submit]').next().show(); return true; }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Checklist import')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => '', 'width' => '920px' ) ); ?> <h2>Checklist import <?=$is_testrun?'<i>TEST</i>':''?> succesvol afgerond!</h2> <? if ($is_testrun): ?> <p> <span style="color:red">Er is nog niets in de database opgeslagen!</span> Er is slechts een test uitgevoerd of de data te importeren viel. Om de data wel op te slaan in de database, ga opnieuw naar de checklist import pagina, zet alle instellingen en selecteer het CSV bestand en <b>vink de "test run" checkbox uit</b>. </p> <p> Test succesvol afgerond. </p> <? else: ?> <p> Checklist geimporteerd in de database! </p> <? endif; ?> <h2>Aantallen</h2> <table style="width:300px"> <tr> <td>Queries:</td> <td><?=sizeof($queries)?></b> </tr> <tr> <td>Aantal geimporteerde checklistgroepen:</td> <td><?=$counts['checklistgroepen']?></b> </tr> <tr> <td>Aantal geimporteerde checklisten:</td> <td><?=$counts['checklisten']?></b> </tr> <tr> <td>Aantal geimporteerde hoofdgroepen:</td> <td><?=$counts['hoofdgroepen']?></b> </tr> <tr> <td>Aantal geimporteerde categorieen:</td> <td><?=$counts['categorieen']?></b> </tr> <tr> <td>Aantal geimporteerde hoofdthemas:</td> <td><?=$counts['hoofdthemas']?></b> </tr> <tr> <td>Aantal geimporteerde themas:</td> <td><?=$counts['themas']?></b> </tr> <tr> <td>Aantal geimporteerde vragen:</td> <td><?=$counts['vragen']?></b> </tr> <tr> <td>Aantal geimporteerde grondslagen:</td> <td><?=$counts['grondslagen']?></b> </tr> <tr> <td>Aantal geimporteerde artikelen:</td> <td><?=$counts['artikelen']?></b> </tr> </table> <h2>Speciale tekens</h2> <? if (sizeof($speciale_tekens_teksten)): ?> <div style="height:auto; padding: 20px; background-color: #eee; border: 1px solid #777;"> <i>Hieronder staan alle teksten die speciale karakters bevatten. Controleer of hier fouten in zijn geslopen. Als dit zo is, dan is de verkeerde import encoding aangegeven!</i> </div> <table> <? foreach ($speciale_tekens_teksten as $i => $tekst): ?> <tr style="background-color: <?=($i%2)?'#fff':'#eee'?>"> <td style="background-color: transparent; padding: 5px;"><?=$tekst?></td> </tr> <? endforeach; ?> </table> <? else: ?> <p> <b>Er zijn geen "speciale tekens" gevonden in de geimporteerde tekst, of de import encoding was UTF-8.</b> </p> <? endif; ?> <h2>Opties</h2> <input type="button" value="Terug naar checklist import" onclick="location.href='/admin/checklist_import';" /> <? if (!$is_testrun): ?> <input type="button" value="Naar checklist wizard" onclick="location.href='/checklistwizard';" /> <? endif; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <input type="button" value="Toon queries" onclick="$(this).hide(); $('#queryList').show();" style="margin-top:20px"> <div id="queryList" style="display:none"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => '', 'width' => '920px' ) ); ?> <pre><?=implode( "\n", $queries )?></pre> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> </div> <? $this->load->view('elements/footer'); ?> <file_sep><?php class DossierBase extends Controller { protected function _dossier_list( $mode=null, $pagenum=null, $pagesize=null, $sortfield=null, $sortorder=null, $search=null ) { // beheer zoekinstellingen $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'dossiers' ); //echo "*** 0 ***<br />"; //d($viewdata['search']); if (!is_array( $viewdata )) $viewdata = array( 'mode' => 'mijn', 'pagenum' => 0, 'pagesize' => 10, 'search' => '', 'sortfield' => 'gepland_datum', 'sortorder' => 'asc', ); // !!! TODO (OJG - 2015-03-13): // For some VERY bizarre reason in many situations the above call sets the search field to the value 'images'. This comes from the above // $viewdata = $this->zoekinstelling->get( 'dossiers' ); call that gets this value from the DB. At this moment the reason for that text // being present there is not yet known and needs to be investigated. // For now, we simply suppress it. if ($viewdata['search'] == 'images') $viewdata['search'] = ''; if (!is_null( $mode )) $viewdata['mode'] = $mode; if (!is_null( $pagenum )) $viewdata['pagenum'] = $pagenum; if (!is_null( $pagesize )) $viewdata['pagesize'] = $pagesize; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; // make sure input is valid if (!in_array( $viewdata['mode'], array( 'mijn', 'alle', 'archief'))) $viewdata['mode'] = 'mijn'; if (!is_int( $viewdata['pagenum'] )) $viewdata['pagenum'] = intval( $viewdata['pagenum'] ); if (!is_int( $viewdata['pagesize'] )) $viewdata['pagesize'] = intval( $viewdata['pagesize'] ); $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; // initialize $this->load->library( 'planningdata' ); $this->load->model( 'dossier' ); $this->load->model( 'gebruiker' ); //get user $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $my_group_users=cut_array($gebruiker->groups_users, "user_id"); // load dossiers if($mode) $viewdata['mode']=$mode; $unusedref = null; switch ($viewdata['mode']) { case 'mijn': $list = array_merge( $this->dossier->get_by_gebruiker( false, $unusedref, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_dossiers_by_toezichthouder( $viewdata['search'], $viewdata['mode'] == 'archief' ) ); break; case 'only_group': $list = array_merge( //$this->dossier->get_by_gebruiker(false, $unusedref, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_by_gebruikers($my_group_users, $unusedref, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_van_collegas($my_group_users, $unusedref, false, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_dossiers_by_toezichthouder( $viewdata['search'], $viewdata['mode'] == 'archief' ) ); break; case 'archief': case 'archief': case 'alle': $list = array_merge( $this->dossier->get_by_gebruiker( false, $unusedref, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_van_collegas( false, $unusedref, false, $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_dossiers_by_toezichthouder( $viewdata['search'], $viewdata['mode'] == 'archief' ), $this->dossier->get_dossiers_by_klant( false, $unusedref, $viewdata['search'], $viewdata['mode'] == 'archief' ) ); break; default: $list = array(); // shouldn't happen break; } // filter out doubles $dossiers = array(); foreach ($list as $dossier){ $dossier=(object)$dossier; $dossiers[$dossier->id] = (object)$dossier; } $dossiers = array_values( $dossiers ); $klant = $gebruiker->get_klant(); // do sorting, except when it's gepland_datum, then it's already sorted $sortfactor = $viewdata['sortorder']=='asc' ? 1 : -1; // 'locatie' => 'locatie_woonplaats', $real_sort_field = array( 'herkomst' => 'herkomst', 'id_nummer' => 'kenmerk', 'beschrijving' => 'beschrijving', 'locatie' => 'locatie_adres', 'gepland_datum' => 'gepland_datum', ); $actualsortfield = @ $real_sort_field[$viewdata['sortfield']]; switch ($viewdata['sortfield']) { case 'id_nummer': usort( $dossiers, function( $a, $b ) use ($actualsortfield, $sortfactor) { return strnatcmp( $a->$actualsortfield, $b->$actualsortfield ) * $sortfactor; }); break; case 'herkomst': case 'beschrijving': case 'locatie': case 'gepland_datum': usort( $dossiers, function( $a, $b ) use ($actualsortfield, $sortfactor) { return strcasecmp( $a->$actualsortfield, $b->$actualsortfield ) * $sortfactor; }); break; case 'gebruiker': $gebruikers = array(); foreach ($klant->get_gebruikers() as $gebruiker) $gebruikers[ $gebruiker->id ] = $gebruiker->volledige_naam; usort( $dossiers, function( $a, $b ) use ($sortfactor, $gebruikers) { return strnatcmp( @$gebruikers[ $a->gebruiker_id ], @$gebruikers[ $b->gebruiker_id ] ) * $sortfactor; }); break; default: break; } // take part we need $total = sizeof($dossiers); $pages = $viewdata['pagesize'] != 'alle' ? ceil( $total / $viewdata['pagesize'] ) : 0; if ($viewdata['pagesize']!='alle') { if ($viewdata['pagenum'] >= $pages) $viewdata['pagenum'] = $pages - 1; if ($viewdata['pagenum'] < 0) $viewdata['pagenum'] = 0; $startindex = $viewdata['pagesize'] * $viewdata['pagenum']; $dossiers = array_slice( $dossiers, $startindex, $viewdata['pagesize'] ); } // sla zoekinstellingen op $this->zoekinstelling->set( 'dossiers', $viewdata ); return array( 'dossiers' => $dossiers, 'viewdata' => array_merge( $viewdata, array( 'total' => $total, 'pages' => $pages, ) ), 'klant' => $klant, ); } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Gebruiker bewerken')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('groups_relationship'), 'width' => '100%' )); ?> <form name="distributeur_add_form" id="distributeur_add_form" method="post" action="/admin/distributeurs_relationship_save/<?=$id?>"> <table class="admintable" width="100%" cellpadding="0" cellspacing="0"> <tr> <th style="text-align: left; padding-left: 0px; border-bottom: 2px solid #777;"><?=tg('group_name');?></th> <th style="text-align: left; padding-left: 0px; border-bottom: 2px solid #777;"></th> </tr> <? foreach ($data as $i => $acc){ ?> <tr class="<?=($i % 2)?'':'zebra'?>"> <td valign="top"><h5><?=$acc->garage_naam?></h5></td> <td valign="top"> <?=($acc->map_id)?"<input type='checkbox' checked='checked' name='$acc->id'>":"<input type='checkbox' name='$acc->id'"?> </td> </tr> <? }?> </table> <br><br> <table> <tr><td><button type="submit" class="greenbutton">Opslaan</button></td></tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><? $test_niveaus = $risico_handler->get_risico_shortnames(); ?> <div tag="<?=$tag?>" class="hoofdthema" style="display:none"> <h2>BESTUURLIJKE MATRIX</h2> <h2>MATRIX: <?=htmlentities($matrix->naam, ENT_COMPAT, 'UTF-8')?></h2> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> <b>Klik op een hoofdthema in de tabel om de bestuurlijke matrix in meer detail te bekijken en bewerken.</b><br/> <table style="width:100%;" cellspacing="0" cellpadding="0" class="prioriteitmatrix bestuurlijkematrix"> <tr> <th style="border:0"></th> <? foreach ($hoofdthemas as $hoofdthema): ?> <th rowspan="2"> <img style="cursor:pointer; margin-bottom: 5px;" class="thema_selectie" tag="<?=$hoofdthema->id?>" src="<?=site_url( '/content/verttext/' . rawurlencode( rawurlencode( rawurlencode( $hoofdthema->naam ) ) ) . '/10/000000/f3f4f6/200' )?>" title="<?=htmlentities($hoofdthema->naam, ENT_COMPAT, 'UTF-8')?>" /><br/> <? if (!$readonly): ?> <select tag="<?=$hoofdthema->id?>" class="globaal" > <option selected disabled value="">-</option> <option value="zeer_laag"><?=$test_niveaus['zeer_laag']?></option> <option value="laag"><?=$test_niveaus['laag']?></option> <option value="gemiddeld"><?=$test_niveaus['gemiddeld']?></option> <option value="hoog"><?=$test_niveaus['hoog']?></option> <option value="zeer_hoog"><?=$test_niveaus['zeer_hoog']?></option> </select> <? endif; ?> </th> <? endforeach; ?> </tr> <tr> <th class="first">Checklist</th> </tr> <? $last_checklist_index = array_pop( array_keys( $checklisten ) ); ?> <? foreach ($checklisten as $i => $checklist): ?> <? $cl_editbaar = !$readonly && $editbaar[$checklist->id]; ?> <tr checklist_id="<?=$checklist->id?>"> <td class="first <?=$i==$last_checklist_index?'last':''?>"> <? if (!$readonly): ?> <a href="javascript:void(0);" onclick="if (confirm( 'Nu naar de risicoanalyse voor deze checklist gaan? U verliest eventuele niet opgeslagen wijzigingen aan de matrix!' )) location.href='<?=site_url('/instellingen/risicoanalyse_effecten/' . $checklist->id . '/' . $matrix->id)?>';"><?=htmlentities($checklist->naam, ENT_COMPAT, 'UTF-8')?><a> <? else: ?> <?=htmlentities($checklist->naam, ENT_COMPAT, 'UTF-8')?> <? endif; ?> <? if (!$readonly && !$cl_editbaar): ?> <img src="<?=site_url('/files/images/letop.png')?>" title="Deze prioriteitstelling is op een risico analyse gebaseerd." style="float:right; margin-right:5px;"> <a style="float:right; margin-right:5px;" href="javascript:void(0);" onclick="if (confirm( 'De risico analyse voor deze checklist werkelijk verwijderen? U kunt deze actie NIET ongedaan maken!' )) location.href='<?=site_url('/instellingen/risicoanalyse_verwijderen/' . $checklist->id . '/' . $matrix->id)?>';" title="Deze risico analyse voor deze checklist verwijderen." style="float:right; margin-right:5px;"> <img src="<?=site_url('/files/images/delete.png')?>"> </a> <? endif; ?> </td> <? foreach ($hoofdthemas as $hoofdthema): ?> <? $p = 'zeer_hoog'; ?> <td hoofdthema_id="<?=$hoofdthema->id?>"> <div style="min-width: 10px; height: 15px;" class="prio_tobedetermined hoofdgroep">-</div> <? if ($cl_editbaar): ?> <select style="display:none"> <option value="zeer_laag"><?=$test_niveaus['zeer_laag']?></option> <option value="laag"><?=$test_niveaus['laag']?></option> <option value="gemiddeld"><?=$test_niveaus['gemiddeld']?></option> <option value="hoog"><?=$test_niveaus['hoog']?></option> <option value="zeer_hoog"><?=$test_niveaus['zeer_hoog']?></option> </select> <? endif; ?> </td> <? endforeach;?> </tr> <? endforeach; ?> </table> </div> <file_sep>var PDFAnnotator = {}; PDFAnnotator.Base = Observable.extend({ init: function() { /* initialize base class */ this._super(); }, findDomElementOffset : function(dom) { var e1=dom, e2=dom; var x=0, y=0; if(e1.offsetParent) { do { x += e1.offsetLeft; y += e1.offsetTop; } while(e1 = e1.offsetParent); } while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') { x -= e2.scrollLeft; y -= e2.scrollTop; } return new PDFAnnotator.Math.IntVector2( x, y ); }, elementInDOM: function(e) { if (e) { while (e = e.parentNode) { if (e == document) { return true; } } } return false; }, debugEnabled: true, /* static member shared among ALL objects! */ log: function( message ) { if (this.debugEnabled && typeof(console)=='object' && typeof(console.log)=='function') console.log( message ); } }); <file_sep><? require_once 'base.php'; class UsergroupsrelationResult extends BaseResult { function UsergroupsrelationResult( &$arr ) { parent::BaseResult( 'usergroupsrelation', $arr ); } } class Usergroupsrelation extends BaseModel { private $_cache = array(); function usergroupsrelation(){ parent::BaseModel( 'UsergroupsrelationResult', 'group_user_map'); } public function check_access( BaseResult $object ) { return; } // public function save( $postdata, $do_transaction=true, $alias=null, $error_on_no_changes=true ){ // return $this->insert($postdata ); // } public function get_group_by_uid($uid, $klant_id){ if($uid && $klant_id){ $sql = "SELECT users_groups.id, users_groups.garage_naam, tab.id as map_id FROM users_groups LEFT JOIN group_user_map AS tab ON (users_groups.id=tab.users_group_id AND tab.user_id=?) WHERE users_groups.klant_id=?"; $stmt_name = 'group_user_map::by_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $uid, $klant_id) ))) throw new Exception( 'Usergroupsrelation model exeption by method get_distributeur_by_uid'); $result = $res->result(); if(isset($result)) return $result; } } public function get_groups_by_uid($uid){ if($uid){ $result = $this->db->select ( 'users_group_id' )->where ( 'user_id',$uid)->get ( 'group_user_map' )->result_array(); if(isset($result)) return $result; } } public function get_users_by_uids($uids){ if($uids){ $uids=implode(",", $uids); $result = $this->db->select ( 'user_id' )->where ( 'users_group_id IN ('.$uids.')')->group_by('user_id')->get ( 'group_user_map' )->result_array(); if(isset($result)) return $result; } } public function get_users_by_gid($gid,$klant_id){ if($gid&&$klant_id){ //group_user_map $sql = "SELECT * FROM group_user_map LEFT JOIN users_groups ON (users_groups.klant_id=?) WHERE users_group_id = ?"; $stmt_name = 'group_user_map::by_users_group_id'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array($klant_id,$gid)))) throw new Exception( 'Usergroupsrelation model exeption by method get_users_by_gid'); $result = $res->result(); if(isset($result)) return $result; } } public function delete($uid){ if($uid){ $sql="DELETE FROM group_user_map WHERE group_user_map.user_id=?"; $stmt_name = 'group_user_map::by_uid'; $this->_CI->dbex->prepare( $stmt_name, $sql ); if (!($res = $this->_CI->dbex->execute( $stmt_name, array( $uid ) ))) throw new Exception( 'Usergroupsrelation model exeption by method delete'); } } } ?><file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.rapportage::checklisten', 'Checklisten', NOW(), 0), ('dossiers.rapportage::checklisten', 'Checklisten', NOW(), 1), ('dossiers.rapportage::checklisten', 'Checklisten', NOW(), 8) ; <file_sep>-- Matrixmeppen Extending (DMM) mappingen.finalmapping.save /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; REPLACE INTO `help_buttons` (`tag`, `taal`, `tekst`, `laast_bijgewerkt_op`) VALUES ('mappingen.finalmapping.save_map_period', 'nl', 'Available periods: \n10.02 - 10.03\n01.04 - 30.04\n12.06 - 31.10\nNot valid information!!!\n', NOW()); DROP TABLE IF EXISTS matrixmap_checklisten; CREATE TABLE `matrixmap_checklisten` ( id INT NOT NULL AUTO_INCREMENT, `matrixmap_id` INT NOT NULL, `checklist_id` INT NOT NULL, `date` DATE COMMENT 'It has meaning only the day and month.', `until` DATE COMMENT 'It has meaning only the day and month.', PRIMARY KEY (id), CONSTRAINT FK_matrixmapchcklls_matrix_mappingen FOREIGN KEY (matrixmap_id) REFERENCES matrix_mappingen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_matrixmapchcklls_btchecklisten FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB; DELIMITER $$ CREATE TRIGGER `default_date_until` BEFORE INSERT ON `matrixmap_checklisten` FOR EACH ROW BEGIN if ( isnull(new.`date`) ) then set new.`date`=CURRENT_DATE; end if; if ( isnull(new.`until`) ) then set new.`until`=DATE_ADD(new.`date`, INTERVAL 1 YEAR); set new.`until`=DATE_SUB(new.`until`, INTERVAL 1 DAY); end if; END $$ delimiter ; ALTER TABLE artikel_vraag_mappen ADD COLUMN map_checklist_id INT DEFAULT NULL AFTER `id`; ALTER TABLE artikel_vraag_mappen ADD CONSTRAINT FK_artikel_vraag_mappen_matrixmap_checklisten_id FOREIGN KEY (map_checklist_id) REFERENCES matrixmap_checklisten(id) ON DELETE CASCADE ON UPDATE CASCADE; INSERT INTO `matrixmap_checklisten` (`matrixmap_id`,`checklist_id`) SELECT `id`,`checklist_id` FROM `matrix_mappingen` ; UPDATE artikel_vraag_mappen `am` LEFT JOIN `matrixmap_checklisten` `mc` ON `am`.matrix_id = `mc`.matrixmap_id SET `am`.map_checklist_id =`mc`.`id`; ALTER TABLE artikel_vraag_mappen DROP FOREIGN KEY FK_artikel_vraag_mappen_matrix_mappingen_id; ALTER TABLE artikel_vraag_mappen DROP COLUMN matrix_id; ALTER TABLE artikel_vraag_mappen DROP INDEX UK_artikel_vraag_mappen, ADD UNIQUE INDEX UK_artikel_vraag_mappen (bt_riskprofiel_id, artikel_id, vraag_id); ALTER TABLE artikel_vraag_mappen CHANGE COLUMN map_checklist_id map_checklist_id INT(11) NOT NULL; ALTER TABLE artikel_vraag_mappen DROP INDEX UK_artikel_vraag_mappen, ADD UNIQUE INDEX UK_artikel_vraag_mappen (map_checklist_id, bt_riskprofiel_id, artikel_id, vraag_id); -- ALTER TABLE matrix_mappingen -- DROP FOREIGN KEY FK_matrix_mappingen_bt_checklisten_id; -- -- ALTER TABLE matrix_mappingen -- DROP COLUMN checklist_id, -- DROP INDEX FK_matrix_mappingen_bt_checklisten_id; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep><? // gezet zijn: // // $deelplan - object van deelplan in kwestie // $checklistgroep - object van checklistgroep in kwestie // $checklist - kan null zijn, anders niet-integreerbare checklist in kwestie // $scope - scope van dit toezicht, ofwel checklistgroep naam, ofwel dat plus de checklist naam // // $mag_toezichthouder_toekennen - wat de naam zegt // $toezichthouders - lijst van alle toezichthouders // $toezichthouder - object (of null), huidige toezichthouder // $toezichthouder_naam - altijd gezet, beschrijving van huidige gebruiker // // $mag_matrix_toekennen - wat de naam zegt // $matrices - lijst van alle matrices // $matrix - object (of null), huidige matrix // $matrix_naam - altijd gezet, beschrijving van huidige matrix // // $mag_initiele_datum_toekennen - wat de naam zegt // $datum - datum (of leeg), huidige initiele plan datum // $datum_desc - omschrijving van huidige datum // $start_tijd - start tijd van afspraak initiele datum, mag leeg/null zijn // $eind_tijd - eind tijd van afspraak initiele datum, mag leeg/null zijn // // $hercontrole_datum - wat de naam zegt // // is dit in de toekomst? $past = strtotime( '01-01-1980' ); $verste_datum = max( $datum ? strtotime($datum) : $past, $hercontrole_datum ? strtotime($hercontrole_datum) : $past ); $is_toekomst = ($verste_datum == $past) || ($verste_datum >= strtotime(date('d-m-Y 00:00:00'))); $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $is_bouwnummer = $klant->heeft_toezichtmomenten_licentie == 'ja' && $deelplan->geintegreerd=='nee'; $toezichtDisallowedForProjectStatusValues = array('open', 'toets gestart', 'toets bouwfase', 'toezicht open'); // For Woningborg we have to hide the toezichtbutton in certain cases. $hideToezichtButton = ( ($klant->heeft_toezichtmomenten_licentie == 'ja') && (!empty($project_status) && in_array($project_status, $toezichtDisallowedForProjectStatusValues)) ); ?> <tr <?=$is_toekomst ? '' : 'style="color:red;"' ?>> <td class="container rounded5" colspan="<?=($is_bouwnummer?10:9) ?>" style="padding: 5px 0px;"> <table class="contents" width="100%"> <tr> <td width="16"></td> <!-- checklistgroep naam --> <td width="<?=$this->is_Mobile?170:230?>"><?=$scope?></td> <? if($is_bouwnummer): ?> <!-- Bouwnummer --> <td width="80"><?=$bouwnummer ?></td> <? endif; ?> <!-- toezichthouder --> <td width="140"> <? if ($mag_toezichthouder_toekennen): ?> <img src="<?=site_url('/files/images/edit.png')?>" style="cursor:pointer" title="Wijzig toezichthouder" class="toezichthouder_text" checklist_groep_id="<?=$checklistgroep->id?>" checklist_id="<?=$checklist ? $checklist->id : ''?>" bouwnummer="<?=$bouwnummer ?>" /> <span><?=$toezichthouder_naam?></span> <select class="hidden" style="width:100px" deelplan_id="<?=$deelplan->id?>"> <? foreach ($toezichthouders as $g): ?> <option <?=($g->id == ($toezichthouder ? $toezichthouder->id : 0)) ? 'selected' : ''?> value="<?=$g->id?>"> <?=$g->get_status()?> </option> <? endforeach; ?> </select> <? else: ?> <?=$toezichthouder_naam?> <? endif; ?> </td> <!-- matrix --> <td width="140"> <? if ($mag_matrix_toekennen): ?> <img src="<?=site_url('/files/images/edit.png')?>" style="cursor:pointer" title="Wijzig matrix" class="matrix_text" checklist_groep_id="<?=$checklistgroep->id?>" checklist_id="<?=$checklist ? $checklist->id : ''?>" /> <span><?=$matrix_naam?></span> <select class="hidden" style="width:100px" deelplan_id="<?=$deelplan->id?>"> <? foreach ($matrices as $m): ?> <option <?=($m->id == ($matrix ? $matrix->id : 0)) ? 'selected' : ''?> value="<?=$m->id?>"> <?=$m->naam?> </option> <? endforeach; ?> </select> <? else: ?> <?=$matrix_naam?> <? endif; ?> </td> <!-- initiele datum --> <td width="<?=$this->is_Mobile?110:120?>"> <? if ($mag_initiele_datum_toekennen): ?> <img src="<?=site_url('/files/images/edit.png')?>" style="cursor:pointer" title="Wijzig initieel geplande datum" class="planningdatum_text" checklist_groep_id="<?=$checklistgroep->id?>" checklist_id="<?=$checklist ? $checklist->id : ''?>" deelplan_id="<?=$deelplan->id?>" /> <span><?=$datum_desc?></span> <input type="hidden" name="datum" value="<?=$datum ? date('d-m-Y', strtotime( $datum ) ) : date('d-m-Y')?>"> <input type="hidden" name="start_tijd" value="<?=$start_tijd ? date('H:i', strtotime( $start_tijd ) ) : ''?>"> <input type="hidden" name="eind_tijd" value="<?=$eind_tijd ? date('H:i', strtotime( $eind_tijd ) ) : ''?>"> <? else: ?> <span><?=$datum_desc?></span> <? endif; ?> </td> <!-- hercontrole datum --> <td width="<?=$this->is_Mobile?110:120?>"> <? if ($hercontrole_datum): ?> <?=date('d-m-Y', strtotime($hercontrole_datum) )?> <? else: ?> - <? endif; ?> </td> <!-- voortgang --> <td width="<?=$this->is_Mobile?100:200?>" style="vertical-align: middle"> <? $perc = intval( $voortgang_percentage ) ; ?> <? $this->load->view( 'elements/laf-blocks/generic-progress-bar', array( 'width' => $this->is_Mobile ? '50px' : '150px', 'proc' => $perc ) ) ?> <?=$perc?>% </td> <!-- open toezicht button --> <? global $__local_debug; // Hide the toezicht button for specific project statuses of Woningborg. if ((isset($__local_debug)&&$__local_debug )|| !$hideToezichtButton): ?> <td> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'text' => tgn('open_toezicht'), 'blank' => $blank, 'url' => $url, 'width' => ($this->is_Mobile ? '100px' : '150px') ) ) ?> </td> <? endif; ?> <td width="16"></td> </tr> </table> </td> </tr><file_sep><? $this->load->view('elements/header', array('page_header'=>'mappingen.checklistenmap','map_view'=>true)); ?> <h1><?=tgg('mappingen.headers.checklistenmap')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list double-list"> <thead> <tr> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoets')?></li> </ul> </th> <th>&nbsp;</th> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('mappingen.tabletitles.bristoezicht')?></li> </ul> </th> </tr> </thead> <tbody> <tr> <td> <ul id="bt_matrix" class="list mappen"> <? foreach( $bt_matrixen as $i=>$entry): ?> <? $entry_css=$entry['id']==$bt_matrix_id?'entry-selected':'entry' ?> <li id="bt_matrix_<?=$entry['id'] ?>" class="<?=$entry_css?> top left right <?=(($i==count($bt_matrixen)-1)?'bottom':'')?>" entry_id="<?=$entry['id'] ?>"> <div class="list-entry"><?=htmlentities( $entry['naam'], ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> </td> <td class="middle">&nbsp;</td> <td class="checklisten-map"> <ul id="checklisten" class="list mappen" style=""> <? foreach( $checklisten as $i=>$entry ): ?> <? $entry_css=$entry->id==$checklist_id?'entry-selected':'entry' ?> <li id="checklist_<?=$entry->id ?>" class="<?=$entry_css?> top left right <?=(($i==count($checklisten)-1)? 'bottom' : '')?>" entry_id="<?=$entry->id ?>"> <div class="list-entry"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> <div id="period_<?=$entry->id ?>" class="checklist-map-date period-div"><?=$entry->map_period ?></div> </li> <? endforeach; ?> </ul> </td> </tr> </tbody> </table> </div> <div id="volgende_btn" class="button" style="float:right"> <?=tgg('mappingen.buttons.volgende')?> </div> <br /> <? $this->load->view('elements/footer'); ?> <?php ?> <script type="text/javascript"> var checklist_map = { "checklist_id":<?=$checklist_id?$checklist_id:'null' ?>, "bt_matrix_id":<?=$bt_matrix_id?$bt_matrix_id:'null' ?> } ,old_bt_matrix_id = <?=$bt_matrix_id?$bt_matrix_id:'null' ?> ; function cancel_map(isSave){ $.ajax({ url: "<?=site_url('mappingen/cancel_checklisten_map').'/'.$matrixmap_id.'/'?>", type: "POST", data: null, dataType: "json", success: function( data ){ if (data && data.success){ location.href = "<?=site_url('mappingen/checklistenmap').'/'.$matrixmap_id.'/'?>"+checklist_map.checklist_id // if(isSave) // save_map(); }else{ showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); } }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } function save_map(){ $.ajax({ url: "<?=site_url('mappingen/save_checklisten_map').'/'.$matrixmap_id.'/'?>", type: "POST", data: checklist_map, dataType: "json", success: function( data ){ if (data && data.success) location.href = "<?=site_url('mappingen/finalmapping').'/'.$matrixmap_id.'/'?>"+checklist_map.bt_matrix_id+"/"+checklist_map.checklist_id else showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } $(document).ready(function(){ $("#volgende_btn").click(function(){ if(checklist_map.bt_matrix_id==null){ showMessageBox({ message: "You must select bristoets matrix.", type: "error", buttons: ["ok"] }); return; } if(checklist_map.checklist_id==null){ showMessageBox({ message: "You must select checklist.", type: "error", buttons: ["ok"] }); return; } if( old_bt_matrix_id!=null && checklist_map.bt_matrix_id!=old_bt_matrix_id ){ showMessageBox({ message: "You changed bristoets matrix. All previous mappings will be canceled.<br \><br \>Are you sure?", type: "warning", buttons: ["yes","no"], onClose: function( res ) { if(res=='yes') cancel_map(true); else{ $("#bt_matrix_"+checklist_map.bt_matrix_id) .removeClass("entry-selected") .addClass("entry"); checklist_map.bt_matrix_id = old_bt_matrix_id; $("#bt_matrix_"+checklist_map.bt_matrix_id) .removeClass("entry") .addClass("entry-selected"); } } }); return; } save_map(); }); $("#checklisten li[entry_id]").click(function(){ if(checklist_map.checklist_id!=null){ $("#checklist_"+checklist_map.checklist_id) .removeClass("entry-selected") .addClass("entry"); } $(this) .removeClass("entry") .addClass("entry-selected"); checklist_map.checklist_id = $(this).attr('entry_id'); }); //------------------------------------------------------------------------------ $('#bt_matrix li[entry_id]').click(function(){ if(checklist_map.bt_matrix_id!=null){ $("#bt_matrix_"+checklist_map.bt_matrix_id) .removeClass("entry-selected") .addClass("entry"); } $(this) .removeClass("entry") .addClass("entry-selected"); checklist_map.bt_matrix_id = $(this).attr('entry_id'); }); //------------------------------------------------------------------------------ }); </script> <file_sep><?php /** This interface must be implemented and an instance of it must be passed to the AnnotatieAfbeeldingProcessor::run function. */ interface AnnotatieAfbeeldingProcessorCallback { /** * Gets called for each ANNOTATION to see if the specified annotation should be processed or not. * * The AnnotatieAfbeeldingDataInterface data object implements various getters to get information * about the annotation. See interface definition below. */ function ShouldProcessAnnotation(AnnotatieAfbeeldingDataInterface $data); /** * Gets called for each ANNOTATION with the necessary information. * * The AnnotatieAfbeeldingDataInterface data object implements various getters to get information * about the annotation. See interface definition below. */ function ProcessAnnotationImage(AnnotatieAfbeeldingDataInterface $data, $png_contents, $output_path = '', &$annotation_data_set = array()); /** * Gets called for each ANNOTATION to get the color the annotation's number and rectangle * should be rendered in, as well as the font size that should be used. * * Return the color in RGB values between 0 and 255. * * The rectangle is automatically fit around the text, change padding to set the amount of * extra space around the text. Set bordersize in pixels (integer). */ function GetAnnotationNumberDetails(AnnotatieAfbeeldingDataInterface $data, &$r, &$g, &$b, &$fontsize, &$padding, &$bordersize); /** * Gets called for each BESCHEIDEN that has at least one annotation on it. * * The specified image is the bescheiden, with numbers for each annotation. * If $format is 'png', then $image_contents is a PNG. If format is 'jpeg', then * $image_contents is a JPEG file. */ function ProcessBescheidenOverview($bescheiden_id, $image_contents, $format, $output_path = '', &$overview_data_set = array()); } interface AnnotatieAfbeeldingDataInterface { public function GetBescheidenId(); public function GetDossierId(); public function GetDeelplanId(); public function GetChecklistGroepId(); public function GetChecklistId(); public function GetHoofdgroepId(); public function GetVraagId(); public function GetAnnotatieNummer(); public function GetAnnotatieType(); public function GetPaginaNummer(); } <file_sep><div class="hidden" id="nlaf_WaardeOordeelUtilsContainer"> <div style="border:0;padding:0;margin:0;background-color:transparent;text-align: right; width: 575px;"> <div class="foto camera-icon" style="display:inline-block"> <img src="<?=site_url('/files/images/nlaf/foto.png')?>" /> <!-- parent block niet veranderen, zie bris.js --> <div class="uploadblock inline-block" style="padding:0; margin:10px 0px; border:0; height:auto; display: none; width: 250px;"> <input type="file" multiple class="upload" /> <?=htag('upload_bestand', 'checklistgroep')?> </div> </div> <div class="documenten documenten-icon" style="display:inline-block; margin-left: 12px;" > <img src="<?=site_url('/files/images/nlaf/documenten-upload.png')?>" style="margin-top: -10px;" /> <!-- parent block niet veranderen, zie bris.js --> <div class="uploadblock inline-block" style="padding:0; margin:10px 0px; border:0; height:auto; display: none; width: 250px;"> <?=htag('upload_bestand', 'checklistgroep')?> </div> </div> <? if (APPLICATION_HAVE_DEELPLAN_EMAIL): ?> <div style="margin-left: 10px; display:inline-block; cursor: pointer"> <span> <img src="<?=site_url('/files/images/emailicoon.png')?>" id="EmailIcon" /> </span> </div> <? endif; ?> <div class="relevante-docs" style="margin-left: 10px; display:inline-block"> <div id="nlaf_NaarRelevanteDocs" class="inlineblock"><?=tg('relevante_documenten')?></div> </div> </div> <div class="verantwoording" style="border:0;padding:0;margin:0;background-color:transparent;vertical-align:top;"> <div id="nlaf_VerantwoordingsTekst" class="rounded5" style="height: 65px;"> <img src="<?=site_url('/files/images/nlaf/verantwoording-edit.png')?>" class="edit" /> <div class="header"><?=tg('toelichting')?></div> <div class="tekst"></div> </div> </div> <div class="nlaf_ToelichtingButtons" style="border:0;padding:0;margin:0;background-color:transparent;vertical-align:top;text-align:left;height: 30px; " > </div> </div> <div class="nlaf_TabContent"> <table class="waardeoordeel" cellpadding="0" cellspacing="5" border="0"> <tr> <td class="groot w00" id="nlaf_Status-w00"></td> <td class="geenwaardeoordeel hidden lege-kolom-helper kolom0"></td> <td class="groot w10" id="nlaf_Status-w10"></td> <td class="geenwaardeoordeel hidden lege-kolom-helper kolom1"></td> <td class="groot w20" id="nlaf_Status-w20"></td> <td class="geenwaardeoordeel hidden lege-kolom-helper kolom2"></td> <td class="geenwaardeoordeel hidden utilscontainer0" style="vertical-align: top" rowspan="7" colspan="2"></td> <td class="geenwaardeoordeel hidden invulvraag" style="vertical-align: top; color: black; width: 100%; text-align: left" colspan="3"> <input type="text" id="nlaf_InvulVraagWaarde" style="font-size: 18pt; width: 860px" maxlength="100"> </td> </tr> <tr> <td class="w01" id="nlaf_Status-w01"></td> <td class="w11" id="nlaf_Status-w11"></td> <td class="w21" id="nlaf_Status-w21"></td> <td class="geenwaardeoordeel invulvraag hidden"></td> <td class="geenwaardeoordeel hidden utilscontainer1" style="vertical-align: top" rowspan="6" colspan="2"></td> <td class="geenwaardeoordeel" style="width: 1px;"></td> </tr> <tr> <td class="w02" id="nlaf_Status-w02"></td> <td class="w12" id="nlaf_Status-w12"></td> <td class="w22" id="nlaf_Status-w22"></td> <td class="geenwaardeoordeel invulvraag hidden"></td> <td class="geenwaardeoordeel hidden utilscontainer2" style="vertical-align: top" rowspan="5" colspan="2"></td> <td class="geenwaardeoordeel" style="width: 1px;"></td> </tr> <tr> <td class="w03" id="nlaf_Status-w03"></td> <td class="w13" id="nlaf_Status-w13"></td> <td class="w23" id="nlaf_Status-w23"></td> <td class="geenwaardeoordeel invulvraag hidden"></td> <td class="geenwaardeoordeel hidden utilscontainer3" style="vertical-align: top" rowspan="4" colspan="2"></td> <td class="geenwaardeoordeel" style="width: 1px;"></td> </tr> <tr> <td class="w04" id="nlaf_Status-w04"></td> <td class="geenwaardeoordeel invulvraag hidden"></td> <td class="geenwaardeoordeel hidden utilscontainer4" style="vertical-align: top" rowspan="3" colspan="2"></td> <td class="geenwaardeoordeel" style="width: 1px;"></td> </tr> <tr style="height:175px;"> <td style="background: none;"> <table> <tr> <td class="betrokkenen geenwaardeoordeel" style="text-align: left;"> <img src="<?=site_url('/files/images/nlaf/betrokkenen.png')?>" style="margin-right: 11px; margin-left: 11px;"/> <div id="nlaf_BewerkBetrokkenen" class="inlineblock"><?=tg('betrokkenen')?> <span></span></div> </td> </tr> <tr> <td class="kalender geenwaardeoordeel"> <img src="<?=site_url('/files/images/nlaf/kalender.png')?>" /> <select name="hercontrole_datum_select" id="hercontrole_datum_select"> <option value="geen" style="font-style:italic"><?=tgn('plan_een_hercontrole')?></option> <option value="nieuw"><?=tg('nieuw')?></option> </select> <input type="text" style="width: 60px" name="hercontrole_datum" class="hidden" readonly /> </td> </tr> </table> </td> <td class="geenwaardeoordeel hidden utilscontainer5" style="vertical-align: top" rowspan="3" colspan="2"></td> </tr> </table> </div> <input id="hoofgroepen_level" type="hidden" name="hoofgroepen_level" value=0> <script type="text/javascript"> var uploadBezig = false; function openBescheidenPopup( id, dossier_id) { if(navigator.onLine) { var url = id+'/'+dossier_id; modalPopup({ url: '<?=site_url('/dossiers/bescheiden_popup/')?>/' + url, width: 900, height: 500, onClose: function() { if (uploadBezig) { showError( '<?=tgn('er_is_nog_een_upload_bezig_even_geduld_aub')?>' ); return false; } } }); } else{ alert( '<?=tg('de_applicatie_is_nog_niet_klaar_voor_offline_gebruik_even_geduld_aub')?>' ); } } function opslaanBescheiden() { var dossier_id=$('.documenten.documenten-icon').attr('dossier_id'); url = '<?=site_url('/dossiers/save_documenten');?>' +'/' + dossier_id+'/'+BRISToezicht.Toets.data.deelplan_id+'/'+BRISToezicht.Toets.Vraag.huidigeVraag; // init busy state uploadBezig = true; getPopup().find( 'input, textarea, select' ).attr( 'readonly', 'readonly' ); var form = getPopup().find('form'); form.attr( 'action', url ); var $fileUpload = $("#bestand_upload"); if (parseInt($fileUpload.get(0).files.length) > 20){ uploadBezig = false; getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); showError('<?=tgn('upload_file_limit')?>'); } else { $('.pleasewaitbar').slideDown(); $('.buttonbar').hide(); BRISToezicht.Upload.start( form[0], function( data ){ // restore state getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); uploadBezig = false; $('.buttonbar').slideDown(); $('.pleasewaitbar').hide(); if (data.match( /^FOUT:\s*(.*?)$/ )) showError( RegExp.$1 ); else if(data){ var data=JSON.parse(data); if(data){ for (var i=0;i<data.length;i++){ if(data[i][0].omschrijving) var omschrijving = data[i][0].omschrijving; else var omschrijving = data[i][0].bestandsnaam; BRISToezicht.Toets.data.bescheiden[data[i][0].id] = { bescheid_id: data[i][0].id, tekening_stuk_nummer: data[i][0].tekening_stuk_nummer, datum_laatste_wijziging: data[i][0].datum_laatste_wijziging, omschrijving: omschrijving, auteur: data[i][0].auteur, bestandsnaam: data[i][0].bestandsnaam, } var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if(vraagData){ var setAantalLabel = function( o, aantal ) { o[ aantal ? 'show' : 'hide' ](); o.text( aantal ); }; vraagData.vraagbescheiden[ data[i][0].id ] = BRISToezicht.Toets.data.bescheiden[data[i][0].id]; vraagData.vraagbescheiden[ data[i][0].id ].relevant = true; var totaalAantalBescheiden = BRISToezicht.Tools.getNumProps( vraagData.vraagbescheiden ); setAantalLabel( $('#nlaf_TotaalAantalBescheiden'), totaalAantalBescheiden ); } $(".documenten.bestanden .lijst div.container").append("<img class='bestand' width='430' target_url='http://btz.localhost/pdfview/bescheiden/"+data[i][0].id+"' src='http://btz.localhost/pdfview/bescheiden/"+data[i][0].id+"' bescheid_id='"+data[i][0].id+"' nr='530'>"); } BRISToezicht.Toets.Bescheiden.updateList(); } closePopup(); } else closePopup(); }); } } $(document).ready(function(){ // handle switching to waardeoordeel panel $('#nlaf_VerantwoordingsTekst').click(function(){ // DO NOT show Terug button! $('#nlaf_HeaderTerug div').hide(); // hide all content panels $('#nlaf_MainPanel').children( ':not(#nlaf_GreenBar):not(#nlaf_Header)' ).hide(); // show target panel $('#nlaf_Waardeoordeel').show(); }); // handle switching to "relevante documenten" $('#nlaf_NaarRelevanteDocs').click(function(){ var input = $('.documenten input[name=document-filter][value=relevant]'); input.attr('checked', 'checked' ); input.trigger('change'); $('#nlaf_TabList [tab-name=documenten]').trigger('click'); }); }); <? if (APPLICATION_HAVE_DEELPLAN_EMAIL): ?> $('#EmailIcon').click(function(){ if (!BRISToezicht.NetworkStatus.getState()) alert( '<?=tgn('u_bent_niet_online_en_kunt_daarom_niet_emailen')?>' ); else if (confirm( '<?=tgn('weet_u_zeker_dat_u_een_status_email_wilt_verzenden')?>' )) $.ajax({ url: '/deelplannen/verzend_email/' + BRISToezicht.Toets.data.checklist_groep_id + '/' + BRISToezicht.Toets.data.deelplan_id + '/' + (BRISToezicht.Toets.data.checklist_id ? BRISToezicht.Toets.data.checklist_id : ''), type: 'POST', dataType: 'html', success: function( data ) { if (data != 'OK') alert( '<?=tgn('er_is_iets_fout_gegaan_bij_het_verzenden_van_de_email')?>\n\n' + data ); else { alert( '<?=tgn('email_verstuurd')?>' ); location.href = location.href; // refresh to show empty checklist! } }, error: function() { alert( '<?=tgn('er_is_iets_fout_gegaan_bij_het_verzenden_van_de_email')?>' ); } }); }); <? endif; ?> </script> <file_sep><? if (isset( $checklist ) && $checklist): $in_gebruik = $checklist->is_in_gebruik(); $afgerond = $checklist->is_afgerond(); ?> <div style="float: right; position: relative; top: 6px;"> <?=htag('checklist-status')?> </div> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.' . ($in_gebruik ? 'in-gebruik' : 'niet-in-gebruik'))?>"> <i class="icon-warning-sign" style="font-size: 12pt; opacity: <?=$in_gebruik ? 1 : 0.25;?>; color: <?=$in_gebruik ? '#000' : '#777'?>;"></i> </div> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.' . ($afgerond ? 'actief' : 'niet-actief'))?>"> <i class="icon-eye-open" style="font-size: 12pt; opacity: <?=$afgerond ? 1 : 0.25;?>; color: <?=$afgerond ? '#000' : '#777'?>;"></i> </div> <div style="float: right; margin-right: 8px; margin-top: 8px; font-weight: bold;"> <?=tgg('checklistwizard.checklist.status')?> </div> <? if (isset( $empty_lines )): ?> <?=str_repeat('<br/>', intval( $empty_lines )); ?> <? endif; ?> <? endif; ?><file_sep>ALTER TABLE `klanten` ADD `outlook_synchronisatie` TINYINT NOT NULL DEFAULT '0'; ALTER TABLE `klanten` ADD `standaard_netwerk_modus` ENUM( 'wifi', '3g' ) NOT NULL DEFAULT 'wifi'; <file_sep><? $this->load->view('elements/header', array('page_header'=>'managementinfo') ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => null, 'width' => '100%' )); ?> <div id="marap-bookmarks"> <span>Bladwijzers</span><br/> <? $i = 0; $indent = 0; $groeptag = null; $categorie = null; ?> <? foreach ($grafieken as $grafiek): ?> <? if ($groeptag && $grafiek['groeptag'] != $groeptag) { $groeptag = null; $indent--; echo '</div>'; } ?> <? if ($grafiek['categorie'] != $categorie): ?> <? $categorie = $grafiek['categorie']; ?> <span class="categorie"><?=$categorie?></span><br/> <? endif; ?> <? if ($grafiek['groep'] && $grafiek['groeptag'] != $groeptag): ?> <img src="<?=site_url('/files/images/list-collapsed.png')?>" /> <a href="javascript:void(0);" onclick="toggleBookmarkGroep(this, <?=$i?>);"><?=$grafiek['title']?></a><br/> <? $groeptag = $grafiek['groeptag']; $indent++; ?> <div class="groep<?=$i?>" style="display:none"> <? endif; ?> <div style="margin-left:<?=$indent*10?>px"><img src="<?=site_url('/files/images/list-item.png')?>" /> <a href="#<?=$i?>"><?=$grafiek['origtitle']?></a></div> <? ++$i; ?> <? endforeach; ?> <? while ($indent--): ?> </div> <? endwhile; ?> </div> <h2>Periode <?=$periode?></h2> <? $i=0; foreach ($grafieken as $grafiek): ?> <a name="<?=$i?>"></a> <? if ($grafiek['title']): ?> <h2><?=$grafiek['title']?></h2> <? endif; ?> <? if ($grafiek['description']):?> <p><?=$grafiek['description']?></p> <? endif; ?> <img src="<?=site_url($grafiek['filename'])?>" style="vertical-align: bottom" /> <a href="#top">Top</a> <br/> <br/> <? ++$i; endforeach; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <script type="text/javascript"> $(document).ready(function(){ $('[name=van]').datepicker({ dateFormat: "dd-mm-yy" }); $('[name=tot]').datepicker({ dateFormat: "dd-mm-yy" }); }); var toggleBookmarkGroep = function( thiz, groep_id ){ var groep = $('div.groep' + groep_id); if (groep.is(':visible')) { groep.hide(); $(thiz).prev().attr( 'src', '<?=site_url('/files/images/list-collapsed.png')?>' ); } else { groep.show(); $(thiz).prev().attr( 'src', '<?=site_url('/files/images/list-expanded.png')?>' ); } }; </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php /** * Rapportage implementation of the AnnotatieAfbeeldingProcessorCallback interface. Handles the files as required for genererating the reports. */ class RapportageAnnotatieAfbeeldingProcessorCallback implements AnnotatieAfbeeldingProcessorCallback { function ShouldProcessAnnotation(AnnotatieAfbeeldingDataInterface $data) { return true; } function ProcessAnnotationImage(AnnotatieAfbeeldingDataInterface $data, $png_contents, $output_path = '', &$annotation_data_set = array()) { /* //$filename = sprintf("./annotatie %07d (%d-%d-%d-%d-%d-%d-%d %s).png", $filename = sprintf($output_path."annotatie %07d (%d-%d-%d-%d-%d-%d-%d %s).png", $data->GetAnnotatieNummer(), $data->GetBescheidenId(), $data->GetDossierId(), $data->GetDeelplanId(), $data->GetChecklistGroepId(), $data->GetChecklistId(), $data->GetHoofdgroepId(), $data->GetVraagid(), $data->GetAnnotatieType() ); file_put_contents($filename, $png_contents); echo "Wrote $filename\n"; * */ // Register the type, data and PNG contents for this annotation $annotation_data_set[] = array('type' => 'snapshot', 'metadata' => $data, 'png_contents' => $png_contents); } function GetAnnotationNumberDetails(AnnotatieAfbeeldingDataInterface $data, &$r, &$g, &$b, &$fontsize, &$padding, &$bordersize) { if ($data->GetAnnotatieType() == 'photo' || $data->GetAnnotatieType() == 'photoassignment') { $r = 128; $g = 0; $b = 0; } else if ($data->GetAnnotatieType() == 'compound') { $r = 0; $g = 128; $b = 0; } else { $r = 0; $g = 0; $b = 255; } $fontsize = 40; $padding = 15; $bordersize = 3; } function ProcessBescheidenOverview($bescheiden_id, $png_contents, $format, $output_path = '', &$overview_data_set = array()) { //$filename = "./bescheiden $bescheiden_id.$format"; $filename = $output_path."bescheiden $bescheiden_id.$format"; //file_put_contents($filename, $png_contents); //echo "Wrote $filename\n"; // Register the type, data and PNG contents for this annotation //$overview_data_set[] = array('type' => 'overview', 'metadata' => $filename, 'png_contents' => $png_contents); $overview_data_set[$bescheiden_id] = array('bescheiden_id' => $bescheiden_id, 'type' => 'overview', 'metadata' => $filename, 'png_contents' => $png_contents); } }; <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.checklisten')?></h1> <? $this->load->view( 'checklistwizard/_lijst', array( 'entries' => $checklisten, 'get_id' => function( $cl ) { return $cl->id; }, 'get_image' => function( $cl ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $cl ) { return $cl->naam; }, 'delete_url' => '/checklistwizard/checklist_verwijderen', 'add_url' => '/checklistwizard/checklist_toevoegen/' . $checklistgroep->id, 'add_uitgebreid_url' => '/checklistwizard/checklist_uitgebreid_toevoegen/' . $checklistgroep->id, 'copy_url' => '/checklistwizard/checklist_kopieren', 'defaults_url' => '/checklistwizard/checklist_bewerken', ) ); ?> <div class="button"> <a href="<?=site_url('/checklistwizard/checklist_volgorde/' . $checklistgroep->id)?>">Wijzig volgorde</a> </div> <?=htag('wijzig-volgorde')?> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = '<?=site_url('/checklistwizard/hoofdgroepen/')?>/' + $(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><p style="font-weight:bold; font-size:16px;"><?=tg("automatic_verantwoordingstekst_title");?></p> <p><?=tg("text_title");?></p> <div class="checklistwizard lijst-nieuwe-stijl"> <form action="" method="post" id="automatic_verantwoordingstekst"> <textarea name="text" class="verantwoordingstekst" cols="65" rows="10" maxlength="1024" style="width:99%;"><? $text ? print $text : ""; ?></textarea> <p><?=tg("description");?></p> <input type="hidden" id="checklistgroep" name="checklistgroep" value="<?=$checklistgroep->id?>"> <input type="hidden" id="checklist" name="checklist" value="<?=$checklist->id?>"> <input type="hidden" id="vraag_id" name="vraag_id" value="<?=$vraag_id?>"> <input type="hidden" id="vraag_verantwtkstn_id" name="vraag_verantwtkstn_id" value="<?isset($verantwoordingen_id) ? print $verantwoordingen_id : "";?>"> <table> <tr> <td> <img style="margin-right:15px;" src="/files/images/nlaf/status-groen.png"> </td> <td> <img style="margin-right:15px;" src="/files/images/nlaf/status-oranje.png"> </td> <td> <img style="margin-right:15px;" src="/files/images/nlaf/status-rood.png"> </td> </tr> <tr> <td style="width:220px; vertical-align:top;"> <table> <? foreach ($groen as $groen_value): ?> <? if ($groen_value['title']):?> <tr><td style="padding: 0;"> <input style="margin-left:0; margin-right: 5px;" type='checkbox' <? $groen_value['checked']===1 ? print 'checked' :''?> name='button_name[]' value='<?=str_replace("wo_kleur_","w",$groen_value['name'])?>'><?=$groen_value['title']?></td></tr> <? endif; ?> <? endforeach;?> </table> </td> <td style="width:220px; vertical-align:top;"> <table> <? foreach ($oranje as $oranje_value): ?> <? if ($oranje_value['title']):?> <tr><td style="padding: 0;"> <input style="margin-left:0; margin-right: 5px;" type='checkbox' <? $oranje_value['checked']===1 ? print 'checked' :''?> name='button_name[]' value='<?=str_replace("wo_kleur_","w",$oranje_value['name'])?>'><?=$oranje_value['title']?></td></tr> <? endif; ?> <? endforeach;?> </table> </td> <td style="width:220px; vertical-align:top;"> <table> <? foreach ($rood as $rood_value): ?> <? if ($rood_value['title']):?> <tr><td style="padding: 0;"> <input style="margin-left:0; margin-right: 5px;" type='checkbox' <? $rood_value['checked']===1 ? print 'checked' :''?> name='button_name[]' value='<?=str_replace("wo_kleur_","w",$rood_value['name'])?>'><?=$rood_value['title']?></td></tr> <? endif; ?> <? endforeach;?> </table> </td> </tr> <tr> <td colspan="3" style="text-align: left; padding-top: 2em; padding-bottom: 1em;"> <input <? //$automatic_verantwtkstn && !$automatish_generate ? print "disabled readonly " : '';?>type='checkbox' style="margin-left:3; margin-right: 5px;" name="automatish" <? $automatish_generate ? print "checked" :''?>><i><?=tgg("automatish");?></i> </td> </tr> <tr> <td class="buttons" colspan="3" style="text-align: center;"> <div class="button opslaan_automatic_afsluiten"> <a href="javascript:void(0);" style="font-weight: bold; font-size: 120%; " onclick="closePopup('ok')">Opslaan</a> </div> <div class="button opslaan_en_afsluiten"> <a href="javascript:void(0);" style="font-weight: bold; font-size: 120%; " onclick="closePopup('cancel')">Annuleren</a> </div> </td> </tr> </table> </form> </div> <file_sep>/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; SELECT @klant_id:=id FROM klanten WHERE naam = 'CSP'; REPLACE INTO rollen (id,klant_id,naam,gemaakt_door_gebruiker_id,is_lease) VALUES (34,@klant_id,'Groep admin',1,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,2,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,3,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,4,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,18,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,5,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,6,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,7,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,8,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,9,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,10,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,12,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,13,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,14,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,23,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,26,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,27,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,34,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,1,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,11,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,15,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,21,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,22,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,19,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,16,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,24,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,25,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,28,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,20,8); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (34,17,1); REPLACE INTO rollen (id,klant_id,naam,gemaakt_door_gebruiker_id,is_lease) VALUES (35,@klant_id,'Groep gebruiker',1,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,2,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,3,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,4,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,18,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,5,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,6,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,7,2); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,8,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,9,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,10,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,12,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,13,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,14,4); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,23,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,26,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,27,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,34,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,1,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,11,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,15,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,21,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,22,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,19,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,16,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,24,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,25,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,28,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,20,1); REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (35,17,2); /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep><table width="100%" height="100%" class="messagebox"> <tr> <td class="icon notice"></td> <td class="message"> <p>Wat voor type upload wilt u toevoegen?</p> <p> <input type="radio" name="soort" value="upload" checked> Bestand (.PDF, .DOC, etc.)<br/> <input type="radio" name="soort" value="url"> URL<br/> <? if (APPLICATION_HAVE_INSTELLINGEN && $this->login->verify( 'beheer', 'index' )): ?> <input type="radio" name="soort" value="exist">Kiezen uit de bestaande geüploade Richtlijnen<br/> <? endif;?> </p> <form soort="upload" method="POST" enctype="multipart/form-data" action="<?=site_url('/checklistwizard/richtlijn_toevoegen')?>"> <h2>Upload een bestand</h2> <input type="hidden" name="type" value="upload" /> <input type="file" name="upload"> <h2>Opslaan</h2> <input type="button" value="Opslaan" /> </form> <form soort="url" class="hidden" method="POST" enctype="multipart/form-data" action="<?=site_url('/checklistwizard/richtlijn_toevoegen')?>"> <h2>Voeg een URL toe</h2> <p><input type="text" size="60" name="url" maxlength="1024" placeholder="URL" /></p> <p><input type="text" size="60" name="url_beschrijving" maxlength="256" placeholder="Beschrijving" /></p> <h2>Opslaan</h2> <input type="button" value="Opslaan" /> </form> <? if (APPLICATION_HAVE_INSTELLINGEN && $this->login->verify( 'beheer', 'index' )): ?> <form soort="exist" class="hidden" method="POST" enctype="multipart/form-data" action="<?=site_url('/checklistwizard/richtlijn_toevoegen')?>"> <h2>Upload een bestand</h2> <input type="hidden" name="type" value="exist" /> <?php foreach ($richtlijn_documents as $value) {?> <input id="exist" type="checkbox" name="exist[]" value="<?=$value->id;?>"><?=$value->filename;?><br> <?php } ?> <h2>Opslaan</h2> <input type="button" value="Opslaan" /> </form> <? endif;?> </td> </tr> </table> <script type="text/javascript"> var popup = getPopup(); popup.find( '[name=soort]' ).change(function(){ var soort = $(this).val(); popup.find( 'form[soort!=' + soort + ']' ).hide(); popup.find( 'form[soort=' + soort + ']' ).show(); }); popup.find( 'form[soort=upload] input[type=button]' ).click(function(){ var form = $(this).closest('form')[0]; var showError = function(error) { // kan geen showMessageBox gebruiken, we zitten al in een popup... alert( 'Er is iets fout gegaan bij het upload van het bestand.\n\n' + error ); }; BRISToezicht.Upload.start( form, function(result) { try { var data = JSON.parse( result ); if (data.success) closePopup( data.richtlijn_id + ':0:' + data.filename ); else showError( data.error ); } catch (e) { showError(); } }, showError ); }); popup.find( 'form[soort=url] input[type=button]' ).click(function(){ var form = $(this).closest('form')[0]; var url = $(form).find('[name=url]').val(); var url_beschrijving = $(form).find('[name=url_beschrijving]').val(); if (url && url.length) { var showError = function(error) { // kan geen showMessageBox gebruiken, we zitten al in een popup... alert( 'Er is iets fout gegaan bij het toevoegen van de URL.\n\n' + error ); }; $.ajax({ url: form.action, type: 'POST', data: {type: 'url', url: url, url_beschrijving: url_beschrijving}, dataType: 'json', success: function( data ) { if (data.success) closePopup( data.richtlijn_id + ':1:' + ((data.url_beschrijving && data.url_beschrijving.length) ? data.url_beschrijving + ' [' + data.url + ']' : data.url) ); else showError( data.error ); }, error: function() { showError(''); } }); } }); popup.find( 'form[soort=exist] input[type=button]' ).click(function(){ var form = $(this).closest('form')[0]; var showError = function(error) { // kan geen showMessageBox gebruiken, we zitten al in een popup... alert( 'Er is iets fout gegaan bij het upload van het bestand.\n\n' + error ); }; if ($('#exist').is(":checked")){ BRISToezicht.Upload.start( form, function(result) { try { var data = JSON.parse( result ); if (data.success){ for(var i=0;i<data.richtlijn_id.length;i++){ closePopup( data.richtlijn_id + ':2:' + data.filename); } } else showError( data.error ); } catch (e) { showError(); } }, showError ); } }); </script><file_sep>-- Result tables sturcture for duplicate checklisten functionality. CREATE TABLE deelplan_checklisten ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, checklist_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, toezicht_gebruiker_id int(11) DEFAULT NULL, matrix_id int(11) DEFAULT NULL, initiele_datum date DEFAULT NULL, initiele_start_tijd char(8) DEFAULT NULL, initiele_eind_tijd char(8) DEFAULT NULL, voortgang_percentage int(11) NOT NULL DEFAULT 0, voortgang_gestart_op datetime DEFAULT NULL, PRIMARY KEY (id), INDEX checklist_id (checklist_id), INDEX matrix_id (matrix_id), INDEX toezicht_gebruiker_id (toezicht_gebruiker_id), UNIQUE INDEX UK_deelplan_checklisten_dcb (deelplan_id, checklist_id, bouwnummer_id), CONSTRAINT deelplan_checklisten_ibfk_4 FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_5 FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_6 FOREIGN KEY (toezicht_gebruiker_id) REFERENCES gebruikers (id) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_7 FOREIGN KEY (matrix_id) REFERENCES matrices (id) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET latin1 COLLATE latin1_swedish_ci; CREATE TABLE supervision_moments_cl ( id int(10) UNSIGNED NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, checklist_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, supervision_start datetime NOT NULL, supervision_end datetime DEFAULT NULL, progress_start float NOT NULL, progress_end float DEFAULT NULL, supervisor_user_id int(11) NOT NULL, PRIMARY KEY (id), INDEX checklist_id (checklist_id), INDEX deelplan_id (deelplan_id), -- INDEX FK_supervision_moments_cl (deelplan_id, checklist_id, bouwnummer_id), INDEX supervisor_user_id (supervisor_user_id), CONSTRAINT FK_s_m_cl__cl_id FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_s_m_cl__d_id FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_s_m_cl__g_id FOREIGN KEY (supervisor_user_id) REFERENCES gebruikers (id) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE deelplan_vragen ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, vraag_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, status varchar(100) binary DEFAULT NULL, toelichting text binary DEFAULT NULL, seconden int(11) NOT NULL, gebruiker_id int(11) NOT NULL, last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, hercontrole_datum date DEFAULT NULL, hercontrole_start_tijd char(8) binary DEFAULT NULL, hercontrole_eind_tijd char(8) binary DEFAULT NULL, flags int(11) NOT NULL, PRIMARY KEY (id), INDEX deelplan_id (deelplan_id), INDEX gebruiker_id (gebruiker_id), INDEX last_updated_at (last_updated_at), INDEX vraag_id (vraag_id), CONSTRAINT FK__deelplan_vragen__bt_vragen FOREIGN KEY (vraag_id) REFERENCES bt_vragen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK__deelplan_vragen__deelplannen FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK__deelplan_vragen__gebruikers FOREIGN KEY (gebruiker_id) REFERENCES gebruikers (id) ON DELETE CASCADE ON UPDATE RESTRICT ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_bin; CREATE TABLE deelplan_uploads ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, gebruiker_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, vraag_id int(11) NOT NULL, filename varchar(256) NOT NULL, preview longblob DEFAULT NULL, mimetype varchar(128) NOT NULL, datasize int(11) NOT NULL, uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, datatype enum ('foto/video', 'annotaties') NOT NULL DEFAULT 'foto/video', png_status enum ('onbekend', 'aangemaakt', 'fout') NOT NULL DEFAULT 'onbekend', PRIMARY KEY (id), INDEX gebruiker_id (gebruiker_id), INDEX rapport_id (deelplan_id), INDEX vraag_id (vraag_id), CONSTRAINT deelplan_uploads_ibfk_2 FOREIGN KEY (gebruiker_id) REFERENCES gebruikers (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_uploads_ibfk_4 FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_uploads_ibfk_5 FOREIGN KEY (vraag_id) REFERENCES bt_vragen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET latin1 COLLATE latin1_swedish_ci; CREATE TABLE deelplan_vraag_geschiedenis ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, vraag_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, status varchar(100) DEFAULT NULL, toelichting text NOT NULL, datum datetime NOT NULL, gebruiker_id int(11) NOT NULL, PRIMARY KEY (id), INDEX datum (datum), INDEX gebruiker_id (gebruiker_id), INDEX rapport_id (deelplan_id), INDEX vraag_id (vraag_id), CONSTRAINT deelplan_vraag_geschiedenis_ibfk_2 FOREIGN KEY (vraag_id) REFERENCES bt_vragen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_vraag_geschiedenis_ibfk_3 FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_vraag_geschiedenis_ibfk_6 FOREIGN KEY (gebruiker_id) REFERENCES gebruikers (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_vraag_geschiedenis_ibfk_7 FOREIGN KEY (gebruiker_id) REFERENCES gebruikers (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET latin1 COLLATE latin1_swedish_ci;<file_sep><?php get_instance()->load->helper( 'tcpdf' ); get_instance()->load->helper( 'export' ); abstract class MarapBase extends ExportBase { protected $_CI; private $_tag; private $_klant; private $_periode; private $_grafiek_types; // array van grafiek types in deze MARAP private $_checklistgroepen; // array van ALLE checklistgroepen private $_alle_checklisten; // array van ALLE checklisten private $_checklisten; // array van arrays per checklistgroep (op ID) private $_theme; // jpgraph theme private $_postcode; public function __construct( $tag, GrafiekPeriode $periode, array $checklistgroepen, array $checklisten, array $grafiek_types, $theme='',$postcode=null ) { // init $this->_CI = get_instance(); $this->_CI->load->library( 'grafiek' ); $this->_tag = $tag; $this->_theme = $theme; $this->_postcode=$postcode; // set klant $this->_klant = $this->_CI->gebruiker->get_logged_in_gebruiker()->get_klant(); // set periode $this->_periode = $periode; // set & check checklistgroepen $this->_checklistgroepen = array_values( $checklistgroepen ); foreach ($this->_checklistgroepen as $checklistgroep) if (!is_object( $checklistgroep ) || !($checklistgroep instanceof ChecklistGroepResult)) throw new Exception( 'Ongeldige invoer: verwachtte ChecklistGroepResult class.' ); // set & check checklisten $this->_alle_checklisten = array_values( $checklisten ); foreach ($this->_alle_checklisten as $checklist) { if (!is_object( $checklist ) || !($checklist instanceof ChecklistResult)) throw new Exception( 'Ongeldige invoer: verwachtte ChecklistResult class.' ); $checklistgroep_id = $checklist->checklist_groep_id; if (!isset( $this->_checklisten[ $checklistgroep_id ] )) $this->_checklisten[ $checklistgroep_id ] = array(); $this->_checklisten[ $checklistgroep_id ][] = $checklist; } // set & check grafiek types $alle_types = $this->_CI->grafiek->get_alle_grafiek_types(); $this->_grafiek_types = $grafiek_types; foreach ($this->_grafiek_types as $type) if (!in_array( $type, $alle_types )) throw new Exception( 'Ongeldige invoer: grafiek type ' . $type . ' onbekend.' ); } public function get_periode() { return $this->_periode; } public function get_postcode(){ return $this->_postcode; } public function get_grafiek_types() { return $this->_grafiek_types; } public function get_checklistgroepen() { return $this->_checklistgroepen; } public function get_checklisten() { return $this->_alle_checklisten; } public function get_checklisten_voor_checklistgroep( $checklist_groep_id ) { if (!isset( $this->_checklisten[$checklist_groep_id] )) return array(); return $this->_checklisten[$checklist_groep_id]; } public function get_klant() { return $this->_klant; } public function get_theme() { return $this->_theme; } public function set_progress( $progress /* tussen 0 en 1 */, $action_description ) { $this->_CI->marap->set_progress( $this->_tag, $progress, $action_description ); } } abstract class MarapPDFBase extends MarapBase { protected $_tcpdf; public function __construct( $tag, GrafiekPeriode $periode, array $checklistgroepen, array $checklisten, array $grafiek_types, $theme='',$postcode=null ) { parent::__construct( $tag, $periode, $checklistgroepen, $checklisten, $grafiek_types, $theme,$postcode ); // create instance $classname = $this->get_tcpdf_classname(); $tcpdf = new $classname; $this->_tcpdf = $tcpdf; } public function get_tcpdf_classname() { return 'TCPDF'; } public function get_filename() { return sprintf( '(%s) Marap Rapportage %s.pdf', date('d-m-Y'), $this->get_periode()->get_human_description() ); } public function get_content_type() { return 'application/pdf'; } public function get_contents() { return $this->_tcpdf->Output('unused.pdf', 'S'); } function generate() { // by default disable header/footer stuff by TCPDF, which adds unwanted stripes to header and footer $this->_tcpdf->SetPrintHeader(false); $this->_tcpdf->SetPrintFooter(false); // let rest be handled by parent return parent::generate(); } } <file_sep>-- voeg toe aan crontab voor LIVE omgeving -- php index.php /cli/cleanup_verlopen_tokens/30 <file_sep><? $test_niveaus = $risico_handler->get_risico_shortnames(); $model = $risico_handler->get_risico_model(); ?> <div style="display:none" class="legenda"> <h2>Legenda</h2> <div style="width:400px"> <div style="padding:4px;" class="prio_zeer_laag"><?=$test_niveaus['zeer_laag']?>. <?=tgg('prioriteitstelling.beschrijving.zeer_laag.' . $model)?></div> <div style="padding:4px;" class="prio_laag"><?=$test_niveaus['laag']?>. <?=tg('prioriteitstelling.beschrijving.laag.' . $model)?></div> <div style="padding:4px;" class="prio_gemiddeld"><?=$test_niveaus['gemiddeld']?>. <?=tgg('prioriteitstelling.beschrijving.gemiddeld.' . $model)?></div> <div style="padding:4px;" class="prio_hoog"><?=$test_niveaus['hoog']?>. <?=tg('prioriteitstelling.beschrijving.hoog.' . $model)?></div> <div style="padding:4px;" class="prio_zeer_hoog"><?=$test_niveaus['zeer_hoog']?>. <?=tgg('prioriteitstelling.beschrijving.zeer_hoog.' . $model)?></div> </div> <h2>Informatie</h2> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> Een checklist met dit icoon heeft een prioriteitstelling die is gebaseerd op een risico analyse. U kunt die prioriteitstellingen niet direct bewerken.<br/> <br/> <b>Klik op de naam van de checklist om diens risico analyse te wijzigen.</b> <? if (@ $bestuurlijk): ?> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> Vanwege de omvang van de prioriteitenmatrix voor deze set van checklisten, is het bewerken ervan opgesplitst naar hoofdthema.<br/> <br/> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> <b>Klik op een hoofdthema in de tabel om de bestuurlijke matrix in meer detail te bekijken en bewerken.</b><br/> <br/> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> Houdt uw muis stil op een onderwerp in een bestuurlijke matrix om de volledige tekst te bekijken.<br/> <br/> <img src="<?=site_url('/files/images/letop.png')?>" style="margin-right: 5px; margin-bottom: 5px; float: left;" /> Als u in de bestuurlijke matrix prioriteiten wijzigt, wijzigt u automatisch alle prioriteiten in de bijbehorende ambtelijke matrix.<br/> Wijzigt u de prioriteiten in de ambtelijke matrix, dan wordt de bestuurlijke matrix ingesteld op het gemiddelde van de bijbehorende ambtelijke matrix.<br/> <? endif; ?> </div><file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_standart_documenten_beheer')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('standart_documenten.header'), 'expanded' => true, 'width' => '100%', 'group_tag' => 'document','height' => 'auto', 'defunct' => true ) ); ?> <? $columns = 4; $index = 0; ?> <br/> <br/> <table width="100%" class="groupcontent"> <? foreach ($documents as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div class="draggable" style="padding:0;margin:0;height:auto;border:0"> <div style="display: inline-block; overflow:hidden; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; width: 190px; " title="<?=htmlentities( $b->filename, ENT_COMPAT, 'UTF-8' )?>"> <input type="checkbox" bescheiden_id="<?=$b->id?>" /> <b><?=htmlentities( $b->filename, ENT_COMPAT, 'UTF-8' )?></b> </div> </div> </td> <? ++$index; ?> <? endforeach;?> <? for ($i=0; $i<($columns - $index); ++$i): ?> <td style="width:<?=round(100/$columns)?>%"></td> <? endfor; ?> </tr> </table> <br/> <br/> <table width="100%" class="defaultActions"> <tr> <? $columns = 4; $index = 0; ?> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.nieuw'), 'blank' => false, 'url' => 'javascript:nieuwDocumenten(0);', 'class' => 'greenbutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.alles_selecteren'), 'blank' => false, 'url' => 'javascript:selecteerAlleDocumenten();', 'class' => 'graybutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.verwijderen'), 'blank' => false, 'url' => 'javascript:verwijderGeselecteerdedocumenten();', 'class' => 'redbutton' ) ); ?> </td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> function showError( msg ) { showMessageBox({message: msg, buttons: ['ok'], type: 'error'}); } function nieuwDocumenten() { openDocumentenPopup (); } function openDocumentenPopup( ) { modalPopup({ url: '<?=site_url('/beheer/show_richtlijn_multi_upload_popup/');?>', width: 400, height: 150, onClose: function() { if (uploadBezig) { showError( '<?=tgn('er_is_nog_een_upload_bezig_even_geduld_aub')?>' ); return false; } } }); } var uploadBezig = false; function opslaanDocument() { url = '<?=site_url('/beheer/richtlijn_multi_upload/');?>'; uploadBezig = true; getPopup().find( 'input, textarea, select' ).attr( 'readonly', 'readonly' ); $('.buttonbar').hide(); $('.pleasewaitbar').slideDown(); var form = getPopup().find('form'); form.attr( 'action', url ); var $fileUpload = $("input[type='file']"); if (parseInt($fileUpload.get(0).files.length) > 20){ uploadBezig = false; getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); showError('<?=tgn('upload_file_limit')?>'); $('.buttonbar').slideDown(); $('.pleasewaitbar').hide(); } else { BRISToezicht.Upload.start( form[0], function( data ){ // restore state getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); uploadBezig = false; $('.buttonbar').slideDown(); $('.pleasewaitbar').hide(); if (data.match( /^FOUT:\s*(.*?)$/ )) showError( RegExp.$1 ); else { closePopup(); location.href = location.href; setTimeout(herlaadDocumentHTML( data ), 1000); } }); } } function getBescheidenParent() { return $('.groupcontent'); } function getBescheidenBase() { return $('.groupcontent'); } function herlaadBescheidenHTML( html ) { var base = getBescheidenBase(); base.html( html ); BRISToezicht.Group.visibleGroup['dossier'] = base.find('.group'); } function selecteerAlleDocumenten(){ getBescheidenParent().find('input[type=checkbox]').attr( 'checked', 'checked' ); } function verwijderGeselecteerdedocumenten() { var selIds = getSelectedDocumentenIds(); if (selIds.length == 0) { showError( '<?=tgn('selecteer_eerst_de_bescheiden_die_u_wenst_te_verwijderen')?>' ); return; } showMessageBox({ message: '<?=tgn('geselecteerde_bescheiden_werkelijk_verwijderen')?>', onClose: function( res ) { if (res == 'ok') { deleteDocumentsByIds( selIds ); } } }); } function deleteDocumentsByIds( ids ) { $.ajax({ url: '/beheer/delete_richtlijn_documents/', type: 'POST', data: { ids: JSON.stringify( ids ) }, dataType: 'html', success: function( data ) { location.href = location.href; }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } function getSelectedDocumentenIds() { var result = []; getBescheidenParent().find('input[type=checkbox]').each(function(){ if (this.checked) { var bescheiden_id = $(this).attr( 'bescheiden_id' ); var bescheiden_map_id = $(this).attr( 'bescheiden_map_id' ); result.push( bescheiden_id ? bescheiden_id : ('m' + bescheiden_map_id) ); } }); return result; } </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?><file_sep>PDFAnnotator.EditableEditor = PDFAnnotator.Base.extend({ /* constructor */ init: function( html ) { /* initialize base class */ this._super(); /* store HTML */ this.html = html; /* create member to later hold reference to our editor (the wrapping DIV) */ this.dom = null; /* top left position for the editor, relative to screen, not container! */ this.topleft = new PDFAnnotator.Math.IntVector2( 0, 0 ); /* register event types */ this.registerEventType( 'loadvalues' ); }, /* creates the editor in the DOM and makes it visible */ show: function() { // check precondition, there shouldn't be another editor in the DOM atm if ($('#PDFAnnotatorEditor').size()) throw 'PDFAnnotatorEditor.show: another editor is still open, not allowed by design'; // assign editor this.dom = $('<div id="PDFAnnotatorEditor">') .html( this.html ) .css( 'position', 'absolute' ) .css( 'left', this.topleft.x ) .css( 'top', this.topleft.y ) .appendTo( $('body') ); // handle events var thiz = this; this.dom.find('input[type=text][name], input[type=checkbox][name], select[name]').change(function(){ var isSelect = this.nodeName.toUpperCase() == 'SELECT'; if (!isSelect && $(this).attr( 'type' ).toUpperCase() == 'CHECKBOX') thiz.dispatchFieldChange( $(this).attr('name'), this.checked ); else thiz.dispatchFieldChange( $(this).attr('name'), $(this).val() ); }); this.dom.find('input[type=text][name]').keyup(function(){ thiz.dispatchFieldChange( $(this).attr('name'), $(this).val() ); }); // fire load values event to initialize this.dispatchEvent('loadvalues'); this.dispatchEvent('show'); }, /* closes the editor by removing it from the dom and setting the dom reference to null */ close: function() { if (this.dom) { this.dom.remove(); this.dom = null; } }, /* sets a new position for the editor. */ setPosition: function( topleft ) { if (!(topleft instanceof PDFAnnotator.Math.IntVector2)) throw 'PDFAnnotator.EditableEditor.setPosition: topleft not an intvector2 object'; this.topleft = topleft; if (this.dom) { this.dom .css( 'left', this.topleft.x ) .css( 'top', this.topleft.y ); } }, /* calculate new position to be just below given dom object. */ setPositionBelow: function( domObj, margin ) { if (!(domObj instanceof jQuery)) domObj = $(domObj); if (margin == undefined) margin = 5; this.setPosition( new PDFAnnotator.Math.IntVector2( parseInt( domObj.css('left') ) + margin, parseInt( domObj.css('top') ) + domObj.height() + margin ) ); }, /* returns dom object (in a jquery collection) for the given field */ getField: function( field ) { return this.dom.find( 'input[name=' + field + '][type=text], select[name='+field+'], input[name=' + field + '][type=checkbox]' ); }, /* updates a form value, can only be called if this editor is currently opened! */ setField: function( field, value ) { if (!this.dom) throw 'PDFAnnotator.EditableEditor.setField: dom is null, editor not opened'; // get input var input = this.getField( field ); if (!input.size()) throw 'PDFAnnotator.EditableEditor.setField: couldn\'t find text, checkbox or select with name ' + field; var isSelect = input[0].nodeName.toUpperCase() == 'SELECT'; var isCheckBox = !isSelect && input.attr( 'type' ).toUpperCase() == 'CHECKBOX'; // set value based on type if (!isCheckBox) input.val( value ); else { if (value) input.attr( 'checked', 'checked' ); else input.removeAttr( 'checked' ); } }, dispatchFieldChange: function( field, value ) { this.dispatchEvent( 'fieldchange', {field:field, value:value} ); } }); <file_sep>-- voeg toe aan crontab: -- LIVE ONLY */5 * * * * php index.php /cli/update_dossier_geolocaties >/dev/null 2>&1 -- -- -- -- -- LET OP! LET OP! Is de geo_locaties tabel gekopieerd vanuit de TEST omgeving? Die is nodig op productie!!! <file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoprofielen.risicoprofielenmapping','map_view'=>true)); ?> <h1><?=tgg('risicoprofielen.headers.risicoprofielenmapping')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list double-list"> <thead> <tr> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('risicoprofielen.tabletitles.btrisicoprofiel')?></li> </ul> </th> <th>&nbsp;</th> <th> <ul class="list"> <li class="top left right tbl-titles"><?=tgg('risicoprofielen.tabletitles.btzvragen')?></li> </ul> </th> </tr> </thead> <tbody> <tr> <td class="double-list-td"> <? foreach( $risicoprofiel['afdelingen'] as $i=>$afdeling): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => htmlentities( $afdeling['naam'], ENT_COMPAT, 'UTF-8' ), 'onclick' => 'showArtikelVragen('.$afdeling['artikelen'][0]['id'].');', 'expanded' => TRUE, 'group_tag' => 'afdelingen', 'width' => '100%', 'height' => (36*$afdeling['count']).'px' )); ?> <ul class="artikelen list mappen"> <? foreach( $afdeling['artikelen'] as $i=>$artikel ): $css_entry = $artikel['active'] ? 'entry' : 'entry-disabled'; ?> <li id="artikel_<?=$artikel['id'] ?>" class="<?=$css_entry ?> top left right" entry_id="<?=$artikel['id'] ?>"> <div class="accordion-list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $artikel['naam'], ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> </td> <td class="middle">&nbsp;</td> <td id="vragen_list">&nbsp;</td> </tr> </tbody> </table> <div id="opslaan_btn" class="button" style="float:right;margin-top: 15px;"> <?=tgg('mappingen.buttons.opslaan')?> </div> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> var dummy ,artikel_id=null ,bt_rp_id=<?=$bt_rp_id ?> ,sdata ,opts=<?=json_encode($opts) ?> ; //------------------------------------------------------------------------------ function setRisicoBw(vraagMapId,btnObj){ artikel = $("#artikel_"+artikel_id); is_act = !artikel.hasClass('entry-disabled'); $.ajax({ url: "<?=site_url('risicoprofielen/set_risico_bw').'/'?>"+vraagMapId+"/"+artikel_id+"/"+bt_rp_id, type: 'POST', data: { "is_bw": !btnObj.hasClass('bw'), "opts": opts, "is_active": is_act }, dataType: 'html', success: function( result ) { $("#vragen_list").html(result); }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); }; //------------------------------------------------------------------------------ function processVraag( vraag ){ var vrg_id = vraag.attr( 'entry_id' ); if( $("#vrg_li_"+vrg_id).hasClass('entry-selected') ){ opts[vrg_id] = 0; $("#vrg_li_"+vrg_id) .removeClass("entry-selected") .addClass("entry"); }else if( $("#vrg_li_"+vrg_id).hasClass('entry') ){ opts[vrg_id] = 1; $("#vrg_li_"+vrg_id) .removeClass("entry") .addClass("entry-selected"); } } //------------------------------------------------------------------------------ function showArtikelVragen( artikelId ){ var is_dis=true ,artikel=null; if(artikel_id != null){ artikel = $("#artikel_"+artikel_id); if( artikel.hasClass('entry-selected') ) artikel .removeClass("entry-selected") .addClass("entry"); else if( artikel.hasClass('entry-selected-disabled') ) artikel .removeClass("entry-selected-disabled") .addClass("entry-disabled"); } artikel_id = artikelId; artikel = $("#artikel_"+artikel_id); if( artikel.hasClass('entry') ){ is_act = true; artikel .removeClass("entry") .addClass("entry-selected"); }else if( artikel.hasClass('entry-disabled') ){ is_act = false; artikel .removeClass("entry-disabled") .addClass("entry-selected-disabled"); } $.ajax({ url: "<?=site_url('risicoprofielen/show_artikel_vragen').'/'?>"+artikelId+"/"+<?=$bt_rp_id ?>, type: 'POST', data: { is_active: is_act, opts: opts }, dataType: 'html', success: function( result ) { $("#vragen_list").html(result); }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); } //------------------------------------------------------------------------------ $(document).ready(function(){ $("#opslaan_btn").click(function(){ $.ajax({ url: "<?=site_url('risicoprofielen/save')?>", type: 'POST', data: {opts:opts}, dataType: 'json', success: function( data ) { showMessageBox({ message: '<?=tgg('risicoprofielen.notice.successful')?>', type: 'notice', buttons: ['ok'] }); }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); }); $('.artikelen li[entry_id]').click(function(){ showArtikelVragen( $(this).attr( 'entry_id' )); }); //------------------------------------------------------------------------------ showArtikelVragen( <?=$risicoprofiel['afdelingen'][0]['artikelen'][0]['id'] ?> ); }); </script> <file_sep> <div id="header" class="menubar"> <form method="post"> <input type="hidden" name="page" value="afsluiten"> <input id="close" type="submit" value="afsluiten" hidden/><label for="close">Afsluiten</label>BRISToezicht - Projecten </form> </div> <div class="objects"> <p>Selecteer een project:</p> <? if (sizeof( $objecten )): ?> <? foreach ($objecten as $klantid=>$klant):?> <p><b><?=$klant['naam']; ?></b></p> <? foreach ($klant['dossiers'] as $id=>$dossier): ?> <form method="post"> <button type="submit" class="object_details"> <input type="hidden" name="page" value="toezichtmomenten"> <input type="hidden" name="klant_id" value="<?=$klantid?>"> <input type="hidden" name="dossier_id" value="<?=$id?>"> <span><b><?=htmlentities( $dossier['naam'], ENT_COMPAT, 'UTF-8' )?></b></span><br /> <span><?=htmlentities( $dossier['locatie'], ENT_COMPAT, 'UTF-8' )?></span><br /> <span>Aantal: <?=$dossier['aantal'] ?></span><br /> <?if (isset($dossier['recheck'])):?><span class="alert">Hercontrole: <?=$dossier['recheck'];?></span><br /><?endif?> <span<?if (isset($dossier['deadline']) && $dossier['deadline'] < date("Y-m-d")):?> class="alert"<?endif?>>Einddatum: <?if(isset($dossier['deadline'])):?><?=$dossier['deadline'];?><?endif?></span> </button> </form> <? endforeach; ?> <hr /> <? endforeach; ?> <? else: ?> <div class="melding">Er zijn momenteel geen opdrachten voor u ingepland.</div> <? endif; ?> </div> <div id="footer" class="menubar"> </div> <file_sep><? $this->load->view('elements/header', array('page_header'=>null));// $is_show_bwnummer = $klant->heeft_toezichtmomenten_licentie == 'ja'; ?> <!-- filters --> <select name="opdrachtgever_id" style="margin-right:15px;"> <option value="-">-- alle opdrachtgevers --</option> <? foreach ($alle_opdrachtgevers as $id=>$opdrachtgever) :?> <option <?=$id == $opdrachtgever_id ? 'selected' : ''?> value="<?=$id?>"><?=htmlentities( $opdrachtgever, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <select name="opdrachtnemer_id" style="margin-right:15px;"> <option value="-">-- alle opdrachtnemers --</option> <? foreach ($alle_opdrachtnemers as $id=>$opdrachtnemer) :?> <option <?=$id == $opdrachtnemer_id ? 'selected' : ''?> value="<?=$id?>"><?=htmlentities( $opdrachtnemer, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <select name="datum" style="margin-right:15px;"> <option value="-">-- alle datums --</option> <? foreach ($alle_data as $d) :?> <option <?=$d == $datum ? 'selected' : ''?> value="<?=$d?>"><?=date( 'd-m-Y', strtotime( $d ) )?></option> <? endforeach; ?> </select> <select name="locatie" style="margin-right:15px;"> <option value="-">-- alle locaties --</option> <? foreach ($alle_locaties as $l) :?> <option <?=$l == $locatie ? 'selected' : ''?> value="<?=$l?>"><?=$l?></option> <? endforeach; ?> </select> <? foreach (array('groen','oranje','rood') as $kleur): ?> <? if ($kleur == 'groen') $enabled = $groen_filter; if ($kleur == 'oranje') $enabled = $oranje_filter; if ($kleur == 'rood') $enabled = $rood_filter; ?> <img style="margin-right:15px; cursor: pointer;" src="/files/images/nlaf/status-<?=$kleur?><?=$enabled?'':'-disabled'?>.png" onclick="var cb=$(this).next()[0]; cb.checked = !cb.checked; $(cb).trigger('click');"> <input type="checkbox" class="hidden" name="status-<?=$kleur?>" <?=$enabled ? 'checked' : ''?> /> <? endforeach; ?> <!-- lijst van objecten --> <div class="lijst-nieuwe-stijl"> <ul id="sortable" class="list" style="margin-top: 10px;"> <? // If there is no context, create array of all checklists if ($context_model && $context_model == '-'): $data_array = $data; else: $data_array= array(array('children'=>$data)); endif; foreach ($data_array as $data_parent): $data = $data_parent['children']; foreach (array_values($data) as $i => $entrydata): if (is_array( $entrydata )) // bouwnummer, checklist, hoofdgroep, vraag, opdracht { $object = $entrydata['object']; $kleur = $entrydata['status']; $bwnummer = $entrydata['bouwnummer']; $gereed = $entrydata['gereed']; $gereed_datum = $entrydata['datum']; $annotatie_tag = null; $klikbaar = true; if(method_exists($object, 'get_dossier_subject') ) { $gebruiker = ($object->get_dossier_subject()->gebruiker_id) ? $object->get_dossier_subject()->get_gebruiker()->volledige_naam : $object->get_dossier_opdrachtgever()->volledige_naam; $opdrachtnemer = (!isset($object->gebruiker_id)) ? $object->get_dossier_subject()->naam : ''; } else { $gebruiker = null; } $gereed = ($is_show_bwnummer && $context_model == 'checklist' && $bwnummer != '-') ? $entrydata['bwgereed']["$bwnummer"] : $gereed; if($context_model == 'checklist' && count($bw_statuses)){ $hf_ind = sha1($object->id.$bwnummer); if(!isset($bw_statuses["$hf_ind"])){ continue; } $bw_color = $bw_statuses["$hf_ind"] ? 'groen' : 'rood'; } $tekst = htmlentities( (isset($object->naam) ? $object->naam : (isset( $object->tekst ) ? $object->tekst : $object->opdracht_omschrijving) ), ENT_COMPAT, 'UTF-8' ); } else // opdracht { $object = $entrydata; $vraag = $object->get_vraag(); $waardeoordeel = $vraag->get_waardeoordeel( true, $object->antwoord ); $opdrachtnemer = (!isset($object->gebruiker_id)) ? $object->get_dossier_subject()->naam : ''; $kleur = $vraag->get_waardeoordeel_kleur( true, $object->antwoord ); $gereed_datum = $object->gereed_datum; $gereed = $object->status == 'gereed'; $gebruiker = ($object->get_dossier_subject()->gebruiker_id) ? $object->get_dossier_subject()->get_gebruiker()->volledige_naam : $object->get_dossier_opdrachtgever()->volledige_naam; $annotatie_tag = $object->annotatie_tag; $klikbaar = false; } $bottom = ($i==sizeof($data)-1) ? 'bottom' : ''; if (!isset($header_set)): $header_set = true;// Insert header ?> <li class="head" style="width: <?=$is_show_bwnummer?'900px':'1000px' ?>"> <? if (!$gebruiker): ?> <div class="list-entry" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: <?=($is_show_bwnummer?'464':'620')?>px;"> <?=tg('omschrijving')?> <? if ($is_show_bwnummer): ?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=tg('bouwnummer')?> <? endif; ?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=tg('gereeddatum')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=tg('status')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 50px; text-align: center;"> <?=tg('statusopdrachtnemer')?> <? if ($is_show_bwnummer && $context_model == 'checklist'): ?> </div><div onclick="changeStatusAkkoord('<?=$object->id?>','<?=$bwnummer?>');" class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 50px; text-align: center;"> <?=tg('statusopdrachtgever')?> <? endif; ?> </div> <? elseif($klikbaar /* this is a clickable opdracht */): ?> <div class="list-entry" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 310px;"> <?=tg('omschrijving')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=tg('opdrachtgever')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=tg('annotatie')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=tg('opdrachtnemer')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=tg('gereeddatum')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=tg('status')?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 25px; text-align: center;"> <?=tg('statusopdrachtnemer')?> </div> <? else: //opdracht specifics?> <div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 100%; text-align: center;"> <?=tg('opdrachttitle')?> </div> <? endif; ?> </li> <? endif; ?> <? if ($context_model != 'deelplanopdracht'): ?> <li class="entry top left right <?=$bottom?>" style="width: <?=$is_show_bwnummer?'900px':'1000px' ?>" <? if ($klikbaar): ?> context_model="<?=$object->get_model_name()?>" context_id="<?=$object->id?>" bouwnummer_id="<?=(is_null($bwnummer)||$bwnummer=='') ? '-' : $bwnummer ?>" <? endif; ?> > <? if (!$gebruiker): ?> <div class="list-entry" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: <?=($is_show_bwnummer?'464':'620')?>px;"> <?=$tekst?> <? if ($is_show_bwnummer): ?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=(is_null($bwnummer)||$bwnummer=='') ? '-' : $bwnummer ;?> <? endif; ?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=date('d-m-Y', strtotime($gereed_datum))?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=$gereed ? 'Gereed' : 'Niet gereed'?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 50px; text-align: center;"> <img src="/files/images/nlaf/status-<?=$kleur?>.png" /> <? if ($is_show_bwnummer && $bwnummer != '-' && $context_model == 'checklist' ): ?> </div><div onclick="changeStatusAkkoord('<?=$object->id?>','<?=$bwnummer?>');" class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 50px; text-align: center;"> <img src="/files/images/nlaf/status-<?=$bw_color?>.png" /> <? endif; ?> </div> <? else: ?> <? if ($klikbaar): ?> <div class="list-entry" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 310px;"> <?=$tekst?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=$gebruiker?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=$annotatie_tag?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px;"> <?=$opdrachtnemer ?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=date('d-m-Y', strtotime($gereed_datum))?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 10px; vertical-align: top; display: inline-block; width: 100px; text-align: center;"> <?=$gereed ? 'Gereed' : 'Niet gereed'?> </div><div class="list-entry left" style="height: 25px; padding-left: 5px; padding-top: 7px; vertical-align: top; display: inline-block; width: 25px; text-align: center;"> <img src="/files/images/nlaf/status-<?=$kleur?>.png" /> </div> <? endif; ?> <? endif; ?> </li> <? endif; ?> <? if ($context_model == 'deelplanopdracht'):?> <div style="border: 1px solid #000000;padding: 5px;border-radius: 5px 5px;width: <?=$is_show_bwnummer?'893px':'993px' ?>"> <div style="display: table;"> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Omschrijving</span> <span style="display:table-cell">: <?=!is_null($object->opdracht_omschrijving) ? $object->opdracht_omschrijving : ''; ?></span></div> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Toelichting</span> <span style="display:table-cell">: <?=!is_null($object->toelichting) ? $object->toelichting: '' ; ?></span></div> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Status</span> <span style="display:table-cell">: <?=!is_null($object->status) ? $object->status : ''; ?></span></div> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Waardeoordeel</span> <span style="display:table-cell">: <?=$waardeoordeel ?></span></div> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Datum Begin</span> <span style="display:table-cell">: <?=!is_null($object->datum_begin) ? $object->datum_begin:''; ?></span></div> <div style="display: table-row;"><span style="display:table-cell;width: 100px;">Datum Einde</span> <span style="display:table-cell">: <?=!is_null($object->datum_einde) ? $object->datum_einde:''; ?></span></div> </div> <? if (method_exists($object, 'get_deelplan_uploads') && !$klikbaar): $deelplanuploads = $object->get_deelplan_uploads(); if (sizeof( $object->get_deelplan_uploads())):?> <div style="vertical-align: top;"> <? foreach ($deelplanuploads as $upload): ?> <a href="<?=$object->get_upload_fullsize_afbeelding_url($upload->id); ?>" target="_blank"><img src="<?=$object->get_upload_thumbnail_afbeelding_url($upload->id); ?>" /></a> <? endforeach; ?> </div> <? endif; ?> <? endif; ?> </div> <? endif; ?> <? endforeach; ?> <? endforeach; ?> </ul> </div> <script type="text/javascript"> var is_context = true ; function changeStatusAkkoord(HfId,bwnummer){ is_context = false; $.ajax({ url: "<?=site_url('deelplannen/change_status_akkoord') ?>/"+HfId, type: "POST", data: { "deelplan_id": '<?=$deelplan->id?>', "checklist_id": '<?=$context_id?>', "bouwnummer": bwnummer }, dataType: "json", success: function( data ){ if (data && data.success){ location.href = '/deelplannen/opdrachtenoverzicht' + '/' + encodeURIComponent('<?=$deelplan->id?>') + '/' + encodeURIComponent('<?=$bouwnummer_id?>') + '/' + encodeURIComponent('<?=$context_model?>') + '/' + encodeURIComponent('<?=$context_id?>') + '/' + encodeURIComponent('<?=$opdrachtgever_id?>') + '/' + encodeURIComponent('<?=$opdrachtnemer_id?>') + '/' + encodeURIComponent('<?=$datum?>') + '/' + encodeURIComponent('<?=$locatie?>') + '/' + encodeURIComponent('<?=$groen_filter?1:0?>') + '/' + encodeURIComponent('<?=$oranje_filter?1:0?>') + '/' + encodeURIComponent('<?=$rood_filter?1:0?>') ; }else showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen:<br/><br/><i>" + data.error + "</i>", type: "error", buttons: ["ok"] }); }, error: function() { showMessageBox({ message: "Er is iets fout gegaan bij het toevoegen.", type: "error", buttons: ["ok"] }); } }); } //------------------------------------- $(document).ready(function(){ // new URL var curDeelplanId = '<?=$deelplan->id?>'; var curBouwnummer = '<?=$bouwnummer_id?>'; var curContextModel = '<?=$context_model?>'; var curContextId = '<?=$context_id?>'; var curOpdrachtgeverId = '<?=$opdrachtgever_id?>'; var curOpdrachtnemerId = '<?=$opdrachtnemer_id?>'; var curDatum = '<?=$datum?>'; var curLocatie = '<?=$locatie?>'; var curGroenFilter = '<?=$groen_filter?1:0?>'; var curOranjeFilter = '<?=$oranje_filter?1:0?>'; var curRoodFilter = '<?=$rood_filter?1:0?>' var applyFilter = function( bouwnummer_id, context_model, context_id, opdrachtgever_id, opdrachtnemer_id, datum, locatie, groen_filter, oranje_filter, rood_filter ) { location.href = '/deelplannen/opdrachtenoverzicht' + '/' + encodeURIComponent(curDeelplanId) + '/' + encodeURIComponent(bouwnummer_id) + '/' + encodeURIComponent(context_model) + '/' + encodeURIComponent(context_id) + '/' + encodeURIComponent(opdrachtgever_id) + '/' + encodeURIComponent(opdrachtnemer_id) + '/' + encodeURIComponent(datum) + '/' + encodeURIComponent(locatie) + '/' + encodeURIComponent(groen_filter) + '/' + encodeURIComponent(oranje_filter) + '/' + encodeURIComponent(rood_filter) ; }; // when row is clicked, go to subpage! $('li[context_model]').click(function(){ var model = $(this).attr('context_model'); var id = $(this).attr('context_id'); var bouwnummer_id = $(this).attr('bouwnummer_id'); if(is_context){ applyFilter( bouwnummer_id, model, id, curOpdrachtgeverId, curOpdrachtnemerId, curDatum, curLocatie, curGroenFilter, curOranjeFilter, curRoodFilter ); } is_context = true; }); // handle filter changes $('select[name=opdrachtgever_id]').change(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, $(this).val(), curOpdrachtnemerId, curDatum, curLocatie, curGroenFilter, curOranjeFilter, curRoodFilter ); }); $('select[name=opdrachtnemer_id]').change(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, $(this).val(), curDatum, curLocatie, curGroenFilter, curOranjeFilter, curRoodFilter ); }); $('select[name=datum]').change(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, curOpdrachtnemerId, $(this).val(), curLocatie, curGroenFilter, curOranjeFilter, curRoodFilter ); }); $('select[name=locatie]').change(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, curOpdrachtnemerId, curDatum, $(this).val(), curGroenFilter, curOranjeFilter, curRoodFilter ); }); $('input[name=status-groen]').click(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, curOpdrachtnemerId, curDatum, curLocatie, this.checked?1:0, curOranjeFilter, curRoodFilter ); }); $('input[name=status-oranje]').click(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, curOpdrachtnemerId, curDatum, curLocatie, curGroenFilter, this.checked?1:0, curRoodFilter ); }); $('input[name=status-rood]').click(function(){ applyFilter( curBouwnummer, curContextModel, curContextId, curOpdrachtgeverId, curOpdrachtnemerId, curDatum, curLocatie, curGroenFilter, curOranjeFilter, this.checked?1:0 ); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('deelplannen.project_specifieke_mapping::projectmatrix', 'Projectmatrix BRIStoets', NOW(), 0); <file_sep>-- duplicate foreign keys ALTER TABLE `deelplan_themas` DROP FOREIGN KEY `deelplan_themas_ibfk_4` ; ALTER TABLE `deelplan_vraag_bescheiden` DROP FOREIGN KEY `deelplan_vraag_bescheiden_ibfk_3` ; ALTER TABLE `deelplan_vraag_bescheiden` DROP FOREIGN KEY `deelplan_vraag_bescheiden_ibfk_4` ; ALTER TABLE `deelplan_vraag_bescheiden` DROP FOREIGN KEY `deelplan_vraag_bescheiden_ibfk_5` ; ALTER TABLE `deelplan_vraag_geschiedenis` DROP FOREIGN KEY `deelplan_vraag_geschiedenis_ibfk_6` ; -- update existing key to allow updates ALTER TABLE `deelplan_vragen` DROP FOREIGN KEY `deelplan_vragen_ibfk_4` ; ALTER TABLE `deelplan_vragen` ADD CONSTRAINT `deelplan_vragen_ibfk_4` FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `gebruiker_collegas` DROP FOREIGN KEY `gebruiker_collegas_ibfk_1` ; ALTER TABLE `gebruiker_collegas` ADD CONSTRAINT `gebruiker_collegas_ibfk_1` FOREIGN KEY ( `gebruiker1_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `gebruiker_collegas` DROP FOREIGN KEY `gebruiker_collegas_ibfk_2` ; ALTER TABLE `gebruiker_collegas` ADD CONSTRAINT `gebruiker_collegas_ibfk_2` FOREIGN KEY ( `gebruiker2_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `logs` DROP FOREIGN KEY `logs_ibfk_2` ; ALTER TABLE `logs` ADD CONSTRAINT `logs_ibfk_2` FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `stats_sessies` DROP FOREIGN KEY `stats_sessies_ibfk_1` ; ALTER TABLE `stats_sessies` ADD CONSTRAINT `stats_sessies_ibfk_1` FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `dossiers` DROP FOREIGN KEY `dossiers_ibfk_1` ; ALTER TABLE `dossiers` ADD CONSTRAINT `dossiers_ibfk_1` FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep><p> <b>Beschikbare matrices</b> <select style="width:150px" name="matrix[<?=$checklistgroep->id?>]" class="matrices"> <? $have_selected = false; foreach ($matrices as $m) { $extra = ''; if ($m->klant_id != $this->session->userdata('kid')) $extra = '(alleen lezen)'; ?> <option <?=$matrix->id == $m->id ? 'selected' : ''?> value="<?=$m->id?>"> <?=htmlentities( $m->naam, ENT_COMPAT, 'UTF-8' )?> <?=$extra?> </option> <? } ?> </select> <a title="Matrix toevoegen voor deze checklist groep" href="javascript:void(0);"><img class="matrix-add" checklist_groep_id="<?=$checklistgroep->id?>" src="<?=site_url('/files/images/add.png')?>" /></a> <a title="Matrix verwijderen voor deze checklist groep" href="javascript:void(0);"><img class="matrix-delete" checklist_groep_id="<?=$checklistgroep->id?>" src="<?=site_url('/files/images/delete.png')?>" /></a> </p> <script type="text/javascript"> $(document).ready(function(){ $('img.matrix-add').click(function(){ showPopup( "Matrix toevoegen", "/instellingen/matrix_toevoegen/" + $(this).attr('checklist_groep_id'), 500, 440 ); }); $('img.matrix-delete').click(function(){ var checklist_groep_id = $(this).attr('checklist_groep_id'); var matrix_id = $(this).parent().siblings('select').val(); showPopup( "Matrix verwijderen", "/instellingen/matrix_verwijderen/" + matrix_id, 500, 200 ); }); $('select.matrices').change(function(){ if (confirm( 'Nu wisselen naar matrix ' + this.options[this.selectedIndex].label + '?' )) location.href='<?=site_url('/instellingen/prioriteitstelling_matrix/' . $checklistgroep->id)?>/' + this.value + '/<?=$weergave?>'; }); }); </script> <file_sep>REPLACE INTO teksten(string, tekst, timestamp, lease_configuratie_id) VALUES ('checklistwizard.section.achtergrondinformatie', 'Achtergrondinformatie', '2014-09-21 20:35:23', 0), ('checklistwizard.section.algemeen', 'Algemeen', '2014-09-21 20:35:02', 0), ('checklistwizard.section.opdrachten', 'Opdrachten', '2014-09-21 20:35:45', 0), ('checklistwizard.section.verantwoordingen', 'Verantwoordingen (Beta!)', '2014-09-21 20:35:38', 0), ('checklistwizard.section.vragen', 'Vraag', '2014-09-21 20:35:12', 0), ('checklistwizard.verantwtkstn', 'Verantwoordingen', '2014-09-21 20:36:21', 0);<file_sep><?php class CI_Utils { public static function store_file($path, $filename, $content) { $filepath = $path . '/' . $filename; self::create_dir($path); if( !file_put_contents($filepath, $content) ) { throw new Exception('Failed to create file "'. $filepath. '"'); } } public static function create_dir($dir, $mode = 0777) { if( !is_dir($dir) ) { if( !mkdir($dir, $mode, TRUE) ) { throw new Exception('Failed to create folder "'. $dir. '"'); } } } public static function check_extension($filename, array $allowed_extensions) { $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if( in_array($ext, $allowed_extensions) ) { return true; } return false; } public static function is_digit($digit) { if( is_int($digit) ) { return true; } elseif( is_string($digit) ) { return ctype_digit($digit); } else { return false; } } }<file_sep>BRISToezicht.Toets.Bescheiden = { imageSet: null, initialize: function() { // init image set collection this.imageSet = $('.documenten .image-set'); // finally, initialize initially viewed images this.updateList(); // make all "maak relevant/maak niet relevant" buttons work $('.nlaf_TabContent .documenten [maak-bescheid-relevant]').live('click', function(){ var bescheid_id = $(this).attr('bescheid_id'); switch ($(this).attr('maak-bescheid-relevant')) { case 'nee': BRISToezicht.Toets.Bescheiden.maakNietLangerRelevantVoorVraag( bescheid_id ); break; case 'ja': BRISToezicht.Toets.Bescheiden.maakRelevantVoorHuidigeVraag( bescheid_id ); break; } var setAantalLabel = function( o, aantal ) { o[ aantal ? 'show' : 'hide' ](); o.text( aantal ); }; var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); var totaalAantalBescheiden = BRISToezicht.Tools.getNumProps( vraagData.vraagbescheiden ); setAantalLabel( $('#nlaf_TotaalAantalBescheiden'), totaalAantalBescheiden ); }); //var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (BRISToezicht.Toets.readonlyMode) $('.nlaf_TabContent .documenten input.maak-relevant').hide(); }, getVisibleBescheidenImage: function() { var img = $('.nlaf_TabContent .documenten .bestand .container').children('[bescheid_id]:visible'); if (!img.size()) return null; return img; }, moveBescheidenToImageView: function() { var img = this.getVisibleBescheidenImage(); if (!img) return false; $('#nlaf_ViewImage').html( '' ); img.detach(); img.appendTo( $('#nlaf_ViewImage') ); img.data( 'oldWidth', img.css( 'width' ) ); img.css( 'width', 'auto' ); return true; }, restoreBescheidenFromImageView: function() { var img = $('#nlaf_ViewImage').find( '[bescheid_id]' ); img.detach(); img.css( 'width', img.data('oldWidth') ); img.appendTo( $('.nlaf_TabContent .documenten .container') ); // om de juiste volgorde van images aan te houden, herladen we nu de bescheidenlijst..... :/ BRISToezicht.Toets.Bescheiden.updateList(); }, loadImageSet: function( images ) { // get base var base = $('.nlaf_TabContent .documenten .bestand .container'); var set = $('.nlaf_TabContent .documenten .image-set'); var dual = $('.nlaf_TabContent .documenten [mode=dual] .dataregels table'); var details = $('.nlaf_TabContent .documenten [mode=details] .dataregels table'); // clear current base.children( '[bescheid_id]' ).detach().appendTo( set ); dual.children().remove(); details.children().remove(); $('.nlaf_TabContent .documenten .info-naam span').text( '' ); // handle images var c = 0; for (var i in images) { var image = images[i]; if (typeof(image) != 'object') continue; // create list of img objects var img = this.imageSet.find('[bescheid_id=' + image.bescheid_id + ']'); img.detach(); // from set img.appendTo( base ); img.data( 'image', image ); img.removeClass( 'hidden' ); if (c) img.addClass( 'hidden' ); // create entry in dual table var tr = $('<tr>').appendTo( dual ).attr( 'bestand-index', c ).data( 'image', image )[ c ? 'removeClass' : 'addClass' ]('selected'); //$('<td>').appendTo( tr ).css( 'width', '37px' ).html( '<img src="/files/images/nlaf/bestand-icon.png" />' ); $('<td>').appendTo( tr ).css( 'width', '150px' ).text( image.bestandsnaam ); $('<td>').appendTo( tr ).css( 'width', '65px' ).text( image.datum_laatste_wijziging ); $('<td>').appendTo( tr ).text( image.omschrijving ); // create entry in details table var tr = $('<tr>').appendTo( details ).attr( 'bestand-index', c ).data( 'image', image )[ c ? 'removeClass' : 'addClass' ]('selected');; //$('<td>').appendTo( tr ).css( 'width', '37px' ).html( '<img src="/files/images/nlaf/bestand-icon.png" />' ); $('<td>').appendTo( tr ).css( 'width', '200px' ).text( image.bestandsnaam ); $('<td>').appendTo( tr ).css( 'width', '80px' ).text( image.datum_laatste_wijziging ); $('<td>').appendTo( tr ).css( 'width', '100px' ).text( image.tekening_stuk_nummer ); $('<td>').appendTo( tr ).text( image.omschrijving ); $('<td>').appendTo( tr ).css( 'width', '100px' ).text( image.auteur ); $('<td>').appendTo( tr ).css( 'width', '140px' ).html( !BRISToezicht.Toets.readonlyMode ? ( image.relevant ? ('<input type="button" value="Maak niet relevant" bescheid_id="' + image.bescheid_id + '" maak-bescheid-relevant="nee" />') : ('<input type="button" value="Maak relevant" bescheid_id="' + image.bescheid_id + '" maak-bescheid-relevant="ja" />') ) : '' ); tr.children().css( 'cursor', 'default' ); // update main "Maak relevant" button to settings for first image if (c == 0) { var relBtn = $('.nlaf_TabContent .documenten input.maak-relevant'); if (image.relevant) { relBtn.attr('maak-bescheid-relevant', 'nee'); relBtn.attr('value', 'Maak niet relevant' ); } else { relBtn.attr('maak-bescheid-relevant', 'ja'); relBtn.attr('value', 'Maak relevant' ); } relBtn.attr( 'bescheid_id', image.bescheid_id ); $('.nlaf_TabContent .documenten .info-naam span').text( image.bestandsnaam ); } // increase index ++c; } // update counter var numImages = BRISToezicht.Tools.getNumProps( images ); $('.nlaf_TabContent .documenten .aantal').text( $('.XvanY').text().replace( /\$1/, numImages ? 1 : 0 ).replace( /\$2/, numImages ) ); }, loadAlles: function() { this.loadImageSet( BRISToezicht.Toets.data.bescheiden ); }, loadRelevant: function() { // update list var images = $.extend( {}, BRISToezicht.Toets.data.bescheiden ); for (var i in images) { if (!images[i].relevant) delete images[i]; } this.loadImageSet( images ); }, updateList: function() { // update relevant image meta data var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraagData) { var images = $.extend( {}, BRISToezicht.Toets.data.bescheiden ); for (var i in images) { var image = images[i]; image.relevant = typeof( vraagData.vraagbescheiden[i] ) == 'object'; } } // herlaadt selectie, dit zet namelijk ook de "maak relevant/maak niet relevant" knoppen correct! if ($( '.documenten [name=document-filter]:checked').val() == 'relevant') { this.loadRelevant(); } else { this.loadAlles(); } }, maakRelevantVoorHuidigeVraag: function( bescheiden_id ) { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; // check of bescheiden niet al is gekoppeld aan deze vraag for (var i in vraagData.vraagbescheiden) { var vb = vraagData.vraagbescheiden[i]; if (typeof( vb ) != 'function') { if (i == bescheiden_id) return; } } // koppel intern vraagData.vraagbescheiden[ bescheiden_id ] = BRISToezicht.Toets.data.bescheiden[bescheiden_id]; vraagData.vraagbescheiden[ bescheiden_id ].relevant = true; // update alle buttons var relBtn = $('.nlaf_TabContent .documenten [maak-bescheid-relevant][bescheid_id=' + bescheiden_id + ']') .attr( 'maak-bescheid-relevant', 'nee' ) .attr( 'value', 'Maak niet relevant' ); // voeg store-once data toe voor deze actie var data = { _command: 'maakbescheidenrelevantvoorvraag', vraag_id: BRISToezicht.Toets.Vraag.huidigeVraag, bescheiden_id: bescheiden_id }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); }, maakNietLangerRelevantVoorVraag: function( bescheiden_id ) { var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; // koppel intern vraagData.vraagbescheiden[ bescheiden_id ].relevant = false; delete vraagData.vraagbescheiden[ bescheiden_id ]; // update alle buttons var relBtn = $('.nlaf_TabContent .documenten [maak-bescheid-relevant][bescheid_id=' + bescheiden_id + ']') .attr( 'maak-bescheid-relevant', 'ja' ) .attr( 'value', 'Maak relevant' ); // voeg store-once data toe voor deze actie var data = { _command: 'maakbescheidennietlangerrelevantvoorvraag', vraag_id: BRISToezicht.Toets.Vraag.huidigeVraag, bescheiden_id: bescheiden_id }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); } }; <file_sep>PDFAnnotator.Engine.Platform = PDFAnnotator.Base.extend({ /* constructor */ init: function() { this.isMobile = navigator && navigator.userAgent && (navigator.userAgent.match( /mobile|android/i ) ? true : false); this.isAndroid = navigator && navigator.userAgent && (navigator.userAgent.match( /android/i ) ? true : false ); } }); <file_sep><? $CI = get_instance(); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); $CI->tekst->set_method( 'bewerken' ); $CI->load->model( 'dossierbescheidenmap' ); if (!isset($dossier_access)) $dossier_access="write"; $dossier_bescheiden_map = $CI->dossierbescheidenmap->get( @$dossier_bescheiden_map_id ); $pad = $dossier_bescheiden_map ? ' [' . $dossier_bescheiden_map->get_pad() . ']' : null; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('documenten.header') . $pad, 'group_tag' => 'dossier', 'expanded' => $open_tab_group=='bescheiden', 'width' => '100%', 'height' => $CI->is_Mobile ? '380px' : 'auto', 'rightheader' => null ) ); ?> <table width="100%"> <tr> <? $columns = 4; $index = 0; ?> <!-- "BACK" option --> <? if (@$dossier_bescheiden_map_id): ?> <? $parent = $this->dossierbescheidenmap->get( $dossier_bescheiden_map_id )->get_parent(); ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div class="droppable" style="padding:0;margin:0;height:auto;border:0"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <img bescheiden_map_id="<?=$parent ? $parent->id : 0?>" src="/files/images/bescheidenmap.png" onclick="openBescheidenMap( <?=$parent ? $parent->id : 0?> );" style="cursor: pointer" /><br/> </div> <div style="display: inline-block; overflow:hidden; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; width: 190px;"> <b><?=tg('terug.naar.parent')?></b> </div> </div> </td> <? ++$index; ?> <? endif; ?> <!-- maps --> <? foreach ($mappen as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div class="droppable" style="padding:0;margin:0;height:auto;border:0"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <img bescheiden_map_id="<?=$b->id?>" src="/files/images/bescheidenmap.png" onclick="openBescheidenMap( <?=$b->id?> );" style="cursor: pointer" /><br/> </div> <div style="display: inline-block; overflow:hidden; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; width: 190px; " title="<?=htmlentities( $b->naam, ENT_COMPAT, 'UTF-8' )?>"> <input type="checkbox" bescheiden_map_id="<?=$b->id?>" /> <b><?=htmlentities( $b->naam, ENT_COMPAT, 'UTF-8' )?></b><br/> <i class="aantal-bescheiden"><?=tg('aantal.sub.bescheiden',$b->get_aantal_bescheiden_in_map())?></i> </div> </div> </td> <? ++$index; ?> <? endforeach;?> <!-- bescheiden --> <? foreach ($bescheiden as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div class="draggable" style="padding:0;margin:0;height:auto;border:0"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <img bescheiden_id="<?=$b->id?>" src="<?=site_url( '/pdfview/bescheiden/' . $b->id . '/1' )?>" onclick="openBescheidenPopup( <?=$b->id?> );" style="cursor: pointer" /><br/> </div> <div style="display: inline-block; overflow:hidden; height: 30px; padding: 5px; margin: 0; border: 0; background-color:#ddd; width: 190px; " title="<?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?>"> <input type="checkbox" bescheiden_id="<?=$b->id?>" /> <b><?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?></b> </div> </div> </td> <? ++$index; ?> <? endforeach;?> <? for ($i=0; $i<($columns - $index); ++$i): ?> <td style="width:<?=round(100/$columns)?>%"></td> <? endfor; ?> </tr> </table> <br/> <br/> <table width="100%" class="defaultActions"> <tr> <?php if($dossier_access=='write') :?> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.nieuwe_map'), 'blank' => false, 'url' => 'javascript:nieuweBescheidenMap();', 'class' => 'greenbutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.nieuw'), 'blank' => false, 'url' => 'javascript:nieuwBescheiden(0,'.$dossier->id.');', 'class' => 'greenbutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.verplaatsen'), 'blank' => false, 'url' => 'javascript:bescheidenVerplaatsen();', 'class' => 'bluebutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.alles_selecteren'), 'blank' => false, 'url' => 'javascript:selecteerAlleBescheiden();', 'class' => 'graybutton' ) ); ?> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.verwijderen'), 'blank' => false, 'url' => 'javascript:verwijderGeselecteerdeBescheiden();', 'class' => 'redbutton' ) ); ?> </td> <?php endif;?> </tr> </table> <table width="100%" class="moveActions hidden"> <tr> <td style="text-align: center" width="20%"> </td> <td style="text-align: center" width="20%"> </td> <td style="text-align: center" width="20%"> </td> <td style="text-align: center" width="20%"> </td> <td style="text-align: center" width="20%"> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.gereed'), 'blank' => false, 'url' => 'javascript:openBescheidenMap(currentBescheidenMapId);', 'class' => 'bluebutton' ) ); ?> </td> </tr> </table> <script type="text/javascript"> var currentBescheidenMapId = <?=intval(@$dossier_bescheiden_map_id)?>; var selectedBescheidenId = 0; /* utilities */ function showError( msg ) { showMessageBox({message: msg, buttons: ['ok'], type: 'error'}); } function getBescheidenParent() { return $('.bescheiden-container'); } function getSelectedBescheidenIds() { var result = []; getBescheidenParent().find('input[type=checkbox]').each(function(){ if (this.checked) { var bescheiden_id = $(this).attr( 'bescheiden_id' ); var bescheiden_map_id = $(this).attr( 'bescheiden_map_id' ); result.push( bescheiden_id ? bescheiden_id : ('m' + bescheiden_map_id) ); } }); return result; } function getBescheidenBase() { return $('.bescheiden-container'); } function herlaadBescheidenHTML( html ) { var base = getBescheidenBase(); base.html( html ); BRISToezicht.Group.visibleGroup['dossier'] = base.find('.group'); } function deleteBescheidenByIds( ids ) { $.ajax({ url: '/dossiers/bescheiden_verwijderen_batch/<?=$dossier->id?>/' + currentBescheidenMapId, type: 'POST', data: { ids: JSON.stringify( ids ) }, dataType: 'html', success: function( data ) { herlaadBescheidenHTML( data ); }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } /* functies aangeroepen vanuit deze pagina */ var uploadBezig = false; function openBescheidenPopup( id, dossier_id) { selectedBescheidenId = id; if(dossier_id){ var url=id+'/'+dossier_id; } else var url=id; modalPopup({ url: '<?=site_url('/dossiers/bescheiden_popup/')?>/' + url, width: 900, height: 500, onClose: function() { if (uploadBezig) { showError( '<?=tgn('er_is_nog_een_upload_bezig_even_geduld_aub')?>' ); return false; } } }); } function selecteerAlleBescheiden() { getBescheidenParent().find('input[type=checkbox]').attr( 'checked', 'checked' ); } function verwijderGeselecteerdeBescheiden() { var selIds = getSelectedBescheidenIds(); if (selIds.length == 0) { showError( '<?=tgn('selecteer_eerst_de_bescheiden_die_u_wenst_te_verwijderen')?>' ); return; } showMessageBox({ message: '<?=tgn('geselecteerde_bescheiden_werkelijk_verwijderen')?>', onClose: function( res ) { if (res == 'ok') { deleteBescheidenByIds( selIds ); } } }); } function nieuwBescheiden(id, dossier_id) { openBescheidenPopup( id, dossier_id ); } function openBescheidenMap( id ) { $.ajax({ url: '/dossiers/bescheiden_lijst/<?=$dossier->id?>/' + id, type: 'POST', dataType: 'html', success: function( data ) { herlaadBescheidenHTML( data ); }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } function nieuweBescheidenMap() { showMessageBox({ message: 'Nieuwe map naam:<br/><br/><input type="text" name="mapnaam" size="60" maxlength="256" />', width: 500, onClose: function( res ) { if (res == 'ok') { var naam = getPopup().find('[name=mapnaam]').val(); $.ajax({ url: '/dossiers/bescheiden_map_toevoegen/<?=$dossier->id?>/' + currentBescheidenMapId, type: 'POST', data: { mapnaam: naam, }, dataType: 'json', success: function( data ) { if (!data.success) showError(data.error || '<?=tgn('er.is.een.onbekende.fout.opgetreden')?>'); else openBescheidenMap( currentBescheidenMapId ); }, error: function() { showError('<?=tgn('er.is.een.onbekende.fout.opgetreden')?>'); } }); } } }); } function bescheidenVerplaatsen() { var base = getBescheidenBase(); // verwijder en disable bepaalde elementen, toon nieuwe knop $('.defaultActions').remove(); base.find('input[type=checkbox]').remove(); base.find('.aantal-bescheiden').remove(); base.find('[onclick]').each(function(){ this.onclick = function(){}; }); $('.moveActions').show(); // maak bescheiden mappen droppable, en bescheiden draggable base.find('img[bescheiden_map_id]').closest('.droppable').droppable({ drop: function(ev, draggable) { var bescheiden_map_id = $(this).find('img[bescheiden_map_id]').attr( 'bescheiden_map_id' ); var bescheiden_id = draggable.helper.attr('bescheiden_id'); var orig = draggable.draggable; showPleaseWait(); $.ajax({ url: '/dossiers/bescheiden_verplaatsen/' + bescheiden_id + '/' + bescheiden_map_id, type: 'POST', dataType: 'json', success: function(data) { hidePleaseWait(); if (!data.success) showError( data.error ); else orig.remove(); }, error: function() { hidePleaseWait(); showError('<?=tgn('er.is.een.onbekende.fout.opgetreden')?>'); } }); } }); base.find('img[bescheiden_id]').closest('.draggable').draggable({ cursor: 'move', containment: base, helper: function( event ) { var img = $(event.currentTarget).find( 'img' ); return $('<div>').append( img.clone() ).html(); } }); } /* functies aangeroepen vanuit de popup */ function editBescheiden() { // First we enable ALL input fields.... getPopup().find( 'input, textarea' ).removeAttr( 'disabled' ); // Then we explicitely disable the 'file upload' input, as we do NOT want to allow the user to replace the file itself! $('#bestand_upload').prop('disabled', true); } function isBescheidenEditbaar() { return getPopup().find( 'input' ).attr( 'disabled' ) ? false : true; } function opslaanBescheiden() { if (!isBescheidenEditbaar()) { closePopup(); return; } if (selectedBescheidenId) url = '<?=site_url('/dossiers/bescheiden_bewerken/')?>/' + selectedBescheidenId + '/' + currentBescheidenMapId; else url = '<?=site_url('/dossiers/bescheiden_toevoegen/' . $dossier->id)?>' + '/' + currentBescheidenMapId; // init busy state uploadBezig = true; getPopup().find( 'input, textarea, select' ).attr( 'readonly', 'readonly' ); var form = getPopup().find('form'); form.attr( 'action', url ); var $fileUpload = $("input[type='file']"); if (parseInt($fileUpload.get(0).files.length) > 20){ uploadBezig = false; getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); showError('<?=tgn('upload_file_limit')?>'); } else { $('.pleasewaitbar').slideDown(); $('.buttonbar').hide(); BRISToezicht.Upload.start( form[0], function( data ){ // restore state getPopup().find( 'input, textarea, select' ).removeAttr( 'readonly' ); uploadBezig = false; $('.buttonbar').slideDown(); $('.pleasewaitbar').hide(); if (data.match( /^FOUT:\s*(.*?)$/ )) showError( RegExp.$1 ); else { closePopup(); herlaadBescheidenHTML( data ); } }); } } function verwijderBescheiden() { if (!selectedBescheidenId) { showError( '<?=tgn('u_kunt_een_nieuw_bescheiden_niet_verwijderen')?>' ); return; } showMessageBox({ message: '<?=tgn('weet_u_zeker_dat_u_dit_bescheiden_wilt_verwijderen')?>', onClose: function( res ) { if (res == 'ok') { setTimeout( function() { // call close popup to close popup underneath us, but do it 1 ms later // because otherwise getPopup (which closePopup uses) will close // our message box, in stead of the popup that called us ;-) closePopup(); }, 1 ); deleteBescheidenByIds( [selectedBescheidenId] ); } } }); } </script> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?><file_sep><? load_view( 'header.php' ); ?> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/logo.png" height="21" /> <p style="width: 400px; text-align: justify;"> Er is iets fout gegaan bij het opstarten van de sessie. Dit komt hoogstwaarschijnlijk door uw cookie instellingen. Als uw browser geen cookies accepteert, dan kunt u geen gebruik maken van de PDF annotator.<br/> <br/> Wijzig de cookie instellingen in uw browser en probeer het opnieuw! </p> <? load_view( 'footer.php' ); ?> <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('nav.checklist_export', 'Checklist export', NOW(), 0), ('dossiers.rapportage::uitvoer.docxpdf', 'PDF nieuwe stijl (beta) - v0.0.3 - 9-9-2014', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.docx', 'DOCX nieuwe stijl (beta) - v0.0.3 - 9-9-2014', '2014-05-08 22:45:00', 0) ; <file_sep>CREATE TABLE bt_vraag_verantwtkstn_automatic ( id INT(11) NOT NULL AUTO_INCREMENT, vraag_id INT(11) NOT NULL, checklist_id INT(11) NOT NULL, checklist_groep_id INT(11) NOT NULL, verantwoordingstekst VARCHAR(1024) NOT NULL, automatic INT(11) DEFAULT 0, automatish_generate INT(11) DEFAULT 0, PRIMARY KEY (id), INDEX checklist_groep_id (checklist_groep_id), INDEX checklist_id (checklist_id), INDEX vraag_id (vraag_id), CONSTRAINT bt_vraag_verantwtkstn_automatic_ibfk_1 FOREIGN KEY (vraag_id) REFERENCES bt_vragen(id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT bt_vraag_verantwtkstn_automatic_ibfk_2 FOREIGN KEY (checklist_groep_id) REFERENCES bt_checklist_groepen(id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT bt_vraag_verantwtkstn_automatic_ibfk_3 FOREIGN KEY (checklist_id) REFERENCES bt_checklisten(id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE verantwoordingstekst_config ( id int(11) NOT NULL AUTO_INCREMENT, vraag_id int(11) DEFAULT NULL, vraag_verantwtkstn_id int(11) DEFAULT NULL, name varchar(255) DEFAULT NULL, UNIQUE INDEX id (id) ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; ALTER TABLE klanten ADD COLUMN automatic_accountability_text INT DEFAULT 0 AFTER kan_dossieroverzichten_genereren; REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('klant.automatic_accountability_text', 'Automatic accountability text? ', NOW(), 0); REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('checklistwizard.automatic_verantwoordingstekst_popup::automatic_verantwoordingstekst_title', 'Standaart verantwoording toevoegen', NOW(), 0); REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('checklistwizard.automatic_verantwoordingstekst_popup::text_title', 'Voer uw tekst in:', NOW(), 0); REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('checklistwizard.automatic_verantwoordingstekst_popup::description::text_title', 'Gef aan bij welke waardeoordelen deze tekst beschikbaar moet zijn', NOW(), 0); REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('automatish', 'Bij een van de gekozen waardeoordelen wordt al automatisch een andere standaardzin gekozen.', NOW(), 0); <file_sep>-- run cli command: -- php index.php /cli/fix_standaard_themas_in_checklistgroepen <file_sep>run: php index.php /cli/inupdate_prio_data <file_sep>REPLACE INTO teksten(string, tekst , timestamp , lease_configuratie_id) VALUES ('dossiers.subject_bewerken::ext_user_already_exists', 'De persoon die u probeert toe te voegen is niet van een externe organisatie', '2015-01-08 14:54:18', '0'), ('dossiers.subject_bewerken::ext_user_already_exists', 'De persoon die u probeert toe te voegen is niet van een externe organisatie', '2015-01-08 14:54:18', '1'), ('dossiers.subject_bewerken::dossier_subject_already_exists', 'De persoon die u probeert toe te voegen bestaat reeds als betrokkene bij dit dossier', '2015-01-08 14:57:38', '0'), ('dossiers.subject_bewerken::dossier_subject_already_exists', 'De persoon die u probeert toe te voegen bestaat reeds als betrokkene bij dit dossier', '2015-01-08 14:57:38', '1'), ('dossiers.rapportage::annotaties_download', 'Annotaties download (full size)', '2015-01-08 14:57:38', '0'), ('dossiers.rapportage::annotaties_download', 'Annotaties download (full size)', '2015-01-08 14:57:38', '1'), ('dossiers.rapportage::uitvoer.docxpdf', 'PDF nieuwe stijl (beta) - v0.9.0 - 30-3-2015', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.docxpdf', 'PDF nieuwe stijl (beta) - v0.9.0 - 30-3-2015', '2014-05-08 22:45:00', 1), ('dossiers.rapportage::uitvoer.docx', 'DOCX nieuwe stijl (beta) - v0.9.0 - 30-3-2015', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.docx', 'DOCX nieuwe stijl (beta) - v0.9.0 - 30-3-2015', '2014-05-08 22:45:00', 1) ; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('nav.checklist_export', 'Checklist export', NOW(), 0), ('dossiers.rapportage::uitvoer.docxpdf', 'PDF nieuwe stijl (beta) - v0.0.3 - 9-9-2014', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.docx', 'DOCX nieuwe stijl (beta) - v0.0.3 - 9-9-2014', '2014-05-08 22:45:00', 0) ; REPLACE INTO help_buttons(tag, taal, tekst) VALUES ('dossiers.bewerken.email_kid', 'nl', 'Geef het email adres op van de externe gebruiker voor de opdrachten'); <file_sep><?php class BRIStoezichtWebserviceModule extends WebserviceModule { public function AandachtspuntenToevoegen() { $this->_log->extra_result .= "BRIStoezichtWebserviceModule::AandachtspuntenToevoegen()\n"; // check members verify_data_members( array( 'Dossier', 'Deelplannen' ), $this->_data ); verify_data_members( array( 'KlantKennisID', 'BAGNummer', 'DossierNaam', 'DossierIdentificatieNummer', 'Adres', 'Postcode', 'Woonplaats' ), $this->_data->Dossier, 'het Dossier object' ); if (!is_array( $this->_data->Deelplannen )) throw new DataSourceException( 'Het element Deelplannen is geen array.' ); foreach ($this->_data->Deelplannen as $j => $deelplan) { verify_data_members( array( 'ID', 'IdentificatieNummer', 'OLONummer', 'DeelplanNaam', 'AanvraagDatum', 'Bouwsom', 'Gebruiksfuncties', 'IsIntegraal', 'IsEenvoudig', 'IsDakkapel', 'IsBestaand', 'Beoordelingen' ), $deelplan, 'deelplan object ' . $j ); if (!is_array( $deelplan->Gebruiksfuncties )) throw new DataSourceException( 'Het element Deelplan.Gebruiksfuncties is wel aanwezig, maar geen array in deelplan ' . $j ); $ongeldige_waarden = array_diff( $deelplan->Gebruiksfuncties, array( 'woonfunctie', 'bijeenkomstfunctie', 'celfunctie', 'gezondheidszorgfunctie', 'industriefunctie', 'kantoorfunctie', 'logiesfunctie', 'onderwijsfunctie', 'sportfunctie', 'winkelfunctie', 'overige gebruiksfunctie', 'bouwwerk geen gebouw zijnde' ) ); if (sizeof( $ongeldige_waarden ) > 0) throw new DataSourceException( 'Het element Deelplan.Gebruiksfuncties bevat ongeldige waarde(n): ' . implode( ', ', $ongeldige_waarden ) . ' in deelplan ' . $j ); if (!is_array( $deelplan->Beoordelingen )) throw new DataSourceException( 'Het element Beoordelingen is geen array in deelplan ' . $j ); foreach ($deelplan->Beoordelingen as $i => $beoordeling) { verify_data_members( array( 'Grondslag', 'Beoordeling', 'Verantwoordingstekst', 'Datum', 'Toetser' ), $beoordeling, 'het Beoordeling object ' . $i ); $c = 0; foreach (array( 'Artikel', 'Afdeling', 'Hoofdstuk' ) as $el) if (isset( $beoordeling->$el )) { ++$c; break; } if (!$c) throw new DataSourceException( 'Elk object in de Beoordelingen array dient tenminste een Artikel, Afdeling, of Hoofdstuk te bevatten, beoordeling ' . $i . ' voldoet hier niet aan in deelplan ' . $j ); if (!in_array( $beoordeling->Grondslag, array( 'ARBO', 'BARIM', 'BB03', 'BB12', 'BV', 'GB', 'MR', 'NEN', 'PGS', 'RARIM', 'SC', 'WABO' ) )) throw new DataSourceException( 'Grondslag "' . $beoordeling->Grondslag . '" niet bekend.' ); } } // find the klant if (!($klant = $this->CI->klant->get_by_kennisid_unique_id( $this->_data->Dossier->KlantKennisID ))) throw new DataSourceException( 'Opgegeven Klant KennisID niet bekend in database.' ); // mag dit webservice account bij deze klant? if (!$this->_account->mag_bij_klant( $klant->id )) throw new ServerSourceException( 'Opgegeven webserviceaccount heeft geen toegang tot opgegeven klant.' ); // get the special "nog niet toegekend" user $this->CI->load->model( 'gebruiker' ); $nnts = $klant->get_gebruikers_by_speciale_functie( 'nog niet toegekend' ); $nnt = reset( $nnts ); if (!$nnt) { $nnt = $this->CI->gebruiker->add( $klant->id, 'nog niet toegekend', NULL /* rol */, NULL /* kennis id */ ); if (!$nnt) throw new ServerSourceException( 'Kon speciale gebruiker niet aanmaken.' ); $nnt->speciale_functie = 'nog niet toegekend'; if (!$nnt->save()) throw new ServerSourceException( 'Kon speciale gebruiker niet bijwerken.' ); } $this->_log->extra_result .= "Logging in.\n"; // login $this->_login( $nnt->klant_id, $nnt->id ); $this->CI->db->trans_start(); try { // lookup dossier $this->CI->load->model( 'dossier' ); $dossiers = $this->CI->dossier->search( array( 'g.klant_id' => $klant->id, 'bag_identificatie_nummer' => $this->_data->Dossier->BAGNummer ), null, null, null, null, 'JOIN gebruikers g ON gebruiker_id = g.id' ); $dossier = reset( $dossiers ); if (!$dossier) { $dossier = $this->CI->dossier->add( $this->_data->Dossier->DossierIdentificatieNummer, /* kenmerk */ $this->_data->Dossier->DossierNaam, /* beschrijving */ time() /* unix timestamp */, /* aanmaakdatum */ $this->_data->Dossier->Adres, /* locatie_adres */ preg_replace( '/\s/', '', $this->_data->Dossier->Postcode ), /* locatie_postcode */ $this->_data->Dossier->Woonplaats, /* locatie_woonplaats */ '' /* kadaster x3 */, '', '', '' /* opmerkingen */, '' /* foto */, 'bristoets' /* herkomst */, $nnt->id /* gebruiker */ ); /* let op, we zetten alleen de gebruiker bij een NIEUW dossier, bij bestaande overschrijven we niet! */ if (!$dossier) throw new ServerSourceException( 'Fout bij aanmaken dossier, geen dossier object (1).' ); $dossier = $this->CI->dossier->get( $dossier ); if (!$dossier) throw new ServerSourceException( 'Fout bij aanmaken dossier, geen dossier object (2).' ); } else { $dossier->kenmerk = $this->_data->Dossier->DossierIdentificatieNummer; $dossier->beschrijving = $this->_data->Dossier->DossierNaam; $dossier->locatie_adres = $this->_data->Dossier->Adres; $dossier->locatie_postcode = $this->_data->Dossier->Postcode; $dossier->locatie_woonplaats = $this->_data->Dossier->Woonplaats; } $dossier->bag_identificatie_nummer = $this->_data->Dossier->BAGNummer; if (!$dossier->save( true, null, false )) throw new ServerSourceException( 'Fout bij bijwerken van dossier.' ); foreach ($this->_data->Deelplannen as $deelplan_index => $deelplan_definitie) { // lookup deelplan $deelplan = null; foreach ($dossier->get_deelplannen() as $d) if ($d->foreignid == $deelplan_definitie->ID) { $deelplan = $d; break; } if (!$deelplan) { $deelplan = $this->CI->deelplan->add( $dossier->id, $deelplan_definitie->DeelplanNaam ); if (!$deelplan) throw new ServerSourceException( 'Fout bij aanmaken deelplan, geen deelplan object (1).' ); $deelplan = $this->CI->deelplan->get( $deelplan ); if (!$deelplan) throw new ServerSourceException( 'Fout bij aanmaken deelplan, geen deelplan object (2).' ); $deelplan->foreignid = $deelplan_definitie->ID; } else { $deelplan->naam = $deelplan_definitie->DeelplanNaam; } $deelplan->kenmerk = $deelplan_definitie->IdentificatieNummer; $deelplan->olo_nummer = $deelplan_definitie->OLONummer; $deelplan->aanvraag_datum = date( 'Y-m-d', strtotime( $deelplan_definitie->AanvraagDatum ) ); if (!$deelplan->save( true, null, false )) throw new ServerSourceException( 'Fout bij bijwerken van deelplan.' ); // haal checklisten en voorwaarden op $this->CI->load->model( 'checklistkoppelvoorwaarde' ); $this->CI->load->model( 'checklistgroep' ); $this->CI->load->model( 'checklist' ); $this->CI->load->model( 'deelplanchecklistgroep' ); $alle_voorwaarden = $this->CI->checklistkoppelvoorwaarde->all(); $mogelijke_checklisten = array(); foreach ($alle_voorwaarden as $voorwaarde) $mogelijke_checklisten[ $voorwaarde->checklist_id ] = true; $onbekend_bouwsom = false; switch ($deelplan_definitie->Bouwsom) { case 'Onbekend': $onbekend_bouwsom = true; $bouwsom = 'onbekend'; break; case '<100.000': case '1': case 'i': case 'I': $bouwsom = 50000; break; case '100.000 - 1.000.000': case '2': case 'ii': case 'II': $bouwsom = 250000; break; case '>1.000.000': case '3': case 'iii': case 'III': $bouwsom = 2000000; break; default: $bouwsom = trim( $deelplan_definitie->Bouwsom ); if (!preg_match( '/^\d+$/', $bouwsom )) throw new DataSourceException( 'Onbekende waarde voor bouwsom: "' . $deelplan_definitie->Bouwsom . '", moet een getal zijn, of "Onbekend", of "<100.000", of "100.000 - 1.000.000", ">1.000.000".' ); $bouwsom = intval( $bouwsom ); break; } $this->_log->extra_result .= "Bouwsom = $bouwsom\n"; $this->_log->extra_result .= "AanvraagDatum = {$deelplan_definitie->AanvraagDatum}\n"; $this->_log->extra_result .= "Gebruiksfuncties = " . implode( ',', $deelplan_definitie->Gebruiksfuncties ) . "\n"; $this->_log->extra_result .= "IsIntegraal = {$deelplan_definitie->IsIntegraal}\n"; $this->_log->extra_result .= "IsEenvoudig = {$deelplan_definitie->IsEenvoudig}\n"; $this->_log->extra_result .= "IsDakkapel = {$deelplan_definitie->IsDakkapel}\n"; $this->_log->extra_result .= "IsBestaand = {$deelplan_definitie->IsBestaand}\n"; $this->_log->extra_result .= "OnbekendBouwsom = $onbekend_bouwsom\n"; if (!$onbekend_bouwsom) { $data = new ChecklistKoppelVoorwaardeData( $deelplan_definitie->AanvraagDatum, $deelplan_definitie->Gebruiksfuncties, $bouwsom, $deelplan_definitie->IsIntegraal, $deelplan_definitie->IsEenvoudig, $deelplan_definitie->IsDakkapel, $deelplan_definitie->IsBestaand ); foreach ($alle_voorwaarden as $voorwaarde) $mogelijke_checklisten[ $voorwaarde->checklist_id ] = $mogelijke_checklisten[ $voorwaarde->checklist_id ] && $voorwaarde->voldoet( $data ); $checklisten = $checklistgroepen = $toezichthouders = $matrices = array(); foreach ($mogelijke_checklisten as $checklist_id => $gebruiken) { $this->_log->extra_result .= "Checklist {$checklist_id}: " . ($gebruiken ? 'ja' : 'nee') . ": " . $this->CI->checklist->get($checklist_id)->naam . "\n"; if ($gebruiken) { $checklisten[ $checklist_id ] = 'on'; // fake checkbox post data $checklist = $this->CI->checklist->get( $checklist_id ); if (!$checklist) throw new ServerSourceException( 'Kon checklist met ID ' . $checklist_id . ' niet vinden' ); $checklistgroepen[ $checklist->checklist_groep_id ] = 'on'; // fake checkbox post data $toezichthouders[ $checklist->checklist_groep_id ] = NULL; $matrices[ $checklist->checklist_groep_id ] = NULL; } } // zet de checklisten die voldoen in dit deelplan if ($deelplan->update_checklisten( array( 'checklistgroep' => $checklistgroepen, 'checklist' => $checklisten, 'toezichthouders' => $toezichthouders, 'matrices' => $matrices, ))) $deelplan->update_content(); // haal alle vragen en grondslagen op voor alle van toepassing zijnde checklisten $this->CI->load->model( 'vraag' ); $this->CI->load->model( 'vraaggrondslag' ); $alle_vragen = array(); foreach ($checklisten as $checklist_id => $unused) $alle_vragen = array_merge( $alle_vragen, $deelplan->get_checklist_vragen( $checklist_id ) ); $grondslagen = $this->CI->vraaggrondslag->get_data_by_vragen( $alle_vragen); // loop nu over de beoordelingen heen, en voeg aandachtspunten toe waar nodig $this->CI->load->model( 'deelplanaandachtspunt' ); $this->CI->load->model( 'deelplanvraagaandachtspunt' ); $this->CI->deelplanaandachtspunt->verwijder_voor_deelplan( $deelplan->id ); $aandachtspunten = array(); $grondslag_not_present = 0; $element_not_present = 0; $element_found = 0; foreach ($deelplan_definitie->Beoordelingen as $beoordeling) { $koppel_aan_vragen = array(); if (!isset( $grondslagen[ $beoordeling->Grondslag ] )) { $grondslag_not_present++; } else { $mygrondslag = $grondslagen[ $beoordeling->Grondslag ]; // geen echte copy zolang we er niks mee doen! // hoofdstuk / afdeling / artikel check is lastig, maar we gaan het toch proberen! $check_keys = array(); if (isset( $beoordeling->Hoofdstuk )) { foreach (explode( ',', $beoordeling->Hoofdstuk ) as $hoofdstuk) $check_keys[] = 'hoofdstuk ' . trim($hoofdstuk); } if (isset( $beoordeling->Afdeling )) { foreach (explode( ',', $beoordeling->Afdeling ) as $afdeling) $check_keys[] = 'afdeling ' . trim($afdeling); } if (isset( $beoordeling->Artikel )) { foreach (explode( ',', $beoordeling->Artikel ) as $artikel) { $check_keys[] = 'artikel ' . trim($artikel); $check_keys[] = trim($artikel); } } foreach ($check_keys as $key) if (isset( $mygrondslag[$key] )) { $koppel_aan_vragen = array_merge( $koppel_aan_vragen, $mygrondslag[$key] ); break; } else { foreach ($mygrondslag as $key => $vragen) if (preg_match( '/(artikel\s+)?([\d\.]+)\s*-\s*([\d\.]+)/i', $key, $matches )) { $from = trim( $matches[2] ); $to = trim( $matches[3] ); foreach ($check_keys as $checkkey) { if ($checkkey >= $from && $checkkey <= $to) { $koppel_aan_vragen = array_merge( $koppel_aan_vragen, $vragen ); break(2); } } } } } $grondslag = $beoordeling->Grondslag . ' '; if (isset( $beoordeling->Hoofdstuk )) $grondslag .= 'hoofdstuk ' . $beoordeling->Hoofdstuk; else if (isset( $beoordeling->Afdeling )) $grondslag .= 'afdeling ' . $beoordeling->Afdeling; else $grondslag .= 'artikel ' . $beoordeling->Artikel; $volledige_tekst = 'Grondslag: ' . $beoordeling->Grondslag . "\n" . (isset( $beoordeling->Hoofdstuk ) ? 'Hoofdstuk: ' . $beoordeling->Hoofdstuk . "\n" : '') . (isset( $beoordeling->Afdeling ) ? 'Afdeling: ' . $beoordeling->Afdeling . "\n" : '') . (isset( $beoordeling->Artikel ) ? 'Artikel: ' . $beoordeling->Artikel . "\n" : '') . 'Beoordeling: ' . $beoordeling->Beoordeling . "\n" . "\n" . $beoordeling->Verantwoordingstekst; if (empty( $koppel_aan_vragen )) { $element_not_present++; $aandachtspunt = $this->CI->deelplanaandachtspunt->add( $deelplan->id, $beoordeling->Toetser, $beoordeling->Datum, $volledige_tekst, $grondslag, true ); } else { $element_found++; $aandachtspunt = $this->CI->deelplanaandachtspunt->add( $deelplan->id, $beoordeling->Toetser, $beoordeling->Datum, $volledige_tekst, $grondslag, false ); foreach (array_unique( $koppel_aan_vragen ) as $vraag) $this->CI->deelplanvraagaandachtspunt->add( $deelplan->id, $aandachtspunt->id, $vraag ); } } $this->_log->extra_result .= "--DEELPLAN $deelplan_index--\nbeoordelingen met niet gebruikte grondslag: $grondslag_not_present\nbeoordelingen met niet herkend artikel/afdeling/hoofdstuk: $element_not_present\nbeoordelingen die gebruikt zijn: $element_found\n"; // kijk of er al thema's gekoppeld zijn aan dit deelplan, zo ja, dan niks meer doen, // zo nee, zoek dan alle hoofd en subthema's op en selecteer deze $this->CI->load->model( 'deelplanthema' ); $sel_themas = $this->CI->deelplanthema->get_by_deelplan( $deelplan->id ); if (empty( $sel_themas )) { $themas = array(); foreach ($alle_vragen as $vraag) { $thema_id = $vraag->thema_id; if ($thema_id) $themas[$thema_id] = $thema_id; } $this->CI->deelplanthema->set_for_deelplan( $deelplan->id, $themas, array() ); } } // if !$onbekend_bouwsom } // finish if (!$this->CI->db->trans_complete()) throw new ServerSourceException( 'Database fout, transactie niet succesvol kunnen afronden.' ); $this->_output_json( array( 'Success' => true, ) ); } catch (Exception $e) { $this->CI->db->_trans_status = false; $this->CI->db->trans_complete(); throw $e; } } } WebserviceModule::register_module( WS_COMPONENT_BRISTOETS_KOPPELING, new BRIStoezichtWebserviceModule() ); <file_sep>BRISToezicht.Maps = { mapContainer: null, // jQuery collection nokiaMap: null, initialize: function() { this.mapContainer = $('#mapContainer'); if (this.mapContainer.size() == 0) return; // Set up is the credentials to use the API nokia.Settings.set("appId", "McvEOKhagR0v_FwbZixf"); nokia.Settings.set("authenticationToken", "<KEY>"); // Initialize map this.nokiaMap = new nokia.maps.map.Display( $("#mapContainer")[0], { 'zoomLevel': 6, // pretty zoomed out 'center': [52.160455,5.524292], // centered on The Netherlands components: [ new nokia.maps.map.component.Behavior(), // allow panning/zooming new nokia.maps.map.component.ZoomBar(), // have zoom bar new nokia.maps.map.component.ScaleBar(), // have scale bar new nokia.maps.map.component.TypeSelector() // have switch map types ] }); // resize the container to be exactly as high as its sibling this.mapContainer.css( 'height', this.mapContainer.prev().css( 'height' ) ); // show address var address = this.mapContainer.attr( 'address' ); if (address) this.showAddress( address ); }, showAddress: function( address, zoom_level ) { var thiz = this; nokia.places.search.manager.findPlaces({ searchTerm: address, onComplete: function( responseData, status ) { if (status == 'OK' && responseData.results.items.length > 0) { // center map on new coordinates var position = responseData.results.items[0].position; var center = [position.latitude, position.longitude]; thiz.nokiaMap.setCenter( center ); thiz.nokiaMap.setZoomLevel( zoom_level || 14 ); // create marker with the exact address var standardMarker = new nokia.maps.map.StandardMarker(thiz.nokiaMap.center); thiz.nokiaMap.objects.add(standardMarker); } } }); } }; <file_sep>BRISToezicht.Toets.SpecialImage = { initialize: function() { // activate special (large) image loader this.activateLoader(); }, specialImages: { total: 0, loaded: 0, list: null, stillLoading: {}, fixIEHandle: null }, activateLoader: function() { this.specialImages.list = $('img[target_url]'); this.specialImages.total = this.specialImages.list.size(); this.specialImages.loaded = 0; if (this.specialImages.total) this.loadImages(); else BRISToezicht.OfflineKlaar.markeerKlaar('afbeeldingen'); // geen afbeeldingen te laden, meteen klaar melden! }, imageLoaded: function( image ) { // see if this image was already handled var nr = $(image).attr('nr'); if (!this.specialImages.stillLoading[ nr ]) return; delete this.specialImages.stillLoading[ nr ]; // unbind all events for this image $(image).unbind( 'load error abort' ); // increase counter this.specialImages.loaded++; // update percentage var perc = this.specialImages.total ? this.specialImages.loaded / this.specialImages.total : 0; $('.offline-klaar .perc').text( Math.round( 100 * perc ) + '%' ); // are we done loading? if (this.specialImages.loaded == this.specialImages.total) { if (!this.alerted) { $('.offline-klaar .perc').hide(); this.alerted = true; BRISToezicht.OfflineKlaar.markeerKlaar('afbeeldingen'); } } }, loadImages: function() { // setup events for all images var thiz = this; this.specialImages.list.bind( 'load', function() { var img = $(this); thiz.imageLoaded( this ); }); this.specialImages.list.bind( 'error abort', function() { var img = $(this); thiz.imageLoaded( this ); }); // load all images for (var i=0; i<this.specialImages.total; ++i) { // get collection with our current image, and reset image to empty var singleImage = this.specialImages.list[ i ]; // set image in list of images that are still loading $(singleImage).attr('nr', '' + i ); this.specialImages.stillLoading[''+i] = singleImage; // Firefox bug fix: set to nothing first! if (navigator && navigator.userAgent && navigator.userAgent.match( /Firefox/i )) singleImage.src = ''; // set it to load a new url! singleImage.src = $(singleImage).attr( 'target_url' ); // IE bug fix: if it's loaded now, it will never fire the events, // so manually check and handle as if it was loaded asynchronously if (singleImage.readyState === 4 || singleImage.readyState == 'complete') { // image is cached in IE this.imageLoaded( singleImage ); } } this.startFixingIEIssues(); }, handleUnfiredCompletedImages: function() { for (var i in this.specialImages.stillLoading) { var img = this.specialImages.stillLoading[i]; if (img.complete) { this.imageLoaded( img ); } } for (var i in this.specialImages.stillLoading) { return true; } return false; }, startFixingIEIssues: function() { if (this.specialImages.fixIEHandle) { clearTimeout( this.specialImages.fixIEHandle ); this.specialImages.fixIEHandle = null; } if (this.handleUnfiredCompletedImages()) { this.specialImages.fixIEHandle = setTimeout( function() { BRISToezicht.Toets.SpecialImage.startFixingIEIssues() }, 250 ); } } }; <file_sep>PDFAnnotator.Editable.Text = PDFAnnotator.Editable.extend({ init: function( config ) { this._super( PDFAnnotator.Tool.prototype.getByName( 'text' ) ); this.setData( config, { text: '<NAME>', font: 'Arial', size: '14pt', bold: true, italic: false, underline: false, background: '#ed1c24', color: '#ffffff', position: new PDFAnnotator.Math.IntVector2( 0, 0 ), boxsize: new PDFAnnotator.Math.IntVector2( 300, 60 ) }, [ /* no required fields */ ] ); }, render: function() { var thiz = this; var base = $('<div>') .addClass( 'Rounded10' ) .css( 'left', this.data.position.x ) .css( 'top', this.data.position.y ) .css( 'width', this.data.boxsize.x + 'px' ) .css( 'height', this.data.boxsize.y + 'px' ) .css( 'border', '3px solid ' + this.data.color ) .css( 'padding', '4px' ) .css( 'position', 'absolute' ) .css( 'background-color', this.data.background ) .click(function(e){ thiz.dispatchEvent( 'click', {event:e} ); }); this.setDisplaySettings( base ); this.addVisual( base ); this.finish(); }, setDisplaySettings: function( dom ) { dom .css( 'font-family', this.data.font ) .css( 'font-size', this.data.size ) .css( 'font-weight', this.data.bold ? 'bold' : 'normal' ) .css( 'font-style', this.data.italic ? 'italic' : 'normal' ) .css( 'text-decoration', this.data.underline ? 'underline' : 'none' ) .css( 'color', this.data.color ); }, edit: function() { this.resetHandles(); var thiz = this; var base = this.visuals; var text = this.data.text; // clear current text inside base.text( '' ); // in stead add in a textarea var textarea = $('<textarea>') .val( text ) .css( 'background-color', 'transparent' ) .css( 'border', '0' ) .css( 'color', this.data.color ) .css( 'width', base.css( 'width' ) ) .css( 'height', base.css( 'height' ) ) .css( 'resize', 'none' ) // disable firefox resizing handle .css( 'padding', '0' ) .click(function(e){e.stopPropagation();}) .blur(function(e){ thiz.finish(); }) .appendTo( base ); this.setDisplaySettings( textarea ); textarea.focus(); textarea.select(); this.addSpeechBubble(); }, finish: function() { var base = this.visuals; var textarea = base.find('textarea'); if (textarea.size()) { this.data.text = textarea.val(); textarea.remove(); } this.setSafeText( this.data.text ); this.addSpeechBubble(); }, setSafeText: function( text ) { // convert text into safe html text = $('<div>').text(text).html(); // convert newlines into <br/>'s text = text.replace( /\n/g, '<br/>' ); // now set HTML safely this.visuals.html( text ); }, addSpeechBubble: function() { if (this.speechBubble) this.speechBubble.remove(); this.speechBubble = $('<div>') .css( 'border-color', this.data.color + ' transparent' ) .css( 'border-style', 'solid' ) .css( 'border-width', '20px 0 0 20px' ) .css( 'bottom', '-20px' ) .css( 'display', 'block' ) .css( 'left', '50px' ) .css( 'position', 'absolute' ) .css( 'width', '0' ) .appendTo( this.visuals[0] ); }, /* static */ getOffset: function() { return new PDFAnnotator.Math.IntVector2(73, 91); }, /* moves the visual objects to a relative position, i.e. move a number of pixels up/down/left/right */ moveRelative: function( relx, rely ) { this._super( relx, rely ); this.data.position.x += relx; this.data.position.y += rely; }, resizeRelative: function( relx, rely ) { this._super( relx, rely ); this.data.boxsize.x += relx; this.data.boxsize.y += rely; }, /* !!overide!! */ rawExport: function() { return { type: 'text', x: this.data.position.x, y: this.data.position.y, w: this.data.boxsize.x, h: this.data.boxsize.y, textcolor: this.data.color, bgcolor: this.data.background, text: this.data.text, font: this.data.font, size: this.data.size, bold: this.data.bold, italic: this.data.italic, underline: this.data.underline }; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Text({ text: data.text, font: data.font, size: data.size, bold: data.bold ? true : false, italic: data.italic ? true : false, underline: data.underline ? true : false, background: data.bgcolor, color: data.textcolor, position: new PDFAnnotator.Math.IntVector2( data.x, data.y ), boxsize: new PDFAnnotator.Math.IntVector2( data.w, data.h ) }); }, /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { var offset = this.getOffset(); var bubblePoint = this.data.position.added( offset ); var newPos = bubblePoint.multiplied( newlevel / oldlevel ).subtracted( offset ); this.moveRelative( newPos.x - this.data.position.x, newPos.y - this.data.position.y ); this.repositionHandles(); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'admin_tekst_sync')); ?> <tr> <td id="content" colspan="2"> <form enctype="multipart/form-data" method="post"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th>Set 1</th> <th>Set 2</th> </tr> <tr> <td><input type="file" name="set1" /></td> <td><input type="file" name="set2" /></td> </tr> <tr> <td align="center" colspan="2"><input type="submit" value="Synchroniseren" /></td> </tr> <? if (isset($set1to2) && isset($set2to1)): ?> <tr> <td valign="top"><h3>Van set 1 naar set 2</h3> <textarea cols="40" rows="10"><?=$set1to2?></textarea> </td> <td valign="top"><h3>Van set 2 naar set 1</h3> <textarea cols="40" rows="10"><?=$set2to1?></textarea> </td> </tr> <? endif; ?> </table> </form> </td> </tr> <? $this->load->view('elements/footer'); ?><file_sep><?php class DeviceInfo extends Controller { public function show() { $this->load->library( 'deviceinfo' ); $this->load->view( 'deviceinfo/show', array( 'agent' => $this->deviceinfo->get_agent(), 'parts' => array( CI_DeviceInfo::FIRST_PART => $this->deviceinfo->get_first_part(), CI_DeviceInfo::SYSTEM_PART => $this->deviceinfo->get_system_part(), CI_DeviceInfo::REST_PART => $this->deviceinfo->get_rest_part(), ), 'types' => array( 'tablet' => $this->deviceinfo->is_tablet_type(), 'phone' => $this->deviceinfo->is_phone_type(), 'other' => $this->deviceinfo->is_other_type(), ), 'browsers' => array( 'explorer' => $this->deviceinfo->is_explorer_browser(), 'chrome' => $this->deviceinfo->is_chrome_browser(), 'safari' => $this->deviceinfo->is_safari_browser(), 'firefox' => $this->deviceinfo->is_firefox_browser(), ), 'os' => array( 'windows' => $this->deviceinfo->is_windows_os(), 'linux' => $this->deviceinfo->is_linux_os(), 'android' => $this->deviceinfo->is_android_os(), 'mac' => $this->deviceinfo->is_mac_os(), ), ) ); } } <file_sep>BRISToezicht.HelpButton = { initialize: function() { // stel editbare helpbuttons in var tags = $('img[help_button_tag].editable'); tags.css( 'cursor', 'pointer' ); tags.mouseover(function(){ var small = $(this).attr( 'small' ) == '1'; this.oldsrc = this.src; this.src = '/files/images/help-edit' + (small ? '-s' : '') + '.png'; }); tags.mouseout(function(){ this.src = this.oldsrc; }); tags.click(function(){ // deze tag zorgt er voor dat de mouseout van de gewone functionaliteit de popup niet killed! var img = this; $(img).addClass( 'editing' ); // verwijder nu de tekst, en zet er een textarea met een submit knop bij var popupDiv = BRISToezicht.HelpButton.getPopupDiv( this ); var text = popupDiv.text(); var stopEditing = function( t ) { popupDiv.text( t ); popupDiv.hide(); $(img).removeClass( 'editing' ); $(img).removeClass( 'empty' ); var small = $(img).attr( 'small' ) == '1'; if (t.length == 0) { $(img).addClass( 'empty' ); img.src = '/files/images/help-empty' + (small ? '-s' : '') + '.png'; } else { img.src = '/files/images/help' + (small ? '-s' : '') + '.png'; } }; var finishEditing = function( newtext ) { $.ajax({ url: '/admin/help_button_store_text', type: 'POST', data: { tag: $(img).attr( 'help_button_tag' ), text: newtext }, success: function() { stopEditing( newtext ); }, error: function() { alert( 'Fout bij opslaan.' ); } }); }; popupDiv.html( '<textarea cols="30" rows="6"></textarea><br/>' + '<input type="button" value="Opslaan" class="opslaan" /> ' + '<img src="/files/images/delete.png" class="verwijderen" />' + '<input type="button" value="Annuleren" class="annuleren" />' ); popupDiv.find('textarea').val( text ); popupDiv.find('.annuleren').click(function(){ stopEditing( text ); }); popupDiv.find('.verwijderen').click(function(){ if (confirm( 'Volledige help tekst verwijderen? U kunt dit niet ongedaan maken!' )) finishEditing( '' ); }); popupDiv.find('.opslaan').click(function(){ finishEditing( popupDiv.find('textarea').val() ); }); }); // stel de gewone functionaliteit van helpbuttons in var tags = $('img[help_button_tag]'); tags.live('mouseover',function(){ BRISToezicht.HelpButton.getPopupDiv( this ).show(); }); tags.live('mouseout',function(){ if (!$(this).hasClass( 'editing' )) BRISToezicht.HelpButton.getPopupDiv( this ).hide(); }); }, getPopupDiv: function( img ) { return $(img).next(); } }; <file_sep><?php class Intro extends Controller { function index() { $this->load->model( 'nieuws' ); $leaseconfiguratie = false; if( $lc = $this->session->_loginSystem->get_lease_configuratie_id() ) { $this->load->model( 'leaseconfiguratie' ); $leaseconfiguratie = $this->leaseconfiguratie->get($lc); } $this->load->view( 'intro/index', array( 'leaseconfiguratie' => $leaseconfiguratie, 'nieuws' => $this->nieuws->get_alle_zichtbare_nieuwsitems( $leaseconfiguratie ), 'notificaties' => $this->notificatie->get_my_notificaties(), ) ); } function notificatie_bekeken( $notificatie_id ) { $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $this->db->query( 'INSERT INTO notificaties_bekeken (gebruiker_id, notificatie_id) VALUES (' . intval($gebruiker->id) . ',' . intval($notificatie_id) . ')' ); echo "OK"; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'wettelijke_grondslag')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => htmlentities( $lg->get_grondslag()->grondslag . ' ' . $lg->artikel, ENT_COMPAT, 'UTF-8'), 'width' => '920px' )); ?> <p> <?=nl2br( htmlentities( $lg->tekst, ENT_COMPAT, 'UTF-8' ) )?> </p> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? require_once 'base.php'; class DeelplanVraagEmailResult extends BaseResult { function DeelplanVraagEmailResult( $arr ) { parent::BaseResult( 'deelplanvraagemail', $arr ); } function get_deelplan_vraag() { $this->_CI->load->model( 'deelplanvraag' ); return $this->_CI->deelplanvraag->get( $this->deelplan_vraag_id ); } function get_gebruiker() { $this->_CI->load->model( 'gebruiker' ); return $this->_CI->gebruiker->get( $this->gebruiker_id ); } } class DeelplanVraagEmail extends BaseModel { function DeelplanVraagEmail() { parent::BaseModel( 'DeelplanVraagEmailResult', 'deelplan_vraag_emails' ); } public function check_access( BaseResult $object ) { //$this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); $this->check_relayed_access( $object, 'deelplanvraag', 'deelplan_vraag_id' ); } function get_db_values_by_deelplan_vraag( $deelplan_vraag_id ) { if (!$this->dbex->is_prepared( 'get_deelplanvraagemail_by_deelplan_vraag' )) $this->dbex->prepare( 'get_deelplanvraagemail_by_deelplan_vraag', ' SELECT * FROM deelplan_vraag_emails WHERE (deelplan_vraag_id = ?) ' ); $res = $this->dbex->execute( 'get_deelplanvraagemail_by_deelplan_vraag', array( $deelplan_vraag_id ) ); return $res; } // Note: currently returns only the first retrieved object, but for this particular table multiple entries can exist per 'deelplanvraag'! function get_by_deelplan_vraag( $deelplan_vraag_id ) { // First get the records using the deelplanvraag ID $res = $this->get_db_values_by_deelplan_vraag($deelplan_vraag_id); $result = array(); foreach ($res->result() as $row) { $result[] = $this->getr( $row ); } return (empty($result)) ? null : $result[0]; } // Note: currently returns only the first retrieved object, but for this particular table multiple entries can exist per 'deelplanvraag'! function get_unsent_by_deelplan_vraag_and_recipient( $deelplan_vraag_id, $recipient ) { // First get the record (if any) using the deelplanvraag ID and the recipient if (!$this->dbex->is_prepared( 'get_deelplanvraagemail_by_unsent_and_deelplan_vraag_and_recipient' )) $this->dbex->prepare( 'get_deelplanvraagemail_by_unsent_and_deelplan_vraag_and_recipient', ' SELECT * FROM deelplan_vraag_emails WHERE (deelplan_vraag_id = ?) AND (recipient = ?) AND (datum_sent IS NULL) ' ); $res = $this->dbex->execute( 'get_deelplanvraagemail_by_unsent_and_deelplan_vraag_and_recipient', array( $deelplan_vraag_id, $recipient ) ); $result = array(); foreach ($res->result() as $row) { $result[] = $this->getr( $row ); } return (empty($result)) ? null : $result[0]; } // Retrieves all sent emails for a specific deelplan (this is used in the reporting code). function get_all_sent_by_deelplan( $deelplan_id ) { // First get the records (if any) using the deelplan ID if (!$this->dbex->is_prepared( 'get_deelplanvraagemails_by_sent_and_deelplan' )) $this->dbex->prepare( 'get_deelplanvraagemails_by_sent_and_deelplan', ' SELECT t1.* FROM deelplan_vraag_emails t1 INNER JOIN deelplan_vragen t2 ON (t1.deelplan_vraag_id = t2.id) WHERE (t1.datum_sent IS NOT NULL) AND (t2.deelplan_id = ?); ' ); $res = $this->dbex->execute( 'get_deelplanvraagemails_by_sent_and_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) { $result[] = $this->getr( $row ); } return $result; } function get_records_by_deelplan_vraag( $deelplan_vraag_id ) { $res = $this->get_db_values_by_deelplan_vraag($deelplan_vraag_id); $row = $res->result(); return $row; } }<file_sep><? require_once 'base.php'; class ToezichtmomentResult extends BaseResult { public function ToezichtmomentResult( &$arr ){ parent::BaseResult( 'toezichtmoment', $arr ); } public function get_hoofdgroepen(){ $CI = get_instance(); $CI->load->model( 'hoofdgroep' ); return $CI->hoofdgroep->get_by_toezichtmoment( $this->id ); } public function save_all( $data ){ $CI = get_instance(); $CI->load->model( 'toezichtmomenthoofdgroep' ); $CI->toezichtmomenthoofdgroep->delete(array('toezichtmoment_id' => $this->id)); foreach( $data['hoofdgroepen'] as $hoofdgroep_id ) { $CI->toezichtmomenthoofdgroep->insert(array('toezichtmoment_id'=>$this->id, 'hoofdgroep_id'=>$hoofdgroep_id)); } if($data['is_new']) { $CI->load->model( 'matrixmapping' ); $CI->load->model( 'bijwoonmomentenmap' ); $matrixes = $CI->matrixmapping->all(); foreach( $matrixes as $matrix ) { $CI->bijwoonmomentenmap->add( $matrix->id, $this->id ); } } $model = $this->get_model(); $result = $model->save((object)array('id'=>$this->id,'codekey'=>$data['codekey'],'naam'=>$data['naam'])); return $result; } } class Toezichtmoment extends BaseModel { public function Toezichtmoment(){ parent::BaseModel( 'ToezichtmomentResult', 'bt_toezichtmomenten' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_by_checklist( $checklistId, $assoc=false ){ $tmoment = $this->db->where('checklist_id', $checklistId ) ->order_by('naam') ->get( $this->_table ) ->result(); $result = array(); foreach( $tmoment as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function add( $codekey, $naam, $checklistId ){ $data = array( 'checklist_id' => $checklistId, 'codekey' => $codekey, 'naam' => $naam ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function get_model(){ $class = $this->_model_class; $inst = new $class($arr); return $inst; } public function get_by_hoofdgroep( $hfId ){ $tbl = $this->_table; $tmoment = $this->db->select($tbl.'.`id` AS `id`,'.$tbl.'.`naam` AS `naam`,'.$tbl.'.`codekey` AS `codekey`,'.$tbl.'.`checklist_id` AS `checklist_id`') ->join('bt_toezichtmomenten_hoofdgroepen', 'bt_toezichtmomenten_hoofdgroepen.toezichtmoment_id = '.$tbl.'.id', 'left' ) ->where('hoofdgroep_id', $hfId ) ->get( $tbl, 1 ) ->result() ; if(isset($tmoment[0])){ $tmoment = $tmoment[0]; }else{ $tmoment = new stdClass(); $tmoment->id = NULL; } $obj = new $this->_model_class( $tmoment ); $this->_set_cache( $tmoment->id, $obj ); return $obj; } }// Class end <file_sep>PDFAnnotator.Handle.LineMove = PDFAnnotator.Handle.Move.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this.direction = ''; this._super( editable ); }, /* !!overide!! */ addNodes: function() { if (this.editable.data.from.x > this.editable.data.to.x) { var swap = this.editable.data.from; this.editable.data.from = this.editable.data.to; this.editable.data.to = swap; } var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/edit-handle-move.png', 32, 32, 'drag', this.execute, 'left', 0, 0 ); this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/edit-handle-move.png', 32, 32, 'drag', this.execute, 'right', 0, 0 ); this.updateDirection(); }, execute: function( relx, rely, side ) { var changeVector = new PDFAnnotator.Math.IntVector2( relx, rely ); if (side == 'left') this.editable.setFrom( this.editable.data.from.added( changeVector ) ); else this.editable.setTo( this.editable.data.to.added( changeVector ) ); this.updateDirection(); this.show(); }, updateDirection: function() { var newDir = this.editable.getDirection(); if (newDir == this.direction) return; var forwards = this.editable.data.from.x < this.editable.data.to.x; this.direction = newDir; switch (this.direction) { case 'up': if (forwards) { this.nodes[0].userdata = 'left'; this.nodes[0].relx = 0; this.nodes[0].rely = 1; this.nodes[1].userdata = 'right'; this.nodes[1].relx = 1; this.nodes[1].rely = 0; } else { this.nodes[0].userdata = 'right'; this.nodes[0].relx = 1; this.nodes[0].rely = 0; this.nodes[1].userdata = 'left'; this.nodes[1].relx = 0; this.nodes[1].rely = 1; } break; case 'down': if (forwards) { this.nodes[0].relx = 0; this.nodes[0].rely = 0; this.nodes[0].userdata = 'left'; this.nodes[1].relx = 1; this.nodes[1].rely = 1; this.nodes[1].userdata = 'right'; } else { this.nodes[0].relx = 1; this.nodes[0].rely = 1; this.nodes[0].userdata = 'right'; this.nodes[1].relx = 0; this.nodes[1].rely = 0; this.nodes[1].userdata = 'left'; } break; default: throw 'PDFAnnotator.Handle.LineMove.updateDirection: unknown direction "' + this.direction + '"'; } } }); <file_sep><? require_once 'base.php'; class DeelplanLayerResult extends BaseResult { private $_layers; // decoded versie van layer_data function DeelplanLayerResult( &$arr ) { parent::BaseResult( 'deelplanlayer', $arr ); } public function get_deelplan() { $CI = get_instance(); $CI->load->model( 'deelplan' ); return $CI->vraag->get( $this->deelplan_id ); } public function decodeer_layer_informatie() { $this->_layers = @json_decode( $this->layer_data ); if (!is_array( $this->_layers )) throw new Exception( 'Fout bij decoderen van layer informatie.' ); } public function geef_layer_voor_vraag( $vraag_id ) { if (is_null( $this->_layers )) $this->decodeer_layer_informatie(); // kijk of er voor de benodigde vraag een layer te vinden is $layer = null; foreach ($this->_layers as $layer) if ($layer->metadata) if (@$layer->metadata->referenceId == $vraag_id) return $layer; return null; } public function hercodeer_layer_informatie() // NOTE: does not store to database, call save() manually! { if (is_null( $this->_layers )) return; // not decoded, so no reason to re-encode $this->layer_data = json_encode( $this->_layers ); } } class DeelplanLayer extends BaseModel { function DeelplanLayer() { parent::BaseModel( 'DeelplanLayerResult', 'deelplan_layers', true ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); } function get_by_deelplan( $deelplan_id ) { $result = array(); foreach ($this->search( array( 'deelplan_id' => $deelplan_id ) ) as $layer) $result[ $layer->dossier_bescheiden_id ] = $layer; return $result; } function replace( $deelplan_id, $bescheiden_id, $layer_data, $pagetransform_data ) { // OJG (2015-04-10): At least two issues occur occassionally with the 'text' member of text/compound annotations: // 1) Their size is too long to be reasonably displayed. // 2) A "multiple-times-encoding" issue occurs somewhere. // The first of these two can cause crashes when the amount of characters is extremely high, the second has been seen in combination with the first, but it is // not yet known where that problem comes from. Down below the first is at least addressed by forcing a hard 500 characters maximum on the 'text' so as to prevent // erroneous enormous texts from taking down the whole server when the texts are used to generate images. // The second one may be more difficult to detect and may require several steps to correct it. // First decode the original (JSON) layer data $layer_data_decoded = json_decode($layer_data); $layers_patched = array(); // Extract each of the layers and patch them as needed. foreach($layer_data_decoded as $layer_decoded) { // Exract the 'pages' member, this is an object that has several different subpages (per 'page' index). Re-create that same structure, using patched subpages. $pages = $layer_decoded->pages; $patched_pages = new stdClass(); // Extract the subpages and patch them. foreach($pages as $page_idx => $sub_pages) { $patched_subpages = array(); foreach($sub_pages as $patched_sub_page) { // Apply the patches to the 'text' member. if (!empty($patched_sub_page->text)) { // Apply the patch for problem number 1: limit the text length to a maximum of 500 characters. $patched_sub_page->text = substr($patched_sub_page->text, 0, 500); } $patched_subpages[] = $patched_sub_page; } // Store the patched subpages $patched_pages->$page_idx = $patched_subpages; } // Store the patched pages $layer_decoded->pages = $patched_pages; // Store the patched layer $layers_patched[] = $layer_decoded; } // The eventual data set is expected in JSON format, so JSON encode it here $layers_patched_encoded = json_encode($layers_patched); // Now proceed to store the data. $CI = get_instance(); $stmt_name = 'DeelplanLayer::replace'; //$CI->dbex->prepare( $stmt_name, 'REPLACE INTO deelplan_layers (deelplan_id, dossier_bescheiden_id, layer_data, pagetransform_data) VALUES (?, ?, ?, ?)' ); $CI->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO deelplan_layers (deelplan_id, dossier_bescheiden_id, layer_data, pagetransform_data) VALUES (?, ?, ?, ?)', null, array('id', 'deelplan_id', 'dossier_bescheiden_id') ); //$CI->dbex->execute( $stmt_name, array( $deelplan_id, $bescheiden_id, $layer_data, $pagetransform_data ) ); $CI->dbex->execute( $stmt_name, array( $deelplan_id, $bescheiden_id, $layers_patched_encoded, $pagetransform_data ) ); } public function get_layer_for_deelplan_bescheiden( $deelplan_id, $dossier_bescheiden_id ) { $layers = $this->search( array( 'deelplan_id' => $deelplan_id, 'dossier_bescheiden_id' => $dossier_bescheiden_id ) ); if (empty( $layers )) return null; return $layers[0]; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $col_widths = array( 'editicon' => 32 ); $col_description = array( 'editicon' => '&nbsp;' ); if ($allow_klanten_edit) { $col_widths['klant'] = 140; $col_description['klant'] = 'Klant'; } $col_widths = array_merge( $col_widths, array( 'checklistgroep' => 140, 'checklist' => 140, 'hoofdthema' => 140, 'thema' => 140, 'beoordeling' => 140, 'tekst' => 350, ) ); $col_description = array_merge( $col_description, array( 'checklistgroep' => 'Checklist groep', 'checklist' => 'Checklist', 'hoofdthema' => 'Hoofdthema', 'thema' => 'Thema', 'beoordeling' => 'Beoordeling', 'tekst' => 'Verantwoording', ) ); if ($this->is_Mobile) { foreach ($col_widths as &$width) if ($width == 140) $width = 150; unset( $col_widths['thema'] ); unset( $col_widths['hoofdthema'] ); unset( $col_description['thema'] ); unset( $col_description['hoofdthema'] ); } $rows = array(); foreach ($verantwoordingsteksten as $i => $vt) { $row = (object)array(); $row->onclick = "location.href='" . site_url('/instellingen/verantwoordingstekst_bewerken/' . $vt->id) . "'"; $row->data = array(); $row->data['editicon'] = '<a title="Verantwoordingstekst bekijken/bewerken" href="' . site_url('/instellingen/verantwoordingstekst_bewerken/' . $vt->id) . '"><img src="' . site_url('/files/images/edit.png') . '" /></a>'; if ($allow_klanten_edit) $row->data['klant'] = ($vt->klant_id && isset($klanten[$vt->klant_id])) ? $klanten[$vt->klant_id]->naam : '- alle -'; $row->data['checklistgroep'] = ($vt->checklist_groep_id && isset($checklistgroepen[$vt->checklist_groep_id])) ? htmlentities( $checklistgroepen[$vt->checklist_groep_id]->naam, ENT_COMPAT, 'UTF-8' ) : '- alle -'; $row->data['checklist'] = ($vt->checklist_id && isset( $checklisten[$vt->checklist_id] )) ? htmlentities( $checklisten[$vt->checklist_id]->naam, ENT_COMPAT, 'UTF-8' ) : '- alle -'; if (!$this->is_Mobile) { $row->data['hoofdthema'] = ($vt->hoofdthema_id && isset( $hoofdthemas[$vt->hoofdthema_id] )) ? htmlentities( $hoofdthemas[$vt->hoofdthema_id]->naam, ENT_COMPAT, 'UTF-8' ) : '- alle -'; $row->data['thema'] = ($vt->thema_id && isset( $themas[$vt->thema_id] )) ? htmlentities( $themas[$vt->thema_id]->thema, ENT_COMPAT, 'UTF-8' ) : '- alle -'; } $row->data['beoordeling'] = $vt->status ? ucfirst(preg_replace('/[_\\-]/', ' ', $vt->status)) : '- alle -'; $row->data['tekst'] = htmlentities( strlen($vt->tekst)>50 ? substr( $vt->tekst, 0, 50 ) . '...' : $vt->tekst, ENT_COMPAT, 'UTF-8' ); $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, 'new_button_js' => "location.href='/instellingen/verantwoordingstekst_nieuw';", 'url' => '/instellingen/verantwoordingsteksten', 'scale_field' => 'tekst', 'do_paging' => true, ) ); ?> <? $this->load->view('elements/footer'); ?><file_sep><div id="nlaf_VoortgangFilters"> <!-- Status filter --> <div class="tekst inlineblock"><?=tg('status_filter')?>:</div> <div class="filter inlineblock selected" title="<?=tgn('klik_om_filtering_op_groen_aan_uit_te_zetten')?>" filter="groen"> <img src="<?=site_url('/files/images/nlaf/waardeoordeel-groen.png')?>" class="waardeoordeel" /> </div><? ?><div class="filter inlineblock selected" title="<?=tgn('klik_om_filtering_op_geel_aan_uit_te_zetten')?>" filter="geel"> <img src="<?=site_url('/files/images/nlaf/waardeoordeel-geel.png')?>" class="waardeoordeel" /> </div><? ?><div class="filter inlineblock selected" title="<?=tgn('klik_om_filtering_op_rood_aan_uit_te_zetten')?>" filter="rood"> <img src="<?=site_url('/files/images/nlaf/waardeoordeel-rood.png')?>" class="waardeoordeel" /> </div> <!-- Betrokkene filter --> <div class="tekst inlineblock"><!-- <?=tg('betrokkene_filter')?>: --></div> <div class="filterSelect inlineblock" title="<?=tgn('kies_een_betrokkene_om_op_te_filteren')?>" filter="betrokkene"> <? $subjecten = $deelplan->get_subjecten(); ?> <select name="betrokkene" id="filterBetrokkene" style="width:150px"> <option value="" style="font-style:italic"><?=tgn('betrokkene_filter_all')?></option> <? foreach ($subjecten as $subject): ?> <option value="<?=$subject->id?>" email_bekend="<?=$subject->email ? 1 : 0?>" is_gebruiker="<?=$subject->gebruiker_id ? 1 : 0?>"><?=$subject->naam?></option> <? endforeach; ?> </select> </div> <!-- Hercontroledatum filter --> <div class="tekst inlineblock"><!-- <?=tg('datum_filter')?>: --></div> <div class="filterSelect inlineblock" title="<?=tgn('kies_een_datum_om_op_te_filteren')?>" filter="datum"> <select name="datum" id="filterDatum" style="width:150px"> <option value="" style="font-style:italic"><?=tgn('datum_filter_all')?></option> </select> </div> <!-- Fase filter --> <div class="tekst inlineblock"><!-- <?=tg('fase_filter')?>: --></div> <div class="filterSelect inlineblock" title="<?=tgn('kies_een_fase_om_op_te_filteren')?>" filter="fase"> <select name="fase" id="filterFase" style="width:150px"> <option value="" style="font-style:italic"><?=tgn('fase_filter_all')?></option> </select> </div> <!-- Toezichtmoment filter --> <div class="tekst inlineblock"><!-- <?=tg('toezichtmoment_filter')?>: --></div> <div class="filterSelect inlineblock" title="<?=tgn('kies_een_toezichtmoment_om_op_te_filteren')?>" filter="toezichtmoment"> <select name="fase" id="filterToezichtmoment" style="width:150px"> <option value="" style="font-style:italic"><?=tgn('toezichtmoment_filter_all')?></option> </select> </div> <div class="filter_style inlineblock" filter="groen" onclick="$('.voortgang .onderwerp').each(function(){$(this).find('.collapsed').hide(),$(this).find('.expanded').show(),VoortgangTableOnderwerp[$(this).attr('onderwerp_id')].vraagRows$.filter('[filtered=nee]').show()});"> <img src="<?=site_url('/files/images/nlaf/open_list.png')?>" class="waardeoordeel" style="width:24px;" /> </div> </div> <div style="overflow: auto; height: 546px; "> <table class="voortgang" cellpadding="0" cellspacing="0" border="0" style="width: 100%"> <tbody> </tbody> </table> </div> <script type="text/javascript"> // NOTE // VoortgangTable is defined in toestdata-js.php var voortangScrollIntoView = function(element, container) { var containerTop = $(container).scrollTop(); var containerBottom = containerTop + $(container).height(); var elemTop = element.offsetTop; var elemBottom = elemTop + $(element).height(); if (elemTop < containerTop) { $(container).scrollTop(elemTop); } else if (elemBottom > containerBottom) { $(container).scrollTop(elemBottom - $(container).height()); } } var voortgangExpandOnderwerp = function( onderwerp_id, scroll_in_view ) { if (!onderwerp_id) return; voortgangCollapseOnderwerpen( VoortgangTable.find('tr.onderwerp') ); var tr = VoortgangTableOnderwerp[onderwerp_id].onderwerpRow; tr.find('.collapsed').hide(); tr.find('.expanded').show(); VoortgangTableOnderwerp[onderwerp_id].vraagRows$.filter('[filtered=nee]').show(); BRISToezicht.Toets.Vraag.initializeVraagVoortgang( onderwerp_id ); if (scroll_in_view) { voortangScrollIntoView( tr, VoortgangTable ); } }; var voortgangCollapseOnderwerpen = function( trs ) { trs.find('.collapsed').show(); trs.find('.expanded').hide(); trs.each(function(){ VoortgangTableOnderwerp[$(this).attr('onderwerp_id')].vraagRows$.filter('[filtered=nee]').hide(); }); }; var voortgangCollapseOnderwerp = function( onderwerp_id ) { voortgangCollapseOnderwerpen( VoortgangTable.find('tr.onderwerp[onderwerp_id=' + onderwerp_id + ']') ); }; $(document).ready(function(){ var getFilterSelector = function() { var checkedButtons = $('#nlaf_VoortgangFilters .filter.selected'); var result = ''; checkedButtons.each(function(){ var items = (''+$(this).attr('filter')).split(','); for (var i=0; i<items.length; ++i) result += ':not([filter=' + items[i] + '])'; }); return result; } // handle openklappen voortgang $('#nlaf_ToezichtVoortgangPanel').on('click', 'img.collapsed', function(e){ eventStopPropagation( e ); voortgangExpandOnderwerp( $(this).parents('[onderwerp_id]').attr( 'onderwerp_id' ) ); }); // handle dichtklappen voortgang $('#nlaf_ToezichtVoortgangPanel').on('click', 'img.expanded', function(e){ eventStopPropagation( e ); voortgangCollapseOnderwerp( $(this).parents('[onderwerp_id]').attr( 'onderwerp_id' ) ); }); // handle selecting an onderwerp $('#nlaf_ToezichtVoortgangPanel').on('click', 'tr.onderwerp', function(){ var onderwerp_id = $(this).attr('onderwerp_id'); if (BRISToezicht.Toets.Vraag.select( onderwerp_id )) $('#nlaf_HeaderTerug div').trigger( 'click' ); }); // handle selecting a vraag $('#nlaf_ToezichtVoortgangPanel').on('click', 'tr.vraag', function(){ var onderwerp_id = $(this).attr('onderwerp_id'); var vraag_id = $(this).attr('vraag_id'); $("#combi_onderwerp_id").val(onderwerp_id); BRISToezicht.Toets.Vraag.select( onderwerp_id, vraag_id ); $('#nlaf_HeaderTerug div').trigger( 'click' ); }); // Handle the complete chain of combined filters. // This checks the filter state of all filters and 'chains' the filtering by calling each of the individual filter methods. function performCompoundFiltering() { // Initialise: 'unfilter' everything // zet alle vraag regels op niet gefilterd (reset naar originele staat) VoortgangTable.children('tr:not(.onderwerp)').attr( 'filtered', 'nee' ); // Status filtering (default: no filtering) // verberg alle vraag regels die niet aan ons huidige filter voldoen VoortgangTable.children('tr:not(.onderwerp)' + getFilterSelector()).hide().attr( 'filtered', 'ja' ); // Chain in the other filters here. When adding filters, make sure to implement a hook for them here. // Betrokkene filtering (default: no filtering) var filterVal = $('#filterBetrokkene').val(); // Check all questions to see which ones should be filtered VoortgangTable.children('tr:not(.onderwerp)').each(function(){ if (!checkRowHasBetrokkene(filterVal, $(this).attr('vraag_id'))) { $(this).hide().attr( 'filtered', 'ja' ); } }); // Hercontrole datum filtering (default: no filtering) var filterVal = $('#filterDatum').val(); // Check all questions to see which ones should be filtered VoortgangTable.children('tr:not(.onderwerp)').each(function(){ if (!checkRowHasHercontroleDatum(filterVal, $(this).attr('vraag_id'))) { $(this).hide().attr( 'filtered', 'ja' ); } }); // Fase filtering (default: no filtering) var filterVal = $('#filterFase').val(); // Check all questions to see which ones should be filtered VoortgangTable.children('tr:not(.onderwerp)').each(function(){ if (!checkRowHasGenericVraagPropertyValue(filterVal, 'fase', $(this).attr('vraag_id'))) { $(this).hide().attr( 'filtered', 'ja' ); } }); // Toezichtmoment filtering (default: no filtering) var filterVal = $('#filterToezichtmoment').val(); // Check all questions to see which ones should be filtered VoortgangTable.children('tr:not(.onderwerp)').each(function(){ if (!checkRowHasGenericVraagPropertyValue(filterVal, 'toezicht_moment', $(this).attr('vraag_id'))) { $(this).hide().attr( 'filtered', 'ja' ); } }); // End of the actual filtering. Make sure the proper subject is expanded and that subjects without visible questions are hidden. // Show the questions of the active subject showQuestionsOfActiveSubjectOnly(); //showQuestionsOfActiveSubject(); // then, hide the onderwerpen that have no vragen visible hideOnderwerpenWithoutVisibleVragen(); } // Helper function. Performs a look-up to test if the passed betrokkene is associated with the passed question function checkRowHasBetrokkene(betrokkeneId, vraagId) { // If no betrokkene was passed, we exit early if (betrokkeneId == '') return true; // If we didn't exit early, perform the actual look-up. Iterate over all 'onderwerpen'. Note: performing an early // return from within the innermost .each does NOT actually return!!! For this reason we initialise a boolean to // false, then check if it needs to be overridden, and return the outcome of that instead! returnValue = false; $.each(BRISToezicht.Toets.data.onderwerpen, function(index, onderwerpen) { // Iterate over all 'vragen' $.each(onderwerpen.vragen, function(index, vraag) { // If we encounter the proper 'vraag', check if that 'vraag' is associated with the passed 'betrokkene' if (index == vraagId) { $.each(vraag.subjecten, function(index, subject) { if (betrokkeneId == subject) { returnValue = true; } }); } }); }); // If we didn't exit early due to having found a match, we exit with a 'false' result //return false; return returnValue; } // Helper function. Performs a look-up to test if the passed 'hercontrole datum' is associated with the passed question function checkRowHasHercontroleDatum(hercontroleDatum, vraagId) { // If no hercontrole datum was passed, we exit early if (hercontroleDatum == '') return true; // If we didn't exit early, perform the actual look-up. Iterate over all 'onderwerpen'. Note: performing an early // return from within the innermost .each does NOT actually return!!! For this reason we initialise a boolean to // false, then check if it needs to be overridden, and return the outcome of that instead! returnValue = false; $.each(BRISToezicht.Toets.data.onderwerpen, function(index, onderwerpen) { // Iterate over all 'vragen' $.each(onderwerpen.vragen, function(index, vraag) { // If we encounter the proper 'vraag', check if that 'vraag' is associated with the passed 'hercontrole datum' if (index == vraagId) { var checkDate = vraag.inputs.hercontrole_datum.value; //if (hercontroleDatum == checkDate.slice(0,10)) { if (hercontroleDatum == checkDate) { returnValue = true; } } }); }); // If we didn't exit early due to having found a match, we exit with a 'false' result //return false; return returnValue; } // Helper function. Performs a look-up to test generically if the passed 'value' is associated with the passed question function checkRowHasGenericVraagPropertyValue(checkValue, propertyName, vraagId) { // If an empty value was passed, we exit early if (checkValue == '') return true; // If we didn't exit early, perform the actual look-up. Iterate over all 'onderwerpen'. Note: performing an early // return from within the innermost .each does NOT actually return!!! For this reason we initialise a boolean to // false, then check if it needs to be overridden, and return the outcome of that instead! returnValue = false; $.each(BRISToezicht.Toets.data.onderwerpen, function(index, onderwerpen) { // Iterate over all 'vragen' $.each(onderwerpen.vragen, function(index, vraag) { // If we encounter the proper 'vraag', check if that 'vraag' is associated with the passed 'hercontrole datum' if (index == vraagId) { // Check the property value generically (NOTE: do so using array notation, so we can easily pass the property name!) if (vraag[propertyName] == checkValue) { returnValue = true; } } }); }); // If we didn't exit early due to having found a match, we exit with a 'false' result //return false; return returnValue; } // !!! TODO: the next two functions do almost the same, except that in the former the state of previously opened subjects // is better maintained, yet doesn't do everything we need for the other filter functions. Unify this properly. // Helper function. Shows the questions of the currently active subject. function showQuestionsOfActiveSubject() { var onderwerp_id = VoortgangTable.find( 'img.expanded:visible' ).closest( '[onderwerp_id]' ).attr('onderwerp_id'); VoortgangTable.children('tr[onderwerp_id='+onderwerp_id+']:not(.onderwerp)[filtered=nee]').show(); } // Helper function. Shows the questions of the currently active subject. function showQuestionsOfActiveSubjectOnly() { var onderwerp_id = VoortgangTable.find( 'img.expanded:visible' ).closest( '[onderwerp_id]' ).attr('onderwerp_id'); //voortgangCollapseOnderwerpen( VoortgangTable.find('tr[onderwerp_id]') ); VoortgangTable.children('tr[onderwerp_id='+onderwerp_id+']:not(.onderwerp)[filtered=nee]').show(); voortgangExpandOnderwerp(onderwerp_id, false); } // Helper function. Hides the onderwerpen that have no vragen visible. function hideOnderwerpenWithoutVisibleVragen() { VoortgangTable.children('tr.onderwerp').each(function(){ var t = $(this); var vragen = t.siblings('.vraag[onderwerp_id=' + t.attr('onderwerp_id') + '][filtered=nee]:first'); if (vragen.size()) t.show(); else t.hide(); }); return; } // handle status filtering click $('#nlaf_VoortgangFilters').on('click', '.filter', function(){ // toggle state of buttons $(this).toggleClass( 'selected' ); // Perform the compound filtering. performCompoundFiltering(); }); // handle betrokkene filtering (default: no filtering) $('#filterBetrokkene').on('change',function(){ performCompoundFiltering(); }); // handle 'hercontrole datum' filtering (default: no filtering) $('#filterDatum').on('change',function(){ performCompoundFiltering(); }); // handle 'fase' filtering (default: no filtering) $('#filterFase').on('change',function(){ performCompoundFiltering(); }); // handle 'toezichtmoment' filtering (default: no filtering) $('#filterToezichtmoment').on('change',function(){ performCompoundFiltering(); }); }); </script> <file_sep><? $this->load->view('elements/header', array('page_header'=>null)); ?> <? $CI = get_instance(); $disable_hiding_tekst = false; ?> <input type="button" value="<?=tgn('deelplan_verwijderen')?>" onclick="if (confirm('<?=tgn('deelplan_werkelijk_verwijderen_u_kunt_deze_actie_niet_ongedaan_maken')?>')) location.href='<?=site_url('/deelplannen/verwijderen/' . $deelplan->id)?>';" /><br/> <br/> <form name="form" method="post"> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('registratiegegevens'), 'expanded' => $open_registratiegegevens, 'width' => '100%', 'height' => '200px' ) ); ?> <!-- left column --> <table style="width:100%"> <tr> <td><h3><?=tg('registratiegegevens')?></h3></td> </tr> <tr> <td><?=tgg('deelplan.deelplan_naam')?>:</td> <td><input type="text" name="deelplan_naam" value="<?=htmlentities($deelplan->naam, ENT_COMPAT, 'UTF-8')?>" size="40" maxlength="128" <?=$deelplan_access!='write'?'readonly':''?> /></td> <td><?=htag('deelplan_hernoemen')?></td> </tr> <tr class="<?=$disable_hiding_tekst || $CI->tekst->has('deelplan.identificatienummer',true) ? '' : 'hidden'?>"> <td><?=tgg('deelplan.identificatienummer')?>:</td> <td><input name="kenmerk" type="text" value="<?=$deelplan->kenmerk?>" size="32" maxlength="32" <?=$deelplan_access!='write'?'readonly':''?>/></td> <td><?=htag('olo_nummer')?></td> </tr> <tr class="<?=$disable_hiding_tekst || $CI->tekst->has('deelplan.olo_nummer',true) ? '' : 'hidden'?>"> <td><?=tgg('deelplan.olo_nummer')?>:</td> <td> <? if (($lc = $CI->gebruiker->get_logged_in_gebruiker()->get_klant()->get_lease_configuratie()) && $lc->speciaal_veld_gebruiken):?> <select name="olo_nummer"> <option></option> <? foreach ($lc->get_speciaal_veld_waarden() as $waarde): ?> <option <?=$waarde == $deelplan->olo_nummer ? 'selected' : ''?>><?=htmlentities( $waarde, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <? else: ?> <input name="olo_nummer" type="text" value="<?=$deelplan->olo_nummer?>" size="40" maxlength="64" <?=$deelplan_access!='write'?'readonly':''?>/> <? endif; ?> </td> <td><?=htag('olo_nummer')?></td> </tr> <tr class="<?=$disable_hiding_tekst || $CI->tekst->has('deelplan.aanvraagdatum',true) ? '' : 'hidden'?>"> <td><?=tgg('deelplan.aanvraagdatum')?>:</td> <td><input name="aanvraag_datum" type="text" size="10" value="<?= date('d-m-Y', ($deelplan->aanvraag_datum) ? strtotime( $deelplan->aanvraag_datum ) : time()) ?>" <?=$deelplan_access!='write'?'readonly':''?>/> (dd-mm-jjjj)</td> <td><?=htag('aanvraag_datum')?></td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('bouwdelen'), 'expanded' => true, 'width' => '100%', 'height' => '300px' ) ); ?> <!-- lijst van bouwdelen --> <div class="bouwdelen lijst-nieuwe-stijl"> <div class="button toevoegen" style="margin-left: 10px;"> <i class="icon-plus" style="font-size: 12pt"></i> <span><?=tgg('form.toevoegen')?></span> </div> <div style="height:270px; overflow-y: auto; padding-right: 10px;"> <ul id="sortable" class="list" style="margin-top: 10px;"> <!-- template HTML for new entries --> <li class="entry top left right hidden"> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton delete" title="<?=tg('bouwdeel.verwijderen')?>"><i class="icon-trash" style="font-size: 12pt"></i></div> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton edit" title="<?=tg('bouwdeel.bewerken')?>"><i class="icon-cog" style="font-size: 12pt"></i></div> <div style="height:15px; padding: 10px; width: 900px" class="display"></div> <div style="height:15px; padding: 7px 10px; width: 900px" class="editor hidden"><input type="text" maxlength="128" size="100" name="bouwdelen[]" /></div> </li> <!-- list existing entries --> <? foreach ($bouwdelen as $bouwdeel): ?> <? $safe_naam = htmlentities($bouwdeel->naam, ENT_COMPAT, 'UTF-8'); ?> <li class="entry top left right "> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton delete" title="<?=tg('bouwdeel.verwijderen')?>"><i class="icon-trash" style="font-size: 12pt"></i></div> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton edit" title="<?=tg('bouwdeel.bewerken')?>"><i class="icon-cog" style="font-size: 12pt"></i></div> <div style="height:15px; padding: 10px; width: 900px" class="display"><?=$safe_naam?></div> <div style="height:15px; padding: 7px 10px; width: 900px" class="editor hidden"><input type="text" maxlength="128" size="100" name="bouwdelen[]" value="<?=$safe_naam?>" /></div> </li> <? endforeach; ?> </ul> </div> </div> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('welke_scopes_wilt_u_toetsen'), 'expanded' => !$open_registratiegegevens, 'width' => '100%', 'height' => $CI->is_Mobile ? '300px' : '550px' ) ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('sjablonen'), 'width' => '100%' ) ); ?> <?=tg('gebruik_een_scope_sjabloon')?> <input type="hidden" name="use_sjabloon_id" value="" /> <select name="sjabloon_id"> <option value="" disabled selected><?=tgn('selecteer_een_sjabloon')?></option> <? foreach ($sjablonen as $s): ?> <option value="<?=$s->id?>"><?=htmlentities( $s->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <? if ($sjabloon): ?> <br/> <p> <img src="<?=site_url('/files/images/information.png')?>" style="vertical-align: top" /> <?=tg('de_huidige_scopeselectie_is_gebaseerd_op', $sjabloon->naam )?> </p> <? endif; ?> <? if ($this->login->verify( 'deelplannen', 'sjabloon_opslaan' )): ?> <h3 style="margin: 10px 0px 2px 0px"><?=tg('nieuw_sjabloon_aanmaken')?></h3> <input type="hidden" name="use_sjabloon_naam" value="" /> <?=tg('sjabloon_naam')?>: <input type="text" size="30" name="sjabloon_naam" placeholder="<?=tgn('naam_van_het_nieuwe_sjabloon')?>" /> <input type="button" value="<?=tgng('form.aanmaken')?>" /> <? endif; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <br/> <? $deelplan_checklistgroepen = $deelplan->get_checklistgroepen_assoc(); $deelplan_checklisten = $deelplan->get_checklisten_assoc(); ?> <? foreach ($checklistgroepen as $checklistgroep): ?> <? $local_scope_access = @$scope_access[$checklistgroep->id]; if (!$local_scope_access) $local_scope_access = $deelplan_access; $any_locked = false; $checklistgroep_checklisten = $checklistgroep->get_checklisten(); foreach ($checklistgroep_checklisten as $i => $checklist) { if (isset($mag_checklisten_verwijderen[$checklist->id]) && !$mag_checklisten_verwijderen[$checklist->id]) { $any_locked = true; } if (!$checklist->is_afgerond()) unset( $checklistgroep_checklisten[$i] ); } $checklistgroep_checklisten = array_values ( $checklistgroep_checklisten ); if (empty( $checklistgroep_checklisten )) continue; ?> <table class="generic-content rounded10 form" style="margin: 0px; padding: 0px;"> <tr> <td class="generic-content checklist_list" style="vertical-align:middle; padding: 3px 0px 0px 10px;"> <table width="100%" style="margin: 0px; padding: 0px;"> <tr> <td style="width: 500px"> <? if ($checklistgroep->image_id): ?> <img src="<?=$checklistgroep->get_image()->get_url()?>" /> <b> <? endif; ?> <?=$checklistgroep->naam?> <? if ($checklistgroep->image_id): ?> </b> <? endif; ?> </td> <td> <input type="checkbox" <?=isset($deelplan_checklistgroepen[$checklistgroep->id])?'checked':''?> name="checklistgroep[<?=$checklistgroep->id?>]" onclick="if (!(<?=intval($any_locked)?>)) $('#sf_checklistgroep<?=$deelplan->id?>_<?=$checklistgroep->id?>').slideToggle('slow');" <?=($deelplan_access!='write' || $local_scope_access!='write')?'disabled':''?> locked="<?=intval($any_locked)?>"/> <? if ($any_locked): ?> <img style="vertical-align: bottom;" src="<?=site_url('/files/images/locked.png')?>" /> <? endif; ?> </td> <td align="right" style="padding-right: 20px"><?=htag('checklistgroep' . $checklistgroep->id)?></td> </tr> </table> <div id="sf_checklistgroep<?=$deelplan->id?>_<?=$checklistgroep->id?>" themas_automatisch_selecteren="<?=$checklistgroep->themas_automatisch_selecteren?>" style="display:none;margin-left:20px; background-color: transparent; border: 0px; height: auto;"> <ul style="list-style-type: none; padding-bottom: 10px; margin:0px; padding:0px;"> <? $any_selected = false; foreach ($checklistgroep_checklisten as $checklist) if (isset($deelplan_checklisten[$checklist->id])) { $any_selected = true; break; } ?> <? foreach ($checklistgroep_checklisten as $checklist): ?> <? $checklist_checked = isset($deelplan_checklisten[$checklist->id]); ?> <? $checklist_locked = isset($mag_checklisten_verwijderen[$checklist->id]) && !$mag_checklisten_verwijderen[$checklist->id]; ?> <li style="display: inline-block; width: 27em; padding: 5px; border: 1px solid #ddd; background-color: white; white-space: nowrap; overflow: hidden" title="<?=$checklist->naam?>"> <label for="sfg_<?=$checklist->id?>" style="cursor:pointer"> <input type="checkbox" id="sfg_<?=$checklist->id?>" name="checklist[<?=$checklist->id?>]" <?=$checklist_checked?'checked':''?> <?=($deelplan_access!='write' || $local_scope_access!='write')?'disabled':''?> locked="<?=intval($checklist_locked)?>" /> <? if ($checklist_locked): ?> <img style="vertical-align: bottom;" src="<?=site_url('/files/images/locked.png')?>" /> <? endif; ?> <?=$checklist->naam?> </label> </li> <? endforeach; ?> </ul> </div> </td> </tr> </table> <? if (isset($deelplan_checklistgroepen[$checklistgroep->id])): ?> <script type="text/javascript"> $('#sf_checklistgroep<?=$deelplan->id?>_<?=$checklistgroep->id?>').slideDown(); </script> <? endif; ?> <script type="text/javascript"> $('input[type=checkbox][locked=1]').click(function( evt ){ if (!this.checked) this.checked = true; eventStopPropagation( evt ); return false; }); </script> <? endforeach; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('themas'), 'expanded' => false, 'width' => '100%', 'height' => $CI->is_Mobile ? '300px' : '550px' ) ); ?> <input type="button" value="<?=tgng('form.deselecteer_alles')?>" select="none" style="float:right" /> <input type="button" value="<?=tgng('form.selecteer_alles')?>" select="all" style="float:right" /> <? foreach ($hoofdthemas as $hoofdthema): ?> <? $themas = $hoofdthema->get_themas(); if (empty( $themas )) continue; ?> <div class="hoofdthema" tag="<?=$hoofdthema->id?>" style="height: auto; border: 0px; "> <input type="checkbox" class="hoofdthema" title="Met deze checkbox (de)selecteert u in een keer alle thema&#39;s behorende bij dit hoofdthema." /> <span style="font-weight:bold; cursor: pointer;" title="Klik om de thema&#39;s behorende bij dit hoofdthema te tonen."><?=$hoofdthema->naam?></span></br> <div style="margin-left: 50px; padding: 10px; height: auto; display: none;"> <ul class="thema"> <? foreach ($themas as $thema): ?> <li class="subthema" tag="<?=$thema->id?>" style="display:inline-block; white-space:nowrap; overflow: hidden;"> <input type="checkbox" name="themas[<?=$thema->id?>]" <?=isset($current_themas[$thema->id])?'checked ':''?> > <?=htmlentities($thema->thema, ENT_COMPAT, 'UTF-8')?> </li> <? endforeach; ?> </ul> </div> </div> <? endforeach; ?> <p class="nothing_selected" style="display:none"> <?=tg('er_zijn_nog_geen_scopes_geselecteerd')?> </p> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('betrokkenen'), 'expanded' => false, 'width' => '100%', 'height' => $CI->is_Mobile ? '300px' : '550px' ) ); ?> <? if (empty( $subjecten )): ?> <?=tg('er_zijn_nog_geen_betrokkenen_gedefinieerd')?> <? else: ?> <input type="button" value="<?=tgng('form.deselecteer_alles')?>" select="none" style="float:right" /> <input type="button" value="<?=tgng('form.selecteer_alles')?>" select="all" style="float:right" /> <ul style="list-style-type: none; padding-bottom: 10px; margin:0px; padding:0px;"> <? foreach ($subjecten as $subject): ?> <? $subject_selected = isset($current_subjecten[$subject->id]); ?> <li style="width: 27em; padding: 5px; border: 1px solid #ddd; margin-bottom: 5px; background-color: white; white-space: nowrap; overflow: hidden"> <input type="checkbox" name="subjecten[<?=$subject->id?>]" <?=$subject_selected?'checked':''?> /> <?=$subject->naam?> <? if ($subject->organisatie): ?> <i>(<?=htmlentities( $subject->organisatie, ENT_COMPAT, 'UTF-8' )?>)</i> <? endif; ?> <? if ($subject->rol): ?> - <?=htmlentities( $subject->rol, ENT_COMPAT, 'UTF-8' )?> <? endif; ?> </li> <? endforeach; ?> </ul> <? endif; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('bescheiden'), 'expanded' => false, 'width' => '100%', 'height' => $CI->is_Mobile ? '300px' : '550px' ) ); ?> <? if (empty( $bescheiden ) && empty( $mappen )): ?> <?=tg('er_zijn_nog_geen_bescheiden_gedefinieerd')?> <? else: ?> <div class="bescheiden-container" style="padding:0;margin:0;border:0;height:auto;"> <? $this->load->view( 'deelplannen/_bescheiden' ); ?> </div> <? endif; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <!-- submit button --> <p align="right"> <input type="submit" value="<?=tgng('form.opslaan')?>" /> </p> <? foreach (array_keys( $current_bescheiden ) as $id): ?> <input type="hidden" name="bescheiden[<?=$id?>]" value="on" /> <? endforeach; ?> </form> <script type="text/javascript"> var groepdata = [ <? // speedup! $num = 0; foreach ($checklistgroepen as $checklistgroep) { foreach ($checklistgroep->get_checklisten() as $checklist) { $hoofdthemas = array(); foreach (get_instance()->hoofdthema->get_by_checklist( $checklist->id ) as $hoofdthema) $hoofdthemas[] = $hoofdthema->id; $themas = array(); foreach (get_instance()->thema->get_by_checklist( $checklist->id ) as $thema) $themas[] = $thema->id; echo $num++ ? ', ' : ''; echo "\n" . '{checklistgroep_id: ' . $checklistgroep->id . ', checklist_id:' . $checklist->id . ', hoofdthemas:[' . implode( ',', $hoofdthemas ) . '], themas:[' . implode( ',', $themas ) . '] } '; } } ?> ]; function update_themas( control_or_id ) { var parentDiv = $('form'); var deelplan_id = <?=$deelplan->id?>; // slideUp all parentDiv.find('div.hoofdthema').hide(); parentDiv.find('li.subthema').hide(); // go over all checklist var selected = 0; var parentData = {}; var hoofdThemas = parentDiv.find('.hoofdthema'); var subThemas = parentDiv.find('.subthema'); for (var i=0; i<groepdata.length; ++i) { // is checkbox checked? if (!parentData[groepdata[i].checklistgroep_id]) { var d = { checkbox: parentDiv.find('input[type=checkbox][name=checklistgroep\\[' + groepdata[i].checklistgroep_id + '\\]]'), }; d.checked = d.checkbox.attr( 'checked' ); d.td = d.checkbox.parents('.checklist_list'); parentData[groepdata[i].checklistgroep_id] = d; } var pd = parentData[groepdata[i].checklistgroep_id]; var checked = pd.td.find('input[type=checkbox][name=checklist\\[' + groepdata[i].checklist_id + '\\]]').attr( 'checked' ); if (pd.checked && checked) { selected++; for (var j=0; j<groepdata[i].hoofdthemas.length; ++j) hoofdThemas.filter('[tag=' + groepdata[i].hoofdthemas[j] + ']' ).show(); for (var j=0; j<groepdata[i].themas.length; ++j) subThemas.filter('[tag=' + groepdata[i].themas[j] + ']' ).show(); } } // nothing selected? if (selected) parentDiv.find('.nothing_selected').hide(); else parentDiv.find('.nothing_selected').show(); } function selecteer_all_themas( checklist_id ) { for (var i=0; i<groepdata.length; ++i) if (groepdata[i].checklist_id == checklist_id) { for (var j=0; j<groepdata[i].themas.length; ++j) { var themaCB = $('[type=checkbox][name=themas\\[' + groepdata[i].themas[j] + '\\]]'); themaCB.attr( 'checked', 'checked' ); var hoofdthemaCB = themaCB.parents('.hoofdthema').children('[type=checkbox]'); hoofdthemaCB.attr( 'checked', 'checked' ); } break; } } // every time something relevant gets clicked, update state $('.checklist_list input[type=checkbox]').click( function() { if (this.checked) { if ($(this).is('[name^=checklist\\[]')) { // we just clicked a checklist checkbox, if the checklistgroep wants us to auto // select all thema's, do so now var themas_automatisch_selecteren = parseInt( $(this).parents( '[themas_automatisch_selecteren]' ).attr( 'themas_automatisch_selecteren' ) ); if (themas_automatisch_selecteren) { var checklist_id = $(this).attr( 'id' ).substr( 4 ); selecteer_all_themas( checklist_id ); } } } update_themas( this ); }); // handle clicking the checkboxes for each hoofdthema $('input[type=checkbox].hoofdthema').click( function(evt){ var cb = $(evt.currentTarget); var themacbs = cb.parent().find('div').find( 'input[type=checkbox]' ); if (cb.attr( 'checked' )) themacbs.attr( 'checked', 'checked' ); else themacbs.removeAttr( 'checked' ); }); // handle toggling the visibility of each hoofdthema's subthema's $('.hoofdthema span').click( function(evt){ var span = $(evt.currentTarget); span.parent().find('div').slideToggle('slow'); }); // // init // update_themas( <?=$deelplan->id?> ); // init state of hoofdthema checkboxes, if ANY subthema is selected, make checkbox selected $('input[type=checkbox].hoofdthema').each( function(){ var cb = $(this); var num = 0; var themacbs = cb.parent().find('div').find( 'input[type=checkbox]' ).each(function(){ if ($(this).attr('checked')) ++num; }); if (num) cb.attr( 'checked', 'checked' ); else cb.removeAttr( 'checked' ); }); // init date fields $('form[name=form] input[name=aanvraag_datum]').datepicker({ dateFormat: "dd-mm-yy" }); // // (de)selecteer alles // $('input[type=button][select]').click(function(evt){ eventStopPropagation(evt); parentDiv = $(this).parent(); var mode = parentDiv.find(this).attr( 'select' ); // do hoofdthema's parentDiv.find('input[type=checkbox]').each(function(){ this.checked = mode == 'all'; }); }); // // sjabloon // $('select[name=sjabloon_id]').change(function(){ if (confirm( 'Geselecteerd sjabloon toepassen?' )) { $('input[name=use_sjabloon_id]').val( '1' ); this.form.submit(); } }); $('input[name=sjabloon_naam]').siblings( '[type=button]' ).click(function(){ $('input[name=use_sjabloon_naam]').val( '1' ); this.form.submit(); }); // // bescheiden stuff // var bescheidenInMappen = { <? // maak een lijst van bescheiden id's die in een map zitten, die informatie // hebben we nodig bij het (de)selecteren van een gehele map! $doMap = function( $map ) use (&$doMap) { // maak javascript lijst van bescheiden ids $str = $map->id . ': ['; foreach ($map->get_bescheiden( true ) as $i => $bescheiden) $str .= ($i ? ',' : '') . $bescheiden->id; $str .= ']'; // maak array wat ons resultaat gaat zijn, zodat we straks nette JS kunnen // uitvoeren (vooral lettende op trailing comma's en IE... :-/) $result = array( $str ); // doe submappen foreach ($map->get_mappen() as $submap) $result = array_merge( $result, $doMap( $submap ) ); return $result; }; $list = array(); foreach (get_instance()->dossierbescheidenmap->get_by_dossier( $deelplan->dossier_id, NULL ) as $map) $list = array_merge( $list, $doMap( $map ) ); echo implode( ",\n", $list ); ?> }; function showError( msg ) { showMessageBox({message: msg, buttons: ['ok'], type: 'error'}); } function updateBescheidenHTML( data ) { $('.bescheiden-container').html( data ); } function openBescheidenMap( id ) { $.ajax({ url: '/deelplannen/bescheiden_lijst/<?=$deelplan->id?>/' + id, type: 'POST', dataType: 'html', success: function( data ) { updateBescheidenHTML( data ); updateBescheidenCheckboxes(); }, error: function() { showError( '<?=tgn('fout_bij_communicatie_met_server')?>' ); } }); } function bescheidenFormNaarArray() { var ids = []; $('form [name^=bescheiden]').each(function(){ var id = $(this).attr('name').replace( /^bescheiden\[(\d+)\]$/, '$1' ); ids.push( parseInt( id ) ); }); return ids; } function arrayNaarBescheidenForm( ids ) { $('form [name^=bescheiden]').remove(); for (var i=0; i<ids.length; ++i) $('form').append( '<input type="hidden" name="bescheiden[' + ids[i] + ']" value="on" />' ); } function selecteerAlleBescheidenInMap( map_id, value ) { showMessageBox({ message: value ? '<?=tgn('alle.bescheiden.in.deze.map.selecteren')?>' : '<?=tgn('alle.bescheiden.in.deze.map.deselecteren')?>', onClose: function( res ) { // haal de lijst op van ids die we gaan (de)selecteren var lijst = bescheidenInMappen[ map_id ]; if (!lijst) return; // maak array van de geselecteerde bescheiden op basis van hidden form entries var selectedBescheiden = bescheidenFormNaarArray(); // zet alle ids aan of uit for (var i=0; i<lijst.length; ++i) { var id = lijst[i]; var cb = $('form [bescheiden_id=' + id + ']'); var index = indexOfArray( selectedBescheiden, id ); if (value) { // vanaf nu hoort ie er bij if (index == -1) selectedBescheiden.push( id ); } else { // vanaf nu hoort ie er niet meer bij if (index != -1) selectedBescheiden.splice( index, 1 ); } } // plaats de lijst terug in de form arrayNaarBescheidenForm( selectedBescheiden ); } }); } function updateBescheidenState( cb, id ) { // maak array van de geselecteerde bescheiden op basis van hidden form entries var selectedBescheiden = bescheidenFormNaarArray(); // bekijk of we hem toe moeten voegen aan de lijst, of juist verwijderen var index = indexOfArray( selectedBescheiden, id ); if (cb.checked) { // vanaf nu hoort ie er bij if (index == -1) selectedBescheiden.push( id ); } else { // vanaf nu hoort ie er niet meer bij if (index != -1) selectedBescheiden.splice( index, 1 ); } // plaats de lijst terug in de form arrayNaarBescheidenForm( selectedBescheiden ); } function updateBescheidenCheckboxes() { $('form [name^=bescheiden]').each(function(){ var id = $(this).attr('name').replace( /^bescheiden\[(\d+)\]$/, '$1' ); $('form input[type=checkbox][bescheiden_id=' + id + ']').attr( 'checked', 'checked' ); }); } updateBescheidenCheckboxes(); // // // BOUWDELEN BOUWDELEN BOUWDELEN BOUWDELEN BOUWDELEN BOUWDELEN BOUWDELEN BOUWDELEN // // var bouwdelenTabel = $('.bouwdelen ul'); var bouwdelenTemplate = $('<div>').append( bouwdelenTabel.find('li.hidden') ).html(); // handle add button $('.bouwdelen .button.toevoegen').click(function(){ var newEntry = $(bouwdelenTemplate).removeClass('hidden'); bouwdelenTabel.append( newEntry ); newEntry.find('.optiebutton.edit').trigger('click'); }); // handle edit button $('.bouwdelen .optiebutton.edit').live( 'click', function(){ var entry = $(this).closest('li'); entry.find('div.display').hide(); entry.find('div.editor').show(); entry.find('div.editor input').focus(); }); $('.bouwdelen .optiebutton.delete').live( 'click', function(){ var entry = $(this).closest('li'); showMessageBox({ message: '<?=jsstr(tgn('dit.bouwdeel.echt.verwijderen'))?>', onClose: function( res ) { if (res != 'ok') return; entry.remove(); } }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><table class="generic-content rounded10 form" style="<? if (isset( $width )):?>width:<?=$width?><? endif; ?>;<?=@$style?>"> <tr> <td class="generic-content"> <table> <tr> <td><h3 style="margin:5px 0"><?=@$header?></h3></td> </tr> <tr> <td> <file_sep><?php class BRIS_SupervisionCheckList extends BRIS_AbstractSupervisionMoments { const CL_SESSION = 'cl_moment_id'; protected $_checklist_id; protected $_bouwnummer; protected static $_model_name = 'supervisionmomentscl'; public function setChecklistId($checklist_id) { $this->_checklist_id = $checklist_id; return $this; } public function setBouwnummertId($bouwnummer) { // $this->_bouwnummer = (bool)$bouwnummer ? $bouwnummer : 0; $this->_bouwnummer = $bouwnummer; return $this; } public function saveMoment() { $this->_checkValues(); if( isset($_SESSION[self::CL_SESSION]) ) { // Update entry // The fields has to be in order of precedence because the library don't take into account the keys $fields = array( 'progress_end' => $this->_progress, 'supervision_end' => $this->_current_time, 'id' => $_SESSION[self::CL_SESSION], ); if( !$this->_model->dbex->is_prepared('supervisionmomentscl::save') ) { $this->_model->dbex->prepare('supervisionmomentscl::save', 'UPDATE supervision_moments_cl SET progress_end = ?, supervision_end = ? ' . 'WHERE id = ?'); } $this->_model->dbex->execute('supervisionmomentscl::save', $fields); } else { // Create a new entry $fields = array( 'deelplan_id' => $this->_deelplan_id, 'checklist_id' => $this->_checklist_id, 'bouwnummer' => $this->_bouwnummer, 'supervisor_user_id' => $this->_supervisor_user_id, 'supervision_start' => $this->_current_time, 'progress_start' => $this->_progress ); $this->_bouwnummer !=NULL && $this->_bouwnummer !='' ? $fields['bouwnummer'] = $this->_bouwnummer : NULL; $res = $this->_model->insert($fields); $_SESSION[self::CL_SESSION] = $res->id; } } }<file_sep><?php class CI_KMXLicenseSystem { private $CI; private $_licsys; private $_tokens = array(); public function __construct() { $this->CI = get_instance(); // hacky, but staying as close to original example as I can include( dirname(__FILE__) . '/kmx/licsys.php' ); $this->_licsys = $licSys; } public function claim_license_seat( $applicationLabel, $kennisid_licentie_id, $recognition ) { $this->_licsys->licenseSystemLabel = $applicationLabel; $result = $this->_licsys->claimLicenseSeat( array( 'identification' => $kennisid_licentie_id, '3thpartyauth' => '1', 'recognition' => $recognition, ) ); if (!is_object( $result ) || !$result->Status ) return 'claimLicenseSeatError'; if ($result->Status == 'Valid') { $this->_tokens[ $this->_licsys->licenseSystemLabel ] = $this->_licsys->lastToken; return true; } return 'KMXError' . $result->Status; } public function get_token_for_application( $applicationLabel ) { return @$this->_tokens[ $applicationLabel ]; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Bewerken', 'width' => '920px' )); ?> <form method="post" enctype="multipart/form-data"> <table style="width:auto"> <tr> <td><b>Aangemaakt door</b></td> <td> <b> <?=$backlog->gebruiker_id ? htmlentities( $this->gebruiker->get( $backlog->gebruiker_id )->volledige_naam, ENT_COMPAT, 'UTF-8' ) : '-niet bekend-'?> </b> <br/> <br/> </td> </tr> <tr> <td>Wens?</td> <td> <input type="checkbox" name="is_wens" <?=$backlog->is_wens ? 'checked' : ''?>><br/> <div style="padding: 20px; border: 1px solid #777; background-color: white; margin-bottom: 40px;"> <i>Aanvinken als dit backlog punt een wens, een idee, of iets wat nog nader moet worden gespecifieerd is.<br/> Uitvinken als dit een concrete opdracht of bug is.</i></td> </div> </tr> <tr> <td>Verbeterpunt:</td> <td><textarea name="verbeterpunt" style="width:500px; height:100px"><?=htmlentities( $backlog->verbeterpunt, ENT_COMPAT, 'UTF-8' )?></textarea></td> </tr> <tr> <td>Actie:</td> <td><textarea name="actie" style="width:500px; height:100px"><?=htmlentities( $backlog->actie, ENT_COMPAT, 'UTF-8' )?></textarea></td> </tr> <tr> <td>Actie voor:</td> <td> <select name="actie_voor_gebruiker_id"> <option value="">-</option> <? foreach ($gebruikers as $id => $g): ?> <option <?=$backlog->actie_voor_gebruiker_id == $id ? 'selected' : ''?> value="<?=$id?>"><?=$g?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td>Prioriteit:</td> <td><input type="text" name="prioriteit" maxlength="128" size="30" value="<?=htmlentities( $backlog->prioriteit, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <? if ($gebruiker->is_super_admin() && $are_special_fields_visible): ?> <tr> <td style="background-color: #fdd;">Prioriteit Imotep:</td> <td style="background-color: #fdd;"><input type="text" name="prio_nr_imotep" maxlength="128" size="30" value="<?=htmlentities( $backlog->prio_nr_imotep, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <tr> <td style="background-color: #fdd;">Prioriteit BRIS:</td> <td style="background-color: #fdd;"><input type="text" name="prio_nr_bris" maxlength="128" size="30" value="<?=htmlentities( $backlog->prio_nr_bris, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <? endif; ?> <tr> <td>Ureninschatting:</td> <td><input type="text" name="ureninschatting" maxlength="128" size="30" value="<?=htmlentities( $backlog->ureninschatting, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <? if ($gebruiker->is_super_admin() && $are_special_fields_visible): ?> <tr> <td style="background-color: #fdd;">Ureninschatting intern:</td> <td style="background-color: #fdd;"><input type="text" name="ureninschatting_intern" maxlength="128" size="30" value="<?=htmlentities( $backlog->ureninschatting_intern, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <? endif; ?> <tr> <td>Status:</td> <td><input type="status" name="status" maxlength="128" size="30" value="<?=htmlentities( $backlog->status, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <tr> <td>Testresultaten:</td> <td><textarea name="testresultaten" style="width:500px; height:100px"><?=htmlentities( $backlog->testresultaten, ENT_COMPAT, 'UTF-8' )?></textarea></td> </tr> <? if ($gebruiker->is_super_admin() && $are_special_fields_visible): ?> <tr> <td style="background-color: #fdd;">Programmeur:</td> <td style="background-color: #fdd;"><input type="text" name="programmeur" maxlength="128" size="30" value="<?=htmlentities( $backlog->programmeur, ENT_COMPAT, 'UTF-8' )?>" /></td> </tr> <? endif; ?> <tr> <td>Afgerond:</td> <td><input type="checkbox" name="afgerond" <?=$backlog->afgerond ? 'checked' : ''?> /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Opslaan" /> <input type="button" value="Verwijderen" onclick="if (confirm('Verantwoording verwijderen?')) location.href='/admin/backlog_verwijderen/<?=$backlog->id?>';" /> <input type="button" value="Naar <?=sizeof($backlog->get_uploads())?> upload(s)" onclick="location.href='/admin/backlog_uploads/<?=$backlog->id?>';" /> <input type="button" value="Terug" onclick="if (confirm('Wijzigingen annuleren?')) location.href='/admin/backlog';" style="float:right" /> </td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><?php function converteer_pdf_file_naar_pdf15( $filename ) { ob_start(); $cmd = 'gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.5 -dNOPAUSE -dQUIET -dBATCH -sOutputFile=- ' . escapeshellarg( $filename ); $descriptorspec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("file", "/dev/null", "a") // stderr is a file to write to ); $cwd = '.'; $process = proc_open($cmd, $descriptorspec, $pipes ); if (is_resource( $process )) { fclose( $pipes[0] ); // no need to write anything to proces stdin $new_pdf_contents = stream_get_contents($pipes[1]); fclose($pipes[1]); $return_value = proc_close($process); if ($return_value) { ob_end_clean(); throw new Exception( tgng('php.fout.bij.conversie') ); } else { ob_end_clean(); return $new_pdf_contents; } } else { ob_end_clean(); throw new Exception( tgng('php.kon.gs.niet.starten') ); } } function converteer_pdf_contents_naar_pdf15( $contents ) { $tmpfilename = '/tmp/pdf15-' . mt_rand() . '-' . time() . '.pdf'; if (!@file_put_contents( $tmpfilename, $contents )) throw new Exception( 'Kon PDF niet naar disk wegschrijven.' ); try { $contents = converteer_pdf_file_naar_pdf15( $tmpfilename ); @unlink( $tmpfilename ); return $contents; } catch (Exception $e) { @unlink( $tmpfilename ); throw $e; } } <file_sep><? $opdracht = $objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['opdrachten'][$status][$opdracht]; $vraag = $opdracht->get_vraag(); $deelplan=$opdracht->get_deelplan(); $type = $vraag->get_wizard_veld_recursief('vraag_type'); $gereed_datum = date('d-m-Y', strtotime( $opdracht->gereed_datum ) ); $is_foto_vraag = !is_null( $opdracht->annotatie_tag ); $uploads = $opdracht->get_deelplan_uploads(); if ($type == 'meerkeuzevraag') { $opties = array(); for ($x=0; $x<3; ++$x) for ($y=0; $y<5; ++$y) if ($x && $y==4) continue; else if ($optie = $vraag->get_wizard_veld_recursief( 'wo_tekst_' . $x . $y )) $opties['w'.$x.$y] = $optie; } ?> <div id="header" class="menubar"> <form method="post"> <input type="hidden" name="page" value="afsluiten"> <input id="close" type="submit" value="afsluiten" hidden/><label for="close">Afsluiten</label>BRISToezicht - Uitvoering Opdracht </form> </div> <div class="objects"> <form id="opdracht" method="POST" enctype="multipart/form-data" class="opdracht<?=$opdracht->status == 'gereed' ? ' disabled' : '' ;?>"> <input type="hidden" name="page" value="opslaan" /> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input type="hidden" name="bouwnummer_id" value="<?=$bouwnummer?>"> <input type="hidden" name="hoofdgroep_id" value="<?=$hoofdgroep?>"> <input type="hidden" name="opdracht_id" value="<?=$opdracht->id?>"> <h1><?=htmlentities( $objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['naam'], ENT_COMPAT, 'UTF-8' )?></h1> <h2><?=htmlentities( $vraag->tekst, ENT_COMPAT, 'UTF-8' )?></h2> <? if ($opdracht->status == 'gereed'):?> <?$disabled= ' disabled' ?> <span class="error">Deze opdracht is al gereed gemeld en kan niet meer worden gewijzigd</span> <?else:?> <?$disabled= '' ?> <?endif;?> <span> Locatie aanduiding uitvoering opdracht </span> <? if ($is_foto_vraag): ?> <span> <!-- <? for ($q=0; $q<$opdracht->get_overzicht_afbeelding_aantal(); ++$q): ?> <a href="<?=$opdracht->get_overzicht_afbeelding_url( $q )?>"><img src="<?=$opdracht->get_overzicht_afbeelding_preview_url( 100 )?>"></a> <a href="<?=$opdracht->get_snapshot_afbeelding_url()?>"><img src="<?=$opdracht->get_snapshot_afbeelding_preview_url( 100 )?>"></a> <? endfor; ?> --> </span> <? endif; ?> <hr /> <span> <?=htmlentities( $opdracht->opdracht_omschrijving, ENT_COMPAT, 'UTF-8' )?> </span> <span> <? if ($opdracht->status != 'gereed'):?> <input type="checkbox" name="gereed" id="gereed" hidden /><label for="gereed" class="right-align">Meld Gereed</label> <?endif;?> </span> <span> <? if ($type == 'meerkeuzevraag'): ?> <select name="waardeoordeel" id="waardeoordeel"<?=$disabled?>> <?if(!$opdracht->antwoord):?> <option selected disabled>Invoer waarden of selectie beoordeling<?//=tgn('kies.een.waardeoordeel')?></option> <?endif;?> <? foreach ($opties as $waardeoordeel => $optie): ?> <? if (isset($opdracht->antwoord) && $opdracht->antwoord == $waardeoordeel):?> <option value="<?=$waardeoordeel?>" selected><?=htmlentities( $optie, ENT_COMPAT, 'UTF-8' )?></option> <? else: ?> <option value="<?=$waardeoordeel?>"><?=htmlentities( $optie, ENT_COMPAT, 'UTF-8' )?></option> <? endif ?> <? endforeach; ?> </select> <? elseif ($type == 'invulvraag'): ?> <input type="text" name="waardeoordeel" id="waardeoordeel" <?= $disabled ?>/> <? endif; ?> </span> <span> <textarea name="toelichting" id="toelichting" rows="5"<?= $disabled ?>><?if (isset($opdracht->toelichting)):?><?=$opdracht->toelichting?><? endif ?></textarea> </span> <span id="pics"> <input type="file" accept="image/*" id="upload1" name="images[]" hidden <?= $disabled ?>><label id="lblupload1" for="upload1" >Foto toevoegen</label> <input type="file" accept="image/*" id="upload2" name="images[]" hidden <?= $disabled ?>><label id="lblupload2" for="upload2" >Foto toevoegen</label> <input type="file" accept="image/*" id="upload3" name="images[]" hidden <?= $disabled ?>><label id="lblupload3" for="upload3" >Foto toevoegen</label> <input type="file" accept="image/*" id="upload4" name="images[]" hidden <?= $disabled ?>><label id="lblupload4" for="upload4" >Foto toevoegen</label> <input type="file" accept="image/*" id="upload5" name="images[]" hidden <?= $disabled ?>><label id="lblupload5" for="upload5" >Foto toevoegen</label><br /> <span id="max"></span> </span> <span>Aantal: <input type="text" id="imagecount" size="2" disabled value="0"></span> <span> <label id="uploadedfiles" for="showgallery" class="right-align<?=(sizeof( $uploads)>0 ? ' hascontent' : '' );?>">Afbeeldingen</label> </span> <input type="checkbox" id="showgallery" hidden /> <div id="gallery" > <div id="new_pics"> </div> <div id="existing_pics"> <?$uploads = $opdracht->get_deelplan_uploads();?> <?if(sizeof( $uploads)>0):?> <p>Aanwezige foto's:</p> <?foreach($uploads as $upload):?> <a href="<?=site_url('/extern/opdracht_afbeelding/'. $opdracht->id."/".$upload->id."/false")?>" target="_blank"><img src="<?=site_url('/extern/opdracht_afbeelding/'. $opdracht->id."/".$upload->id."/true")?>" /></a> <?endforeach;?> <?endif;?> </div> </div> <? if ($opdracht->status != 'gereed'):?> <input id="save_opdracht" type="submit" value="Opslaan" hidden/> <?endif;?> </form> <span id="loader"><div id="inner-loader"></div></span> </div> <div id="footer" class="menubar"> <form method="post"> <input type="hidden" name="page" value="opdrachten"> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input type="hidden" name="bouwnummer_id" value="<?=$bouwnummer?>"> <input type="hidden" name="hoofdgroep_id" value="<?=$hoofdgroep?>"> <input id="terug" type="submit" value="terug" hidden /> <label id="back" for="terug">Terug</label> <? if ($opdracht->status != 'gereed'):?> <label id="save_label" for="save_opdracht" class="submit_loading">Opslaan</label> <?endif;?> </form> </div> <file_sep><div class="main"> <? $this->load->view( 'checklistwizard/_checklist_status', array( 'empty_lines' => 2 ) ) ?> <ul id="sortable" class="list"> <? foreach ($entries as $i => $entry): ?> <? $bottom = ($i==sizeof($entries)-1) ? 'bottom' : ''; ?> <li class="entry checklistgroep top left right <?=$bottom?>" entry_id="<?=$get_id($entry)?>"> <img style="margin-left: 3px; padding-top: 10px; vertical-align: bottom;" src="<?=($im=$get_image($entry)) ? $im->get_url() : site_url('/files/checklistwizard/checklistgroep-icoon.png')?>"> <div style="vertical-align: bottom; display: inline-block; *display: inline; *zoom: 1; max-width: 1000px; white-space: nowrap; overflow: hidden;"><?=htmlentities( $get_naam($entry), ENT_COMPAT, 'UTF-8' )?></div> <div style="margin-top: 3px; margin-left: 3px; float:right;" class="optiebutton sorteer"><i class="icon-move" style="font-size: 12pt"></i></div> </li> <? endforeach; ?> </ul> </div> <div class="button opslaan"> <a href="javascript:void(0);">Bewaar volgorde</a> </div> <script type="text/javascript"> $(document).ready(function(){ // make list sorted $('#sortable').sortable(); $('#sortable').disableSelection(); // handle opslaan button var showError = function() { showMessageBox({ message: 'Er is iets fout gegaan bij het opslaan van de volgorde.', type: 'warning', buttons: ['ok'] }); }; $('.button.opslaan').click(function(){ var data = {}; var i = 0; $('#sortable').children().each(function(){ data[$(this).attr('entry_id')] = i++; }); $.ajax({ url: '<?=site_url($store_url)?>', type: 'POST', data: { order: data }, dataType: 'html', success: function( data ) { if (data != 'OK') showError(); else location.href='<?=site_url($return_url)?>'; }, error: function() { showError(); } }); }); }); </script> <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $gebruiker_id = $this->gebruiker->get_logged_in_gebruiker()->id; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Instellingen', 'expanded' => true, 'width' => '1185px', 'height' => '300px' ) ); ?> <ul> <li><?=tga('log_info', '/instellingen/log')?></li> <li><?=tga('instellingen', '/instellingen/instellingen')?></li> <? if ($this->login->verify( 'checklistwizard', 'index' )): ?> <li><?=tga('wizard', '/checklistwizard')?></li> <? endif; ?> <? if($klant->heeft_toezichtmomenten_licentie == 'ja' && $this->rechten->geef_recht_modus( RECHT_TYPE_TOEZICHTMOMENTEN, $gebruiker_id ) != RECHT_MODUS_GEEN): ?> <li><?=tga('toezichtmomenten', '/toezichtmomenten/checklistgroepen')?></li> <? endif; ?> <? if ( intval($this->gebruiker->get_logged_in_gebruiker()->klant_id) == 1 ): ?> <li><?=tga('wetten_en_regelgeving', '/wettenregelgeving')?></li> <li><?=tga('themabeheer', '/instellingen/themabeheer')?></li> <li><?=tga('verantwoordingsteksten', '/instellingen/verantwoordingsteksten')?></li> <? endif; ?> <!--<? if ($this->login->verify( 'admin', 'index' )): ?> <li><?=tga('scope_sjablonen', '/instellingen/scopesjablonen')?></li> <? endif; ?> --> <? if (($lc = $klant->get_lease_configuratie()) && $lc->speciaal_veld_gebruiken): ?> <li><?=tga('speciaal_veld_instellingen', '/instellingen/speciaalveld')?></li> <? endif; ?> <? if ($klant->standaard_documenten){ ?> <li><?=tga('standard_documents', '/instellingen/standard_documents')?></li> <? }; ?> <? if ($klant->standaard_deelplannen){ ?> <li><?=tga('standaard_deelplannen', '/instellingen/standard_deelplannen')?></li> <? }; ?> <? if ($klant->heeft_toezichtmomenten_licentie == 'ja' && $this->rechten->geef_recht_modus( RECHT_TYPE_MAPPINGEN, $gebruiker_id ) != RECHT_MODUS_GEEN): ?> <li><?=tga('mappingen', '/mappingen/mappingenlist')?></li> <li><?=tga('risicoprofielen', '/risicoprofielen/drsmlist')?></li> <? endif; ?> <li><?=tga('richtlijn_multi_upload', '/instellingen/richtlijn_multi_upload')?></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Hulpmiddelen', 'expanded' => false, 'width' => '1185px', 'height' => '300px' ) ); ?> <ul> <li><?=tga('pdf.converter', '/instellingen/pdf_converter')?></li> </ul> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? require_once 'base.php'; class AppErrorReportResult extends BaseResult { function AppErrorReportResult( &$arr ) { parent::BaseResult( 'apperrorreport', $arr ); } } class AppErrorReport extends BaseModel { function AppErrorReport() { parent::BaseModel( 'AppErrorReportResult', 'app_error_reports' ); } public function check_access( BaseResult $object ) { return; } } <file_sep> <? if (!isset( $skip_regular_header ) || !$skip_regular_header): ?> </div> </div> </td> <td class="content-container-right"></td> </tr> <tr> <td class="content-container-bottomleft"></td> <td class="content-container-bottom"></td> <td class="content-container-bottomright"></td> </tr> </table> </div> <? endif; ?> </td></tr></table> <? if (!isset( $skip_regular_header ) || !$skip_regular_header): ?> <? if (config_item( 'development_version' ) === 'TEST'): ?> <div style="background-color: #555; color:yellow; font-weight:bold; font-size:150%; text-align: center;">- <?=tgg('versie.test')?> -</div> <? elseif (config_item( 'development_version' )): ?> <div style="background-color: #555; color:yellow; font-weight:bold; font-size:150%; text-align: center;">- <?=tgg('versie.development')?> -</div> <? endif; ?> <? if (IP_LIMIT_ENABLED): ?> <div style="background-color: #555; color:red; font-weight:bold; font-size:150%; text-align: center;">- <?=tgg('versie.ip_versie_actief')?> -</div> <? endif; ?> <? endif; ?> <script type="text/javascript"> $(document).ready(function(){ BRISToezicht.initialize(); }); </script> </body> </html> <file_sep>ALTER TABLE `deelplannen` ADD `aangemaakt_op` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; CREATE TEMPORARY TABLE foo SELECT MIN( a.last_updated_at ) AS d, a.deelplan_id FROM deelplan_vragen a WHERE a.status IS NOT NULL GROUP BY a.deelplan_id; UPDATE deelplannen SET aangemaakt_op = (SELECT d FROM foo WHERE deelplan_id = id);<file_sep>#Create new teksten for opdrachtenoverzicht REPLACE INTO `teksten` (`string` ,`tekst` ,`timestamp` ,`lease_configuratie_id`) VALUES ('deelplannen.opdrachtenoverzicht::opdrachttitle', 'Opdracht', NOW(), 0), ('deelplannen.opdrachtenoverzicht::opdrachttitle', 'Opdracht', NOW(), 1); <file_sep><?php class GenericExporter { function _export_generic( $data ) { unset( $data['id'] ); return $data; } function output( $data ) { $str = serialize( $data ); echo "# datum export: " . date('Y-m-d H:i:s') . "\n"; echo "# sha1: " . sha1( $str ) . "\n"; echo "# md5: " . md5( $str ) . "\n"; echo base64_encode( $str ); } } class ChecklistExporter extends GenericExporter { private $themas = array(); private $grondslagen = array(); private $richtlijnen = array(); function ChecklistExporter() { $CI = get_instance(); $CI->load->model( 'thema' ); $this->themas = array(); foreach ($CI->thema->get_for_huidige_klant() as $thema) $this->themas[ $thema->id ] = $thema; $CI->load->model( 'grondslag' ); $this->grondslagen = array(); foreach ($CI->grondslag->get_for_huidige_klant() as $grondslag) $this->grondslagen[ $grondslag->id ] = $grondslag; $CI->load->model( 'richtlijn' ); $this->richtlijnen = array(); foreach ($CI->richtlijn->get_for_huidige_klant() as $richtlijn) $this->richtlijnen[ $richtlijn->id ] = $richtlijn; } function _export_checklist( $data ) { $data = $this->_export_generic( $data ); unset( $data['gebruiksfunctie_id'] ); return $data; } function _export_hoofdgroep( $data ) { $data = $this->_export_generic( $data ); unset( $data['checklist_id'] ); return $data; } function _export_categorie( $data ) { $data = $this->_export_generic( $data ); unset( $data['afdeling_id'] ); return $data; } function _export_vraag( $data ) { $data = $this->_export_generic( $data ); if ($data['thema_id']) $data['thema'] = $this->themas[ $data['thema_id'] ]->thema; else $data['thema'] = NULL; unset( $data['thema_id'] ); unset( $data['artikel_id'] ); return $data; } function _export_grondslag( $data ) { $data = $this->_export_generic( $data ); if ($data['grondslag_id']) $data['grondslag'] = $this->grondslagen[ $data['grondslag_id'] ]->grondslag; else $data['grondslag'] = NULL; unset( $data['grondslag_id'] ); unset( $data['vraag_id'] ); return $data; } function _export_richtlijn( $data ) { $data = $this->_export_generic( $data ); if ($data['richtlijn_id']) $data['richtlijn'] = $this->richtlijnen[ $data['richtlijn_id'] ]->filename; else $data['richtlijn'] = NULL; unset( $data['richtlijn_id'] ); unset( $data['vraag_id'] ); return $data; } function export( ChecklistResult $checklist ) { // build data $data = array( 'type' => 'checklist', 'host' => gethostname(), 'date' => date('Y-m-d H:i:s'), 'checklist' => $this->_export_checklist( $checklist->get_array_copy() ), 'hoofdgroepen' => array(), ); foreach ($checklist->get_hoofdgroepen() as $hoofdgroep) { $valh = array( 'hoofdgroep' => $this->_export_hoofdgroep( $hoofdgroep->get_array_copy() ), 'categorieen' => array(), ); foreach ($hoofdgroep->get_categorieen() as $categorie) { $valc = array( 'categorie' => $this->_export_categorie( $categorie->get_array_copy() ), 'vragen' => array(), ); foreach ($categorie->get_vragen() as $vraag) { $valv = array( 'vraag' => $this->_export_vraag( $vraag->get_array_copy() ), 'grondslagen' => array(), 'richtlijnen' => array(), ); foreach ($vraag->get_grondslagen() as $grondslag) $valv['grondslagen'][] = $this->_export_grondslag( $grondslag->get_array_copy() ); foreach ($vraag->get_richtlijnen() as $richtlijn) $valv['richtlijnen'][] = $this->_export_richtlijn( $richtlijn->get_array_copy() ); $valc['vragen'][] = $valv; } $valh['categorieen'][] = $valc; } $data['hoofdgroepen'][] = $valh; } // export! $this->output( $data ); } } class ChecklistGroepExporter extends GenericExporter { function _export_checklistgroep( $data ) { $data = $this->_export_generic( $data ); unset( $data['gebruiksfunctie_id'] ); return $data; } function export( ChecklistGroepResult $checklistgroep ) { // build data $data = array( 'type' => 'checklistgroep', 'host' => gethostname(), 'date' => date('Y-m-d H:i:s'), 'checklistgroep' => $this->_export_checklistgroep( $checklistgroep->get_array_copy() ), 'checklisten' => array(), ); foreach ($checklistgroep->get_checklisten() as $checklist) $data['checklisten'][] = export_checklist_as_php( $checklist ); // export! $this->output( $data ); } } function export_checklist_as_php( ChecklistResult $checklist ) { ob_start(); $exp = new ChecklistExporter(); $exp->export( $checklist ); return ob_get_clean(); } function export_checklistgroep_as_php( ChecklistGroepResult $checklistgroep ) { ob_start(); $exp = new ChecklistGroepExporter(); $exp->export( $checklistgroep ); return ob_get_clean(); } <file_sep><? $this->load->view('elements/header', array('page_header'=>'admin.nieuws')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Nieuws items', 'width' => '920px' ) ); ?> <table width="850"> <tr> <th align="left">Datum</th> <th align="left">Titel</th> <th style='text-align:center'>Zichtbaar</th> <th align="left">Opties</th> </tr> <? foreach ($nieuws as $n): ?> <tr> <td><?=date('d-m-Y', $n->datum)?></td> <td><?=htmlentities($n->titel)?></td> <td style='text-align:center'><?=$n->is_zichtbaar()?'Ja':'Nee'?></td> <td> <a href="<?=site_url('/admin/nieuws/toggle/'.$n->id)?>"><?=$n->is_zichtbaar()?'Verwijderen':'Publiceren'?></a> </td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Nieuw nieuws item', 'width' => '920px' ) ); ?> <b>Let op</b> <ul> <li>Eenmaal ingevoerde teksten kunnen nog niet bewerkt worden via deze interface.</li> <li>Nieuwe items zijn standaard <b>nog niet</b> zichtbaar!</li> </ul> <form name="form" method="post" action="<?=site_url('/admin/nieuws/add/')?>"> <table style="width:auto"> <tr> <th id='form_header'>Titel</th> </tr> <tr> <td id='form_value'><input type='text' name='titel' value='<?=$titel?>' style="width:500px" maxlength='512' /></td> </tr> <tr> <th id='form_header'>Tekst</th> </tr> <tr> <td id='form_value'><textarea name='tekst' style="width:500px" rows='10' /><?=$tekst?></textarea></td> </tr> <tr> <td id='form_button'><input type='submit' value='<?=tgng('form.toevoegen')?>'></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.rapportage::uitvoer.formaat', 'Uitvoer formaat', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.pdf', 'PDF oude stijl', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::uitvoer.docx', 'DOCX nieuwe stijl (beta) - v0.0.2 - 15-5-2014', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::selectiemogelijkheden.toekomstig', 'Toekomstige selectiemogelijkheden', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::revisies.tonen', 'Revisies tonen', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::revisies.tonen.ja', 'Wel tonen', '2014-05-08 22:45:00', 0), ('dossiers.rapportage::revisies.tonen.nee', '<NAME>', '2014-05-08 22:45:00', 0) ; <file_sep>ALTER TABLE `bt_checklisten` ADD `naam_kort` VARCHAR( 20 ) NULL DEFAULT NULL ; <file_sep>ALTER TABLE `deelplan_opdrachten` ADD `tag` VARCHAR( 128 ) NOT NULL ; UPDATE deelplan_opdrachten SET tag = id; ALTER TABLE `deelplan_opdrachten` ADD UNIQUE (`tag`); <file_sep><? load_view( 'header.php' ); ?> <h2>Opslaan mislukt.</h2> <? load_view( 'footer.php' ); ?><file_sep><? require_once 'base.php'; class DossierBescheidenResult extends BaseResult { function DossierBescheidenResult( &$arr ) { parent::BaseResult( 'dossierbescheiden', $arr ); } function get_edit_fields() { return array( $this->_edit_textfield( 'Tekening/Stuk nummer', 'tekening_stuk_nummer', $this->tekening_stuk_nummer ), $this->_edit_textfield( 'Auteur', 'auteur', $this->auteur ), $this->_edit_textfield( 'Omschrijving', 'omschrijving', $this->omschrijving ), $this->_edit_textfield( 'Datum laatste wijziging', 'datum_laatste_wijziging', $this->datum_laatste_wijziging ), $this->_edit_uploadfield( 'Bestand', 'bestand', $this->bestandsnaam ), ); } function to_string() { return $this->tekening_stuk_nummer . ': '. $this->omschrijving; } function is_zichtbaar() { $res = strlen(trim($this->tekening_stuk_nummer)) || strlen(trim($this->omschrijving) || strlen($this->bestand)>0); if (!$res) $this->delete(); return $res; } public function get_dossier() { $CI = get_instance(); $CI->load->model( 'dossier' ); return $CI->dossier->get( $this->dossier_id ); } public function get_dossier_map() { $CI = get_instance(); $CI->load->model( 'dossierbescheidenmap' ); return $CI->dossierbescheidenmap->get( $this->dossier_bescheiden_map_id ); } // Small helper function that can be used to determine the path (only) of the binary file data public function get_file_path() { $folder = DIR_DOSSIER_BESCHEIDEN . '/' . $this->dossier_id; return $folder; } // Small helper function that can be used to determine the full location (i.e. path + filename) of the binary file data public function get_file_location() { $folder = $this->get_file_path(); $file_name = $folder.'/'.$this->id; return $file_name; } public function laad_inhoud() { if (isset( $this->bestand )) return; //$folder = BASEPATH.'../documents/'.$this->dossier_id; //$file_name = $folder.'/'.$this->id; $file_name = $this->get_file_location(); $fhandle = fopen( $file_name, 'a+' ); $file = fread($fhandle, filesize($file_name)); $this->bestand = $file; fclose($fhandle); // if (isset( $this->bestand )) // return; // $res = $this->_CI->db->query( 'SELECT bestand FROM dossier_bescheiden WHERE id = ' . intval( $this->id ) ); // if (!$res) // throw new Exception( 'Fout bij ophalen dossier bescheiden inhoud (1).' ); // if ($res->num_rows() != 1) // throw new Exception( 'Fout bij ophalen dossier bescheiden inhoud (2) (' . $res->num_rows . ').' ); // $rows = $res->result(); // $res->free_result(); // $this->bestand = reset( $rows )->bestand; // unset( $rows ); } public function geef_inhoud_vrij() { unset( $this->bestand ); } public function get_download_url() { // niet site_url overheen halen hier ivm app, mag buiten deze functie uiteraard wel return '/dossiers/bescheiden_downloaden/' . intval( $this->id ); } /* Returns bescheiden-to-image converted image data (raw PNG/JPG file) */ public function imageprocessor_get_original_contents() { $ip = get_instance()->imageprocessor; $ip->id( $this->id ); $ip->type( 'bescheiden' ); $ip->mode( 'original' ); $ip->slice( null ); return $ip->contents(); } /* Returns URL to view converted image of bescheiden */ public function imageprocessor_get_original_url() { // niet site_url overheen halen hier ivm app, mag buiten deze functie uiteraard wel return '/pdfview/bescheiden/' . $this->id . '/0'; } /* Returns URL to view converted PREVIEW image of bescheiden */ public function imageprocessor_get_thumbnail_url() { // niet site_url overheen halen hier ivm app, mag buiten deze functie uiteraard wel return '/pdfview/bescheiden/' . $this->id . '/1'; } /* Returns whether or not the converted image can be obtained in slices. */ public function imageprocessor_original_sliced() { return $this->imageprocessor_original_num_slices() > 0; } /* Returns number of available slices for converted image */ public function imageprocessor_original_num_slices() { $ip = get_instance()->imageprocessor; $ip->id( $this->id ); $ip->type( 'bescheiden' ); $ip->mode( 'original' ); return $ip->count_slices(); } public function imageprocessor_get_original_dimensions( $pagina = 1 ) { $ip = get_instance()->imageprocessor; $ip->id( $this->id ); $ip->type( 'bescheiden' ); $ip->mode( 'original' ); $ip->page_number( $pagina ); $filename = $ip->get_image_filename(); if (!is_file( $filename )) throw new Exception( 'Fout bij ophalen lokale PNG afbeelding van bescheiden: ' . $this->bestandsnaam ); $settings = @getimagesize( $filename ); return array( 'w' => $settings[0], 'h' => $settings[1], ); } /* Returns URL to view slice from converted image of bescheiden. * Slices are zero based. */ public function imageprocessor_get_original_slice_url( $url ) { return site_url( '/pdfview/bescheiden/' . $this->id . '/0/' . intval($url) ); } /** Returns map this bescheiden belongs to. */ public function get_dossier_bescheiden_map() { $map_id = $this->dossier_bescheiden_map_id; if (!$map_id) return null; if (!isset( $this->_CI->dossierbescheidenmap )) $this->_CI->load->model( 'dossierbescheidenmap' ); return $this->_CI->dossierbescheidenmap->get( $map_id ); } } class DossierBescheiden extends BaseModel { function DossierBescheiden() { parent::BaseModel( 'DossierBescheidenResult', 'dossier_bescheiden' ); // load imageprocessor if not yet loaded $CI = get_instance(); if (!isset( $CI->imageprocessor )) $CI->load->library( 'imageprocessor' ); } protected function _get_select_list() { // alles behalve bestand, zie DossierBescheidenResult::geef_inhoud_vrij functie return 'id, dossier_id, tekening_stuk_nummer, auteur, omschrijving, zaaknummer_registratie, versienummer, datum_laatste_wijziging, bestandsnaam, png_status, laatste_bestands_wijziging_op, dossier_bescheiden_map_id'; } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } public function get_by_png_status( $status ) { if (!$this->dbex->is_prepared( 'get_bescheiden_by_png_status' )) $this->dbex->prepare( 'get_bescheiden_by_png_status', 'SELECT * FROM dossier_bescheiden WHERE png_status = ?' ); $res = $this->dbex->execute( 'get_bescheiden_by_png_status', array( $status ) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $res->free_result(); return $result; } public function get_by_bescheiden($bescheiden_id){ $query = 'SELECT * FROM dossier_bescheiden where id=?'; if (!$this->dbex->is_prepared( 'get_by_bescheiden' )) { $this->dbex->prepare( 'get_by_bescheiden', $query ); } $res = $this->dbex->execute( 'get_by_bescheiden', array( $bescheiden_id ) ); $result = $res->result(); return $result; } public function get_by_dossier( $dossier_id, $assoc=false, $parent_map_id=null ) { $query = 'SELECT db.id, db.dossier_id, db.tekening_stuk_nummer, db.auteur, db.omschrijving, db.zaaknummer_registratie, db.versienummer, db.datum_laatste_wijziging, db.bestandsnaam, db.png_status, db.laatste_bestands_wijziging_op, db.has_pdfa_copy, db.dossier_bescheiden_map_id '. 'FROM dossier_bescheiden db '. 'WHERE db.dossier_id = ? '. 'AND ( ((? IS NULL) '. 'AND (db.dossier_bescheiden_map_id IS NULL)) OR ((? IS NOT NULL) '. 'AND (db.dossier_bescheiden_map_id = ?)) ) '. 'ORDER BY db.id'. ''; if (!$this->dbex->is_prepared( 'get_bescheiden_by_dossier' )) { $this->dbex->prepare( 'get_bescheiden_by_dossier', $query ); } $res = $this->dbex->execute( 'get_bescheiden_by_dossier', array( $dossier_id ,$parent_map_id ? $parent_map_id : null ,$parent_map_id ? $parent_map_id : null ,$parent_map_id ? $parent_map_id : null ) ); $result = array(); foreach ($res->result() as $row){ $row->is_standard = FALSE; $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } $res->free_result(); return $result; } public function add( $dossier_id ) { /* if (!$this->dbex->is_prepared( 'add_bescheiden' )) $this->dbex->prepare( 'add_bescheiden', 'INSERT INTO dossier_bescheiden (dossier_id) VALUES (?)' ); $args = array( 'dossier_id' => $dossier_id, ); $this->dbex->execute( 'add_bescheiden', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $data = array_merge( array( 'id' => $id ), $args ); return new $this->_model_class( $data ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'dossier_id' => $dossier_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } /** LET OP! De documenten die hier uitkomen hebben hun INHOUD niet in zich! * Roep de functie laad_inhoud op het resulterende (DossierBescheidenResult) object * om de data als nog te laden. Deze functie doet niks als de data al geladen is. */ public function get_by_herkomst( $herkomst ) { $stmt_name = 'dossierbescheiden::get_by_herkomst'; $this->dbex->prepare( $stmt_name, ' SELECT db.id, db.dossier_id, db.tekening_stuk_nummer, db.auteur, db.omschrijving, db.zaaknummer_registratie, db.versienummer, db.datum_laatste_wijziging, db.bestandsnaam, db.png_status, db.laatste_bestands_wijziging_op, db.dossier_bescheiden_map_id FROM dossier_bescheiden db JOIN dossiers d ON db.dossier_id = d.id WHERE d.herkomst = ? AND d.gearchiveerd = 0 AND d.verwijderd = 0 '); $res = $this->dbex->execute( $stmt_name, array( $herkomst ) ); if (!$res) throw new Exception( 'Fout bij ophalen bescheiden uit database.' ); return $this->convert_results( $res ); } // Small helper function that can be used to determine the path (only) of the binary file data public function get_file_path($object) { $folder = DIR_DOSSIER_BESCHEIDEN . '/' .$object->dossier_id; return $folder; } // Small helper function that can be used to determine the full location (i.e. path + filename) of the binary file data public function get_file_location($object) { $folder = $this->get_file_path($object); $file_name = $folder.'/'.$object->id; return $file_name; } // Converts a file to PDF/A-1a format, if necessary (or if forced to do so). // Note: the $generate_graphical_version parameter is used to first convert the source PDF file to PNG files (one per page), these are then converted to 1-page PDF files, and // those in turn are combined into a single stitched PDF, that shall be used as source for the conversion to PDF/A-1a. Note that this is a much heavier process than just using // the source PDF file. This is done hoping that a 100% graphical PDF file will behave more predictable in the iPad. public function convert_pdf_to_optimised_pdfa($object, $generate_graphical_version = true, $force = false, $silent = true) { //return true; $conversion_successful = false; // For now we are only likely to run this method in non-silent mode from the cli controller so do no fancy logic to try to detect // if we're being called from a browser or the command line and simply set the line breaks to those for the command line. $eol = "\n"; //$eol = "<br />"; // Allow each conversion to run for maximally 10 minutes. set_time_limit(600); $CI = get_instance(); // First check (by filename) if the file is a PDF. If it isn't, there is no need to convert it. $path_parts = pathinfo($object->bestandsnaam); // Only proceed in case the input file is a PDF file if (strtolower($path_parts['extension']) == 'pdf') { // Now, perform several tests (if necessary) to check if the file was already converted or whether we still need to do so. $source_file_name = $this->get_file_location($object); $source_file_path = $this->get_file_path($object); // First check if the PDF was already converted once. We can tell by checking for the presence of a file with the very same name and location as that // of the source file, but with a '_original' suffix. $source_file_name_unconverted = $source_file_name . '_original'; $source_file_name_converted = $source_file_name . '.pdf'; $source_file_name_graphical = $source_file_name . '_graphical.pdf'; // Now determine whether to proceed with the conversion or not. // For now, simply check the 'force' option and/or if an unconverted file exists or not. Further checks (e.g. on the filesize) are possible too. $perform_conversion = ($force || !file_exists($source_file_name_unconverted)); // Only perform the conversion if we need to do so. if ($perform_conversion) { // We need to perform the conversion! Do so in a -hopefully- error proof way. if (!$silent) { echo "Unconverted PDF found (or forcing conversion). Converting....{$eol}"; } // First try to create a back-up copy of the original file. If that succeeds we proceed to convert the original. if (copy($source_file_name, $source_file_name_unconverted)) { if (!$silent) { echo "Back-up copy {$source_file_name_unconverted} created successfully. Starting conversion...{$eol}"; } // If we need to generate a graphical PDF file, first slice the source PDF, then convert to 1-page PDF files, then unite them and use the resulting PDF file for // the conversion to PDF/A-1a format. if ($generate_graphical_version) { if (!$silent) { echo "Generating 100% graphical version.{$eol}"; } if (file_exists($source_file_name_graphical)) { if (!$silent) { echo "Removing previously generated graphical source file '{$source_file_name_graphical}'.{$eol}"; } unlink($source_file_name_graphical); } // Create a temporary directory $temp_dir_name = $source_file_path . DIRECTORY_SEPARATOR . $object->id . '_png_pages'; $temp_pdf_name = $temp_dir_name . DIRECTORY_SEPARATOR . $object->id . '_before_slicing.pdf'; if (!$silent) { echo "Trying to create temporary directory: {$temp_dir_name}.{$eol}"; } // If we fail to create the directory, we fall back to the input file, otherwise, we continue if (mkdir($temp_dir_name)) { if (!$silent) { echo "Temporary directory was successfully created.{$eol}"; } // Copy the source PDF file to the temporary directory if (copy($source_file_name, $temp_pdf_name)) { if (!$silent) { echo "Temporary PDF source file was successfully created.{$eol}"; } // First change to the new directory. Afterwards we return the user to the location the script was called from. $original_caller_directory = getcwd(); if (chdir($temp_dir_name)) { if (!$silent) { echo "Temporary directory was successfully entered.{$eol}"; } // Get the proper locations of the binaries that perform the actual conversions. // Note: these must be specified in the application/config/config.php file! $pdftoppm_executable = $CI->config->item('pdftoppm_executable'); $pdfunite_executable = $CI->config->item('pdfunite_executable'); $mogrify_executable = $CI->config->item('mogrify_executable'); // Slice the source PDF file into 1-page PNG files if (!$silent) { echo "Trying to slice the source PDF file into PNG slices...{$eol}"; } $pdftoppm_cmd = "{$pdftoppm_executable} -png {$temp_pdf_name} png_slice"; //echo $pdftoppm_cmd . $eol; $exec_return_value = shell_exec($pdftoppm_cmd); // Remove the temporary PDF file unlink($temp_pdf_name); // Now we make sure that at least one PNG file was created. If this is not the case, pdftoppm probably exited with an // error in which case we want to fall back to using the original source file for the conversion $generated_png_files = array(); if ($handle = opendir($temp_dir_name)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { //echo "$entry\n"; if (substr(strtolower($entry),-4) == '.png') { $generated_png_files[] = $entry; } } } closedir($handle); } // If we have encountered PNG files, we continue, if not, we fall back to using the original input file. if (!empty($generated_png_files)) { if (!$silent) { echo "Successfully generated " . sizeof($generated_png_files) . " PNG slice(s).{$eol}"; } // Convert the 1-page PNG files to 1-page PDF files if (!$silent) { echo "Trying to create single page PDF files of PNG slices...{$eol}"; } $mogrify_cmd = "{$mogrify_executable} -format pdf -- *.png"; //echo $mogrify_cmd . $eol; $exec_return_value = shell_exec($mogrify_cmd); // Now we make sure that at least one PDF file was created. If this is not the case, mogrify probably exited with an // error in which case we want to fall back to using the original source file for the conversion $generated_pdf_files = array(); if ($handle = opendir($temp_dir_name)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { //echo "$entry\n"; if (substr(strtolower($entry),-4) == '.pdf') { $generated_pdf_files[] = $entry; } } } closedir($handle); } // If we have encountered PDF files, we continue, if not, we fall back to using the original input file. if (!empty($generated_pdf_files)) { $amount_of_pdf_files = sizeof($generated_pdf_files); if (!$silent) { echo "Successfully generated " . $amount_of_pdf_files . " single page PDF file(s).{$eol}"; } // Now either unite the PDF files (in case more than 1 were generated) or directly copy the generated PDF file. if ($amount_of_pdf_files == 1) { // If we have exactly 1 PDF file, we do not have to unite anything and we just directly copy it to the location from where it will be used // as the source file for the PDF/A-1a conversion. if (!$silent) { echo "Trying to copy single page PDF file to the destination location...{$eol}"; } // Copy the generated PDF file to the target location from where it will serve as the source for the PDF/A-1a conversion. if (copy($generated_pdf_files[0], $source_file_name_graphical)) { if (!$silent) { echo "Successfully copied '" . $generated_pdf_files[0] . "' to '" . $source_file_name_graphical . "'. Ready for PDF/A-1a conversion.{$eol}"; } } // if (copy($generated_pdf_files[0], $source_file_name_graphical)) else { if (!$silent) { echo "Failed to copy '" . $generated_pdf_files[0] . "' to '" . $source_file_name_graphical . "'. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (copy($generated_pdf_files[0], $source_file_name_graphical)) } // if ($amount_of_pdf_files == 1) else { // Unite the 1-page PDF files into a single PDF file if (!$silent) { echo "Trying to unite single page PDF files into one large PDF file...{$eol}"; } $stitched_pdf_file_name = $object->id . '_graphical.pdf'; $pdfunite_cmd = "{$pdfunite_executable} *.pdf {$stitched_pdf_file_name}"; //echo $pdfunite_cmd . $eol; $exec_return_value = shell_exec($pdfunite_cmd); // Check if the stitched file was generated successfully. If so, copy it, if not, fall back to using the original file. if (file_exists($stitched_pdf_file_name)) { if (!$silent) { echo "Successfully united the single page PDF files to the file '" . $stitched_pdf_file_name . "'.{$eol}"; } // Copy the stitched PDF file to the target location from where it will serve as the source for the PDF/A-1a conversion. if (copy($stitched_pdf_file_name, $source_file_name_graphical)) { if (!$silent) { echo "Successfully copied '" . $stitched_pdf_file_name . "' to '" . $source_file_name_graphical . "'. Ready for PDF/A-1a conversion.{$eol}"; } } // if (copy($stitched_pdf_file_name, $source_file_name_graphical)) else { if (!$silent) { echo "Failed to copy '" . $stitched_pdf_file_name . "' to '" . $source_file_name_graphical . "'. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (copy($stitched_pdf_file_name, $source_file_name_graphical)) } // if (copy($generated_pdf_files[0], $source_file_name_graphical)) else { if (!$silent) { echo "Failed to unite the single page PDF files to the file '" . $stitched_pdf_file_name . "'. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } } // else of clause: if ($amount_of_pdf_files == 1) } // if (!empty($generated_pdf_files)) else { if (!$silent) { echo "Failed to create single page PDF file(s). Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (!empty($generated_pdf_files)) } // if (!empty($generated_png_files)) else { if (!$silent) { echo "Failed to create PNG slice(s). Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (!empty($generated_png_files)) } // if (chdir($temp_dir_name)) else { if (!$silent) { echo "Failed to enter the temporary directory. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (chdir($temp_dir_name)) // When we have reached this location, we return to the directory the script was called from. chdir($original_caller_directory); } // if (copy($source_file_name, $temp_pdf_name)) else { if (!$silent) { echo "Temporary PDF source file could not be created. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (copy($source_file_name, $temp_pdf_name)) // Remove the temporary directory. Check if the directory is not empty or '/' by any chance. if (!empty($temp_dir_name) && ($temp_dir_name != '/')) { $rmdir_cmd = "rm -rf {$temp_dir_name}"; //echo $rmdir_cmd . $eol; $exec_return_value = shell_exec($rmdir_cmd); } } // if (mkdir($temp_dir_name)) else { if (!$silent) { echo "Temporary directory could not be created. Falling back to using the original source file.{$eol}"; } // Set the $generate_graphical_version boolean to false, so the rest of the code will use the original source file. $generate_graphical_version = false; } // else of clause: if (mkdir($temp_dir_name)) } // if ($generate_graphical_version) // Get the proper location of the binary that performs the conversion. Note: this must be specified in the application/config/config.php file! $libre_office_executable = $CI->config->item('libre_office_executable'); // Work out which source file to use; this is either the original one, or the graphical version. Note that the boolean $generate_graphical_version // at this point will only be true if it successfully performed ALL steps of generating the graphical PDF version of the source file! if ($generate_graphical_version) { $use_source_file_name = $source_file_name_graphical; $source_file_name_converted = $source_file_name_graphical; // !!! temporarily store a back-up copy of the unconverted graphical input file, for comparison purposes. copy($source_file_name_graphical, $source_file_name_graphical.'_bck'); if (!$silent) { echo "Using graphical PDF version of source file. Source filename: '{$use_source_file_name}'.{$eol}"; } } else { $use_source_file_name = $source_file_name; if (!$silent) { echo "Using original PDF version of source file. Source filename: '{$use_source_file_name}'.{$eol}"; } } // Now work out the conversion command. // NOTE: On Ubuntu Linux the 'timeout' command seems to be available by default. On OS-X it is necessary to install e.g. the 'timeout' port for it! // We should add a configuration for working with time outs. For now, we simply set this here by means of a locally defined value. Set it to 0 to never time out. // As an alternative, we could pass it as a parameter to the call of this method. $time_out_value = 180; //$cmd = "{$libre_office_executable} --headless --convert-to pdf {$use_source_file_name} --outdir {$source_file_name_converted}"; if (empty($time_out_value)) { $cmd = "{$libre_office_executable} --headless --convert-to pdf {$use_source_file_name} --outdir {$source_file_path}"; } else { $cmd = "timeout {$time_out_value} {$libre_office_executable} --headless --convert-to pdf {$use_source_file_name} --outdir {$source_file_path}"; } // Perform the conversion $exec_return_value = shell_exec($cmd); // If the conversion was performed successfully, we should now have a file with the name specified in $source_file_name_converted that does // not have zero length. If so, remove the original file (i.e. not the back-up copy!) and rename the converted file. if (file_exists($source_file_name_converted) && (filesize($source_file_name_converted) > 0)) { // Get the size of the converted file and that of the unconverted file $unconverted_file_size = filesize($source_file_name); $unconverted_file_size_kb_str = sprintf("%0.2f", ($unconverted_file_size/1024)); $unconverted_file_size_mb_str = sprintf("%0.2f", ($unconverted_file_size/1048576)); $converted_file_size = filesize($source_file_name_converted); $converted_file_size_kb_str = sprintf("%0.2f", ($converted_file_size/1024)); $converted_file_size_mb_str = sprintf("%0.2f", ($converted_file_size/1048576)); if (!$silent) { echo "File was successfully converted. Activating converted file...{$eol}"; } // First remove the original file - should not be necessary, as the rename call should overwrite it. //unlink($source_file_name); // Then rename the converted file if (rename($source_file_name_converted, $source_file_name)) { if (!$silent) { echo "File was successfully activated. Done.{$eol}"; } // Only if everything went without errors do we deem the conversion to have been successful. $conversion_successful = true; } else { if (!$silent) { echo "File could not be activated. Done (with errors).{$eol}"; } } if (!$silent) { echo "Original file size: {$unconverted_file_size} bytes ({$unconverted_file_size_kb_str}KB - {$unconverted_file_size_mb_str}MB). " . "Converted file size: {$converted_file_size} bytes ({$converted_file_size_kb_str}KB - {$converted_file_size_mb_str}MB).{$eol}"; } } // if (file_exists($source_file_name_converted) && (filesize($source_file_name_converted) > 0)) } // if (copy($source_file_name, $source_file_name_unconverted)) else { if (!$silent) { echo "Back-up copy {$source_file_name_unconverted} could not be created. Aborting...{$eol}"; } } } else { // We do not need to perform any conversion. Notify the user in case we are not run in silent mode. if (!$silent) { echo "No conversion required. Skipping....{$eol}"; // Return 'true' in this case, as the cli controller can then flag that this file already was converted once, so it // can be flagged for being excluded in subsequent runs. $conversion_successful = true; } } echo $eol.$eol; } // if (strtolower($path_parts['extension']) == 'pdf') return $conversion_successful; } //_______________________ public function save( $object, $do_transaction=true, $alias=null, $error_on_no_changes=true ) { // Make sure to unset the binary data from the model before calling the parent 'save' method as the 'bestand' column no longer exists in the DB! $bestand = (!empty($object->bestand) && !is_null($object->bestand)) ? $object->bestand : null; unset($object->bestand); // Store the DB record first $res = parent::save( $object, $do_transaction, $alias, $error_on_no_changes ); if( !$res ) { throw new Exception( 'Failed to save in DB. Inner Error.' ); } // If the DB record was successfully created, proceed to save the binary data to the file system. // Note: in case no 'bestand' was determined, we skip the attempt to save the record to the filesystem. This way we can still perform normal model calls to the // save method, without risking accidentally overwriting the file! if (!is_null($bestand)) { //$folder = BASEPATH.'../documents/'.$object->dossier_id; $folder = $this->get_file_path($object); CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file($folder, $object->id, $bestand); } // Once the file itself is created, we convert it to PDF/A-1a format, if necessary. // At this point do not use the 'force' option. That option is destined for specific pieces of code that intentionally (re-)generate the PDF/A-1a files! //$this->convert_pdf_to_optimised_pdfa($object, false); // Now return either the conrted result or the unconverted one. //return (is_null($convertedRes)) ? $res : $convertedRes; return $res; } //_______________________ public function delete( $object ){ $file_name = $this->get_file_location($object); $res = parent::delete( $object ); if( !$res ) throw new Exception( 'Failed to delete in DB. Inner Error.' ); unlink( $file_name ); } //_______________________ public function get_bescheiden_id_by_file_name($file_name, $assoc=false ){ $docs = $this->db->where('bestandsnaam', $file_name ) ->get( $this->_table ) ->result(); $result = array(); foreach( $docs as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } } <file_sep><?php require_once('KMXMagmaClient.php'); $quest = new KMXMagmaClient(); $quest->magmaUrl = 'http://brismagma.intramax.eu/'; $quest->magmaName = 'BRIStoezicht'; $quest->magmaSecret = '<KEY>'; $quest->magmaCalculationType = 'md5'; $quest->cachePath = dirname(__FILE__) . '/token-quest.cache'; <file_sep><form method="POST" enctype="multipart/form-data"> <table width="100%"> <tr> <td style="vertical-align:top"> <div style="overflow:auto;height:470px;width:450px;border:0;margin:0;padding:0;"> <? if ($document): ?> <a target="_blank" href="<?=site_url('/instellingen/document_downloaden/' . $document->id)?>"> <div class="NoSelect"> <? if ($num_slices): ?> <? for ($i=0; $i<$num_slices; ++$i): ?> <img style="display: block; width:100%; padding: 0; margin: 0; border: 0;" src="<?=site_url('/pdfview/bescheiden/' . $document->id . '/0/' . $i )?>" /> <? endfor; ?> <? else: ?> <img width="100%" src="<?=site_url('/pdfview/bescheiden/' . $document->id )?>" /> <? endif; ?> </div> </a> <? else: ?> <center><i><?=tg('nog_geen_voorbeeld_beschikbaar')?></i></center> <? endif; ?> </div> </td> <td style="vertical-align:top"> <table width="100%"> <tr> <td style="vertical-align:top"><b><?=tg('omschrijving')?>:</b></td> <td style="vertical-align:top"><textarea name="omschrijving" style="width:240px;height:100px" <?=$document?'disabled':''?> ><?=htmlentities( $document ? $document->omschrijving : '', ENT_COMPAT, 'UTF-8' )?></textarea></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('zaaknummer_registratie')?>:</b></td> <td style="vertical-align:top"><input type="text" name="zaaknummer_registratie" size="35" maxlength="256" value="<?=htmlentities( $document ? $document->zaaknummer_registratie : '', ENT_COMPAT, 'UTF-8' )?>" <?=$document?'disabled':''?> ></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('tekeningnummer')?>:</b></td> <td style="vertical-align:top"><input type="text" name="tekening_stuk_nummer" size="35" maxlength="256" value="<?=htmlentities( $document ? $document->tekening_stuk_nummer : '', ENT_COMPAT, 'UTF-8' )?>" <?=$document?'disabled':''?> ></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('versienummer')?>:</b></td> <td style="vertical-align:top"><input type="text" name="versienummer" size="10" maxlength="32" value="<?=htmlentities( $document ? $document->versienummer : '', ENT_COMPAT, 'UTF-8' )?>" <?=$document?'disabled':''?> ></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('datum_laatste_wijziging')?>:</b></td> <td style="vertical-align:top"><input type="text" name="datum_laatste_wijziging" size="16" maxlength="64" value="<?=htmlentities( $document ? $document->datum_laatste_wijziging : '', ENT_COMPAT, 'UTF-8' )?>" <?=$document?'disabled':''?> ></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('auteur')?>:</b></td> <td style="vertical-align:top"><input type="text" name="auteur" size="35" maxlength="256" value="<?=htmlentities( $document ? $document->auteur : '', ENT_COMPAT, 'UTF-8' )?>" <?=$document?'disabled':''?> ></td> </tr> <tr> <td style="vertical-align:top"><b><?=tg('bestand(en)')?>:</b></td> <td style="vertical-align:top"><input type="file" name="document[]" multiple="true" <?=$document?'disabled':''?> ></td> </tr> <table> <table width="100%" class="buttonbar"> <tr> <td style="text-align: center" width="33%" align="center"> <? if ($document): ?> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.verwijderen'), 'blank' => false, 'url' => 'javascript:verwijderDocument();', 'class' => 'redbutton' ) ); ?> <? endif; ?> </td> <td style="text-align: center" width="33%"> <? if ($document): ?> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.wijzigen'), 'blank' => false, 'url' => 'javascript:editBescheiden();', 'class' => 'graybutton' ) ); ?> <? endif; ?> </td> <td style="text-align: center" width="33%"> <? if ($document): ?> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.opslaan'), 'blank' => false, 'url' => 'javascript:opslaanDocument();', 'class' => 'greenbutton' ) ); ?> <? else: ?> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.toevoegen'), 'blank' => false, 'url' => 'javascript:opslaanDocument();', 'class' => 'greenbutton' ) ); ?> <? endif; ?> </td> </tr> <tr> <td style="text-align: center" width="33%" align="center"> <? if ($document): ?> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'centered' => true, 'width' => '120px', 'text' => tgng('form.verwijder_alles'), 'blank' => false, 'url' => 'javascript:verwijderAllesDocument();', 'class' => 'redbutton' ) ); ?> <? endif; ?> </td> </tr> </table> <div class="pleasewaitbar hidden" style="text-align:center"> <img src="<?=site_url('/files/images/ajax-loader.gif')?>" /><br/> <i><?=tg('even_geduld_aub_uw_upload_kan_even_duren')?></i> </div> </td> </tr> </table> </form> <script type="text/javascript"> $('input[name=datum_laatste_wijziging]').datepicker({ dateFormat: "dd-mm-yy" }); </script><file_sep>PDFAnnotator.Editable.Image = PDFAnnotator.Editable.extend({ init: function( config ) { this._super( PDFAnnotator.Tool.prototype.getByName( 'image' ) ); this.setData( config, { position: new PDFAnnotator.Math.IntVector2( 0, 0 ), keepaspect: true }, ['dimensions', 'src', 'size'] ); this.conditionallyKeepAspect(); }, render: function() { var thiz = this; var base = $('<div>') .css( 'width', Math.round( this.data.size.x ) + 'px' ) .css( 'height', Math.round( this.data.size.y ) + 'px' ) .css( 'position', 'absolute' ) .css( 'left', this.data.position.x ) .css( 'top', this.data.position.y ) .css( 'padding', '0' ) .css( 'margin', '0' ) .click(function(e){ thiz.dispatchEvent( 'click', {event:e} ); }); var img = $('<img>') .css( 'width', '100%' ) .css( 'height', '100%' ) .attr( 'src', this.data.src ) .appendTo( base ); this.addVisual( base ); }, /* !!override!! */ resizeRelative: function( relx, rely ) { var curSize = new PDFAnnotator.Math.IntVector2( parseInt( this.visuals.css('width') ), parseInt( this.visuals.css('height') ) ); this.data.size.x = curSize.x + relx; this.data.size.y = curSize.y + rely; this.conditionallyKeepAspect(); var thiz = this; this.visuals.each(function(){ $(this).css({ width: thiz.data.size.x, height: thiz.data.size.y }); }); return { relx: this.data.size.x - curSize.x, rely: this.data.size.y - curSize.y }; }, conditionallyKeepAspect: function() { if (!this.data.keepaspect) return; // the original dimensions must be >0, no exceptions if (this.data.dimensions.x <= 0 || this.data.dimensions.y <= 0) throw 'PDFAnnotator.Editable.Image.conditionallyKeepAspect: specified dimensions invalid: ' + this.data.dimensions.x + 'x' + this.data.dimensions.y; // make sure the required size is valid if (this.data.size.x <= 0) this.data.size.x = 1; if (this.data.size.y <= 0) this.data.size.y = 1; // get aspect ratios, if they're equal then we're good, otherwise correct var daspect = this.data.dimensions.x / this.data.dimensions.y; var saspect = this.data.size.x / this.data.size.y; if (daspect == saspect) return; if (daspect < saspect) this.data.size.x = Math.round( this.data.size.y * daspect ); else this.data.size.y = Math.round( this.data.size.x / daspect ); }, /* moves the visual objects to a relative position, i.e. move a number of pixels up/down/left/right */ moveRelative: function( relx, rely ) { this._super( relx, rely ); this.data.position.x += relx; this.data.position.y += rely; }, /* !!overide!! */ rawExport: function() { var d = this.visuals; return { type: 'image', x: this.data.position.x, y: this.data.position.y, w: parseInt( d.css( 'width' ) ), h: parseInt( d.css( 'height' ) ), src: this.data.src, origw: this.data.dimensions.x, origh: this.data.dimensions.y, keepaspect: this.data.keepaspect ? 1 : 0 }; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Image({ position: new PDFAnnotator.Math.IntVector2( data.x, data.y ), keepaspect: data.keepaspect ? true : false, dimensions: new PDFAnnotator.Math.IntVector2( data.origw, data.origh ), src: data.src, size: new PDFAnnotator.Math.IntVector2( data.w, data.h ) }); } }); <file_sep><?php // WebService States define( 'WSS_CREATED', 'CREATED' ); // SSS = SoapServer state define( 'WSS_INITIALIZED', 'INITIALIZED' ); define( 'WSS_FINALIZED', 'FINALIZED' ); /** Abstract, base webservice class. Can register types and methods. */ abstract class AbstractWebservice { private $_methods = array(); private $_callbacks = array(); private $_types = array(); private $_state = WSS_CREATED; protected function __construct() { } public function get_methods() { return $this->_methods; } public function get_types() { return $this->_types; } public function call( $method, $args ) { // validate input if (!is_array( $args )) $args = array(); // call function and store result $returnvalue = call_user_func_array( $this->_callbacks[ $method ], $args ); // verify type of return value if (isset( $this->_methods[ $method ][ 'out' ] )) $this->verify_value_type( $returnvalue, $this->_methods[ $method ][ 'out' ][ 'result' ] ); else $this->verify_value_type( $returnvalue, null ); // done! return $returnvalue; } protected function _initialize() { // check we're in correct state $this->_check_state( WSS_CREATED, WSS_INITIALIZED ); // register basic types $this->_register_basic_type( 'string' ); $this->_register_basic_type( 'int' ); $this->_register_basic_type( 'float' ); $this->_register_basic_type( 'boolean' ); $this->_register_basic_type( 'base64Binary' ); } protected function _finalize() { // check we're in correct state $this->_check_state( WSS_INITIALIZED, WSS_FINALIZED ); } /** Registers a compound type. Compound types are what structs are in C. * So the definition of a compound type is an array, where the keys are the member names * and the the values are the types of the members. Note that recursive definition is NOT * allowed or possible, i.e. you cannot specify an array as a value in the array! Use multiple * calls in that case. * * Note: all specified type names must be known beforehand. So register any types your struct * uses before registering the struct type itself! */ protected function _register_compound_type( $name, array $definition ) { // check we're in correct state $this->_check_state( WSS_INITIALIZED ); // check input $name = strval( $name ); if (!$name) throw new Exception( 'CI_SoapServer::_register_compound_type: empty name not allowed' ); if (empty( $definition )) throw new Exception( 'CI_SoapServer::_register_compound_type: empty type definition not allowed' ); // check if all used types are known $this->_check_type_array( $definition ); foreach ($definition as $field_name => &$field_type) $field_type = $field_type; // store! $this->_register_type( $name, $definition ); } /** Registers a basic type. Should only be used for basic POD data types supported by SOAP. * * Note: by default, the following basic data types are always registered by this library: * int, string, boolean, base64Binary */ protected function _register_basic_type( $name ) { // check we're in correct state $this->_check_state( WSS_INITIALIZED ); // check input $name = strval( $name ); if (!$name) throw new Exception( 'CI_SoapServer::_register_basic_type: empty name not allowed' ); // store! $this->_register_type( $name, true ); } /** Registers an array type, indicating the the specified name should be an array of values of the * the specified type. Can be used to make string array types, struct array types, etc. * Value type must be name, if you require an array of structs, register the struct type first and * then use its name in this function as the $value_type. */ protected function _register_array_type( $name, $value_type ) { // check we're in correct state $this->_check_state( WSS_INITIALIZED ); // check input $name = strval( $name ); if (!$name) throw new Exception( 'CI_SoapServer::_register_array_type: empty name not allowed' ); if (!is_string( $value_type )) throw new Exception( 'CI_SoapServer::_register_array_type: value type must be string' ); if (!$this->_is_known_type( $value_type )) throw new Exception( 'CI_SoapServer::_register_array_type: unknown value type "' . $value_type . '"' ); // store! $this->_register_type( $name, strval( $value_type ) ); } /** Registers method for SOAP service. All specified types must be pre-registered! * The result type must be a valid registered type, or "void". The parameter types * must be specified like compound types: the keys are the parameter names, the * values are types. */ protected function _register_method( $result_type, $name, array $parameter_types=array(), $callback=null ) { // check we're in correct state $this->_check_state( WSS_INITIALIZED ); // check input if (!is_null( $callback ) && !is_callable( $callback )) throw new Exception( 'CI_SoapServer::_register_method: callback is not callable!' ); if (!$this->_is_known_type( $result_type, true )) throw new Exception( 'CI_SoapServer::_register_method: result type "' . $result_type .'" is unknown' ); if ($this->_is_known_method( $name )) throw new Exception( 'CI_SoapServer::_register_method: method "' . $name .'" already registered' ); $this->_check_type_array( $parameter_types ); // create data $data = array( 'in' => array() ); if ($result_type != 'void') $data['out'] = array( 'result' => $result_type ); foreach ($parameter_types as $field_name => $field_type) $data['in'][ $field_name ] = $field_type; // store! $this->_methods[ $name ] = $data; $this->_callbacks[ $name ] = $callback ? $callback : array( $this, $name ); } /** Checks if the specified type name is known. Returns true when registered, false if unknown. */ private function _is_known_type( $name, $allow_void=false ) { if ($allow_void && $name=='void') return true; return isset( $this->_types[ $name ] ); } /** Checks if the specified method name is known. */ private function _is_known_method( $name ) { return isset( $this->_methods[ $name ] ); } /** Internal registry function. Does not check much other than if type is known, because it's internal * and the functions that call us should take care of checking. */ private function _register_type( $name, $definition ) { // check we're in correct state $this->_check_state( WSS_INITIALIZED ); // check if not already known if ($this->_is_known_type( $name, true )) throw new Exception( 'CI_SoapServer::_register_type: type with name "' . $name . '" already registered!' ); $this->_types[ $name ] = $definition; } /** Checks an array with type values. */ private function _check_type_array( array $types ) { foreach ($types as $field_name => $field_type) if (!is_string( $field_type )) throw new Exception( 'CI_SoapServer::_check_type_array: field type must be string type' ); else if (!$this->_is_known_type( $field_type )) throw new Exception( 'CI_SoapServer::_check_type_array: unknown type "' . $field_type . '" specified' ); else if (!is_string( $field_name )) throw new Exception( 'CI_SoapServer::_check_type_array: field name must be string type' ); } /** Checks if specified state is current state, throws exception if states don't match. * Optionally sets new state. */ private function _check_state( $state, $new_state=null ) { if ($this->_state != $state) throw new Exception( 'CI_SoapServer::_check_state: not in required state: required=' . $state . ', current=' . $this->_state ); if (!is_null( $new_state )) $this->_state = $new_state; } /** Dump development tool. */ public function devel_dump() { echo '<h1>State</h1><pre>' . $this->_state . '</pre>'; echo '<h1>Types</h1><pre>' . var_export( $this->_types, true ) . '</pre>'; echo '<h1>Methods</h1><pre>' . var_export( $this->_methods, true ) . '</pre>'; } /** Makes sure the specified value is of the specified type, exactly matching the type description. * Given value is altered in place (by reference). Throws exception when value cannot be converted (if necessary) * to right data type. * * NOTE: may be slowish on large input. */ public function verify_value_type( &$value, $type ) { if (is_null( $type ) && !is_null( $value )) throw new Exception( 'AbstractWebservice::verify_value_type: expected null value' ); if ($type=='void') { if (!is_null( $value )) throw new Exception( 'AbstractWebservice::verify_value_type: expected void value (null), but got value of type "' . gettype($value) . '"' ); } else { if (!isset( $this->_types[ $type ] )) throw new Exception( 'AbstractWebservice::verify_value_type: specified type "' . $type . '" is not a known type' ); if (is_bool( $this->_types[ $type ] )) { if (is_object( $value ) || is_array( $value )) throw new Exception( 'AbstractWebservice::verify_value_type: specified value is of type "' . gettype($value) . '", but regular POD type expected' ); switch ($type) { case 'string': case 'base64Binary': $value = strval( $value ); break; case 'int': $value = intval( $value ); break; case 'float': $value = floatval( $value ); break; case 'boolean': $value = $value ? true : false; break; default: throw new Exception( 'AbstractWebservice::verify_value_type: unknown basic type encountered: "' . $type . '"' ); } } else if (is_string( $this->_types[ $type ] )) { // check that input is an indexed array if (!is_array( $value )) throw new Exception( 'AbstractWebservice::verify_value_type: type "' . $type . '" is an array type, but value is of type "' . gettype($value) . '"' ); if (!isset( $value[0] ) || !isset( $value[sizeof($value)-1] )) throw new Exception( 'AbstractWebservice::verify_value_type: type "' . $type . '" expects indexed array value, not associative' ); // make sure all subvalues are also of the proper type foreach ($value as &$subvalue) $this->verify_value_type( $subvalue, $this->_types[ $type ] ); $value = array_values( $value ); } else if (is_array( $this->_types[ $type ] )) { // when input is an array, it must be an associative array $is_associative_array = false; if (is_array( $value )) if (!empty( $value )) if (!(isset( $value[0] ) && isset( $value[sizeof($value)-1] ))) $is_associative_array = true; // when $value is not an object and $is_associative_array == false, barf if (!is_object( $value ) && !$is_associative_array) { //throw new Exception( 'AbstractWebservice::verify_value_type: value "'.$value.'" is of type "' . gettype($type) . '", expected object or associative array' ); throw new Exception( 'AbstractWebservice::verify_value_type: value "'.$value.'" is of type "' . gettype($type) . '", expected object or associative array' ); } // to easily access all properties, convert to associative array if not already of that type if (!$is_associative_array) $value = (array)$value; if (sizeof( $value ) != sizeof( $this->_types[ $type ] )) throw new Exception( 'AbstractWebservice::verify_value_type: complex type "' . $type . '" has ' . sizeof( $this->_types[ $type ] ) . ' elements, value has ' . sizeof($value) ); foreach ($this->_types[ $type ] as $fieldname => $fieldtype) { if (!isset( $value[$fieldname] )) throw new Exception( 'AbstractWebservice::verify_value_type: missing element "' . $fieldname . '" in complex type "' . $type . '"' ); $this->verify_value_type( $value[$fieldname], $fieldtype ); } } } } } <file_sep><?php class CI_GenericCache { var $keybase; var $enabled; function CI_GenericCache() { $this->keybase = $_SERVER['SERVER_NAME']; $this->enabled = function_exists( 'apc_fetch' ); } private function _get_key( $key ) { return $this->keybase . '_' . $key; } function get( $key ) { if (!$this->enabled) return null; $key = $this->_get_key( $key ); return apc_fetch( $key ); } function set( $key, $value ) { if (!$this->enabled) return; $key = $this->_get_key( $key ); apc_store( $key, $value ); } }<file_sep>var adressen = [ <? foreach (array_values($dossiers) as $i => $dossier): ?> <? $volledig_adres = htmlentities( $dossier->locatie_adres . ', ' . $dossier->locatie_postcode . ', ' . $dossier->locatie_woonplaats, ENT_COMPAT, 'UTF-8' ); if ($volledig_adres == ', , ') // "empty" adres continue; ?> { dossier_id: <?=$dossier->id?>, kenmerk: '<?=jsstr($dossier->kenmerk)?>', volledig_adres: '<?=jsstr($volledig_adres)?>', adres: '<?=jsstr($dossier->locatie_adres);?>', postcode: '<?=jsstr($dossier->locatie_postcode);?>', woonplaats: '<?=jsstr($dossier->locatie_woonplaats);?>', url: '<?=site_url('/dossiers/bekijken/' . $dossier->id)?>' }<?=($i == sizeof($dossiers)-1) ? '' : ','?> <? endforeach; ?> ]; <file_sep>PDFAnnotator.Tool.DownloadScherm = PDFAnnotator.Tool.Download.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'downloadscherm' ); }, /* !!overide!! */ getDimensions: function() { // 'server' is a wrongly chosen term, a better term would be "interface to the outside, // whatever it is" // var server = PDFAnnotator.Server.prototype.instance; var windowProps = server.getWindowProportions(); return { x: windowProps.scrollX, // corrected in relation to margin y: windowProps.scrollY, w: windowProps.width, h: windowProps.height }; } }); <file_sep><?php require_once( dirname(__FILE__) . '/tcpdf-1.6/tcpdf.php' );<file_sep>ALTER TABLE `dossiers` CHANGE COLUMN `locatie_adres` `locatie_adres` varchar(255) NOT NULL; ALTER TABLE `dossiers` CHANGE COLUMN `beschrijving` `beschrijving` varchar(512) NOT NULL; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Logo\'s uploaden')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Logo toevoegen', 'width' => '920px' ) ); ?> Het logo dient <?=$this->config->item('logo_width')?> bij <?=$this->config->item('logo_height')?> pixels groot te zijn. Deze grootste versie van het logo wordt gebruikt in deelplannen. Er wordt automatisch een kleinere versie gegenereerd van <?=$this->config->item('logo_display_width')?> bij <?=$this->config->item('logo_display_height')?> pixels die gebruikt wordt op de website. <form method="post" enctype="multipart/form-data"> <table> <tr> <th id="form_header">Bestand uploaden:</th> </tr> <tr> <td id="form_value"><input type="file" name="logo" /><br/>U kunt vrijwel elk logo formaat gebruiken!</td> </tr> <tr> <th id="form_header">Bestand op het web gebruiken:</th> </tr> <tr> <td id="form_value"><input type="text" name="weblogo" value="http://" size="80" /></td> </tr> <tr> <th id="form_header">Opties:</th> </tr> <tr> <td id="form_value"><input type="checkbox" name="resize" checked /> Logo in grootte aanpassen wanneer nodig</td> </tr> <tr> <td id="form_value"><input type="checkbox" name="border" /> Logo zwarte rand van 1 pixel geven</td> </tr> <tr> <th id="form_header">Koppel aan:</th> </tr> <tr> <td id="form_value"> <select name="klant_id"> <? foreach ($klanten as $klant): ?> <option value="<?=$klant->id?>"><?=$klant->volledige_naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form_button"><input type="submit" value="Uploaden" name="upload" /></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>CREATE TABLE deelplan_hoofgroep ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) DEFAULT NULL, hoofgroep_id int(11) DEFAULT NULL, toelichting blob DEFAULT NULL, status varchar(255) DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_deelplan_hoofgroep_bt_hoofdgroepen_id FOREIGN KEY (hoofgroep_id) REFERENCES bt_hoofdgroepen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_deelplan_hoofgroep_deelplan_checklist_groepen_deelplan_id FOREIGN KEY (deelplan_id) REFERENCES deelplan_checklist_groepen (deelplan_id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 0 CHARACTER SET utf8 COLLATE utf8_general_ci;<file_sep>PDFAnnotator.Handle.OverviewHide = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0, 0, baseurl + 'images/nlaf/overview-hide.png', 28, 28, 'click', this.execute, null, 1, 1, 9, 12 ); }, execute: function( relx, rely ) { // hide overview window this.editable.hide(); } }); <file_sep>ALTER TABLE `bt_checklist_groepen` CHANGE `standaard_waardeoordeel_tekst_00` `standaard_waardeoordeel_tekst_00` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_01` `standaard_waardeoordeel_tekst_01` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_02` `standaard_waardeoordeel_tekst_02` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_03` `standaard_waardeoordeel_tekst_03` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_04` `standaard_waardeoordeel_tekst_04` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_10` `standaard_waardeoordeel_tekst_10` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_11` `standaard_waardeoordeel_tekst_11` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_12` `standaard_waardeoordeel_tekst_12` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_13` `standaard_waardeoordeel_tekst_13` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_20` `standaard_waardeoordeel_tekst_20` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_21` `standaard_waardeoordeel_tekst_21` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_22` `standaard_waardeoordeel_tekst_22` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_23` `standaard_waardeoordeel_tekst_23` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_steekproef_tekst` `standaard_waardeoordeel_steekproef_tekst` VARCHAR(64) NULL DEFAULT NULL; ALTER TABLE `bt_checklisten` CHANGE `standaard_waardeoordeel_tekst_00` `standaard_waardeoordeel_tekst_00` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_01` `standaard_waardeoordeel_tekst_01` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_02` `standaard_waardeoordeel_tekst_02` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_03` `standaard_waardeoordeel_tekst_03` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_04` `standaard_waardeoordeel_tekst_04` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_10` `standaard_waardeoordeel_tekst_10` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_11` `standaard_waardeoordeel_tekst_11` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_12` `standaard_waardeoordeel_tekst_12` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_13` `standaard_waardeoordeel_tekst_13` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_20` `standaard_waardeoordeel_tekst_20` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_21` `standaard_waardeoordeel_tekst_21` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_22` `standaard_waardeoordeel_tekst_22` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_23` `standaard_waardeoordeel_tekst_23` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_steekproef_tekst` `standaard_waardeoordeel_steekproef_tekst` VARCHAR(64) NULL DEFAULT NULL; ALTER TABLE `bt_hoofdgroepen` CHANGE `standaard_waardeoordeel_tekst_00` `standaard_waardeoordeel_tekst_00` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_01` `standaard_waardeoordeel_tekst_01` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_02` `standaard_waardeoordeel_tekst_02` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_03` `standaard_waardeoordeel_tekst_03` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_04` `standaard_waardeoordeel_tekst_04` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_10` `standaard_waardeoordeel_tekst_10` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_11` `standaard_waardeoordeel_tekst_11` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_12` `standaard_waardeoordeel_tekst_12` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_13` `standaard_waardeoordeel_tekst_13` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_20` `standaard_waardeoordeel_tekst_20` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_21` `standaard_waardeoordeel_tekst_21` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_22` `standaard_waardeoordeel_tekst_22` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_tekst_23` `standaard_waardeoordeel_tekst_23` VARCHAR(64) NULL DEFAULT NULL, CHANGE `standaard_waardeoordeel_steekproef_tekst` `standaard_waardeoordeel_steekproef_tekst` VARCHAR(64) NULL DEFAULT NULL; ALTER TABLE `bt_vragen` CHANGE `waardeoordeel_tekst_00` `waardeoordeel_tekst_00` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_01` `waardeoordeel_tekst_01` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_02` `waardeoordeel_tekst_02` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_03` `waardeoordeel_tekst_03` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_04` `waardeoordeel_tekst_04` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_10` `waardeoordeel_tekst_10` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_11` `waardeoordeel_tekst_11` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_12` `waardeoordeel_tekst_12` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_13` `waardeoordeel_tekst_13` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_20` `waardeoordeel_tekst_20` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_21` `waardeoordeel_tekst_21` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_22` `waardeoordeel_tekst_22` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_tekst_23` `waardeoordeel_tekst_23` VARCHAR(64) NULL DEFAULT NULL, CHANGE `waardeoordeel_steekproef_tekst` `waardeoordeel_steekproef_tekst` VARCHAR(64) NULL DEFAULT NULL; UPDATE `bt_checklist_groepen` SET `standaard_waardeoordeel_steekproef_tekst` = 'Niet gecontroleerd ivm steekproef'; <file_sep>-- This file contains fixes to the DB migrations in the 3.1.1 tree. Almost all of the migration files had undesired errors (even if only in the column names etc.) -- that can be corrected by just running these queries in case the migrations 000 - 006 have already been executed on a specific environment before. Note that the -- corresponding migrations 000-006 have been corrected too now, so if they were not run before, it should be sufficient to simply run 000-006 and then 007 should not -- be necessary. -- Fixes for migration file 000: ALTER TABLE `klanten` CHANGE COLUMN `standaar_documenten` `standaard_documenten` tinyint(3) DEFAULT '0'; -- Fixes for migration file 001: -- Run the entire migration again! -- Fixes for migration file 002: -- None. -- Fixes for migration file 003: -- None (only a file name rename, the content was not changed). -- Fixes for migration file 004: ALTER TABLE `klanten` CHANGE COLUMN `standard_deeplannen` `standaard_deelplannen` tinyint(3) DEFAULT '0' NOT NULL; DELETE FROM `teksten` WHERE `string` IN ('klant.standard_deeplannen', 'standard_deeplplannen.headers.standard_deeplplannen', 'beheer.index::standart_deeplannen'); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'klant.standaard_deelplannen', ' Standaard Deelplannen?', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'standaard_deelplannen.headers.standaard_deelplannen', ' Standaard Deelplannen', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'beheer.index::standaard_deelplannen', ' <NAME>', '2015-03-19 15:14:13' ); REPLACE INTO `teksten` ( `lease_configuratie_id`, `string`, `tekst`, `timestamp`) VALUES ( 0, 'klant.standaard_documenten', ' Standaard Documemten?', '2015-03-19 15:14:13' ); -- Fixes for migration file 005: -- None. -- Fixes for migration file 006: -- None now, even though it would be better if the combination of the columns: `deelplan_id`, `vraag_id` and `dossier_bescheiden_id` would be changed to a single -- column deelplan_vraag_bescheiden_id. This was not done now so as to not interfere with Netrunner's work. <file_sep><? $this->load->view('elements/header'); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Device informatie', 'width' => 'auto' )); ?> <table> <tr> <th>User agent</th> <td><?=$agent?></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <? foreach ($parts as $part => $value): ?> <tr> <th><?=ucfirst($part)?> part</th> <td><?=$value?></td> </tr> <? endforeach; ?> <tr> <td colspan="2">&nbsp;</td> </tr> <? foreach ($types as $type => $value): ?> <tr> <th><?=ucfirst($type)?></th> <td><?=$value ? 'yes' : 'no'?></td> </tr> <? endforeach; ?> <tr> <td colspan="2">&nbsp;</td> </tr> <? foreach ($browsers as $browser => $value): ?> <tr> <th><?=ucfirst($browser)?></th> <td><?=$value ? 'yes' : 'no'?></td> </tr> <? endforeach; ?> <tr> <td colspan="2">&nbsp;</td> </tr> <? foreach ($os as $o => $value): ?> <tr> <th><?=ucfirst($o)?></th> <td><?=$value ? 'yes' : 'no'?></td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.rapportage::projecten', 'Projecten', NOW(), 0), ('dossiers.rapportage::deelplannen', 'Deelplannen', NOW(), 0), ('dossiers.rapportage::bijlage_pago_pmo', 'Bijlage: PAGO/PMO', NOW(), 0), ('dossiers.rapportage::bijlage_pbm', 'Bijlage: PBM', NOW(), 0), ('dossiers.rapportage::bijlage_annotaties', 'Bijlage: Annotaties', NOW(), 0), ('dossiers.rapportage::toetsing_kerndeskundige', 'Toetsing kerndeskundige', NOW(), 0), ('dossiers.rapportage::projecten', 'Projecten', NOW(), 1), ('dossiers.rapportage::deelplannen', 'Deelplannen', NOW(), 1), ('dossiers.rapportage::bijlage_pago_pmo', 'Bijlage: PAGO/PMO', NOW(), 1), ('dossiers.rapportage::bijlage_pbm', 'Bijlage: PBM', NOW(), 1), ('dossiers.rapportage::bijlage_annotaties', 'Bijlage: Annotaties', NOW(), 1), ('dossiers.rapportage::toetsing_kerndeskundige', 'Toetsing kerndeskundige', NOW(), 1) ; <file_sep>BRISToezicht.InlineEdit = { elements: null, initialize: function() { // find all inline-editable (ie) elements $('img.ie').live( 'click', function( e ){ var thiz = $(this); eventStopPropagation( e ); var tag = thiz.attr( 'tag' ); modalPopup({ width: 700, height: 150, url: '/admin/inline_edit/' + tag, onClose: function( res ) { if (typeof(res) == 'string') { thiz.prev().text( res ); } } }); }); } }; <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('redirect')) { function redirect($uri = '', $method = 'location', $http_response_code = 302) { // if this is an APP request, do not redirect, but send error code // NOTE: we can never know when we're being called, so use the isset() method // in stead of relying on defines from the Session library! if (isset( $_SERVER['PHP_AUTH_USER'] )) { echo json_encode(array( 'Success' => false, 'ErrorMessage' => 'Wegens beveilingsredenen is uw verzoek door de server geweigerd. (302: ' . $uri . ')', ) ); exit; } if (!preg_match( '#^https?://#i', $uri )) $uri = site_url($uri); switch($method) { case 'refresh' : header("Refresh:0;url=".$uri); break; default : header("Location: ".$uri, TRUE, $http_response_code); break; } exit; } } // require normal url helper from system require_once(APPPATH . '../system/helpers/url_helper.php'); <file_sep><?php require_once 'common.php'; require_once __DIR__ . '/../application/libraries/Utils.php'; // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit(3600); // --------------------------------- dossier_bescheiden ---------------------------------- // echo "\nStage 1: dossier bescheiden....\n"; if( !is_dir(DIR_DOSSIER_BESCHEIDEN) ) { $source_path = BASEPATH . '/../documents'; $target_path = BASEPATH . '/../dossier_bescheiden'; rename($source_path, $target_path); echo "Step 1: Moving documents from '{$source_path}' to '{$target_path}'....\n"; // Create a new Dir called documents $new_documents_directory = BASEPATH . '/../documents'; echo "Step 2: Creating directory '{$new_documents_directory}'....\n"; CI_Utils::create_dir($new_documents_directory); $source_path = BASEPATH . '/../dossier_bescheiden'; //$target_path = BASEPATH . '/../documents'; $target_path = BASEPATH . '/../documents/dossier_bescheiden'; echo "Step 3: Moving documents from '{$source_path}' to '{$target_path}'....\n"; rename($source_path, $target_path); echo "\n\n"; } else { echo "Already done. Skipping.\n"; } // --------------------------------- dossier_rapporten ---------------------------------- // echo "\nStage 2: dossier rapporten....\n"; if( !is_dir(DIR_DOSSIER_RAPPORT) ) { // Start by getting the highest ID that is present in the dossier_rapporten table. $query = "SELECT MAX(id) AS max_dr_id FROM dossier_rapporten"; $stmt = $dbh->query($query); $row = $stmt->fetch(); $max_dr_id = (empty($row['max_dr_id'])) ? 0 : $row['max_dr_id']; $last_used_upper_dr_id = 0; $chunk_size = 100; $i = 0; if ($max_dr_id > 0) { echo "Upper id to use: {$max_dr_id}. Using chunks of {$chunk_size} ID values.\n"; while ($last_used_upper_dr_id < $max_dr_id) { $current_upper_dr_id = $last_used_upper_dr_id + $chunk_size; echo "Processing chunk from id: {$last_used_upper_dr_id} to id: {$current_upper_dr_id}...\n"; $query = 'SELECT id, bestand, dossier_id FROM dossier_rapporten ' . "WHERE (id > {$last_used_upper_dr_id}) AND (id <= {$current_upper_dr_id})"; $stmt = $dbh->query($query); while( $row = $stmt->fetch() ) { $bestand_deflated = gzinflate($row['bestand']); //echo "File with ID: {$row['dossier_id']} - {$row['id']}. File start: " . substr($bestand_deflated, 0, 10) . "\n"; CI_Utils::store_file(DIR_DOSSIER_RAPPORT . '/' . $row['dossier_id'], $row['id'], $bestand_deflated); ++$i; } // Update the last used ID value $last_used_upper_dr_id = $current_upper_dr_id; } } logger('dossier_rapporten - Number of records: ' . $i . "\n"); //$drop_query = 'ALTER TABLE dossier_rapporten DROP bestand'; //$stmt = $dbh->exec($drop_query); } else { echo "Already done. Skipping.\n"; } // --------------------------------- deelplan_uploads ---------------------------------- // // Note: the deelplan uploads table contains too much data in the live environment to pull it all in in one go. Therefore it has now been chunked by // processing batches of 100 deelplan id values at most. echo "\nStage 3: deelplan uploads....\n"; // Start by getting the highest deelplan ID that is present in the deelplan_uploads table. $query = "SELECT MAX(deelplan_id) AS max_dp_id FROM deelplan_uploads"; $stmt = $dbh->query($query); $row = $stmt->fetch(); $max_dp_id = (empty($row['max_dp_id'])) ? 0 : $row['max_dp_id']; $last_used_upper_dp_id = 0; $chunk_size = 100; if ($max_dp_id > 0) { echo "Upper deelplan id to use: {$max_dp_id}. Using chunks of {$chunk_size} deelplan ID values.\n"; while ($last_used_upper_dp_id < $max_dp_id) { $current_upper_dp_id = $last_used_upper_dp_id + $chunk_size; echo "Processing chunk from id: {$last_used_upper_dp_id} to id: {$current_upper_dp_id}...\n"; $query = 'SELECT dud.id dud_id, du.id du_id, du.deelplan_id, d.dossier_id dossier_id, dud.data '. 'FROM deelplan_uploads du '. 'INNER JOIN deelplan_upload_data dud ON dud.id = du.deelplan_upload_data_id '. 'INNER JOIN deelplannen d ON d.id = du.deelplan_id ' . "WHERE (du.deelplan_id > {$last_used_upper_dp_id}) AND (du.deelplan_id <= {$current_upper_dp_id})"; $stmt = $dbh->query($query); // Do the stuff using the old logic... $i = 0; while( $row = $stmt->fetch() ) { if( isset($dud_du_rel[$row['dud_id']]) ) { // create symlinks if has already been create the data_file $target = DIR_DEELPLAN_UPLOAD . '/' . $row['dossier_id'] . '/' .$row['deelplan_id'] . '/' . $dud_du_rel[$row['dud_id']]; $link = DIR_DEELPLAN_UPLOAD . '/' . $row['dossier_id'] . '/' . $row['deelplan_id'] . '/' . $row['du_id']; symlink($target, $link); logger($target . ' --> '. $link); } else { // If is the first time stores the data in the filesystem CI_Utils::store_file(DIR_DEELPLAN_UPLOAD . '/' . $row['dossier_id'] . '/' .$row['deelplan_id'], $row['du_id'], $row['data']); $dud_du_rel[$row['dud_id']] = $row['du_id']; logger('FILE: ' . DIR_DEELPLAN_UPLOAD . '/' . $row['dossier_id'] . '/' .$row['deelplan_id'] . '/' . $row['du_id']); } ++$i; } // Update the last used ID value $last_used_upper_dp_id = $current_upper_dp_id; //logger('deelplan_uploads - Number of records: ' . $i); } //$drop_query = 'ALTER TABLE deelplan_uploads DROP deelplan_upload_data_id;'. // 'DROP TABLE deelplan_upload_data'; // //$stmt = $dbh->exec($drop_query); // Proper queries (to avoid key trouble!): // ALTER TABLE deelplan_uploads DROP FOREIGN KEY deelplan_uploads_ibfk_6; // ALTER TABLE deelplan_uploads DROP KEY deelplan_upload_data_id; // ALTER TABLE deelplan_uploads DROP COLUMN deelplan_upload_data_id; // DROP TABLE deelplan_upload_data; } <file_sep>ALTER TABLE `dossier_subjecten` ADD `laatst_bijgewerkt_op` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; UPDATE dossier_subjecten SET laatst_bijgewerkt_op = NOW(); ALTER TABLE `webservice_applicatie_dossiers` ADD UNIQUE (`webservice_applicatie_id` ,`dossier_id`); CREATE TABLE IF NOT EXISTS `webservice_applicatie_bescheiden` ( `id` int(11) NOT NULL, `webservice_applicatie_id` int(11) NOT NULL, `dossier_bescheiden_id` int(11) NOT NULL, `laatst_bijgewerkt_op` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY `webservice_applicatie_id_2` (`webservice_applicatie_id`,`dossier_bescheiden_id`), KEY `webservice_applicatie_id` (`webservice_applicatie_id`), KEY `dossier_bescheiden_id` (`dossier_bescheiden_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `webservice_applicatie_bescheiden` ADD CONSTRAINT `webservice_applicatie_bescheiden_ibfk_1` FOREIGN KEY (`webservice_applicatie_id`) REFERENCES `webservice_applicaties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `webservice_applicatie_bescheiden_ibfk_2` FOREIGN KEY (`dossier_bescheiden_id`) REFERENCES `dossier_bescheiden` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `webservice_log` ADD `request_uri` VARCHAR( 512 ) NOT NULL AFTER `id` ; <file_sep>REPLACE INTO teksten(`string`, tekst , timestamp , lease_configuratie_id) VALUES ('dossiers.export::geengegevens', 'No content', NOW(), '0'); <file_sep>ALTER TABLE `outlook_sync_data` CHANGE COLUMN `uid` `entry_uid` varchar(64) NOT NULL; ALTER TABLE `outlook_sync_data` CHANGE COLUMN `date` `entry_date` date NOT NULL; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Logo\'s bekijken')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Logo\'s bekijken', 'width' => '920px' ) ); ?> <form name="form"> <table> <tr> <td id="form_value"> <select onchange="show_logo('logo','logo_klein',this);" name="klant_id"> <option disabled selected>-- selecteer een account</option> <? foreach ($bestaande_logos as $logo): ?> <option value="<?=$logo->id?>"><?=$logo->volledige_naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td> <h3>Grote variant</h3> <img id="logo"><br/> <h3>Kleine variant</h3> <img id="logo_klein"> </td> </tr> </table> </form> <? if ($klant_id!=null): ?> <script language="JavaScript"> for (var i=0; i<document.form.klant_id.options.length; ++i) { if (document.form.klant_id.options[i].value == <?=$klant_id?>) { document.form.klant_id.selectedIndex = i; break; } } show_logo('logo','logo_klein',document.form.klant_id); </script> <? endif; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>PDFAnnotator.Server.BTZVraag = PDFAnnotator.LayerReference.extend({ init: function( id, naam, status ) { this._super(); this.id = id; this.naam = naam; this.status = status; }, getId: function() { return this.id; }, /* should return displayed name of object */ getName: function() { return this.naam; }, /* should return filter state of object */ getFilter: function() { return this.status; }, /* should be called by deriving classes when filter state changed. */ setFilter: function( filter ) { this.status = filter; this._super( filter ); } }); <file_sep><div id="pago_pmo_content"> <button type="button" onclick="show_pago_pmo_form('');">Toevoegen</button> <? if( count($funcs) > 0 ): ?> <table class="appendix_tbl"> <thead> <tr> <th class="left_th" rowspan="2" style="width:18.51%;"><?=tg('functie')?></th> <th class="mid_th" rowspan="2" style="width:9.26%;"><?=tg('n_medewerkers')?></th> <th class="right_th" colspan="6"><?=tg('onderwerp')?></th> </tr> <tr> <th class="left_th" style="width:12.04%;"><?=tg('beeldschermwerk')?></th> <th class="mid_th" style="width:12.04%;"><?=tg('biologische_agentia')?></th> <th class="mid_th" style="width:12.04%;"><?=tg('gevaarlijke_stoffen')?></th> <th class="mid_th" style="width:12.04%;"><?=tg('schadelijk_geluid')?></th> <th class="mid_th" style="width:12.04%;"><?=tg('fysieke_belasting')?></th> <th class="right_th" style="width:12.04%;"><?=tg('werkdruk_belasting')?></th> </tr> </thead> <tbody> <? foreach ($funcs as $func): ?> <tr> <td class="left_td"><a href="#" title="Bewerk" onclick="show_pago_pmo_form('/<?=$func->id ?>');"><?=$func->functie ?></a></td> <td class="mid_td"><?=$func->n_medewerkers ?></td> <td class="mid_td"><?=$func->beeldschermwerk ?></td> <td class="mid_td"><?=$func->biologische_agentia ?></td> <td class="mid_td"><?=$func->gevaarlijke_stoffen ?></td> <td class="mid_td"><?=$func->schadelijk_geluid ?></td> <td class="mid_td"><?=$func->fysieke_belasting ?></td> <td class="right_td"><?=$func->werkdruk_belasting ?></td> </tr> <? endforeach; ?> </tbody> </table> <? else: ?> <div><?=tg('no_items_found');?></div> <? endif; ?> </div> <script> function show_pago_pmo_form(recId){ var target = $("#pago_pmo_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/show_pago_pmo_form/' . $dossier->id)?>'+recId ); } </script><file_sep><?php define( 'TABEL_BETEKENISNIVEAU', 0 ); define( 'TABEL_CONTROLEELEMENT', 1 ); define( 'TABEL_CONTROLEELEMENTTOETSTINGLINK', 2 ); define( 'TABEL_CONTROLENIVEAU', 3 ); define( 'TABEL_CONTROLEONDERDEEL', 4 ); define( 'TABEL_OBJECTCATEGORIE', 5 ); define( 'TABEL_REGELGEVING', 6 ); define( 'TABEL_SUBTHEMA', 7 ); define( 'TABEL_THEMA', 8 ); define( 'TABEL_TOETSINGSKADER', 9 ); class CI_ITPImport { function create( array $filenames, $checklistgroepnaam ) { return new ITPImport( $filenames, $checklistgroepnaam ); } function get_tabellen() { return array( TABEL_BETEKENISNIVEAU => 'BetekenisNiveau', TABEL_CONTROLEELEMENT => 'ControleElement', TABEL_CONTROLEELEMENTTOETSTINGLINK => 'ControleElementToetsingLink', TABEL_CONTROLENIVEAU => 'ControleNiveau', TABEL_CONTROLEONDERDEEL => 'ControleOnderdeel', TABEL_OBJECTCATEGORIE => 'ObjectCategorie', TABEL_REGELGEVING => 'Regelgeving', TABEL_SUBTHEMA => 'SubThema', TABEL_THEMA => 'Thema', TABEL_TOETSINGSKADER => 'Toetsingskader', ); } function get_tabel_naam( $tabel_nummer ) { $tabellen = $this->get_tabellen(); if (!isset( $tabellen[$tabel_nummer] )) return false; return $tabellen[$tabel_nummer]; } } class ITPTabel { private $_headers = array(); private $_rows = array(); public function __construct( array $rows=array(), array $headers=array() ) { $this->_headers = $headers; $this->_rows = $rows; foreach ($this->_rows as $regel => $row) { if (!is_array( $row )) throw new Exception( 'Fout in IPTTabel, regel ' . $regel . ' is geen array.' ); if (sizeof($row) != sizeof($this->_headers)) throw new Exception( 'Fout in IPTTabel, kolom aantal op regel ' . $regel . ' niet correct, vond er ' . sizeof($row) . ', verwachtte er ' . sizeof($this->_headers) ); } } public function header_size() { return sizeof($this->_headers); } public function header( $index ) { if (!isset( $this->_headers[$index] )) return false; return $this->_headers[$index]; } public function has_header( $header ) { return in_array( $header, $this->_headers ); } public function row_size() { return sizeof($this->_rows); } public function row( $index ) { if (!isset( $this->_rows[$index] )) return false; return $this->_rows[$index]; } public function field( $index, $field ) { if (false === ($row = $this->row( $index ))) return false; if (!isset( $row[$field] )) return false; return $row[$field]; } static public function create_from_csv( $filename, $eerste_regel_heeft_headers ) { // attempt to open file if (!($fd = fopen( $filename, 'rb' ))) throw new Exception( 'Kon CSV bestand ' . $filename . ' niet laden' ); // try to determine delimiter $num = array(); foreach (array( ',', ';', "\t" ) as $delim) { $row = fgetcsv( $fd, 1024, $delim ); $num[$delim] = is_array( $row ) ? sizeof($row) : 0; fseek( $fd, 0, SEEK_SET ); } $max = 0; $delimiter = null; foreach ($num as $delim => $actualnum) if ($actualnum > 1 && $actualnum > $max) { $max = $actualnum; $delimiter = $delim; } if (is_null( $delimiter )) throw new Exception( 'Kon scheidingsteken voor kolommen niet bepalen.' ); // read rows $rows = $headers = array(); while ($row = fgetcsv( $fd, 0, $delimiter )) { if (empty($headers)) { // first line if ($eerste_regel_heeft_headers) { $headers = $row; $add_row = false; } else { $headers = array(); foreach ($row as $i => $unused) $headers[] = 'Column ' . $i; $add_row = true; } } else $add_row = true; if ($add_row) { $newrow = array(); foreach ($row as $i => $value) { $encoding = 'CP437'; $utf8_value = iconv( $encoding, 'UTF-8', $value ); $newrow[ $headers[$i] ] = $utf8_value; // yay, zo hoeft dit maar op 1 plek \o/ } $rows[] = $newrow; } } return new ITPTabel( $rows, $headers ); } } class ITPImport { private $_CI; private $_tabellen = array(); private $_checklistgroepnaam; private $_num_new = array( 'checklistgroep' => 0, 'checklist' => 0, 'hoofdthema' => 0, 'thema' => 0, 'hoofdgroep' => 0, 'categorie' => 0, 'vraag' => 0, 'aandachtspunt' => 0, 'grondslag' => 0, 'vraaggrondslag' => 0, 'prioriteitstelling' => 0, ); private $_num_missing = array( 'element' => 0, 'niveau' => 0, 'onderdeel' => 0, 'hoofdthema' => 0, 'subthema' => 0, 'objectcategorie' => 0, 'regelgeving' => 0, 'toetsingskader' => 0, ); /************************************************************************************************************ * * * PUBLIEKE INTERFACE * * * ************************************************************************************************************/ public function __construct( array $filenames, $checklistgroepnaam ) { // initializeer $this->_CI = get_instance(); $this->_CI->load->library( 'prioriteitstelling' ); $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'hoofdgroep' ); $this->_CI->load->model( 'categorie' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'grondslag' ); $this->_CI->load->model( 'vraaggrondslag' ); $this->_CI->load->model( 'hoofdthema' ); $this->_CI->load->model( 'thema' ); $this->_CI->load->model( 'matrix' ); $this->_load_tabel( TABEL_BETEKENISNIVEAU, @ $filenames[TABEL_BETEKENISNIVEAU] ); $this->_load_tabel( TABEL_CONTROLEELEMENTTOETSTINGLINK, @ $filenames[TABEL_CONTROLEELEMENTTOETSTINGLINK] ); $this->_load_tabel( TABEL_CONTROLEELEMENT, @ $filenames[TABEL_CONTROLEELEMENT] ); $this->_load_tabel( TABEL_CONTROLENIVEAU, @ $filenames[TABEL_CONTROLENIVEAU] ); $this->_load_tabel( TABEL_CONTROLEONDERDEEL, @ $filenames[TABEL_CONTROLEONDERDEEL] ); $this->_load_tabel( TABEL_OBJECTCATEGORIE, @ $filenames[TABEL_OBJECTCATEGORIE] ); $this->_load_tabel( TABEL_REGELGEVING, @ $filenames[TABEL_REGELGEVING] ); $this->_load_tabel( TABEL_SUBTHEMA, @ $filenames[TABEL_SUBTHEMA] ); $this->_load_tabel( TABEL_THEMA, @ $filenames[TABEL_THEMA] ); $this->_load_tabel( TABEL_TOETSINGSKADER, @ $filenames[TABEL_TOETSINGSKADER] ); $this->_checklistgroepnaam = $checklistgroepnaam; } public function run() { // check headers $this->_has_headers( TABEL_OBJECTCATEGORIE, array( 'ObjectCategorie_ID', 'ObjectCategorie', 'InGebruik' ) ); $this->_has_headers( TABEL_CONTROLEONDERDEEL, array( 'ControleOnderdeel_ID', 'ControleOnderdeel', 'InGebruik' ) ); $this->_has_headers( TABEL_CONTROLEELEMENT, array( 'ControleElement_ID', 'ControleOnderdeel_ID', 'ObjectCategorie_ID', 'SubThema_ID', 'Aandachtspunt', 'InGebruik' ) ); $this->_has_headers( TABEL_CONTROLENIVEAU, array( 'ControleNiveau_ID', 'ControleNiveau' ) ); $this->_has_headers( TABEL_BETEKENISNIVEAU, array( 'BetekenisNiveau_ID', 'ControleElement_ID', 'ControleNiveau_ID', 'BetekenisNiveau', 'InGebruik' ) ); $this->_has_headers( TABEL_THEMA, array( 'Thema_ID', 'Thema', 'InGebruik' ) ); $this->_has_headers( TABEL_SUBTHEMA, array( 'SubThema_ID', 'SubThema', 'InGebruik' ) ); $this->_has_headers( TABEL_REGELGEVING, array( 'Regelgeving_ID', 'Regelgeving', 'InGebruik' ) ); $this->_has_headers( TABEL_TOETSINGSKADER, array( 'Toetsingskader_ID', 'Toetsingskader', 'Regelgeving_ID', 'InGebruik' ) ); $this->_has_headers( TABEL_CONTROLEELEMENTTOETSTINGLINK, array( 'ControleElementToetsingLink_ID', 'Toetsingskader_ID', 'ControleElement_ID', 'InGebruik' ) ); // maak checklistgroep if (!($checklistgroep = $this->_CI->checklistgroep->add( $this->_checklistgroepnaam ))) throw new Exception( 'Fout bij aanmaken checklistgroep.' ); $this->_num_new['checklistgroep']++; $checklistgroep->beschikbaarheid = 'publiek-voor-beperkt'; $checklistgroep->save(); // initialiseer een aantal temp translatie tabellen $co_translate = $this->_maak_temp_translatie( $this->_tabellen[TABEL_CONTROLEONDERDEEL], 'ControleOnderdeel_ID', 'ControleOnderdeel' ); $ce_translate = $this->_maak_temp_translatie( $this->_tabellen[TABEL_CONTROLEELEMENT], 'ControleElement_ID', array( 'ControleOnderdeel_ID', 'ObjectCategorie_ID', 'SubThema_ID', 'Aandachtspunt' ) ); $cn_translate = $this->_maak_temp_translatie( $this->_tabellen[TABEL_CONTROLENIVEAU], 'ControleNiveau_ID', 'ControleNiveau' ); $tk_translate = $this->_maak_temp_translatie( $this->_tabellen[TABEL_TOETSINGSKADER], 'Toetsingskader_ID', array( 'Toetsingskader', 'Regelgeving_ID' ) ); $tl_translate = $this->_maak_temp_translatie( $this->_tabellen[TABEL_CONTROLEELEMENTTOETSTINGLINK], 'ControleElementToetsingLink_ID', array( 'Toetsingskader_ID', 'ControleElement_ID' ) ); // maak aantal basis objecten $cl_translate = $this->_maak_checklisten( $this->_tabellen[TABEL_OBJECTCATEGORIE], $checklistgroep ); $ht_translate = $this->_maak_hoofdthemas( $this->_tabellen[TABEL_THEMA] ); $st_translate = $this->_maak_themas( $this->_tabellen[TABEL_SUBTHEMA], $ht_translate ); $gs_translate = $this->_maak_grondslagen( $this->_tabellen[TABEL_REGELGEVING] ); // maak hoofdgroepen, categorieen (standaard "B: Uitvoering"), en vragen $prios = $this->_maak_hoofdgroepen_categorieen_vragen( $this->_tabellen[TABEL_BETEKENISNIVEAU], $co_translate, $ce_translate, $cl_translate, $cn_translate, $st_translate, $gs_translate, $tk_translate, $tl_translate ); // rond alle checklisten af, en verwijder lege foreach ($cl_translate as $checklist) if (sizeof( $checklist->get_hoofdgroepen() ) == 0) { $this->_num_new['checklist']--; $checklist->delete(); } else $checklist->afronden(); // maak prioriteitstellingen in de standaard matrix $this->_maak_prioriteitstellingen( $checklistgroep, $prios ); } public function get_num_created_objects() { return $this->_num_new; } public function get_num_missing_objects() { return $this->_num_missing; } /************************************************************************************************************ * * * SIMPELE UTIL FUNCTIES * * * ************************************************************************************************************/ private function _in_gebruik( $tabel, $i ) { // return $tabel->field( $i, 'InGebruik' ) == 'WAAR'; return true; } private function _has_headers( $tabel_nummer, array $headers ) { if (!($tabel = $this->_tabellen[$tabel_nummer])) throw new Exception( 'ITP tabel ' . $tabel_nummer . ' niet aanwezig' ); foreach ($headers as $header) if (!$tabel->has_header( $header )) throw new Exception( 'ITP tabel "' . get_instance()->itpimport->get_tabel_naam( $tabel_nummer ) . '" bevat kolom "' . $header . '" niet. Verkeerd CSV bestand geupload?' ); } private function _load_tabel( $tabel_nummer, $filename ) { if (!$filename) throw new Exception( 'Ongeldig ITP tabel bestandsnaam: "' . $filename . '"' ); if (isset( $this->_tabellen[ $tabel_nummer ] )) throw new Exception( 'Interne fout, dubbele tabel nummer ' . $tabel_nummer ); $this->_tabellen[ $tabel_nummer ] = ITPTabel::create_from_csv( $filename, true ); } private function _maak_temp_translatie( $tabel, $idfield, $valuefields ) { $translate = array(); for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; $id = $tabel->field( $i, $idfield ); if (is_array( $valuefields )) { $value = array(); foreach ($valuefields as $valuefield) $value[$valuefield] = $tabel->field( $i, $valuefield ); } else $value = $tabel->field( $i, $valuefields ); $translate[$id] = $value; } return $translate; } private function _resolve_translatie( $translate, $id ) { // resolve if (!isset( $translate[$id] )) return false; return $translate[$id]; } private function _converteer_itp_prioriteit( $prio ) { switch ($prio) { case 'S': return 'zeer_laag'; case '1': return 'laag'; case '2': return 'gemiddeld'; case '3': return 'hoog'; case '4': return 'zeer_hoog'; default: throw new Exception( 'Onbekende iTP prioriteit waarde: "' . $prio . '"' ); } } /************************************************************************************************************ * * * DATA LAAD FUNCTIES * * * ************************************************************************************************************/ private function _maak_checklisten( $tabel, ChecklistGroepResult $checklistgroep ) { $translate = array(); for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; $checklistnaam = $tabel->field( $i, 'ObjectCategorie' ); if (!($checklist = $this->_CI->checklist->add( $checklistgroep->id, $checklistnaam ))) throw new Exception( 'Fout bij aanmaken checklist "' . $checklistnaam . '"' ); $this->_num_new['checklist']++; // update beschikbaarheid $checklist->beschikbaarheid = 'publiek-voor-beperkt'; $checklist->save(); $translate[ $tabel->field( $i, 'ObjectCategorie_ID' ) ] = $checklist; } return $translate; } private function _maak_grondslagen( $tabel ) { $translate = array(); for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; $grondslag = $tabel->field( $i, 'Regelgeving' ); $id = $tabel->field( $i, 'Regelgeving_ID' ); if (!($found = $this->_CI->grondslag->find( $grondslag ))) { if (!($checklist = $this->_CI->grondslag->add( $grondslag ))) throw new Exception( 'Fout bij aanmaken grondslag "' . $checklistnaam . '"' ); $this->_num_new['grondslag']++; $translate[ $id ] = $checklist; } else $translate[ $id ] = $found; } return $translate; } private function _maak_hoofdthemas( $tabel ) { $translate = array(); for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; $hoofdthema = $tabel->field( $i, 'Thema' ); $id = $tabel->field( $i, 'Thema_ID' ); if (!($found = $this->_CI->hoofdthema->find( $hoofdthema ))) { if (!($thema = $this->_CI->hoofdthema->add( $hoofdthema, $id, 'iTP' ))) throw new Exception( 'Fout bij aanmaken hoofdthema "' . $hoofdthema . '"' ); $this->_num_new['hoofdthema']++; $translate[ $id ] = $thema; } else $translate[ $id ] = $found; } return $translate; } private function _maak_themas( $tabel, array $ht_translate ) { $translate = array(); for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; $thema = preg_replace( '/^[a-z]+\s+-\s+/i', '', $tabel->field( $i, 'SubThema' ) ); $id = $tabel->field( $i, 'SubThema_ID' ); $hoofdthema_id = $tabel->field( $i, 'Thema_ID' ); if (!($hoofdthema_obj = $this->_resolve_translatie( $ht_translate, $hoofdthema_id ))) { $this->_num_missing['hoofdthema']++; continue; } if (!($found = $this->_CI->thema->find( $thema )) || ($hoofdthema_obj->id != $found->hoofdthema_id)) { if (!($thema = $this->_CI->thema->add( $thema, $id, $hoofdthema_obj->id ))) throw new Exception( 'Fout bij aanmaken thema "' . $thema . '"' ); $this->_num_new['thema']++; $translate[ $id ] = $thema; } else $translate[ $id ] = $found; } return $translate; } private function _maak_hoofdgroepen_categorieen_vragen( $tabel, $co_translate, $ce_translate, $cl_translate, $cn_translate, $st_translate, $gs_translate, $tk_translate, $tl_translate ) { $hoofdgroepen = array(); // key=checklist_id, value=array( key=onderdeel_id, value=hoofdgroep ) $categorieen = array(); // key=checklist_id, value=array( key=onderdeel_id, value=categorie ) NOTE: elke hoofdgroep heeft maar 1 categorie! $prios = array(); // key=checklist_id, value=array( key=hoofdgroep_id, value=advies-prioriteit-totaal ) NOTE: resultaat array, voor aanmaken default matrix! for ($i=0; $i < $tabel->row_size(); ++$i) { if (!$this->_in_gebruik( $tabel, $i )) continue; // resolve references $element_id = $tabel->field( $i, 'ControleElement_ID' ); if (!($element = $this->_resolve_translatie( $ce_translate, $element_id ))) // array { $this->_num_missing['element']++; continue; } if (!($niveau = $this->_resolve_translatie( $cn_translate, $tabel->field( $i, 'ControleNiveau_ID' ) ))) // string (prioriteit, S, 1, 2, 3, of 4) { $this->_num_missing['niveau']++; continue; } if (!($onderdeel = $this->_resolve_translatie( $co_translate, $element['ControleOnderdeel_ID'] ))) // string (naam van onderdeel) { $this->_num_missing['onderdeel']++; continue; } if (!($thema = $this->_resolve_translatie( $st_translate, $element['SubThema_ID'] ))) // object { $this->_num_missing['subthema']++; continue; } if (!($checklist = $this->_resolve_translatie( $cl_translate, $element['ObjectCategorie_ID'] ))) // object { $this->_num_missing['objectcategorie']++; continue; } // hoofdgroep maken? if (!isset( $hoofdgroepen[$checklist->id] )) $hoofdgroepen[$checklist->id] = array(); if (!isset( $hoofdgroepen[$checklist->id][ $element['ControleOnderdeel_ID'] ] )) { $hoofdgroepen[$checklist->id][ $element['ControleOnderdeel_ID'] ] = $this->_CI->hoofdgroep->add( $checklist->id, $onderdeel ); $categorieen[$checklist->id][ $element['ControleOnderdeel_ID'] ] = $this->_CI->categorie->add( $hoofdgroepen[$checklist->id][ $element['ControleOnderdeel_ID'] ]->id, 'B: Uitvoering' ); $this->_num_new['hoofdgroep']++; $this->_num_new['categorie']++; } $hoofdgroep = $hoofdgroepen[$checklist->id][ $element['ControleOnderdeel_ID'] ]; // object $categorie = $categorieen[$checklist->id][ $element['ControleOnderdeel_ID'] ]; // object // maak aandachtspunt $aandachtspunt = $element['Aandachtspunt']; // string if ($aandachtspunt) { $this->_CI->vraag->add( $categorie->id, $aandachtspunt, $thema->id, 31 /* altijd overal aanwezig! */, true ); $this->_num_new['aandachtspunt']++; } // maak vraag $tekst = $tabel->field( $i, 'BetekenisNiveau' ); $vraag = $this->_CI->vraag->add( $categorie->id, $tekst, $thema->id, 31 /* altijd overal aanwezig! */, false, $this->_converteer_itp_prioriteit( $niveau ) ); // object $this->_num_new['vraag']++; // tel prioriteit bij hoofdgroep totaal op if (!isset( $prios[$checklist->id][$hoofdgroep->id] )) $prios[$checklist->id][$hoofdgroep->id] = array( 'aantal' => 0, 'totaal' => 0, ); $prios[$checklist->id][$hoofdgroep->id]['totaal'] += intval( $niveau ); // '1' wordt 1, '2' wordt 2, en 'S' wordt 0, wat precies goed is! :-)) $prios[$checklist->id][$hoofdgroep->id]['aantal']++; // doorloop de lijst van controle element toetsings links, om te zien of er grondslagen gekoppeld moeten worden foreach ($tl_translate as $tl_row) { if ($tl_row['ControleElement_ID'] == $element_id) { if (!($toetsingskader = $this->_resolve_translatie( $tk_translate, $tl_row['Toetsingskader_ID'] ))) // array { $this->_num_missing['toetsingskader']++; continue; } if (!($grondslag = $this->_resolve_translatie( $gs_translate, $toetsingskader['Regelgeving_ID'] ))) // object { $this->_num_missing['regelgeving']++; continue; } $this->_CI->vraaggrondslag->add( $vraag->id, $grondslag->id, $toetsingskader['Toetsingskader'], null ); $this->_num_new['vraaggrondslag']++; } } } return $prios; } private function _maak_prioriteitstellingen( ChecklistGroepResult $checklistgroep, array $prios ) { $matrix = $this->_CI->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ); $first = true; foreach ($prios as $checklist_id => $hoofdgroepen) { $ps = $this->_CI->prioriteitstelling->lookup_or_create( $matrix->id, $checklist_id ); $this->_num_new['prioriteitstelling']++; foreach ($hoofdgroepen as $hoofdgroep_id => $data) { $hoofdgroep = $this->_CI->hoofdgroep->get( $hoofdgroep_id ); foreach ($hoofdgroep->get_hoofdthemas( $first ) as $hoofdthema) { $prio = round( $data['totaal'] / $data['aantal'] ); $ps->set_waarde( $hoofdgroep_id, $hoofdthema['hoofdthema']->id, $this->_converteer_itp_prioriteit( $prio ) ); } $first = false; } $ps->update_db( $this->_CI->db ); } } } <file_sep><?php function verify_data_members( array $varnames, $data, $beschrijving='verzoek' ) { foreach ($varnames as $varname) if (!isset( $data->$varname )) throw new DataSourceException( 'Missend(e) data element(en) in ' . $beschrijving . ', verwachtte op z\'n minst: ' . implode( ', ', $varnames ) ); } <file_sep>ALTER TABLE `rollen` ADD `factuur_flags` INT NOT NULL ; ALTER TABLE `rollen` CHANGE `factuur_flags` `factuur_flags` INT( 11 ) NOT NULL COMMENT 'M=1,P=2,T=4'; UPDATE rollen SET factuur_flags = (factuur_flags | 1) WHERE naam LIKE '%(%M%)'; UPDATE rollen SET factuur_flags = (factuur_flags | 2) WHERE naam LIKE '%(%P%)'; UPDATE rollen SET factuur_flags = (factuur_flags | 4) WHERE naam LIKE '%(%T%)'; ALTER TABLE `gebruikers` ADD `factuur_flags` INT NOT NULL ; ALTER TABLE `gebruikers` CHANGE `factuur_flags` `factuur_flags` INT( 11 ) NOT NULL COMMENT 'M=1,P=2,T=4'; <file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoanalyse')); ?> <? $handler = $ra->get_handler(); $effect_waarden = $handler->get_effect_values(); $kans_waarden = $handler->get_kans_values(); $test_niveaus = $handler->get_risico_shortnames(); ?> <form name="form" method="post"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8'), 'width' => '920px' ) ); ?> <h2>MATRIX: <?=htmlentities($matrix->naam, ENT_COMPAT, 'UTF-8')?></h2> <? $colspan = 7 + sizeof($ra->get_effecten()); ?> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <td colspan="<?=$colspan?>"><?=tg('main_tekst')?></td> </tr> <tr> <td colspan="2">&nbsp;</td> <? foreach ($effecten as $effect): ?> <td style="text-align:center" width="15"><img src="<?=site_url( '/content/verttext/'.rawurlencode(rawurlencode($effect->get_effect()).'%20['.rawurlencode(round($effect->get_waarde(),2))).'x]/8/000000/F3F4F6/250')?>"/></td> <? endforeach; ?> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/Gemiddelde/8/222222/dddddd/250')?>"/></td> <? if (!is_null($kans_waarden)): ?> <? foreach ($kans_waarden as $k => $waarden): ?> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/' . tgn('kanswaarde.'.$k) . '/8/000000/F3F4F6/250')?>"/></td> <? endforeach; ?> <? endif; ?> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/Kans/8/000000/F3F4F6/250')?>"/></td> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/' . $handler->get_naleefgedrag() . '/8/000000/ddeeee/250')?>"/></td> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/Risico/9/000000/F3F4F6/250')?>"/></td> <td style="text-align:center"><img src="<?=site_url( '/content/verttext/Prioriteit/9/000000/F3F4F6/250')?>"/></td> </tr> <? foreach ($hoofdgroepen as $hoofdgroep): ?> <tr> <td></td> <td style="width:100%"><?=$hoofdgroep->naam?></td> <? foreach ($effecten as $effect): ?> <? $val = $ra->get_waarde( $hoofdgroep->id, $effect->get_id() ); ?> <td style="text-align:center"> <? if (is_null($effect_waarden)): ?> <input type="text" value="<?=$val?>" name="waarde[<?=$hoofdgroep->id?>][<?=$effect->get_id()?>]" size="2" maxlength="2" <?=$val?'':'style="background-color:#cde3ff"'?> /> <? else: ?> <select name="waarde[<?=$hoofdgroep->id?>][<?=$effect->get_id()?>]" style="width:4em;"> <? foreach ($effect_waarden as $k => $v): ?> <option <?=$val == $k ? 'selected' : ''?> value="<?=$k?>"><?=($k ? $k . ' - ' . tgg('effectwaarde.' . $v) : '')?></option> <? endforeach; ?> </select> <? endif; ?> </td> <? endforeach; ?> <td style="padding: 0px 4px; text-align:center; background-color: #dddddd;"><?=number_format( $ra->get_gemiddelde( $hoofdgroep->id ), 1 )?></td> <? $origval = $ra->get_kans( $hoofdgroep->id ); $val = $handler->kans_data_to_kans_value($origval); ?> <? if (is_null($kans_waarden)): ?> <td style="text-align:center"> <input type="text" value="<?=$val?>" name="kans[<?=$hoofdgroep->id?>]" size="2" maxlength="2" <?=$val?'':'style="background-color:#cde3ff"'?> /> </td> <? else: ?> <? foreach ($kans_waarden as $k => $waarden): ?> <td style="text-align:center"> <? if (is_null( $waarden )): ?> <input type="text" value="<?=$origval[$k]?>" name="kans[<?=$hoofdgroep->id?>][<?=$k?>]" size="4" maxlength="4" <?=$origval[$k]?'':'style="background-color:#cde3ff"'?> /> <? else: ?> <select name="kans[<?=$hoofdgroep->id?>][<?=$k?>]" style="width:4em;"> <? foreach ($waarden as $wk => $v): ?> <option <?=number_format(floatval($origval[$k]), 5) == number_format(floatval($wk), 5) ? 'selected' : ''?> value="<?=$wk?>"> <?=($wk ? $wk . ' - ' . tgg('kanswaarde.' . $k . '.' . $v) : '')?> </option> <? endforeach; ?> </select> <? endif; ?> </td> <? endforeach; ?> <td style="text-align:center"> <?=number_format($val, 1);?> </td> <? endif; ?> <td style="padding: 0px 4px; text-align:center; background-color: #ddeeee"> <? if (isset( $kans_uit_naleefgedrag[$hoofdgroep->id] )): ?> <?=number_format( (100 * $kans_uit_naleefgedrag[$hoofdgroep->id]) / 20, 1); ?> <? else: ?> - <? endif; ?> </td> <td style="padding: 0px 4px; text-align:center"><?=number_format( $ra->get_risico( $hoofdgroep->id ), 1 )?></td> <td style="padding: 0px 4px; text-align:center"><?=$test_niveaus[$ra->get_prioriteit( $hoofdgroep->id )]?></td> </tr> <? endforeach; ?> <tr> <td colspan="<?=$colspan?>"> <input type="submit" name="action" value="<?=tgng('form.opslaan')?>"/> <?=htag('opslaan')?> </td> </tr> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view( 'beheer/risicoanalyse_buttons', array( 'prev' => 'beheer/risicoanalyse_effecten/' . $checklist->id . '/' . $matrix->id, 'next' => true, 'colspan' => $colspan, ) ); ?> </form> <? $this->load->view('elements/footer'); ?><file_sep><br/> <input type="button" value="<?=tgng('form.vorige')?>" <?=$prev===false?'disabled':''?> <?=$prev===false?'':'onclick="location.href=\''.site_url($prev).'\';"'?> /> <input type="submit" value="<?=tgng('form.volgende')?>" <?=$next===false?'disabled':''?> /> <?=htag('buttons')?> <file_sep><? require_once 'base.php'; class MatrixmapchecklistenResult extends BaseResult { public function MatrixmapchecklistenResult( &$arr ){ parent::BaseResult( 'matrixmapchecklisten', $arr ); } } class Matrixmapchecklisten extends BaseModel { public function Matrixmapchecklisten(){ parent::BaseModel( 'MatrixmapchecklistenResult', 'matrixmap_checklisten' ); } private static function process_id( $res ){ return is_object($res) ? $res->id : $res; } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_by_matrixmap_checklist( $matrixmap=FALSE, $checklist=FALSE, $assoc=FALSE ){ if( !$matrixmap && !$checklist ) return array(); $matrixmap_id = self::process_id( $matrixmap ); $checklist_id = self::process_id( $checklist ); $list = $matrixmap_id ? $this->db->where('matrixmap_id', $matrixmap_id ):NULL; $list = $checklist_id ? $this->db->where('checklist_id', $checklist_id ):NULL; $list = $this->db ->get( $this->_table ) ->result(); $result = array(); foreach( $list as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function delete_by_matrixmap( $matrixmap ){ $matrixmap_id = self::process_id( $matrixmap ); $result = $this->db ->where('matrixmap_id', $matrixmap_id ) ->delete( $this->_table ) ; return $result; } }// Class end <file_sep> <div id="header" class="menubar"> <form method="post"> <input type="hidden" name="page" value="afsluiten"> <input id="close" type="submit" value="afsluiten" hidden/><label for="close">Afsluiten</label>BRISToezicht - Opdrachten </form> </div> <div class="objects"> <p>Selecteer een opdracht:</p> <?$opdrachten = $objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['opdrachten'];?> <? if (sizeof( $opdrachten )):?> <p><b>Toezichtmoment: <?=$objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['naam']; ?></b></p> <?krsort($opdrachten);?> <? foreach ($opdrachten as $status =>$id_and_opdracht): ?> <p><b><?=$status?></b></p> <? foreach ($id_and_opdracht as $id =>$opdracht): ?> <form method="post"> <button type="submit" class="object_details"> <input type="hidden" name="page" value="opdracht"> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input type="hidden" name="bouwnummer_id" value="<?=$bouwnummer?>"> <input type="hidden" name="hoofdgroep_id" value="<?=$hoofdgroep?>"> <input type="hidden" name="opdracht_id" value="<?=$opdracht->id?>"> <span><b><?=htmlentities( $opdracht->opdracht_omschrijving, ENT_COMPAT, 'UTF-8' )?></b></span><br /> <?if (isset($objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['recheck'])):?><span class="alert">Hercontrole: <?=$objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'][$bouwnummer][$hoofdgroep]['recheck'];?></span><br /><?endif?> <span<?if (isset($opdracht->gereed_datum) && $opdracht->gereed_datum < date("Y-m-d")):?> class="alert"<?endif?>>Einddatum: <?if(isset($opdracht->gereed_datum)):?><?=$opdracht->gereed_datum;?><?endif?></span> </button> </form> <br /> <? endforeach; ?> <? endforeach; ?> <? else: ?> <div class="melding">Er zijn momenteel geen opdrachten voor u ingepland.</div> <? endif; ?> </div> <div id="footer" class="menubar"> <form method="post"> <input type="hidden" name="page" value="toezichtmomenten"> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input id="terug" type="submit" value="terug" hidden /> <label id="back" for="terug">Terug</label> </form> </div> <file_sep>-- draai php index.php /cli/checkutf8, en daarna met /1 om te fixen!<file_sep><? load_view( 'header.php' ); ?> <h2>Download verzoek mislukt.</h2> Helaas kunt u momenteel niet uw document geannoteerd downloaden. Onze excuses. <? load_view( 'footer.php' ); ?><file_sep><table cellspacing="0" cellpadding="0" border="0" class="bt-proj-matrix"> <? $count = count($btz_project_mappen); foreach( $btz_project_mappen as $i=>$pr_vraag): $status_onlcick = ''; switch( $pr_vraag->status ){ case 'P': $css_status='status-p';break; case 'S': $css_status='status-s';break; default: $css_status='status-d';$status_onlcick='addBristoezicht('.$pr_vraag->id.');'; } $no_btt_line= ($count-1) == $i ? 'no-bottom-line' : ''; $bw_onclick = $pr_vraag->bw!='' ? 'changeBW('.$pr_vraag->id.');':''; $bw_cusor = $pr_vraag->bw!='' ? 'cursor: pointer;' : ''; ?> <tr> <td class="status <?=$css_status?>" onclick="<?=$status_onlcick?>"><?=$pr_vraag->status ?></td> <td class="vraag-naam"><?=$pr_vraag->naam ?></td> <td class="vraag-param bouw">5</td> <td class="vraag-param"><?=$pr_vraag->codekey ?></td> <td class="vraag-param bw" style="color:<?=$pr_vraag->bw_color ?>;<?=$bw_cusor ?>" onclick="<?=$bw_onclick ?>"><?=$pr_vraag->bw ?></td> </tr> <? endforeach; ?> </table> <file_sep><? $this->load->view('extern/header'); ?> <div class='loginpage'> <div class='logo'> <img src="<?=site_url('/files/images/logo-transparent.png')?>" /> </div> <div class='main'> <div class='login'> <? $class = '' ; $message = ''; if ( isset($information )): $class = 'information'; $message=$information; elseif ( isset($error)): $class = 'error'; $message=$error; endif; ?> <div<? if ($class): ?> class="<?=$class?>"<?endif;?>> <span><?=$message; ?></span> </div><br/> <?if (!isset($information)):?> <form method="post" class="login-form"> <input type="hidden" name="post_login_location" value="<?=$post_login_location?>"> <? if ( isset($token )): ?> <? if ( isset($token_is_valid ) && $token_is_valid == true): ?> <input type="text" name="email" placeholder="<?=tg('mail')?>:"><br> <input type="<PASSWORD>" name="password" placeholder="<?=tg('newpassword')?>:"><br> <input type="password" name="new_password" placeholder="<?=tg('newpasswordconfirm')?>:"><br> <input type="hidden" name="token" value="<?=$token?>"> <button value="setpassword"><?=tg('setpassword')?></button> <? endif; ?> <? else: ?> <input type="text" name="email" placeholder="<?=tg('mail')?>:"><br> <input type="password" name="password" placeholder="<?=tg('password')?>:"><br> <button name="login" type="submit" value="login"><?=tg('login')?></button><button name="pwdreset" value="resetpwd" title="Reset Password">?</button><!--<input type="checkbox" title="<?//=tg('stayloggedin')?>">--> <? endif; ?> </form> <?endif?> </div> </div> </div> <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('checklistwizard.checklist.gedeeltelijk-actief', 'gedeeltelijk actief', '2013-09-09 19:19:42', 0), ('checklistwizard.opdrachten', 'Opdrachten', '2013-09-09 14:36:24', 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('intro.index::melding', 'Melding', '2013-09-10 20:37:28', 0), ('intro.index::datum', 'Datum', '2013-09-10 20:37:24', 0); <file_sep><? require_once 'base.php'; class MatrixmappingResult extends BaseResult { public function MatrixmappingResult( &$arr ){ parent::BaseResult( 'matrixmapping', $arr ); } public function save_btmatrix_map($btMatrixId){ $this->get_model()->save((object)array('id'=>$this->id,'bt_matrix_id'=>$btMatrixId)); } public function cancel_map(){ $CI = get_instance(); $CI->load->model( 'matrixmapchecklisten' ); return $CI->matrixmapchecklisten->delete_by_matrixmap( $this->id ); } public function getRisicoprofielen(){ $CI = get_instance(); $CI->load->model( 'colectivematrix' ); if (!$bt_collective_matrix = $CI->colectivematrix->get( $this->bt_matrix_id )) throw new Exception( 'Ongeldig collective matrix ID'); $CI->load->model( 'artikelvraagmap' ); $profiles = $CI->artikelvraagmap->get_risicoprofilen_list_map_by_matrix( $this->id ); foreach( $profiles as &$profile ){ $bt_profiel = $bt_collective_matrix->getRisicoprofiel( $profile->bt_riskprofiel_id ); $profile->naam = $this->naam.' - '.$bt_profiel['naam']; } return $profiles; } public function getArticelVraagMap( $assoc=FALSE ){ $list = array(); $this->_CI->load->model( 'artikelvraagmap' ); $list = $this->_CI->artikelvraagmap->get_artikel_vraag_mappingen($this->id); return $list; } } class Matrixmapping extends BaseModel { public function Matrixmapping(){ parent::BaseModel( 'MatrixmappingResult', 'matrix_mappingen' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_model(){ $class = $this->_model_class; $inst = new $class($arr); return $inst; } public function add( $naam, $klantId ){ $data = array( 'naam' => $naam, 'klant_id' => $klantId ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function get_dmms( $klantId, $isFreeOnly=FALSE, $assoc=FALSE ){ $list = $this->db ->where('klant_id', $klantId ); $list = ( $isFreeOnly ) ? $this->db->where('NOT EXISTS(SELECT * FROM `risicoprofiel_mappingen` WHERE `risicoprofiel_mappingen`.`dmm_id`='.$this->_table.'.`id`)',NULL, FALSE) : $list; $list = $this->db ->order_by('naam') ->get( $this->_table ) ->result(); $result = array(); foreach( $list as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } }// Class end <file_sep><?php // categorie grafiek define( 'GRAFIEKCATEGORIE_BESTUURLIJKE_INFORMATIE', 'Politieke en bestuurlijke informatie' ); define( 'GRAFIEKCATEGORIE_BEDRIJFSVOERING_INFORMATIE', 'Bedrijfsvoering informatie' ); // soort grafiek, is het er eentje, een per geselecteerde checklistgroep, of een per geselecteerde checklist zelfs? define( 'GRAFIEKSOORT_ENKEL', 1 ); define( 'GRAFIEKSOORT_PER_CHECKLISTGROEP', 2 ); define( 'GRAFIEKSOORT_PER_CHECKLIST', 3 ); // politieke en bestuurlijke informatie define( 'GRAFIEKTYPE_AANTALLEN_PER_CHECKLISTGROEP', 1 ); define( 'GRAFIEKTYPE_STATUS_PER_CHECKLISTGROEP', 2 ); define( 'GRAFIEKTYPE_STATUS_PER_CHECKLIST', 3 ); define( 'GRAFIEKTYPE_AANTAL_BEZOEKEN', 4 ); define( 'GRAFIEKTYPE_AANTAL_BEZOEKEN_PER_CHECKLISTGROEP', 5 ); define( 'GRAFIEKTYPE_AANTAL_KEER_NIET_VOLDOET', 6 ); define( 'GRAFIEKTYPE_AANTAL_KEER_NIET_VOLDOET_PER_CHECKLISTGROEP', 7 ); define( 'GRAFIEKTYPE_PERCENTAGE_OVERTREDINGEN', 8 ); define( 'GRAFIEKTYPE_NALEEFGEDRAG', 9 ); define( 'GRAFIEKTYPE_NALEEFGEDRAG_PER_CHECKLIST', 10 ); define( 'GRAFIEKTYPE_NALEEFGEDRAG_PER_CHECKLISTGROEP', 11 ); define( 'GRAFIEKTYPE_AFWIJKINGEN_PRIORITEIT', 12 ); define( 'GRAFIEKTYPE_AFWIJKINGEN_PRIORITEIT_PERCENTAGE', 13 ); define( 'GRAFIEKTYPE_AFWIJKINGEN_PRIORITEIT_PER_CHECKLISTGROEP', 14 ); define( 'GRAFIEKTYPE_TIJDSBESTEDING', 15 ); define( 'GRAFIEKTYPE_TIJDSBESTEDING_PER_CHECKLISTGROEP', 16 ); define( 'GRAFIEKTYPE_WAARDEOORDELEN', 17 ); define( 'GRAFIEKTYPE_WAARDEOORDELEN_PER_CHECKLISTGROEP', 18 ); // bedrijfsvoeringinformatie define( 'GRAFIEKTYPE_AANTAL_CHECKLISTEN_NAAR_STATUS_PER_CHECKLISTGROEP', 19 ); // define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER', 20 ); // define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLISTGROEP', 21 ); // define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLIST', 22 ); define( 'GRAFIEKTYPE_AFWIJKINGEN_PRIORITEIT_PER_MEDEWERKER', 23 ); define( 'GRAFIEKTYPE_WAARDEOORDELEN_PER_MEDEWERKER', 24 ); // +----------------> ja, 25 mist, is geschrapt define( 'GRAFIEKTYPE_TIJDSBESTEDING_PER_DOSSIER', 26 ); // / define( 'GRAFIEKTYPE_TIJDSBESTEDING_PER_DEELPLAN', 27 ); define( 'GRAFIEKTYPE_KENGETALLEN_TIJDSBESTEDING', 28 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER', 29 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_GEFILTERD', 30 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLISTGROEP', 31 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLISTGROEP_GEFILTERD', 32 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLIST', 33 ); define( 'GRAFIEKTYPE_DOSSIERS_PER_MEDEWERKER_PER_CHECKLIST_GEFILTERD', 34 ); class CI_Grafiek { private $_CI; static private $_grafiek_register = array(); public function __construct() { $this->_CI = get_instance(); define( 'TTF_DIR', APPPATH . 'libraries/grafieken/fonts/' ); $this->_CI->load->helper( 'jpgraph' ); $this->_CI->load->library( 'planningdata' ); } public function maak( GrafiekPeriode $periode, GrafiekAfmeting $afmeting, $grafiek_type, $theme='universal', $extra_data1=null, $extra_data2=null, $postcode=null ) { if (!isset( self::$_grafiek_register[$grafiek_type] )) throw new Exception( 'Grafiek type ' . $grafiek_type . ' onbekend.' ); $class_name = self::$_grafiek_register[$grafiek_type]['class_name']; $grafiek = new $class_name( $periode, $afmeting, $extra_data1, $extra_data2,$postcode); $grafiek->set_theme( $theme ); return $grafiek; } public function cache( $png_data ) { $path = APPPATH . '/../'; $filename = '/files/cache/grafieken/' . sha1( mt_rand() . microtime(true) ) . '.png'; if (!file_put_contents( $path . $filename, strval( $png_data ) )) throw new Exception( 'Schijffout bij aanmaken van grafiek.' ); return $filename; } static public function register_grafiek( $grafiek_type, $class_name, $grafiek_soort ) { self::$_grafiek_register[$grafiek_type] = array( 'class_name' => $class_name, 'soort' => $grafiek_soort, ); } public function get_grafiek_soort( $grafiek_type ) { if (!isset( self::$_grafiek_register[$grafiek_type] )) throw new Exception( 'Grafiek type ' . $grafiek_type . ' onbekend.' ); return self::$_grafiek_register[$grafiek_type]['soort']; } public function get_alle_grafiek_types() { $alle = array_keys( self::$_grafiek_register ); sort( $alle ); return $alle; } public function maak_grafieken( GrafiekPeriode $periode, GrafiekAfmeting $afmeting, array $checklistgroepen, array $checklisten, array $grafiek_types, $theme, $on_start_grafiek_callback=null, $postcode=null ) { $grafieken = array(); foreach (array_values( $grafiek_types ) as $i => $grafiek_type) { if (is_callable( $on_start_grafiek_callback )) { $grafiek = $this->maak( $periode, $afmeting, $grafiek_type ); call_user_func( $on_start_grafiek_callback, $grafiek, $i+1, sizeof($grafiek_types) ); unset( $grafiek ); } switch ($this->get_grafiek_soort( $grafiek_type )) { case GRAFIEKSOORT_ENKEL: $grafiek = $this->maak( $periode, $afmeting, $grafiek_type, $theme, $checklistgroepen, $checklisten,$postcode ); $png = $grafiek->generate(); if ($png) { $fn = $this->cache( $png ); $grafieken[] = array( 'title' => $grafiek->get_title(), 'origtitle' => $grafiek->get_title(), 'filename' => $fn, 'groep' => false, 'groeptag' => null, 'categorie' => $grafiek->get_categorie(), 'description'=>$grafiek->get_description(), ); } unset( $grafiek ); break; case GRAFIEKSOORT_PER_CHECKLISTGROEP: $c = 0; foreach ($checklistgroepen as $i => $checklistgroep) { $grafiek = $this->maak( $periode, $afmeting, $grafiek_type, $theme, $checklistgroep, $checklisten,$postcode ); $png = $grafiek->generate(); if ($png) { $fn = $this->cache( $png ); $grafieken[] = array( 'title' => $c++ ? null : $grafiek->get_groeptitle(), 'origtitle' => $grafiek->get_title(), 'filename' => $fn, 'groep' => true, 'groeptag' => 'groep' . $grafiek_type, 'categorie' => $grafiek->get_categorie(), 'description'=>$grafiek->get_description(), ); } unset( $grafiek ); } break; case GRAFIEKSOORT_PER_CHECKLIST: $c = 0; foreach ($checklisten as $i => $checklist) { $grafiek = $this->maak( $periode, $afmeting, $grafiek_type, $theme, $checklist,$postcode ); $png = $grafiek->generate(); if ($png) { $fn = $this->cache( $png ); $grafieken[] = array( 'title' => $c++ ? null : $grafiek->get_groeptitle(), 'origtitle' => $grafiek->get_title(), 'filename' => $fn, 'groep' => true, 'groeptag' => 'groep' . $grafiek_type, 'categorie' => $grafiek->get_categorie(), 'description'=>$grafiek->get_description(), ); } unset( $grafiek ); } break; } } return $grafieken; } } abstract class GrafiekBase { protected $_CI; private $_title; private $_groeptitle; private $_periode; // GrafiekPeriode object private $_afmeting; // GrafiekAfmeting object private $_categorie; // GRAFIEKCATEGORIE_xxx constante private $_theme; // jpgraph theme private $_description; public function __construct( $title, $groeptitle, $categorie, GrafiekPeriode $periode, GrafiekAfmeting $afmeting, $description ) { $this->_CI = get_instance(); $this->_title = $title; $this->_groeptitle = $groeptitle; $this->_periode = $periode; $this->_afmeting = $afmeting; $this->_categorie = $categorie; $this->_theme = null; $this->_description=$description; } public function get_description(){ return $this->_description; } public function get_title() { return $this->_title; } public function get_groeptitle() { return $this->_groeptitle; } public function get_periode() { return $this->_periode; } public function get_afmeting() { return $this->_afmeting; } public function get_categorie() { return $this->_categorie; } public function get_theme() { return $this->_theme; } protected function _get_theme() { if (!$this->_theme) return new GreenTheme; else { $classname = $this->_theme . 'theme'; return new $classname; // Jpgraph Classes! } } public function set_theme( $theme ) { $this->_theme = $theme; } protected function _stroke( Graph $graph ) { ob_start(); try { $graph->Stroke(); header( 'Content-Type: text/html' ); $png = ob_get_clean(); // NOTE: unset graph image, cleaning up ALOT OF MEMORY // NOTE: remove this if it ever causes problems! unset( $graph->img ); } catch (Exception $e) { ob_end_clean(); header( 'Content-Type: text/html' ); throw new Exception( 'Grafiek fout: ' . $e->getMessage() ); } return $png; } abstract public function generate(); } abstract class GrafiekSimpel extends GrafiekBase { protected $_values; protected $_legend; /** Initializes simple pie 3d grafiek by loading values, which are * key->value pairs. The $legend array must be a key->legend array, * with exactly the same keys present as in $values. */ public function initialize( array $values, array $legend ) { $this->_values = $values; $this->_legend = $legend; } public function check_legend_width(array $legends){ unset($count); $count=3; foreach ($legends as $legend){ if(strlen($legend)>=55){ $count=2; } else if (strlen($legend)>=70){ $count=1; } } return $count; } /** Overridable function to modify a graph before it gets stroked. */ public function alter_graph( $graph ) { } /** Overridable function to modify a plot before it gets added to the graph. */ public function alter_plot( $plot ) { } } class GrafiekSimpelPie3D extends GrafiekSimpel { public function generate() { // new graph $count_column=$this->check_legend_width($this->_legend); if(count($this->_legend)>24){ $new_height=(count($this->_legend)/$count_column)*18; } else $new_height=0; $graph = new PieGraph( $this->get_afmeting()->get_width(), $this->get_afmeting()->get_height()+$new_height ); $graph->SetTheme($this->_get_theme()); $graph->SetBox( false ); $graph->title->Set( $this->get_title() ); // add plot $p1 = new PiePlot3D( $this->_values ); $x = $y = 0; if (($this->_get_theme() instanceof UniversalTheme) || ($this->_get_theme() instanceof AquaTheme) || ($this->_get_theme() instanceof PastelTheme) || ($this->_get_theme() instanceof VividTheme) || false) { $x = 0.5; $y = 0.42; } else { $x = 0.3; $y = 0.5; } if (strpos( $this->get_title(), "\n" ) !== false) { $p1->SetSize( 0.45 ); $y += 0.03; } else $p1->SetSize( 0.5 ); $p1->SetCenter( $x, $y ); if(count($this->_legend)>24){ $p1->SetSize(370); $p1->posy=320; //$p1->SetCenter( 0.5, 0.01); } //d(round($new_height/$this->get_afmeting()->get_height(),1)); $p1->SetLegends( $this->_legend ); $this->alter_plot( $p1 ); $graph->Add( $p1 ); // set fonts $graph->title->SetFont( FF_ARIAL, FS_BOLD, 16 ); $graph->legend->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $p1->value->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $graph->SetMargin(100, 100, 100, 100); $graph->legend->SetPos(0.5,0.99,'center','bottom'); $graph->legend->SetColumns($count_column); // set legend frame $graph->legend->SetFrameWeight(1); // stroke! $this->alter_graph( $graph ); return $this->_stroke( $graph ); } } class GrafiekSimpelBar extends GrafiekSimpel // meerdere plots zodat je een legende kan hebben { public function generate() { // new graph $graph = new Graph( $this->get_afmeting()->get_width(), $this->get_afmeting()->get_height() ); $graph->SetScale( "textlin" ); $graph->SetTheme($this->_get_theme()); $graph->SetBox( false ); $graph->SetMargin( 40, 20, 20, 20 ); $graph->title->Set( $this->get_title() ); $graph->yaxis->scale->SetGrace( 30 ); $graph->xaxis->SetLabelAngle( 25 ); $graph->legend->SetPos(0.5,0.99,'center','bottom'); $graph->legend->SetColumns(3); $graph->yaxis->HideTicks(false,false); $graph->xaxis->HideTicks(true,true); $graph->xaxis->HideLabels(true); // add plot $plots = array(); foreach ($this->_values as $i => $value) { $p1 = new BarPlot( array( $value ) ); $p1->value->Show(); $p1->value->SetFormat('%d'); $p1->value->SetFont( FF_ARIAL, FS_NORMAL, 8 ); $p1->SetLegend( $this->_legend[$i] ); $this->alter_plot( $p1 ); $plots[] = $p1; } $gbplot = new GroupBarPlot( $plots ); $graph->Add( $gbplot ); $count_column=$this->check_legend_width($this->_legend); $graph->legend->SetColumns($count_column); // set fonts $graph->title->SetFont( FF_ARIAL, FS_BOLD, 16 ); $graph->yaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $graph->xaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); // set legend frame $graph->legend->SetFrameWeight(1); // stroke! $this->alter_graph( $graph ); return $this->_stroke( $graph ); } } class GrafiekSimpelBar2 extends GrafiekSimpel // een plot, echt simpele bar grafiek { public function generate() { // new graph $graph = new Graph( $this->get_afmeting()->get_width(), $this->get_afmeting()->get_height() ); $graph->SetScale( "textlin" ); $graph->SetTheme($this->_get_theme()); $graph->SetBox( false ); $graph->SetMargin( 40, 20, 20, 20 ); $graph->title->Set( $this->get_title() ); $graph->yaxis->scale->SetGrace( 30 ); $graph->xaxis->SetLabelAngle( 0 ); $graph->legend->SetPos(0.5,0.99,'center','bottom'); $graph->legend->SetColumns(3); $graph->yaxis->HideTicks(false,false); $graph->xaxis->HideTicks(false, false); $graph->xaxis->HideLabels(false); $graph->xaxis->SetTickLabels( $this->_legend ); // add plot $p1 = new BarPlot( $this->_values ); $p1->value->Show(); $p1->value->SetFormat('%d'); $p1->value->SetFont( FF_ARIAL, FS_NORMAL, 8 ); $this->alter_plot( $p1 ); $graph->Add( $p1 ); // set fonts $graph->title->SetFont( FF_ARIAL, FS_BOLD, 16 ); $graph->yaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $graph->xaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $count_column=$this->check_legend_width($this->_legend); $graph->legend->SetColumns($count_column); // set legend frame $graph->legend->SetFrameWeight(1); // stroke! $this->alter_graph( $graph ); return $this->_stroke( $graph ); } } abstract class GrafiekMultiBar extends GrafiekSimpel { protected $_series; public function initialize( array $values, array $legend, array $series ) { parent::initialize( $values, $legend ); $this->_series = $series; } public function generate() { // Create the graph. These two calls are always required $graph = new Graph( $this->get_afmeting()->get_width(), $this->get_afmeting()->get_height() ); $graph->SetScale("textlin"); $graph->SetTheme($this->_get_theme()); $graph->SetBox(false); $graph->yaxis->scale->SetGrace( 30 ); $graph->xaxis->SetLabelAngle( 25 ); $graph->legend->SetPos(0.5,0.99,'center','bottom'); $graph->legend->SetColumns(3); $graph->ygrid->SetFill(false); $graph->xaxis->SetTickLabels( $this->_legend ); $graph->yaxis->HideLine(false); $graph->yaxis->HideTicks(false,false); // Create the bar plots $plots = array(); foreach ($this->_series as $serie => $serienaam) { $plots[$serie] = new BarPlot($this->_values[$serie]); $plots[$serie]->SetLegend( $serienaam ); $this->alter_plot( $plots[$serie] ); } // Create the grouped bar plot $gbplot = new GroupBarPlot(array_values( $plots )); $graph->Add($gbplot); $graph->title->Set( $this->get_title() ); // set fonts $graph->title->SetFont( FF_ARIAL, FS_BOLD, 16 ); $graph->yaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $graph->xaxis->SetFont( FF_ARIAL, FS_NORMAL, 7 ); $count_column=$this->check_legend_width($this->_legend); $graph->legend->SetColumns($count_column); // set legend frame $graph->legend->SetFrameWeight(1); // stroke! $this->alter_graph( $graph ); return $this->_stroke( $graph ); } } class GrafiekPeriode { private $_van; private $_tot; public function __construct( $van, $tot ) { $this->_van = strtotime( $van ); $this->_tot = strtotime( $tot ); if ($this->_tot < $this->_van) { $swap = $this->_van; $this->_van = $this->_tot; $this->_tot = $swap; } } public function get_van() { return $this->_van; } public function get_tot() { return $this->_tot; } public function get_van_string() { return date('Y-m-d', $this->_van ); } public function get_tot_string() { return date('Y-m-d', $this->_tot ); } public function get_human_description() { return date('d-m-Y', $this->_van) . ' - ' . date('d-m-Y', $this->_tot); } public function get_db_between( $db_expr ) { return get_db_between($db_expr, $this->get_van_string(), $this->get_tot_string()); } } class GrafiekAfmeting { private $_w; private $_h; public function __construct( $w, $h ) { $this->_w = $w; $this->_h = $h; } public function get_width() { return $this->_w; } public function get_height() { return $this->_h; } } require_once( APPPATH . '/libraries/grafieken/tools.php' ); foreach (scandir( APPPATH . '/libraries/grafieken' ) as $file) if (preg_match( '/\.php$/i', $file )) require_once( APPPATH . '/libraries/grafieken/' . $file ); <file_sep><?php class CI_PlanningData { private $_CI; private $_deelplan_checklistgroep_planning = null; private $_deelplan_checklist_planning = null; private $_dossier_planning = null; public function __construct() { $this->_CI = get_instance(); } public function get_deelplan_checklistgroep_planning() { if (is_null( $this->_deelplan_checklistgroep_planning )) { $res = $this->_CI->db->query( 'SELECT * FROM deelplan_checklistgroep_plnng' ); $this->_deelplan_checklistgroep_planning = array(); foreach ($res->result() as $row) { if (!isset( $this->_deelplan_checklistgroep_planning[ $row->deelplan_id ] )) $this->_deelplan_checklistgroep_planning[ $row->deelplan_id ] = array(); $this->_deelplan_checklistgroep_planning[ $row->deelplan_id ][ $row->checklist_groep_id ] = $row->eerste_hercontrole_datum; } $res->free_result(); } return $this->_deelplan_checklistgroep_planning; } public function get_deelplan_checklist_planning() { if (is_null( $this->_deelplan_checklist_planning )) { $res = $this->_CI->db->query( 'SELECT * FROM deelplan_checklist_planning' ); $this->_deelplan_checklist_planning = array(); foreach ($res->result() as $row) { if (!isset( $this->_deelplan_checklist_planning[ $row->deelplan_id ] )) $this->_deelplan_checklist_planning[ $row->deelplan_id ] = array(); $this->_deelplan_checklist_planning[ $row->deelplan_id ][ $row->checklist_id ] = $row->eerste_hercontrole_datum; } $res->free_result(); } return $this->_deelplan_checklist_planning; } public function get_dossier_planning() { if (is_null( $this->_dossier_planning )) { $res = $this->_CI->db->query( 'SELECT * FROM dossier_planning' ); $this->_dossier_planning = array(); foreach ($res->result() as $row) $this->_dossier_planning[ $row->dossier_id ] = $row->gepland_datum; $res->free_result(); } return $this->_dossier_planning; } } <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_checklist_planning` ( `deelplan_id` int(11) NOT NULL, `checklist_id` int(11) DEFAULT NULL, `eerste_hercontrole_datum` date DEFAULT NULL, KEY `deelplan_id` (`deelplan_id`,`checklist_id`), KEY `checklist_id` (`checklist_id`), KEY `eerste_hercontrole_datum` (`eerste_hercontrole_datum`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `deelplan_checklist_planning` ADD CONSTRAINT `deelplan_checklist_planning_ibfk_2` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_checklist_planning_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>BRISToezicht.Toets.Vraag = { huidigOnderwerp: null, huidigeVraag: null, selectTime: null, dirty: false, initialize: function() { // init vorige/volgende references in vragen en onderwerpen function iterate(data) { var arr = []; var new_obj={} for (var prop in data) { if (data.hasOwnProperty(prop)) { var obj = {}; obj[prop] = data[prop]; obj.tempSortName = data[prop].order; arr.push(obj); } } arr.sort(function(a, b) { var at = a.tempSortName, bt = b.tempSortName; return at > bt ? 1 : ( at < bt ? -1 : 0 ); }); for (var i = 0, l = arr.length; i < l; i++) { var obj = arr[i]; delete obj.tempSortName; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var id = prop; //gets the obj "index" (id?) } } var item = obj[id]; //do stuff with item new_obj=arr; } return arr; } var previousVraag = null; var laatsteVraagVorigeHoofdgroep = null; var vorigOnderwerp = null; var toets_data_new_array=iterate(BRISToezicht.Toets.data.onderwerpen); //for (var i in BRISToezicht.Toets.data.onderwerpen) { for (var k in toets_data_new_array){ for (var i in toets_data_new_array[k]){ i=i; } var o = BRISToezicht.Toets.data.onderwerpen[i]; o.previousVraag = laatsteVraagVorigeHoofdgroep; // wordt laatste vraag van vorige hoofdgroep o.nextVraag = null; // wordt eerste vraag van volgende hoofdgroep var vraag_order_array=iterate(o.vragen); for (var p in vraag_order_array){ for (var j in vraag_order_array[p]){ j=j; } //for (var j in o.vragen) { var v = o.vragen[j]; if (vorigOnderwerp) { vorigOnderwerp.nextVraag = v; vorigOnderwerp = null; } v.nextVraag = null; v.previousVraag = previousVraag; if (previousVraag) previousVraag.nextVraag = v; previousVraag = v; laatsteVraagVorigeHoofdgroep = v; } vorigOnderwerp = o; } // select initiele vraag if (BRISToezicht.Toets.data.initiele_vraag) { var v = BRISToezicht.Toets.data.initiele_vraag; BRISToezicht.Toets.Vraag.select( v.onderwerp_id, v.vraag_id ); } // handle clicking a waardeoordeel button $('.waardeoordeel td:not(.geenwaardeoordeel)').click( function(){ if (BRISToezicht.Toets.readonlyMode) return; // haal waardeoordeel op var nlaf_status = $(this).attr( 'id' ).replace( /nlaf_Status-/, '' ); //if (!nlaf_status || $(this).hasClass( 'leeg')) //return; // maak onderscheid hier in hoe we geselecteerde vragen en onderwerpen // afhandelen. var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraagData) { // als vraag gelocked is (verantwoording + toelichting), dan nu vragen of er // een nieuwe moet worden toegevoegd if (vraagData.verantwoording_locked) { if (!confirm( 'Dit waardeoordeel staat vast, nu een nieuwe verantwoording aanmaken?' )) return; BRISToezicht.Toets.Verantwoording.addNieuw(); } // update internally BRISToezicht.Toets.Vraag.updateHuidige( nlaf_status ); } // update visually before we continue $(this).parents('table.waardeoordeel').find('td').removeClass( 'selected' ); $(this).addClass( 'selected' ); if (!vraagData) { var onderwerpData = BRISToezicht.Toets.Vraag.getHuidigeOnderwerpData(); if (onderwerpData) { if (confirm( 'Nu dit waardeoordeel zonder toelichting opslaan bij het huidige onderwerp?\n' + '\n' + 'Klik OK om nu op te slaan zonder toelichting.\n' + 'Klik Annuleren om nu eerst een toelichting in te voeren.' )) { // opslaan! BRISToezicht.Toets.Vraag.handleOnderwerpVerantwoordingEnWaardeoordeel( true ); } else { $('#nlaf_VerantwoordingsTekst').trigger( 'click' ); } } } }); // handle setting an invulvraag value $('#nlaf_InvulVraagWaarde').change(function(){ var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraagData.verantwoording_locked) { var newValue = $(this).val(); if (!confirm( 'Dit waardeoordeel staat vast, nu een nieuwe verantwoording aanmaken?' )) { $(this).val( vraagData.inputs.status.value ); return; } BRISToezicht.Toets.Verantwoording.addNieuw(); $(this).val( newValue ); // reset by addNieuw (voor meerkeuzevragen heel normaal, dus herstel hier) } BRISToezicht.Toets.Vraag.updateHuidigeInvulvraag( $(this).val(), vraagData ? 0 : 1 ); }); // set startup percentage this.updateProgress(); }, initializeOnderwerpVoortgang: function() { // init voortgang for (var h in BRISToezicht.Toets.data.onderwerpen) { var onderwerp = BRISToezicht.Toets.data.onderwerpen[h]; if (typeof( onderwerp ) == 'object') { onderwerp.initialize(); this.updateOnderwerpState( h /* is de id van het onderwerp */ ); } } }, initializeVraagVoortgang: function( onderwerp_id ) { // init voortgang var onderwerp = BRISToezicht.Toets.data.onderwerpen[onderwerp_id]; if (typeof( onderwerp ) == 'object') { for (var j in onderwerp.vragen) { var vraag = onderwerp.vragen[j]; if (typeof( vraag ) == 'object') { vraag.initialize(); // build human readably text var val = vraag.inputs.status.value; if (val) { var groepsantwoord = parseInt( vraag.inputs.groepsantwoord.value ); vraag.samenvattingSpan.html( groepsantwoord ? '<span class="groepsantwoord">Waardeoordeel op onderwerpniveau</span>' : this.getStatusVoorVraag( vraag ).tekst ); } } } } }, findOnderwerpIdByVraagId: function( vraag_id ) { for (var i in BRISToezicht.Toets.data.onderwerpen) { var o = BRISToezicht.Toets.data.onderwerpen[i]; for (var j in o.vragen) { var v = o.vragen[j]; if (v.vraag_id == vraag_id) return o.onderwerp_id; } } return null; }, createInputs: function( vraag_id, status, seconden, toelichting, toelichting_id, hercontrole_datum, groepsantwoord ) { return { status: this.createInput( 'vraag_' + vraag_id, 'hidden', status ? status : '' /* IE fix, otherwise status will have the string "null" as value! */ ), seconden: this.createInput( 'sec_' + vraag_id, 'hidden', seconden ), toelichting: this.createInput( 'toel_' + vraag_id, 'hidden', toelichting ), toelichting_id: this.createInput( 'toel_id_' + vraag_id, 'hidden', toelichting_id ), hercontrole_datum: this.createInput( 'hcd_' + vraag_id, 'hidden', hercontrole_datum ), groepsantwoord: this.createInput( 'ga_' + vraag_id, 'hidden', groepsantwoord ) }; }, createInput: function( name, type, value ) { var i = document.createElement( 'input' ); i.type = type; i.value = value; i.name = name; $('form')[0].appendChild( i ); return i; }, markDirty: function( dirty ) { this.dirty = dirty; BRISToezicht.DirtyStatus.updateState(); }, isDirty: function() { return this.dirty; }, getHuidigeOnderwerpData: function() { if (!this.huidigOnderwerp) return; var onderwerpData = BRISToezicht.Toets.data.onderwerpen[this.huidigOnderwerp]; onderwerpData.initialize(); return onderwerpData; }, getHuidigeVraagData: function() { if (!this.huidigeVraag) return; var onderwerpData = this.getHuidigeOnderwerpData(); var vraagData = onderwerpData.vragen[this.huidigeVraag]; vraagData.initialize(); return vraagData; }, getVraagData: function( onderwerp_id, vraag_id ) { var onderwerpData = BRISToezicht.Toets.data.onderwerpen[onderwerp_id]; if (!onderwerpData) return; var vraagData = onderwerpData.vragen[vraag_id]; if (!vraagData) return; vraagData.initialize(); return vraagData; }, gotoPrevious: function() { // haal vorige vraag uit huidige vraag, of huidige onderwerp var vraag = null; var vraagData = this.getHuidigeVraagData(); if (vraagData) { vraag = vraagData.previousVraag; } else { var onderwerpData = this.getHuidigeOnderwerpData(); if (onderwerpData) vraag = onderwerpData.previousVraag; } if (vraag) this.select( vraag.onderwerp_id, vraag.vraag_id ); }, gotoNext: function() { // haal vorige vraag uit huidige vraag, of huidige onderwerp var vraag = null; var vraagData = this.getHuidigeVraagData(); if (vraagData) { vraag = vraagData.nextVraag; } else { var onderwerpData = this.getHuidigeOnderwerpData(); if (onderwerpData) vraag = onderwerpData.nextVraag; } if (vraag) this.select( vraag.onderwerp_id, vraag.vraag_id ); }, updateHuidigeInvulvraag: function( new_val, groepsantwoord ) { // things have changed, be sure to save em when possible this.markDirty( true ); // build human readably text var curTime = BRISToezicht.Tools.getUnixTimestamp(); // maak lijst van alle vragen die we gaan bewerken // dat is er ofwel 1tje (de huidige), of alle vragen // binnen het huidige geselecteerde onderwerp var vraagData = this.getHuidigeVraagData(); var alleVragen = []; if (vraagData) alleVragen.push( vraagData ); else { var onderwerpData = this.getHuidigeOnderwerpData(); if (!onderwerpData) return; for (var i in onderwerpData.vragen) // is een object, geen array alleVragen.push( onderwerpData.vragen[i] ); } // update nu alle vragen for (var i=0; i<alleVragen.length; ++i) { var vraagData = alleVragen[i]; vraagData.inputs.status.value = new_val; vraagData.inputs.seconden.value = parseInt( vraagData.inputs.seconden.value ) + (curTime - this.selectTime); vraagData.inputs.groepsantwoord.value = groepsantwoord ? 1 : 0; vraagData.statusImage.attr( 'src', '/files/images/nlaf/status-groen.png' ); vraagData.statusImage.parents('[vraag_id]').attr( 'filter', 'groen' ); vraagData.samenvattingSpan.html( groepsantwoord ? '<span class="groepsantwoord">Ingevoerd op onderwerpniveau</span>' : this.getStatusVoorVraag( vraagData ).tekst ); } // update time this.selectTime = curTime; // update hoofdgroep this.updateOnderwerpState( this.huidigOnderwerp ); // update progress this.updateProgress(); // update kies-verantwoording-state BRISToezicht.Toets.Verantwoording.updatePresetVerantwoordingen(); }, updateHuidige: function( new_val, groepsantwoord ) { // things have changed, be sure to save em when possible this.markDirty( true ); // build human readably text var curTime = BRISToezicht.Tools.getUnixTimestamp(); // is there a question selected? var vraagData = this.getHuidigeVraagData(); if (!vraagData) return; // update vraag vraagData.inputs.status.value = new_val!='in_bewerking' ? new_val : ''; vraagData.inputs.seconden.value = parseInt( vraagData.inputs.seconden.value ) + (curTime - this.selectTime); vraagData.inputs.groepsantwoord.value = groepsantwoord ? 1 : 0; var data = this.getStatusVoorVraag( vraagData ); var kleur = BRISToezicht.Toets.Status.waardeKleur[ data.waarde ]; vraagData.statusImage.attr( 'src', '/files/images/nlaf/status-' + kleur + '.png' ); vraagData.statusImage.parents('[vraag_id]').attr( 'filter', kleur ); vraagData.samenvattingSpan.html( groepsantwoord ? '<span class="groepsantwoord">Waardeoordeel op onderwerpniveau</span>' : data.tekst ); // update time this.selectTime = curTime; // update hoofdgroep this.updateOnderwerpState( this.huidigOnderwerp ); // update progress this.updateProgress(); // update kies-verantwoording-state BRISToezicht.Toets.Verantwoording.updatePresetVerantwoordingen(); }, getStatusVoorVraag: function( vraagData, niet_default_meenemen ) { var status = vraagData.inputs.status.value; switch (vraagData.type) { case 'meerkeuzevraag': var realStatus = status; if (!status && !niet_default_meenemen) status = vraagData.button_config.standaard; var coord = status ? BRISToezicht.Toets.ButtonConfig.statusNaarPositie( status ) : null; if (!status || (niet_default_meenemen && status == vraagData.button_config.standaard && vraagData.button_config.is_leeg[coord.x][coord.y])) { return {tekst: 'Nog niet ingevoerd', waarde: 100}; } else { // bepaal kleur voor het huidige antwoord var kleur = vraagData.button_config.kleur[coord.x][coord.y]; switch (kleur) { case 'rood': return {tekst: 'Handhaven', waarde: 1}; case 'oranje': return {tekst: 'Nader onderzoek', waarde: 10}; case 'groen': return {tekst: 'Geen handhaving nodig', waarde: 1000}; } // als we hier komen, is er een antwoord gegeven dat in de huidige knoppen combi niet meer // geldig is return {tekst: 'Nog niet ingevoerd', waarde: 100}; } break; case 'invulvraag': if ((''+status).length) return {tekst: 'Geen handhaving nodig', waarde: 1000}; else return {tekst: 'Nog niet ingevoerd', waarde: 100}; break; default: throw 'getStatusVoorVraag: ongeldig vraag type: ' + vraagData.type; } }, updateProgress: function() { var total = 0; var done = 0; for (var h in BRISToezicht.Toets.data.onderwerpen) { var onderwerp = BRISToezicht.Toets.data.onderwerpen[h]; if (typeof( onderwerp ) == 'object') { for (var l in onderwerp.vragen) { var vraag = onderwerp.vragen[l]; if (typeof( vraag ) != 'function') { total++; if (vraag.type == 'invulvraag') { if (vraag.inputs.status.value) done++; } else if (vraag.type == 'meerkeuzevraag') { var status; // als er een status (antwoord) gezet is, dan deze gebruiken if (vraag.inputs.status.value) status = vraag.inputs.status.value; // anders de standaard waarde pakken voor dit veld else status = vraag.button_config.standaard; // controleer status waarde if (!status) // geen default, mag eigenlijk niet, maar niet op crashen! continue; if (!status.match( /^w(\d{2})s?/ )) throw 'Fout bij bepalen voortgang, status ' + status + ' niet geldig.'; // vervolgens van de gevonden status bepalen of deze moet worden meegeteld // of niet var x = RegExp.$1[0]; var y = RegExp.$1[1]; var is_leeg = vraag.button_config.is_leeg[x][y]; if (is_leeg == 0) done++; } else throw 'Onbekend vraag type: ' + vraag.type; } } } } var perc = total ? done / total : 0; var barwidth = 166; var totalpadding = 8; $('#nlaf_HeaderVoortgang .mid .mid').css( 'width', Math.round( barwidth * (perc * ((barwidth-totalpadding)/barwidth)) ) + 'px' ); $('#nlaf_HeaderVoortgangPerc').text( Math.round( 100 * perc ) + '%' ); }, updateOnderwerpState: function( onderwerp_id ) { var aantalLegeVragen = 0; var worstState = 1000; var statusTekst = ''; var onderwerp = BRISToezicht.Toets.data.onderwerpen[onderwerp_id]; for (var i in onderwerp.vragen) { if (typeof(onderwerp.vragen[i]) != 'function') { var vraagData = onderwerp.vragen[i]; var data = this.getStatusVoorVraag( vraagData, true /* niet default meenemen, maar in dat geval 100 teruggeven! */ ); if (data.waarde == 100) ++aantalLegeVragen; if (data.waarde > 0 && data.waarde <= worstState) { worstState = data.waarde; statusTekst = data.tekst; } } } // is het "ergste" wat er aan de hand is, dat er dingen moeten worden ingevuld? dan de hoofdgroep // als status meegeven dat er nog vragen te voldoen zijn (en dus overschrijven wat er hierboven // uit is gekomen.) if (worstState == 100) { if (aantalLegeVragen != 1) statusTekst = 'Nog ' + aantalLegeVragen + ' vragen te voldoen.'; else statusTekst = 'Nog 1 vraag te voldoen.'; } onderwerp.samenvattingSpan.text( statusTekst ); // update image var kleur = BRISToezicht.Toets.Status.waardeKleur[ worstState ]; onderwerp.statusImage[0].src = BRISToezicht.Toets.Status.waardeImage[worstState]; onderwerp.statusImage.parents('[onderwerp_id]').attr( 'filter', BRISToezicht.Toets.Status.waardeKleur[kleur] ); }, handleOnderwerpVerantwoordingEnWaardeoordeel: function( disable_checks ) { // als er uberhaupt geen onderwerp gezet is, hoeven we niks te doen var onderwerpData = this.getHuidigeOnderwerpData(); if (!onderwerpData) return false; var onderwerpNaam = onderwerpData.naam; // als er WEL een vraag gezet is, hoeven we ook niks te doen! var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraagData) return false; // haal data op, als er geen data is, hoeven we niks te doen var verantwoordingTekst = $('#nlaf_ToelichtingTextarea').val(); if (!disable_checks && !verantwoordingTekst) { alert( 'U heeft geen tekst ingevoerd.\n\nSelecteer uw beoordeling en vul een waardeoordeel (tekst) in. Pas dan kunt u deze opslaan voor alle vragen binnen het onderwerp ' + onderwerpNaam + '.' ); return false; } var status = $('.waardeoordeel td:not(.geenwaardeoordeel).selected').attr('id'); status = (''+status).replace( /nlaf_Status-/, '' ); if (!disable_checks && (!status || status == 'in_bewerking')) { alert( 'U heeft geen beoordeeling geselecteerd.\n\nSelecteer uw beoordeling en vul een waardeoordeel (tekst) in. Pas dan kunt u deze opslaan voor alle vragen binnen het onderwerp ' + onderwerpNaam + '.' ); return false; } // vraag gebruiker of hij dit echt wil zetten als nieuwe verantwoording voor alle vragen if (!disable_checks && !confirm( 'Door op OK te klikken wordt het huidige waardeoordeel inclusief de door u ingevoerde toelichting bij iedere vraag onder dit onderwerp overgenomen.' )) return false; // update alle vragen binnen dit onderwerp for (var i in onderwerpData.vragen) { if (typeof( onderwerpData.vragen[i] ) == 'object') { // init object state this.huidigOnderwerp = onderwerpData.onderwerp_id; this.huidigeVraag = onderwerpData.vragen[i].vraag_id; // zet nieuwe revisie BRISToezicht.Toets.Verantwoording.addNieuw(); // zet status BRISToezicht.Toets.Vraag.updateHuidige( status, 1 /* groepsantwoord */ ); // zet toelichting var text = verantwoordingTekst.search("Verantwoording op onderwerpniveau:"); if(text!=-1) var newVerantwoordingTekst=verantwoordingTekst; else newVerantwoordingTekst='Verantwoording op onderwerpniveau:\n\n' + verantwoordingTekst; $('#nlaf_ToelichtingTextarea').val( newVerantwoordingTekst ); BRISToezicht.Toets.Verantwoording.updateToelichting(); // lock huidige revisie onderwerpData.vragen[i].verantwoording_locked = true; } } // reset to original state this.huidigOnderwerp = onderwerpData.onderwerp_id; this.huidigeVraag = null; this.reselect(); this.zetWaardeoordeelVisueel( status ); return true; }, reselect: function() { this.select( this.huidigOnderwerp, this.huidigeVraag ); }, select: function( onderwerp_id, vraag_id ) { // alleen een onderwerp id, geen vraag id? // dan voordat we ook maar iets doen controleren of dit onderwerp allemaal dezelfde button configuratie(s) // heeft, zo ja dan mag het, zo nee dan niet if (onderwerp_id && !vraag_id) { var onderwerpData = BRISToezicht.Toets.data.onderwerpen[onderwerp_id]; var tag = null; for (var i in onderwerpData.vragen) { var vraag = onderwerpData.vragen[i]; if (typeof( vraag ) == 'function') continue; if (tag && vraag.button_config.tag == tag) continue; else if (!tag) tag = vraag.button_config.tag; else { showMessageBox({ type: 'warning', message: 'Dit onderwerp bevat vragen met verschillende soorten waardeoordeelmogelijkheden. Er kan daarom niet op onderwerpsniveau een waardeoordeel gegeven worden.', buttons: ['ok'] }); return false; } } } // store current time var curTime = BRISToezicht.Tools.getUnixTimestamp(); // unmark current vraag as current, update time if (this.huidigOnderwerp && this.huidigeVraag) { var onderwerpData = BRISToezicht.Toets.data.onderwerpen[this.huidigOnderwerp]; var vraagData = onderwerpData.vragen[this.huidigeVraag]; vraagData.inputs.seconden.value = parseInt( vraagData.inputs.seconden.value ) + (curTime - this.selectTime); } // update state this.huidigOnderwerp = onderwerp_id; this.huidigeVraag = vraag_id; this.selectTime = curTime; // set hoofdgroep var onderwerpData = this.getHuidigeOnderwerpData(); onderwerpData.initialize(); $('#nlaf_PrioVraagPanel .hoofdgroep').html( onderwerpData.naam ); // ga nu verder gebaseerd op de tweedeling dat er wel of niet een vraag geselecteerd is // (iig altijd een onderwerp!) if (this.huidigeVraag) { // zet prio var hoofdgroepData = BRISToezicht.Toets.data.hoofdgroepen[ onderwerpData.vragen[vraag_id].hoofdgroep_id ]; var prio = hoofdgroepData.hoofdgroep_prioriteit; $('#hoofgroepen_level').val(0); var matrixPrio = hoofdgroepData.matrix_test_niveau; $('#nlaf_PrioPanel .button').removeClass( 'selected disabled' ); $('#nlaf_PrioPanel .button.' + prio).addClass( 'selected' ); switch (matrixPrio) { case 'zeer_laag': break; case 'laag': $('#nlaf_PrioPanel .button.zeer_laag').addClass( 'disabled' ); break; case 'gemiddeld': $('#nlaf_PrioPanel .button.zeer_laag').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.laag').addClass( 'disabled' ); break; case 'hoog': $('#nlaf_PrioPanel .button.gemiddeld').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.zeer_laag').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.laag').addClass( 'disabled' ); break; case 'zeer_hoog': $('#nlaf_PrioPanel .button.hoog').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.gemiddeld').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.zeer_laag').addClass( 'disabled' ); $('#nlaf_PrioPanel .button.laag').addClass( 'disabled' ); break; } // zet vraag data var vraagData = onderwerpData.vragen[vraag_id]; vraagData.initialize(); // zet vraag tekst $('#nlaf_PrioVraagPanel .vraag').html( vraagData.tekst ); // zet verantwoording tekst op hoofdscherm en popup BRISToezicht.Toets.Verantwoording.setVerantwoordingsTekst( vraagData.inputs.toelichting.value ); // verander de "niet gecontroleerd" button op basis van de huidige waarde var status = vraagData.inputs.status.value; switch (vraagData.type) { case 'meerkeuzevraag': if (!status) status = vraagData.button_config.standaard; this.updateSteekproefButton( vraagData, status ); this.updateLegeButtons( vraagData, status ); // zet status this.zetWaardeoordeelVisueel( status ); break; case 'invulvraag': $('#nlaf_InvulVraagWaarde').val( status ); break; } // zet vraag geschiedenis $('.nlaf_ToelichtingButtons').html(''); var toelichtingNum = 1; for (var i=0; i<vraagData.vraaggeschiedenis.length; ++i) { var vg = vraagData.vraaggeschiedenis[i]; $('.nlaf_ToelichtingButtons').append( '<input type="button" class="versie" toelichting_index="' + toelichtingNum + '" value="' + toelichtingNum + '" title="Toelichting van ' + vg.datum + '" />' ); ++toelichtingNum; }; $('.nlaf_ToelichtingButtons').append( '<input type="button" class="versie" toelichting_index="' + toelichtingNum + '" value="' + toelichtingNum + '" title="Toelichting van ' + vraagData.last_updated_at + '" disabled />' ); // enable/disable waardeoordeel controls if (BRISToezicht.Toets.readonlyMode || vraagData.verantwoording_locked) { $('#nlaf_VoegToeToelichting').attr( 'disabled', 'disabled' ); } else { $('#nlaf_VoegToeToelichting').removeAttr( 'disabled' ); } // enable vorige & volgende vraag knoppen if applicable if (vraagData.previousVraag) $('#nlaf_VorigeVraag div').removeClass( 'disabled' ); else $('#nlaf_VorigeVraag div').addClass( 'disabled' ); if (vraagData.nextVraag) $('#nlaf_VolgendeVraag div').removeClass( 'disabled' ); else $('#nlaf_VolgendeVraag div').addClass( 'disabled' ); // show & set aantallen labels var setAantalLabel = function( o, aantal ) { o[ aantal ? 'show' : 'hide' ](); o.text( aantal ); }; var aandachtspunten = this.filterAandachtspunten( vraagData ); var richtlijnen = this.filterRichtlijnen( vraagData ); var grondslagen = this.filterGrondslagen( vraagData ); var aantalRichtlijnen = richtlijnen.length; var aantalGrondslagen = grondslagen.length; var aantalAandachtspunten = aandachtspunten.length; var totaalAantalAandachtspunten = aantalRichtlijnen + aantalGrondslagen + aantalAandachtspunten; var totaalAantalFotos = BRISToezicht.Tools.getNumProps( vraagData.deelplanuploads ); var totaalAantalBescheiden = BRISToezicht.Tools.getNumProps( vraagData.vraagbescheiden ); setAantalLabel( $('#nlaf_AantalRichtlijnen'), aantalRichtlijnen ); setAantalLabel( $('#nlaf_AantalGrondslagen'), aantalGrondslagen ); setAantalLabel( $('#nlaf_AantalAandachtspunten'), aantalAandachtspunten ); setAantalLabel( $('#nlaf_TotaalAantalAandachtspunten'), totaalAantalAandachtspunten ); setAantalLabel( $('#nlaf_TotaalAantalFotos'), totaalAantalFotos ); setAantalLabel( $('#nlaf_TotaalAantalBescheiden'), totaalAantalBescheiden ); // zet grondslagen var base = $('.subtabcontents[tab-name=grondslagen]'); base.html('<img src="/files/images/nlaf/aandachtspunten-background.png">'); for (var i in grondslagen) { var grondslag = grondslagen[i]; if (typeof(grondslag) != 'function') { var beschrijving = grondslag.grondslag + ' '; if ((''+grondslag.display_hoofdstuk).length) beschrijving += 'hst. ' + grondslag.display_hoofdstuk + ' '; if ((''+grondslag.display_afdeling).length) beschrijving += 'afd. ' + grondslag.display_afdeling + ' '; if ((''+grondslag.display_paragraaf).length) beschrijving += 'par. ' + grondslag.display_paragraaf + ' '; if ((''+grondslag.display_artikel).length) beschrijving += 'art. ' + grondslag.display_artikel + ' '; if ((''+grondslag.display_lid).length) beschrijving += 'lid ' + grondslag.display_lid + ' '; var header = $('<h1>').appendTo( base ).text( beschrijving + ' ' ); if (grondslag.bw_url||false) { $('<div>') .addClass( 'briswarenhuis-link' ) .append( $('<a>') .attr('target','_blank') .attr('href',grondslag.bw_url) .text('BRISwarenhuis') ) .appendTo( header ); } var lines = (typeof(grondslag.tekst) == 'string' && grondslag.tekst.length) ? grondslag.tekst.split( '\n' ) : ['Tekst niet aanwezig.']; for (var i in lines) $('<p style="text-align:justify; margin: 2px;">').appendTo( base ).html( lines[i] ); } } // zet richtlijnen var base = $('.subtabcontents[tab-name=richtlijnen]'); base.html( '<h1>Richtlijnen</h1><ul>' ); for (var i in richtlijnen) { var richtlijn = richtlijnen[i]; if (typeof(richtlijn) != 'function') { if (richtlijn.url) $('<a>').appendTo( $('<li>').appendTo( base.find('ul') ) ).text( richtlijn.url_beschrijving ? richtlijn.url_beschrijving : richtlijn.url ).attr( 'href', richtlijn.url ).attr('target', '_blank'); else $('<a>').appendTo( $('<li>').appendTo( base.find('ul') ) ).text( richtlijn.filename ).attr( 'href', '/deelplannen/download_richtlijn/' + richtlijn.richtlijn_id ).attr('target', '_blank'); } } // zet aandachtspunten var base = $('.subtabcontents[tab-name=aandachtspunten]'); base.html( '' ); for (var i=0; i<aandachtspunten.length; ++i) { var aandachtspunt = aandachtspunten[i]; var lines = aandachtspunt.aandachtspunt.split( '\n' ); $('<h1>').appendTo( base ).text( aandachtspunt.titel ); for (var j in lines) $('<p style="text-align:justify; margin: 2px;">').appendTo( base ).html( lines[j] ); } // update button config BRISToezicht.Toets.ButtonConfig.zetButtonConfig( vraagData.button_config ); // update bescheiden en foto's (vraagupload) tabs BRISToezicht.Toets.Bescheiden.updateList(); BRISToezicht.Toets.VraagUpload.updateList(); // enable & set hercontrole datum BRISToezicht.Toets.Planning.enable(); BRISToezicht.Toets.Planning.selectDatum( vraagData.inputs.hercontrole_datum.value ); } else { // clear prio uit $('#nlaf_PrioPanel .button').removeClass( 'selected disabled' ); $('#nlaf_PrioPanel .button').addClass( 'disabled' ); // clear vraag tekst, zet special text $('#nlaf_PrioVraagPanel .vraag').html('<span style="color:red; font-style:italic; font-size: 14px;">Wanneer u een waardeoordeel met eventuele verantwoording geeft beantwoordt u daarmee ineens alle vragen bij het door u geselecteerde onderwerp.</span>'); // clear verantwoording tekst op hoofdscherm en popup var hoofgroepen_id=this.getHuidigeOnderwerpData().onderwerp_id; if(BRISToezicht.Toets.data.use_default!=1){ if(BRISToezicht.Toets.data.last_hoofgroepen_toelichting && BRISToezicht.Toets.data.last_hoofgroepen_toelichting[hoofgroepen_id]) BRISToezicht.Toets.Verantwoording.setVerantwoordingsTekst( BRISToezicht.Toets.data.last_hoofgroepen_toelichting[hoofgroepen_id].toelichting ); else BRISToezicht.Toets.Verantwoording.setVerantwoordingsTekst(""); BRISToezicht.Toets.data.use_default=0; } // clear status en selecteer "geen waardeoordeel" (in_bewerking) var eersteVraag = null; for (var i in onderwerpData.vragen) if (typeof( onderwerpData.vragen[i] ) != 'function') { eersteVraag = onderwerpData.vragen[i]; break; } this.updateLegeButtons( eersteVraag, eersteVraag.button_config.standaard ); if(BRISToezicht.Toets.data.last_hoofgroepen_toelichting[hoofgroepen_id]) this.zetWaardeoordeelVisueel(BRISToezicht.Toets.data.last_hoofgroepen_toelichting[hoofgroepen_id].status); else this.zetWaardeoordeelVisueel( eersteVraag.button_config.standaard ); $('#hoofgroepen_level').val(1); // clear vraag geschiedenis $('.nlaf_ToelichtingButtons').html(''); // enable waardeoordeel controls if (BRISToezicht.Toets.readonlyMode) $('#nlaf_VoegToeToelichting').attr( 'disabled', 'disabled' ); else $('#nlaf_VoegToeToelichting').removeAttr( 'disabled' ); // enable vorige & volgende vraag knoppen if applicable if (onderwerpData.previousVraag) $('#nlaf_VorigeVraag div').removeClass( 'disabled' ); else $('#nlaf_VorigeVraag div').addClass( 'disabled' ); if (onderwerpData.nextVraag) $('#nlaf_VolgendeVraag div').removeClass( 'disabled' ); else $('#nlaf_VolgendeVraag div').addClass( 'disabled' ); // hide aantallen labels $('#nlaf_AantalRichtlijnen, #nlaf_AantalGrondslagen, #nlaf_AantalAandachtspunten, #nlaf_TotaalAantalAandachtspunten, #nlaf_TotaalAantalFotos').hide(); // clear grondslagen, richtlijnen en aandachtspunten $('.subtabcontents[tab-name=grondslagen], .subtabcontents[tab-name=richtlijnen], .subtabcontents[tab-name=aandachtspunten]').html(''); // disable hercontrole datum BRISToezicht.Toets.Planning.disable(); } BRISToezicht.Toets.Subject.zetAantalSubjecten(); BRISToezicht.Toets.Opdracht.updateLijstInTab(); // update verantwoordingen-button-state BRISToezicht.Toets.Verantwoording.updatePresetVerantwoordingen(); return true; }, filterAandachtspunten: function (vraagData) { var result = []; for (var i=0; i<BRISToezicht.Toets.data.aandachtspunten.length; ++i) { var aandachtspunt = BRISToezicht.Toets.data.aandachtspunten[i]; switch (aandachtspunt.soort) { case 'altijd': if (aandachtspunt.checklist_groep_id && aandachtspunt.checklist_groep_id != BRISToezicht.Toets.data.checklist_groep_id) continue; if (aandachtspunt.checklist_id && aandachtspunt.checklist_id != BRISToezicht.Toets.data.checklist_id) // werkt ook als we geen checklist_id hebben! continue; if (aandachtspunt.hoofdgroep_id && aandachtspunt.hoofdgroep_id != vraagData.hoofdgroep_id) continue; if (aandachtspunt.vraag_id && aandachtspunt.vraag_id != vraagData.vraag_id) continue; break; case 'voorwaardelijk': var gebruik = false; switch (vraagData.gebruik_ndchtspntn) { case 'cg': gebruik = (aandachtspunt.checklist_groep_id == BRISToezicht.Toets.data.checklist_groep_id); break; case 'cl': gebruik = (aandachtspunt.checklist_id == BRISToezicht.Toets.data.checklist_id); break; case 'h': gebruik = (aandachtspunt.hoofdgroep_id == vraagData.hoofdgroep_id); break; case 'v': gebruik = (aandachtspunt.vraag_id == vraagData.vraag_id); break; } if (!gebruik) continue; break; } result.push( aandachtspunt ); } return result; }, filterGrondslagen: function (vraagData) { var result = []; for (var i=0; i<BRISToezicht.Toets.data.grondslagen.length; ++i) { var grondslag = BRISToezicht.Toets.data.grondslagen[i]; var gebruik = false; switch (vraagData.gebruik_grndslgn) { case 'cg': gebruik = (grondslag.checklist_groep_id == BRISToezicht.Toets.data.checklist_groep_id); break; case 'cl': gebruik = (grondslag.checklist_id == BRISToezicht.Toets.data.checklist_id); break; case 'h': gebruik = (grondslag.hoofdgroep_id == vraagData.hoofdgroep_id); break; case 'v': gebruik = (grondslag.vraag_id == vraagData.vraag_id); break; } if (!gebruik) continue; result.push( grondslag ); } return result; }, filterRichtlijnen: function (vraagData) { var result = []; for (var i=0; i<BRISToezicht.Toets.data.richtlijnen.length; ++i) { var richtlijn = BRISToezicht.Toets.data.richtlijnen[i]; var gebruik = false; switch (vraagData.gebruik_rchtlnn) { case 'cg': gebruik = (richtlijn.checklist_groep_id == BRISToezicht.Toets.data.checklist_groep_id); break; case 'cl': gebruik = (richtlijn.checklist_id == BRISToezicht.Toets.data.checklist_id); break; case 'h': gebruik = (richtlijn.hoofdgroep_id == vraagData.hoofdgroep_id); break; case 'v': gebruik = (richtlijn.vraag_id == vraagData.vraag_id); break; } if (!gebruik) continue; result.push( richtlijn ); } return result; }, filterOpdrachten: function (vraagData) { var result = []; for (var i=0; i<BRISToezicht.Toets.data.opdrachten.length; ++i) { var opdracht = BRISToezicht.Toets.data.opdrachten[i]; if (opdracht.checklist_groep_id && opdracht.checklist_groep_id != BRISToezicht.Toets.data.checklist_groep_id) continue; if (opdracht.checklist_id && opdracht.checklist_id != BRISToezicht.Toets.data.checklist_id) // werkt ook als we geen checklist_id hebben! continue; if (opdracht.hoofdgroep_id && opdracht.hoofdgroep_id != vraagData.hoofdgroep_id) continue; if (opdracht.vraag_id && opdracht.vraag_id != vraagData.vraag_id) continue; result.push( opdracht ); } return result; }, updateSteekproefButton: function( vraagData, huidige_status ) { // let op: huidige status is op dit punt altijd gezet op een geldige "w00"-achtige waarde // bekijk of de huidige waarde de steekproef waarde is // LET OP: de button designated als steekproef button kan TWEE betekenissen hebben: een normale, en de steekproef // bij de standaard setup is w04 (dus linksonderin) de steekproef button // - als de huidige_status dan "w04s" is, dan betekent dat: overslaan ivm steekproef (dus niet controleren // omdat nu geen steekproef gedaan moet worden). in dat geval moet de button_config.steekproeftekst tekst // gezet worden; de tekst die er anders op zou staan ("niet gecontroleerd") moet dus NIET zichtbaar / te selecteren // zijn voor de gebruiker // - als de huidige_status leeg is, of "w04", dan moet de reguliere tekst er staan (namelijk: // niet gecontroleerd), omdat het dan een totaal andere functionele waarde vertegenwoordigd // // er kan maar 1 button de steekproef button zijn, en die staat in vraagData.button_config.steekproef var coord = BRISToezicht.Toets.ButtonConfig.statusNaarPositie( vraagData.button_config.steekproef ); var isSteekProefWaarde = vraagData.button_config.steekproef == huidige_status.substr( 0, 3 ) && huidige_status[3] == 's'; // bepaal de werkelijke button positie var btn = BRISToezicht.Toets.ButtonConfig.buttonDom[coord.x][coord.y]; // zet juiste tekst en status if (isSteekProefWaarde) { // zet ID (dat bepaalt namelijk de waarde die het veld krijgt!) op de steekproef variant btn .attr( 'id', 'nlaf_Status-w' + coord.x + coord.y + 's' ) .text( vraagData.button_config.steekproeftekst ); } else { // zet ID (dat bepaalt namelijk de waarde die het veld krijgt!) op de NIET-steekproef variant btn .attr( 'id', 'nlaf_Status-w' + coord.x + coord.y ) .text( vraagData.button_config.tekst[coord.x][coord.y] ); } }, updateLegeButtons: function( vraagData, huidige_status ) { // let op: huidige status is op dit punt altijd gezet op een geldige "w00"-achtige waarde // bepaal of het huidige antwoord een "leeg" antwoord is var coord = BRISToezicht.Toets.ButtonConfig.statusNaarPositie( huidige_status ); var huidigeIsLeeg = vraagData.button_config.is_leeg[coord.x][coord.y]; // loop dan alle zichtbare buttons af, en zet buttons op disabled // wannneer: // - EN de huidige status NIET een lege is // - EN de huidige button WEL een lege waarde vertegenwoordigd // het idee is dat lege buttons niet meer geselecteerd moeten kunnen worden // zodra een 'echt' antwoord gegeven is BRISToezicht.Toets.ButtonConfig.forEachPosition(function( x, y ){ BRISToezicht.Toets.ButtonConfig.buttonDom[x][y].removeClass( 'disabled' ); if (!huidigeIsLeeg && vraagData.button_config.is_leeg[x][y]) BRISToezicht.Toets.ButtonConfig.buttonDom[x][y].addClass( 'disabled' ); }); }, zetWaardeoordeelVisueel: function( huidige_status ) { if (!huidige_status) huidige_status = 'in_bewerking'; $('.waardeoordeel td[id]').removeClass( 'selected' ); $('#nlaf_Status-' + huidige_status ).addClass( 'selected' ); }, verhoogHoofdgroepPrioriteit: function( newPrio ) { var onderwerpData = this.getHuidigeOnderwerpData(); if (!onderwerpData) return; var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; if (!confirm( 'Weet u zeker dat u de prioriteit voor de huidige hoofdgroep wilt wijzigen?' )) return; var hoofdgroepData = BRISToezicht.Toets.data.hoofdgroepen[vraagData.hoofdgroep_id]; if (newPrio == hoofdgroepData.hoofdgroep_prioriteit) return; if (newPrio != 'zeer_laag' && newPrio != 'laag' && newPrio != 'gemiddeld' && newPrio != 'hoog' && newPrio != 'zeer_hoog') return; // update prioriteit hoofdgroepData.hoofdgroep_prioriteit = newPrio; // reselect current, to reflect changes visually BRISToezicht.Toets.Vraag.reselect(); var data = { _command: 'verhooghoofdgroepprioriteit', hoofdgroep_id: vraagData.hoofdgroep_id, nieuwe_prio: newPrio }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); } }; <file_sep><?php class CheckThemas { private $CI; private $_klant; private $_themas = array(); public function __construct( KlantResult $klant ) { $this->CI = get_instance(); $this->_klant = $klant; } public function run( $fix ) { echo '-------------------------------------------------------------------------------------' . "\n"; echo 'Klant: ' . $this->_klant->naam . "\n"; echo '-------------------------------------------------------------------------------------' . "\n"; echo ($fix ? 'Fouten worden gerepareerd' : '!!!! FOUTEN WORDEN NIET GEREPAREERD !!!!') . "\n"; echo '-------------------------------------------------------------------------------------' . "\n"; $this->_init_thema_duplicates(); // start transaction $this->CI->db->trans_start(); // assemble query list foreach ($this->_themas as $thema => $remove_ids) { $keep_id = array_shift( $remove_ids ); echo 'Behoud: ' . sprintf('%5d', $keep_id ) . ' - verwijder: ' . implode(', ', $remove_ids) . "\n"; $queries = array(); $queries[] = 'UPDATE bt_vragen SET thema_id = ' . $keep_id . ' WHERE thema_id IN (' . implode(',', $remove_ids) . ');'; $queries[] = 'UPDATE deelplan_themas SET thema_id = ' . $keep_id . ' WHERE thema_id IN (' . implode(',', $remove_ids) . ');'; $queries[] = 'UPDATE verantwoordingen SET thema_id = ' . $keep_id . ' WHERE thema_id IN (' . implode(',', $remove_ids) . ');'; $queries[] = 'DELETE FROM bt_themas WHERE id IN (' . implode(',', $remove_ids) . ');'; foreach ($queries as $q) $this->CI->db->query( $q ); } // finish transaction if (!$fix) { $this->CI->db->_trans_status = false; $this->CI->db->trans_complete(); } else if (!$this->CI->db->trans_complete()) throw new Exception( 'Fout bij transactie wegschrijven.' ); } private function _init_thema_duplicates() { $res = $this->CI->db->query( 'SELECT id, thema FROM bt_themas WHERE klant_id = ' . intval($this->_klant->id) . ' ORDER BY id' ); foreach ($res->result() as $row) if (!isset( $this->_themas[$row->thema] )) $this->_themas[$row->thema] = array( $row->id ); else $this->_themas[$row->thema][] = $row->id; $res->free_result(); foreach ($this->_themas as $thema => $ids) if (sizeof($ids) == 1) unset( $this->_themas[$thema] ); } } <file_sep><? $klant = get_instance()->gebruiker->get_logged_in_gebruiker()->get_klant(); ?> <script type="text/javascript"> // client side helper, kind of a hack, but great performance gain var VoortgangTable = $('table.voortgang tbody'); var VoortgangTableOnderwerp = {}; // init readonly mode BRISToezicht.Toets.readonlyMode = <?=($access_mode == 'readonly') ? 'true' : 'false' ?>; // client-side helper only, server checks this too! BRISToezicht.Toets.is_automatic_accountability_text=<?=($klant->automatic_accountability_text==1) ? 'true' : 'false'?>; // init base structure BRISToezicht.Toets.data = {}; // init various id's BRISToezicht.Toets.data.checklist_groep_id = <?=$checklistgroep->id?>; BRISToezicht.Toets.data.checklist_id = <?=$checklist ? $checklist->id : 'null'?>; BRISToezicht.Toets.data.deelplan_id = <?=$deelplan->id?>; BRISToezicht.Toets.data.gebruiker_id = <?=get_instance()->login->get_user_id()?>; BRISToezicht.Toets.data.deelplanchecklist_id = <?=$deelplanchecklist_id?>; BRISToezicht.Toets.data.dossier_id = <?=$deelplan->get_dossier()->id?>; BRISToezicht.Toets.data.bouwnummer = "<?=htmlspecialchars($bouwnummer)?>"; BRISToezicht.Toets.data.bouwnummer_id = "<?=encode_bouwnummer($bouwnummer)?>"; // init verantwoordingen BRISToezicht.Toets.data.verantwoordingen = []; // ingeladen via AJAX $('.documenten.documenten-icon').attr('dossier_id',BRISToezicht.Toets.data.dossier_id); $('.documenten.documenten-icon').attr('onClick','openBescheidenPopup(0,'+BRISToezicht.Toets.data.dossier_id+')'); // laadt verantwoordingen $(document).ready(function(){ $.ajax({ url: '/deelplannen/verantwoordingen2/<?=$checklistgroep->id?><?=$checklist?'/'.$checklist->id:''?>', type: 'POST', success: function( data ) { BRISToezicht.OfflineKlaar.markeerKlaar('verantwoordingen'); eval( data ); }, error: function() { BRISToezicht.OfflineKlaar.markeerKlaar('verantwoordingen'); alert( 'Er is iets fout gegaan bij het laden van de verantwoordingen, deze zullen niet beschikbaar zijn.' ); } }); }); $(document).ready(function(){ var errorOops = function(errmsg) { alert( 'Er is iets fout gegaan bij het laden van de toezichtgegevens.\nU kunt deze pagina nu sluiten, of proberen te herladen.\n\nOnze excuses voor het ongemak.\n\nCODE: ' + errmsg ); } $.ajax({ url: '/deelplannen/toezichtgegevens/<?=$checklistgroep->id?>/<?=$deelplan->id?>/<?=$checklist?$checklist->id:''?>/<?=$bouwnummer==''||$bouwnummer==null?'':urlencode($bouwnummer)?>', type: 'POST', dataType: 'json', success: function( data ) { if (!data.success) { errorOops( data.error_message ); return; } // markeer stap klaar BRISToezicht.OfflineKlaar.markeerKlaar('dossierinfo'); // laad wetteksten, doe dit pas als toezichtgegevens klaar zijn, want deze call // vult die gegevens aan! $.ajax({ url: '/deelplannen/wetteksten/<?=$checklistgroep->id?>/<?=$deelplan->id?>', type: 'POST', data: { grondslag_tekst_ids: JSON.stringify( data.grondslag_tekst_ids ) }, success: function( data ) { BRISToezicht.OfflineKlaar.markeerKlaar('wetteksten'); eval( data ); }, error: function() { BRISToezicht.OfflineKlaar.markeerKlaar('wetteksten'); alert( 'Er is iets fout gegaan bij het laden van de wetteksten, deze zullen niet beschikbaar zijn.' ); } }); // initialiseer BRIStoezicht met de ontvangen gegevens, doe dit 1ms later, zodat het verzoek bij de server // alvast begonnen is, voordat we een mega blob aan javascript gaan verwerken setTimeout( function() { // initialize BRIStoezicht BRISToezicht.initialize( data ); // fake click toezichtvoortgang button so the main view switches to the toezichtvoortgang $('#nlaf_NaarToezichtVoortgang').trigger( 'click' ); }, 1 ); }, error: function() { errorOops('Global error'); } }); }); </script> <file_sep>-- Change the name of the 'FirstWatch' to be more appropriate, being that of the 'General SOAP interface' UPDATE webservice_applicaties SET naam = 'Breed SOAP koppelvlak' WHERE naam = 'FirstWatch'; -- Allow webservice accounts to be client specific. ALTER TABLE webservice_accounts ADD COLUMN klant_id int(11) DEFAULT NULL; ALTER TABLE webservice_accounts ADD KEY klant_id (klant_id); ALTER TABLE webservice_accounts ADD CONSTRAINT `fk__w_a__klant_id` FOREIGN KEY (`klant_id`) REFERENCES `klanten` (`id`); -- Get some IDs in temporary variables SELECT @klant_id_imotep:=id FROM klanten WHERE naam = 'Imotep'; SELECT @klant_id_cebes:=id FROM klanten WHERE naam = 'Cebes'; SELECT @klant_id_den_haag:=id FROM klanten WHERE naam = '<NAME>'; SELECT @ws_id:=id FROM webservice_applicaties WHERE naam = 'Breed SOAP koppelvlak'; -- Limit some of the webservice accounts to specific 'klant_id' values UPDATE webservice_accounts SET klant_id = @klant_id_cebes WHERE omschrijving LIKE 'First Watch%'; UPDATE webservice_accounts SET klant_id = @klant_id_den_haag WHERE omschrijving LIKE 'Den Haag%'; -- Create a table for the first defined filter in the Soap Dossier webservice (used for limiting lists of clients per WS user). DROP TABLE IF EXISTS `webservice_account_filter_01`; CREATE TABLE IF NOT EXISTS `webservice_account_filter_01` ( `id` int(11) NOT NULL AUTO_INCREMENT, `webservice_applicatie_id` int(11) NOT NULL, `source_id` int(11) NOT NULL, `target_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK__ws_acc_filter_01` (`webservice_applicatie_id`, `source_id`, `target_id`), KEY `webservice_applicatie_id` (`webservice_applicatie_id`), KEY `source_id` (`source_id`), KEY `target_id` (`target_id`), CONSTRAINT `FK__ws_acc_filter_01__w_a_id` FOREIGN KEY (`webservice_applicatie_id`) REFERENCES `webservice_applicaties` (`id`), CONSTRAINT `FK__ws_acc_filter_01__s_id` FOREIGN KEY (`source_id`) REFERENCES `klanten` (`id`), CONSTRAINT `FK__ws_acc_filter_01__t_id` FOREIGN KEY (`target_id`) REFERENCES `klanten` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Insert the data for Cebes INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_cebes, target_id = @klant_id_imotep; INSERT INTO webservice_account_filter_01 SET webservice_applicatie_id = @ws_id, source_id = @klant_id_cebes, target_id = @klant_id_cebes; INSERT INTO webservice_account_filter_01 (webservice_applicatie_id, source_id, target_id) SELECT @ws_id, @klant_id_cebes, id FROM klanten WHERE naam LIKE 'Veiligheidsregio%'; <file_sep><? require_once 'base.php'; class UploadResult extends BaseResult { function UploadResult( &$arr ) { parent::BaseResult( 'upload', $arr ); } } class Upload extends BaseModel { function Upload() { parent::BaseModel( 'UploadResult', 'uploads', true ); } public function check_access( BaseResult $object ) { // disabled for model } function add( $filename, $data ) { // cleanup old uploads if (get_db_type() == 'oracle') { $this->db->Query( 'DELETE FROM uploads WHERE uploaded_at < to_date(' . date('Y-m-d H:i:s', time() - 86400 ) . ', \'YYYY-MM-DD HH24:MI:SS\')' ); } else { $this->db->Query( 'DELETE FROM uploads WHERE uploaded_at < \'' . date('Y-m-d H:i:s', time() - 86400 ) . '\'' ); } /* if (!$this->dbex->is_prepared( 'Upload::add' )) $this->dbex->prepare( 'Upload::add', 'INSERT INTO uploads (filename, data) VALUES (?, ?)' ); $args = array( 'filename' => $filename, 'data' => $data, ); $this->dbex->execute( 'Upload::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'filename' => $filename, 'data' => $data, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'sb' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } } <file_sep><?php // test stuff for Foddex, never bother about this in any way! class FoddexTest { public $CI; public function __construct() { $this->CI = get_instance(); echo "------- FoddexTest -------\n"; } public function run() { $this->CI->load->library('pdfannotatorlib'); $this->_do_pdfannotator_lib_test(9566, 4886); $this->_do_pdfannotator_lib_test(9566, 4867); } private function _do_pdfannotator_lib_test($deelplan_id, $bescheiden_id) { $numpages = $this->CI->pdfannotatorlib->bescheiden_num_pages($bescheiden_id); echo "$numpages pages in $deelplan_id $bescheiden_id\n"; for ($page = 1; $page <= $numpages; ++$page) { $png = $this->CI->pdfannotatorlib->bescheiden_naar_png($deelplan_id, $bescheiden_id, null, $page); file_put_contents("test-$bescheiden_id-$deelplan_id-$page.png", $png); } } } <file_sep><? global $class; if (!strcasecmp( $class, 'webservice' )) throw new Exception( 'Database error: ' . $message ); ?> <!doctype html> <html> <head> <title>BRIStoezicht - Fout</title> <meta http-equiv="expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- css --> <link rel="stylesheet" href="/files/css/toezicht.css?v2.6.2" type="text/css" /> <link rel="stylesheet" href="/files/css/bris.css?v2.6.2" type="text/css" /> <link rel="stylesheet" href="/files/jquery/jquery-ui-1.8.21.custom.css" type="text/css" /> </head> <body> <div style="padding: 20px"> <img src="/files/images/bristoezicht.png" /> <h1>Er is een database fout opgetreden</h1> <?php echo $message; ?> </div> </body> </html><file_sep>PDFAnnotator.Handle.ChangeVraag = PDFAnnotator.Handle.extend({ // constructor init: function( editable ) { // initialize base class this._super( editable ); this.addNodes(); } // overrideable function that adds the nodes ,addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 1, 0, baseurl + 'images/nlaf/edit-handle-changevraag.png', 32, 32, 'click', this.showLayersList, '{"evn_type":"changevraag"}' ); } ,showLayersList: function(){ annot_selected = this; } }); <file_sep>ALTER TABLE bt_checklisten ADD created_at DATE DEFAULT NULL; ALTER TABLE bt_checklist_groepen ADD created_at DATE DEFAULT NULL; -- Get approximations of the 'created_at' values, by using the earliest occurence of a checklist in a deelplan. UPDATE bt_checklisten bt_cl INNER JOIN ( SELECT bt_cl2.id, MIN(dp.aangemaakt_op) checklist_date FROM bt_checklisten bt_cl2 INNER JOIN deelplan_checklisten dp_cl ON dp_cl.checklist_id = bt_cl2.id INNER JOIN deelplannen dp ON dp.id = dp_cl.deelplan_id GROUP BY bt_cl2.id ) t ON t.id = bt_cl.id SET bt_cl.created_at = t.checklist_date; -- Get approximations of the 'created_at' values, by using the earliest occurence of a checklist group in a deelplan. UPDATE bt_checklist_groepen bt_clg INNER JOIN ( SELECT bt_clg2.id, MIN(dp.aangemaakt_op) checklist_group_date FROM bt_checklist_groepen bt_clg2 INNER JOIN deelplan_checklist_groepen dp_clg ON dp_clg.checklist_groep_id = bt_clg2.id INNER JOIN deelplannen dp ON dp.id = dp_clg.deelplan_id GROUP BY bt_clg2.id ) t ON t.id = bt_clg.id SET bt_clg.created_at = t.checklist_group_date; REPLACE INTO teksten(string, tekst, timestamp, lease_configuratie_id) VALUES ('nav.usage_overview', 'Gebruiksoverzicht', NOW(), 0), ('nav.usage_overview', 'Gebruiksoverzicht', NOW(), 1); <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_blokkeren')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('gebruiker_blokkeren', $gebruiker->volledige_naam), 'width' => '920px' )); ?> <?=tg('gebruiker_blokkeren_tekst', $gebruiker->volledige_naam)?><br/><br/> <form method="post"> <input type="submit" name="blokkeer" value="<?=tgng('form.ja')?>"> <input type="submit" value="<?=tgng('form.nee')?>"> <input type="hidden" name="referer" value="<?=$referer?>" /> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><? require_once 'base.php'; class VraagResult extends BaseResult { function VraagResult( &$arr ) { parent::BaseResult( 'vraag', $arr ); } public function get_wizard_parent() { return $this->get_categorie()->get_hoofdgroep(); } public function get_wizard_veld( $veld ) { if (!property_exists( $this, $veld )) { switch ($veld) { case 'wo_tekst_00': return $this->get_wizard_veld( 'wt00' ); case 'wo_tekst_01': return $this->get_wizard_veld( 'wt01' ); case 'wo_tekst_02': return $this->get_wizard_veld( 'wt02' ); case 'wo_tekst_03': return $this->get_wizard_veld( 'wt03' ); case 'wo_tekst_04': return $this->get_wizard_veld( 'wt04' ); case 'wo_tekst_10': return $this->get_wizard_veld( 'wt10' ); case 'wo_tekst_11': return $this->get_wizard_veld( 'wt11' ); case 'wo_tekst_12': return $this->get_wizard_veld( 'wt12' ); case 'wo_tekst_13': return $this->get_wizard_veld( 'wt13' ); case 'wo_tekst_20': return $this->get_wizard_veld( 'wt20' ); case 'wo_tekst_21': return $this->get_wizard_veld( 'wt21' ); case 'wo_tekst_22': return $this->get_wizard_veld( 'wt22' ); case 'wo_tekst_23': return $this->get_wizard_veld( 'wt23' ); case 'wo_is_leeg_00': return $this->get_wizard_veld( 'wl00' ); case 'wo_is_leeg_01': return $this->get_wizard_veld( 'wl01' ); case 'wo_is_leeg_02': return $this->get_wizard_veld( 'wl02' ); case 'wo_is_leeg_03': return $this->get_wizard_veld( 'wl03' ); case 'wo_is_leeg_04': return $this->get_wizard_veld( 'wl04' ); case 'wo_is_leeg_10': return $this->get_wizard_veld( 'wl10' ); case 'wo_is_leeg_11': return $this->get_wizard_veld( 'wl11' ); case 'wo_is_leeg_12': return $this->get_wizard_veld( 'wl12' ); case 'wo_is_leeg_13': return $this->get_wizard_veld( 'wl13' ); case 'wo_is_leeg_20': return $this->get_wizard_veld( 'wl20' ); case 'wo_is_leeg_21': return $this->get_wizard_veld( 'wl21' ); case 'wo_is_leeg_22': return $this->get_wizard_veld( 'wl22' ); case 'wo_is_leeg_23': return $this->get_wizard_veld( 'wl23' ); case 'wo_in_gebruik_00': return $this->get_wizard_veld( 'wg00' ); case 'wo_in_gebruik_01': return $this->get_wizard_veld( 'wg01' ); case 'wo_in_gebruik_02': return $this->get_wizard_veld( 'wg02' ); case 'wo_in_gebruik_03': return $this->get_wizard_veld( 'wg03' ); case 'wo_in_gebruik_04': return $this->get_wizard_veld( 'wg04' ); case 'wo_in_gebruik_10': return $this->get_wizard_veld( 'wg10' ); case 'wo_in_gebruik_11': return $this->get_wizard_veld( 'wg11' ); case 'wo_in_gebruik_12': return $this->get_wizard_veld( 'wg12' ); case 'wo_in_gebruik_13': return $this->get_wizard_veld( 'wg13' ); case 'wo_in_gebruik_20': return $this->get_wizard_veld( 'wg20' ); case 'wo_in_gebruik_21': return $this->get_wizard_veld( 'wg21' ); case 'wo_in_gebruik_22': return $this->get_wizard_veld( 'wg22' ); case 'wo_in_gebruik_23': return $this->get_wizard_veld( 'wg23' ); case 'wo_kleur_00': return $this->get_wizard_veld( 'wk00' ); case 'wo_kleur_01': return $this->get_wizard_veld( 'wk01' ); case 'wo_kleur_02': return $this->get_wizard_veld( 'wk02' ); case 'wo_kleur_03': return $this->get_wizard_veld( 'wk03' ); case 'wo_kleur_04': return $this->get_wizard_veld( 'wk04' ); case 'wo_kleur_10': return $this->get_wizard_veld( 'wk10' ); case 'wo_kleur_11': return $this->get_wizard_veld( 'wk11' ); case 'wo_kleur_12': return $this->get_wizard_veld( 'wk12' ); case 'wo_kleur_13': return $this->get_wizard_veld( 'wk13' ); case 'wo_kleur_20': return $this->get_wizard_veld( 'wk20' ); case 'wo_kleur_21': return $this->get_wizard_veld( 'wk21' ); case 'wo_kleur_22': return $this->get_wizard_veld( 'wk22' ); case 'wo_kleur_23': return $this->get_wizard_veld( 'wk23' ); case 'wo_standaard': return $this->get_wizard_veld( 'wstandaard' ); case 'wo_steekproef': return $this->get_wizard_veld( 'wsteekproef' ); case 'wo_steekproef_tekst': return $this->get_wizard_veld( 'wsteekproeftekst' ); } throw new Exception( 'Object van type ' . get_class($this) . ' bevat veld ' . $veld . ' niet!' ); } return $this->$veld; } public function get_wizard_veld_recursief( $veld ) { $value = $this->get_wizard_veld( $veld ); return is_null($value) ? $this->get_wizard_parent()->get_wizard_veld_recursief( $veld ) : $value; } public function get_wizard_onderliggenden() { return array(); } public function is_wizard_readonly() { return $this->get_categorie()->get_hoofdgroep()->is_wizard_readonly(); } public function rename( $vraag, $thema_id, $aanwezigheid ) { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'VraagResult::rename', 'UPDATE bt_vragen SET tekst = ?, thema_id = ?, aanwezigheid = ?, WHERE id = ?', $db ); $CI->dbex->execute( 'VraagResult::rename', array( $vraag, $thema_id, $aanwezigheid, $this->id ), $db ); $this->tekst = $vraag; $this->thema_id = $thema_id; $this->aanwezigheid = $aanwezigheid; } public function get_thema() { $CI = get_instance(); $CI->load->model( 'thema' ); return $CI->thema->get( $this->thema_id ); } public function get_grondslagen() { $CI = get_instance(); $CI->load->model( 'vraaggrondslag' ); return $CI->vraaggrondslag->get_by_vraag( $this->id ); } public function get_richtlijnen() { $CI = get_instance(); $CI->load->model( 'vraagrichtlijn' ); return $CI->vraagrichtlijn->get_by_vraag( $this->id ); } public function get_aandachtspunten() { $CI = get_instance(); $CI->load->model( 'vraagaandachtspunt' ); return $CI->vraagaandachtspunt->get_by_vraag( $this->id ); } public function get_categorie() { $CI = get_instance(); $CI->load->model( 'categorie' ); return $CI->categorie->get( $this->categorie_id ); } function toon_adhv_priomode( $priomode ) { return ($this->aanwezigheid & (1 << ($priomode-1))) ? true : false; } function is_toetsbaar() { return true; } // If $set is not null, the prioriteiten are SET to that value. If it's NULL, nothing is initially done. // If $or is not null, the prioriteiten are OR'd with that value, making it easy to add e.g. "prio 5" to all existing prioriteiten, without changing the rest of the bits // If $clear is not null, the prioriteiten are AND (NOT $clear)'d, making it easy to remove e.g. "prio 3" from all existing prioriteiten, without changing the rest of the bits function verander_prioriteiten( $set=null, $or=null, $clear=null ) { $was = $this->aanwezigheid; if (!is_null( $set )) $this->aanwezigheid = intval( $set ); if (!is_null( $or )) $this->aanwezigheid |= intval( $or ); if (!is_null( $clear )) $this->aanwezigheid &= ~intval( $clear ); if ($was != $this->aanwezigheid) $this->save(); } public function expand_automatische_toel_template( $deelplan_id ) { if (!strlen( $this->automatische_toel_template )) return null; // maak data om mee te werken $CI = get_instance(); $CI->load->model( 'deelplan' ); if (!($deelplan = $CI->deelplan->get( $deelplan_id ))) throw new Exception( 'Ongeldig deelplan ID ' . $deelplan_id ); if (!($dossier = $deelplan->get_dossier())) throw new Exception( 'Kon dossier bij deelplan met ID ' . $deelplan_id . ' niet laden' ); $data = (object)array( 'deelplan' => $deelplan, 'dossier' => $dossier, 'dossier_extra' => (object)array( 'eerste_revisie_datum' => $deelplan->get_eerste_revisie_datum(), ), 'systeem' => (object)array( 'datum' => date('d-m-Y'), 'datum_en_tijd' => date('d-m-Y H:i'), ), ); // parse template return preg_replace_callback( '/\{(.*?)\}/', function( $matches ) use ($data) { $parts = explode( '.', $matches[1], 2 ); if (sizeof( $parts ) != 2) return $matches[0]; if (!property_exists( $data, $parts[0] )) return '[!' . $matches[0] . ']'; if (!property_exists( $data->{$parts[0]}, $parts[1] )) return '[' . $matches[0] . '!]'; return $data->{$parts[0]}->{$parts[1]}; }, $this->automatische_toel_template ); } /** Kopieert deze vraag. Als er een ander categorie ID wordt meegegeven, dan * komt de kopie onder die categorie te hangen. Anders wordt het een identieke * kopie onder dezelfde categorie. * Als een andere categorie ID is opgegeven, verandert de sortering verder ook niet. * Wordt een categorie ID weggelaten, dan wordt de sortering dusdanig aangepast dat * de kopie onderaan de categorie komt te hangen. * * @return Geeft de kopie terug in object vorm. */ public function kopieer( $ander_categorie_id=null ) { return kopieer_object( $this, 'categorie_id', $ander_categorie_id ); } public function get_standaard_antwoord() { $type = $this->get_wizard_veld_recursief( 'vraag_type' ); if ($type == 'invulvraag') return (object)array( 'status' => '', 'is_leeg' => true, ); $status = $this->get_wizard_veld_recursief( 'wo_standaard' ); $is_leeg = false; if ($status) // geen default, mag eigenlijk niet, maar niet op crashen! if (preg_match( '/^w(\d{2})s?/', $status, $matches )) // geen geldige waarde, ook niet op crashen $is_leeg = $this->get_wizard_veld_recursief( 'wo_is_leeg_' . $matches[1] ) == '1'; return (object)array( 'status' => $status, 'is_leeg' => $is_leeg, ); } public function get_waardeoordeel( $zet_standaard /* bool */, $use_status=null ) { if (is_null( $use_status )) $status = @$this->status; else $status = $use_status; if ($this->get_wizard_veld_recursief( 'vraag_type' ) == 'invulvraag') return $status; if (!$status || $status == 'in_bewerking' /* nood hack */) { if (!$zet_standaard) return ''; $status = $this->get_wizard_veld_recursief( 'wo_standaard' ); } preg_match( '/^w(\d{2})s?/', $status, $matches ); return $this->get_wizard_veld_recursief( 'wo_tekst_' . $matches[1] ); } public function get_waardeoordeel_kleur( $zet_standaard /* bool */, $use_status=null ) { if (is_null( $use_status )) $status = @$this->status; else $status = $use_status; if ($this->get_wizard_veld_recursief( 'vraag_type' ) == 'invulvraag') return strlen($status) ? 'groen' : ($zet_standaard ? 'oranje' : ''); if (!$status) { if (!$zet_standaard) return ''; $status = $this->get_wizard_veld_recursief( 'wo_standaard' ); } preg_match( '/^w(\d{2})s?/', $status, $matches ); return $this->get_wizard_veld_recursief( 'wo_kleur_' . $matches[1] ); } } class Vraag extends BaseModel { function Vraag() { parent::BaseModel( 'VraagResult', 'bt_vragen' ); } public function get( $id ) { $vraag = parent::get($id); $vraag->naam = $vraag->tekst; return $vraag; } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'categorie', 'categorie_id' ); } function get_by_categorie( $categorie_id ) { if (!$this->dbex->is_prepared( 'get_by_categorie' )) $this->dbex->prepare( 'get_by_categorie', 'SELECT *, `tekst` AS `naam` FROM '.$this->_table.' WHERE categorie_id = ? ORDER BY sortering', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'get_by_categorie', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $res->free_result(); return $result; } function get_by_categorie_map( $categorie_id, $matrixmapId=0, $artikelId=0 ){ $status = "IF(". "EXISTS(". "SELECT * FROM `artikel_vraag_mappen` `avm` ". 'LEFT JOIN `matrixmap_checklisten` `mcl` ON `mcl`.`id`=`avm`.`map_checklist_id` '. "WHERE ".$this->_table.".id=`avm`.`vraag_id` AND `mcl`.`matrixmap_id`=? AND `avm`.`artikel_id`=?". ")". ",'owner',". "IF(". "EXISTS(". "SELECT * FROM `artikel_vraag_mappen` `avm` ". 'LEFT JOIN `matrixmap_checklisten` `mcl` ON `mcl`.`id`=`avm`.`map_checklist_id` '. "WHERE ".$this->_table.".id=`avm`.`vraag_id` AND `mcl`.`matrixmap_id`=? AND `avm`.`artikel_id`!=?". "),". "'busy',". "'free'". ")". ") AS `status`"; $sql = 'SELECT '.$this->_table.'.id AS id, '.$this->_table.'.tekst AS naam, categorie_id ,'.$status.''. ' FROM '.$this->_table. ' WHERE categorie_id = ? ORDER BY sortering'; if ( !$this->dbex->is_prepared( 'get_by_categorie_map' )) $this->dbex->prepare( 'get_by_categorie_map', $sql, $this->get_db() ); $args = array($matrixmapId, $artikelId, $matrixmapId, $artikelId, $categorie_id ); $res = $this->dbex->execute( 'get_by_categorie_map', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row, false ); $res->free_result(); return $result; }//-------------------- /** * TODO: ATTANTION. DON'T DELETE. * This method was used in DRSM functionality which is disabled now. * DRSM functionality might be used in the future so DON'T DELETE this method, please. * @param unknown $artikelId */ function get_by_artikel_map( $btRpId, $artikelId ){ $CI = get_instance(); $CI->load->model( 'klant' ); $klant = $CI->klant->get_logged_in_klant(); $sql_tmp = ''. '(SELECT %s FROM `bijwoonmomenten_map` '. 'LEFT JOIN `matrix_mappingen` ON `bijwoonmomenten_map`.`matrix_id`=`matrix_mappingen`.`id` '. 'LEFT JOIN bt_toezichtmomenten ON bt_toezichtmomenten.`id`=`bijwoonmomenten_map`.toezichtmoment_id '. 'LEFT JOIN bt_toezichtmomenten_hoofdgroepen ON bt_toezichtmomenten_hoofdgroepen.toezichtmoment_id=bt_toezichtmomenten.`id` '. 'LEFT JOIN bt_hoofdgroepen ON bt_hoofdgroepen.`id`=bt_toezichtmomenten_hoofdgroepen.hoofdgroep_id '. 'LEFT JOIN bt_categorieen ON bt_categorieen.`hoofdgroep_id`=bt_hoofdgroepen.`id` '. 'LEFT JOIN '.$this->_table.' ON '.$this->_table.'.categorie_id=bt_categorieen.`id` '. 'WHERE 1=1 '. 'AND`artikel_vraag_mappen`.`matrix_id`=`bijwoonmomenten_map`.`matrix_id` '. 'AND '.$this->_table.'.`id`=artikel_vraag_mappen.vraag_id '. 'AND `klant_id`= '.$klant->id.' '. 'LIMIT 1)'. ''; $is_drsm_bw = sprintf($sql_tmp,'`is_drsm_bw`'); $is_dmm_bw = sprintf($sql_tmp,'`is_dmm_bw`'); $is_btn = 'EXISTS('.sprintf($sql_tmp,'*').')'; $sql = 'SELECT '. '`bt_riskprofiel_id`'. ',`'.$this->_table.'`.`id` AS `id`'. ',`'.$this->_table.'`.`tekst` AS `naam`'. ',`categorie_id`'. ',`artikel_id`'. ',`artikel_vraag_mappen`.`id` AS `vraag_map_id`'. ',`is_active`'. // ',TRUE AS `is_bw`'. ','.$is_dmm_bw.' AS `is_dmm_bw` '. ','.$is_drsm_bw.' AS `is_drsm_bw` '. ','.$is_btn.' AS `is_btn` '. ',`klant_id`'. 'FROM `'.$this->_table.'` '. "LEFT JOIN artikel_vraag_mappen ON artikel_vraag_mappen.vraag_id=`".$this->_table.'`.`id`'. 'LEFT JOIN `matrix_mappingen` ON `artikel_vraag_mappen`.`matrix_id`=`matrix_mappingen`.`id` '. 'WHERE 1=1 '. 'AND bt_riskprofiel_id=? '. 'AND artikel_id = ? '. 'AND `klant_id`= ? '. 'ORDER BY naam'; if (!$this->dbex->is_prepared( 'get_by_artikel_map' )) $this->dbex->prepare( 'get_by_artikel_map', $sql, $this->get_db() ); $args = func_get_args(); $args[] = $klant->id; $res = $this->dbex->execute( 'get_by_artikel_map', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row){ $result[] = $this->getr( $row, false ); } $res->free_result(); return $result; } public function add( $categorie_id, $tekst, $thema_id=null, $aanwezigheid=null, $advies_prioriteit=null ) { // Determine which "null function" should be used $null_func = get_db_null_function(); // prepare statements //$this->dbex->prepare( 'Vraag::add', 'INSERT INTO bt_vragen (categorie_id, sortering, tekst, thema_id, aanwezigheid, advies_prioriteit) VALUES (?, ?, ?, ?, ?, ?)' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'Vraag::search', 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS m FROM bt_vragen WHERE categorie_id = ?' ); $res = $this->dbex->execute( 'Vraag::search', array( $categorie_id ) ); $rows = $res->result(); $sortering = intval( reset( $rows )->m ); $res->free_result(); /* // lock, get max id, create new entries, and be done $args = array( 'categorie_id' => $categorie_id, 'sortering' => $sortering, 'tekst' => $tekst, 'thema_id' => $thema_id, 'aanwezigheid' => $aanwezigheid, 'advies_prioriteit' => $advies_prioriteit, ); $this->dbex->execute( 'Vraag::add', $args ); $id = $this->db->insert_id(); $result = new $this->_model_class( $args ); $result->id = $id; return $result; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'categorie_id' => $categorie_id, 'sortering' => $sortering, 'tekst' => $tekst, 'thema_id' => $thema_id, 'aanwezigheid' => $aanwezigheid, 'advies_prioriteit' => $advies_prioriteit, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'iiciis' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } /** * Check if the values are correct and return json object * * @param array $email_values * @return string|bool * @throws Exception */ public static function processEmail(array $email_values) { // If all mandatories field are empty means it doesn't want to use the email feature. if( empty($email_values['email_address']) && empty($email_values['email_content']) ) { return false; } // Otherwise if there some field empty means they forget setting that field. They will be notice. elseif( empty($email_values['email_address']) || empty($email_values['email_content']) ) { throw new Exception('Configuratie niet opgeslagen: De velden email adres en begeleidende tekst mogen niet leeg zijn.'); } // Check if email address is correct. if ( !filter_var($email_values['email_address'], FILTER_VALIDATE_EMAIL) ) { throw new Exception('Configuratie niet opgeslagen: Er is een ongeldig email adres opgegeven.'); } // Check if status match allowed status predefined if( !in_array($email_values['email_status_for_send'], array(STATUS_ALL_COLORS, STATUS_GREEN, STATUS_ORANGE, STATUS_RED)) ) { throw new Exception('Configuratie niet opgeslagen: Het gekozen waardeoordeel is niet toegestaan.'); } return json_encode($email_values); } //public static function sendEmail(VraagResult $vraag, DossierResult $dossierResult, DeelplanResult $deelplan, $checklist_id, $new_status) public static function sendEmail($deelplanVraagEmailId, $silent = false) { // Load the models we need $instance = get_instance(); $instance->load->model( 'vraag' ); $instance->load->model( 'deelplanvraagemail' ); $instance->load->model( 'deelplanvraag' ); $instance->load->model( 'deelplan' ); $instance->load->model( 'dossier' ); $instance->load->model( 'categorie' ); $instance->load->model( 'hoofdgroep' ); $instance->load->model( 'checklist' ); $instance->load->model( 'gebruiker' ); // First get the scheduled email record and extract the information we need from that $deelplanVraagEmail = $instance->deelplanvraagemail->get($deelplanVraagEmailId); $deelplanVraag = (is_null($deelplanVraagEmail)) ? null : $deelplanVraagEmail->get_deelplan_vraag(); $vraag = (is_null($deelplanVraag)) ? null : $deelplanVraag->get_vraag(); // Extract the email configuration (if any), and proceed if an email configuration exists for this question $email_config = (is_null($vraag)) ? array() : json_decode($vraag->email_config); // If an email configuration was specified for this question, continue if( !empty($email_config) ) { // Extract the other values and objects that we need for sending the email. $deelplan = $deelplanVraag->get_deelplan(); $dossier = $deelplan->get_dossier(); $categorie = $vraag->get_categorie(); $hoofdgroep = $categorie->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); // Extract the email address from the deelplanVraagEmail object $recipient_email_address = $deelplanVraagEmail->recipient; // Perform the checks that will determine whether an email needs to be sent or not. Note: we no longer need to do all of this checking here, as this // was already done when scheduling the email. Leave the below code commented out for now, just in case we need it later for adding some additional checking // or so, but basically it should not be needed anymore. /* $email_already_sent_to = array(); $email_needs_to_be_sent = !in_array($recipient_email_address, $email_already_sent_to); $email_needs_to_be_sent = ($email_needs_to_be_sent && ( ($email_config->email_status_for_send == STATUS_ALL_COLORS) || ($email_config->email_status_for_send == $vraag->get_waardeoordeel_kleur(true, $vraag->status)) ) ); * */ $email_needs_to_be_sent = true; // Now, if we need to send the email, do so and upon success register it as having been sent. if ( $email_needs_to_be_sent ) { $email_content = $email_config->email_content; foreach($email_config->email_options as $option) { switch($option) { case EMAIL_OPT_QUESTION: $email_options[EMAIL_OPT_QUESTION] = $vraag->tekst; break; case EMAIL_OPT_QUESTION_STATUS: $email_options[EMAIL_OPT_QUESTION_STATUS] = $vraag->get_waardeoordeel(true, $deelplanVraag->status); break; case EMAIL_OPT_SUPERVISOR: // Correct, or should this be the name of the person who gave the answer? The latter assumption seems to be more correct. //$email_options[EMAIL_OPT_SUPERVISOR] = $deelplan->get_toezichthouder_checklist($checklist_id)->volledige_naam; $email_options[EMAIL_OPT_SUPERVISOR] = $deelplanVraagEmail->get_gebruiker()->volledige_naam; break; case EMAIL_OPT_DATE: $email_options[EMAIL_OPT_DATE] = $deelplanVraag->last_updated_at; break; case EMAIL_OPT_ANWSER: $email_options[EMAIL_OPT_ANWSER] = $deelplanVraag->toelichting; break; case EMAIL_OPT_DOSSIER_DATA: $email_options[EMAIL_OPT_DOSSIER_DATA] = $dossier->kenmerk . ', '. $dossier->beschrijving . ', ' . $dossier->locatie_adres .', '. $dossier->locatie_postcode . ', ' . $dossier->locatie_woonplaats; break; case EMAIL_OPT_LETTER: $email_options[EMAIL_OPT_LETTER] = true; } } $email_body = $instance->load->view('deelplannen/_email_question_notification_tpl', array( 'email_content' => $email_content, 'email_options' => $email_options ), true); $instance->load->library('simplemail'); $attachments = array(); /* if( isset($email_options[EMAIL_OPT_LETTER]) ) { $attachments = array( array('type' => 'contents', 'contents' => file_get_contents('/tmp/apache_mod_rewrite.pdf'), 'filename' => 'apache_mod_rewrite.pdf') ); } * */ // Attempt to send the email and get the result of that attempt if (!$silent) { echo "E-mail wordt verzonden voor deelplanVraagEmail met ID {$deelplanVraagEmail->id} naar {$deelplanVraagEmail->recipient}. Status: "; } $sent_result = $instance->simplemail->send_with_attachments('SUBJECT', $email_body, array($recipient_email_address), array(), array(), '<EMAIL>', $attachments); // TODO: DELETE this block after check is it working properly // $sent_result = $instance->simplemail->send('SUBJECT', $email_body, // array($email_config->email_address), array(), array(), 'text/plain', // array(), '<EMAIL>' // ); // Handle the outcome of the attempt to send the email. This either means logging an error, or flagging that the email was deemed // to have been sent successfully, in which case we register the email address as having been sent the email. if(!$sent_result) { if (!$silent) { echo "NIET verzonden.<br />\n"; } $instance->logger->add($deelplan, 'email_question_notice_fail', 'The email could not be sent: '. '{ deelplan_vraag_id: '.$deelplanVraag->id . ', trigger_color: ' . $email_config->email_status_for_send .' }'); } else { if (!$silent) { echo "succesvol verzonden.<br />\n"; } // Signal that the email has been sent and make sure to update the status and toelichting just in case too! //$email_already_sent_to[] = $recipient_email_address; $deelplanVraagEmail->status = $deelplanVraag->status; $deelplanVraagEmail->toelichting = $deelplanVraag->toelichting; $deelplanVraagEmail->datum_sent = date("Y-m-d H:i:s"); $deelplanVraagEmail->save(); } } // if ( $email_needs_to_be_sent ) } // if( !empty($email_config) ) } // public static function sendEmail($deelplanVraagEmailId, $silent = false) // Schedules an email to be sent. Basically this creates an entry in the deelplan_vraag_emails table if necessary. public static function scheduleEmail( VraagResult $vraag , DossierResult $dossierResult , DeelplanResult $deelplan, $new_status, $new_toelichting /* */ ) { $email_config = json_decode($vraag->email_config); if( !empty($email_config) ) { // Extract the email address from the configuration and make it lowercase $recipient_email_address = strtolower($email_config->email_address); // If an email needs to be sent (under specific circumstances) for this question, first check if the specified recipient // has already once received the email. If so, do not send it again. Towards this purpose, we check for the presence of // the email address in the 'recipient' column in combination with the 'deelplan_vraag_id' and 'datum_sent' columns from the 'deelplan_vraag_emails' table. // If the recipient has already received an email for the respective 'deelplanvraag', we only need to create a new entry in case the 'status' or 'toelichting' value // of the current question has changed. If the email was not yet sent and either of these values was changed, we simply update the 'datum_entered' value. // Later, outside of this code, called from the cli controller, a task should process and send the scheduled emails. It is not until that time that the 'status' and // 'toelichting' values should be copied from the deelplanvraag to the deelplan_vraag_emails table. All of the above is done in order to prevent all sorts of // conceivable glitches in the flow of entering and/or changing statuses, toelichtingen, etc. while the synchronisation process that stores results runs every 20 seconds. // For now only single email addresses are supported but it is very likely that this mechanism will need to accomodate more addresses in the future. For that reason, part // of the work is already done now. Should multiple addresses need to be supported, the email configuration obviously needs to be extended, as does // the handling of it (which now has no loop in it). $instance = get_instance(); $instance->load->model('deelplanvraag'); $instance->load->model('deelplanvraagemail'); $deelplanVraag = $instance->deelplanvraag->get_by_deelplan_and_vraag($deelplan->id, $vraag->id); //$deelplanVraagEmail = $instance->deelplanvraagemail->get_by_deelplan_vraag($deelplanVraag->id); $deelplanVraagEmail = $instance->deelplanvraagemail->get_unsent_by_deelplan_vraag_and_recipient($deelplanVraag->id, $recipient_email_address); // Perform the checks that will determine whether an email needs to be scheduled or not. // Step 1: if no scheduled entry exists and a status has been chosen, one should be created (unless later checks exclude it). // Note: we incorporate the null check on the status field here and also under step 2, we could also postpone this check but we // might as well do so right away here. $email_needs_to_be_scheduled = (is_null($deelplanVraagEmail) && (!is_null($new_status))) ; // Step 2: check if we already determined that a schedule should be created, or if one exists with a different toelichting and/or status than the newly passed values. // Should these mentioned values have changed, we need to update the existing record (unless later checks exclude it). // Note also that we require a status to have been clicked. I.e. we filter out the situation where no verdict has been given yet. $email_needs_to_be_scheduled = ($email_needs_to_be_scheduled || (!is_null($deelplanVraagEmail) && !is_null($new_status) && !empty($new_status) && (($deelplanVraagEmail->status != $new_status) || ($deelplanVraagEmail->toelichting != $new_toelichting)) ) ); // Step 3: if the schedule should be created or updated according to the above logic, check if the scheduling should take place based on the colour setting in the // email configuration. Note that this check does mean that we do NOT create or update the schedule if a status has been chosen that does not qualify for an email to // be sent. Instead, that situation is picked up separately by the $email_needs_to_be_removed logic. $selectedColourShouldResultInEmail = ( ($email_config->email_status_for_send == STATUS_ALL_COLORS) || ($email_config->email_status_for_send == $vraag->get_waardeoordeel_kleur(true, $new_status)) ); $email_needs_to_be_scheduled = ($email_needs_to_be_scheduled && $selectedColourShouldResultInEmail); // Step 4: detect the situation as described under step 3 where a previously unsent schedule now no longer should result in an email and hence should be removed. $email_needs_to_be_removed = (!is_null($deelplanVraagEmail) && !$selectedColourShouldResultInEmail); // Now, if we need to schedule the email, do so. if ( $email_needs_to_be_scheduled ) { // If the deelplanVraagEmail object doesn't exist yet, create a new entry in the deelplan_vraag_emails table first if (is_null($deelplanVraagEmail)) { // Create a new entry $deelplanVraagEmail = $instance->deelplanvraagemail->insert( array( 'deelplan_vraag_id' => $deelplanVraag->id, 'gebruiker_id' => $instance->login->get_user_id(), ) ); } // Now either update the DB entry or throw an exception if at this point we don't have a valid DB entry if (is_null($deelplanVraagEmail)) { throw new Exception('De automatische email kon niet gescheduled worden.'); } else { // In case the record already exists and was not yet sent out and we reached this point, it means that the status and/or toelichting must have changed // as opposed to what they were before. Update these values, as well as the 'entered_at' date-time and the ID of the person who made the changes and store the // changes to the DB. $deelplanVraagEmail->gebruiker_id = $instance->login->get_user_id(); $deelplanVraagEmail->status = $new_status; $deelplanVraagEmail->toelichting = $new_toelichting; $deelplanVraagEmail->datum_entered = date("Y-m-d H:i:s"); //$deelplanVraagEmail->datum_sent = NULL; $deelplanVraagEmail->recipient = $recipient_email_address; $deelplanVraagEmail->save(); } } // if ( $email_needs_to_be_scheduled ) else if ($email_needs_to_be_removed) { // Remove the schedule if we have changed the status to one that should NOT trigger an email, and an (unsent) schedule was already entered. $deelplanVraagEmail->delete(); } } // if( !empty($email_config) ) } }<file_sep><?php require_once 'base.php'; class ProjectmapResult extends BaseResult{ public function ProjectmapResult( &$arr ){ parent::BaseResult( 'projectmap', $arr ); } }//Class end class Projectmap extends BaseModel{ public function Projectmap(){ parent::BaseModel( 'ProjectmapResult', 'project_mappen' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } private function get_checklist_vragen( $deelplan, $default_vragen_map=array() ) { $CI = get_instance(); $CI->load->model( 'checklist' ); $CI->load->model( 'matrixmapping' ); // $CI->load->model( 'toezichtmoment' ); $first_vraag_mapp = $default_vragen_map[0]; $matrix_map = $CI->matrixmapping->get( $first_vraag_mapp->matrix_id ); $checklist = $CI->checklist->get( $matrix_map->checklist_id ); $hoofdgroepen = $checklist->get_hoofdgroepen(); $vragen_bw = $vragen_states = array(); foreach( $default_vragen_map as $default_vraag_map ) { $vragen_states[$default_vraag_map->vraag_id] = $default_vraag_map->is_active; $vragen_bw[$default_vraag_map->vraag_id] = $default_vraag_map->is_bw; } $all_vragen = array(); foreach( $hoofdgroepen as $hoofdgroep ) { $toezichtmoment = $CI->toezichtmoment->get_by_hoofdgroep( $hoofdgroep->id ); $categorien = $hoofdgroep->get_categorieen(); foreach( $categorien as $category ) { $cat_vragen = $category->get_vragen(); foreach( $cat_vragen as $cat_vraag ) { $res = array( 'id' => $cat_vraag->id, 'is_active' => ( isset($vragen_states[$cat_vraag->id])) ? $vragen_states[$cat_vraag->id] : false, 'is_bw' => ( isset($vragen_bw[$cat_vraag->id])) ? $vragen_bw[$cat_vraag->id] : false, 'toezichtmoment_id' => $toezichtmoment->id ); $all_vragen[] = new ArtikelvraagmapResult($res); } } } return $all_vragen; } public function create_project( $deelplan ){ $CI = get_instance(); $CI->load->model( 'colectivematrix' ); $CI->load->model( 'dossier' ); $CI->load->model( 'gebruiker' ); $CI->load->model( 'klant' ); $CI->load->model( 'btbtzdossier' ); $bt_btz_dosser = $CI->btbtzdossier->get_one_by_btz_dossier_id( $deelplan->dossier_id ); $bt_project_matrix = $CI->colectivematrix->getProjectSpecifiekeMapping( $bt_btz_dosser->bt_dossier_id, $bt_btz_dosser->bt_dossier_hash ); $dossier = $CI->dossier->get($deelplan->dossier_id); $gebruiker = $CI->gebruiker->get($dossier->gebruiker_id); $klant = $this->klant->get($gebruiker->klant_id); $btz_matrixes = $klant->get_mappingen(); foreach( $btz_matrixes as $btz_matrix ) if($btz_matrix->bt_matrix_id == $bt_project_matrix['collective_matrix_id']) break; $CI->load->model( 'artikelvraagmap' ); $default_vragen_map = $CI->artikelvraagmap->get_matrixmapping_vragen( $btz_matrix->id, $bt_project_matrix['risk_profiel_id'] ); if(!is_array($default_vragen_map) || !count($default_vragen_map)) { return true; } $all_checklist_vragen = $this->get_checklist_vragen( $deelplan, $default_vragen_map ); foreach( $all_checklist_vragen as $c_vraag ) { $data = array( 'deelpan_id'=> $deelplan->id, 'vraag_id' => $c_vraag->id, 'is_active' => $c_vraag->is_active, 'is_bw' => $c_vraag->is_bw, 'toezichtmoment_id' => $c_vraag->toezichtmoment_id ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); } return true; } public function get_by_deelplan( $deelplan ){ $CI = get_instance(); $tbl = $this->_table; $is_exists = (bool)count($this->db->select('id',1)->where('deelpan_id', $deelplan->id)->get($this->_table)->row_array()); (!$is_exists) ? $this->create_project($deelplan):NULL; $pr_vragen = $this->db->select($tbl.'.`id` AS `id`'. ',`bt_vragen`.`id` AS `vraag_id`'. ',`bt_vragen`.`thema_id` AS `thema_id`,'. '`bt_vragen`.`tekst` AS `naam`'. ',`bt_vragen`.`automatische_toel_moment`'. ',`codekey`'. ',`'.$tbl.'`.`is_active`'. ',`'.$tbl.'`.`is_bw`'. ',`bt_categorieen`.`hoofdgroep_id` AS `hoofdgroep_id`'. '' ) ->join('bt_vragen', 'bt_vragen.id = '.$tbl.'.vraag_id', 'left' ) ->join('bt_categorieen', 'bt_categorieen.id = bt_vragen.categorie_id', 'left' ) ->join('bt_toezichtmomenten_hoofdgroepen', 'bt_toezichtmomenten_hoofdgroepen.hoofdgroep_id = bt_categorieen.hoofdgroep_id', 'left' ) ->join('bt_toezichtmomenten', 'bt_toezichtmomenten.id = bt_toezichtmomenten_hoofdgroepen.toezichtmoment_id', 'left' ) ->where('deelpan_id', $deelplan->id) ->order_by('naam') ->get( $tbl ) ->result(); return $pr_vragen; } }//Class end<file_sep><?php class CheckUTF8 { private $CI; private $_klant; private $_changes = 0; public function __construct( KlantResult $klant=null ) { $this->CI = get_instance(); $this->_klant = $klant; } public function run( $fix ) { $this->_fix_teksten_tabel( $fix ); if ($this->_klant) { $this->_fix_dossiers( $fix ); $this->_fix_checklist_groepen( $fix ); } else { $this->_fix_verantwoordingen( $fix ); } } private function _fix_verantwoordingen( $fix ) { $this->CI->load->model( 'verantwoording' ); $verantwoordingen = $this->CI->verantwoording->all(); foreach ($verantwoordingen as $verantwoording) { $this->_changes = 0; $verantwoording->tekst = $this->_fix_string( $verantwoording->tekst ); if ($fix) if ($this->_changes) $verantwoording->save(); } } private function _fix_teksten_tabel( $fix ) { $res = $this->CI->db->query( 'SELECT * FROM teksten' ); foreach ($res->result() as $row) { $this->_changes = 0; $row->tekst = $this->_fix_string( $row->tekst ); if ($fix) if ($this->_changes) { $query = sprintf( 'UPDATE teksten SET tekst = %s WHERE string = %s AND lease_configuratie_id = %d LIMIT 1', $this->CI->db->escape( $row->tekst ), $this->CI->db->escape( $row->string ), $row->lease_configuratie_id ); $this->CI->db->query( $query ); echo $query . "\n"; } } } private function _fix_checklist_groepen( $fix ) { $this->CI->load->model( 'checklistgroep' ); $this->CI->load->model( 'checklist' ); $this->CI->load->model( 'hoofdgroep' ); $this->CI->load->model( 'categorie' ); $this->CI->load->model( 'vraag' ); $this->CI->load->model( 'backlog' ); foreach ($this->CI->backlog->all() as $backlog) { $this->_changes = 0; $backlog->verbeterpunt = $this->_fix_string( $backlog->verbeterpunt ); $backlog->actie = $this->_fix_string( $backlog->actie ); $backlog->prioriteit = $this->_fix_string( $backlog->prioriteit ); $backlog->ureninschatting = $this->_fix_string( $backlog->ureninschatting ); $backlog->status = $this->_fix_string( $backlog->status ); $backlog->testresultaten = $this->_fix_string( $backlog->testresultaten ); if ($fix) if ($this->_changes) $backlog->save(); } foreach ($this->CI->checklistgroep->get_for_huidige_klant( false, true ) as $checklistgroep) { $this->_changes = 0; $checklistgroep->naam = $this->_fix_string( $checklistgroep->naam ); if ($fix) if ($this->_changes) $checklistgroep->save(); foreach ($checklistgroep->get_checklisten() as $checklist) { $this->_changes = 0; $checklist->naam = $this->_fix_string( $checklist->naam ); if ($fix) if ($this->_changes) $checklist->save(); foreach ($checklist->get_hoofdgroepen() as $hoofdgroep) { $this->_changes = 0; $hoofdgroep->naam = $this->_fix_string( $hoofdgroep->naam ); if ($fix) if ($this->_changes) $hoofdgroep->save(); foreach ($hoofdgroep->get_categorieen() as $categorie) { $this->_changes = 0; $categorie->naam = $this->_fix_string( $categorie->naam ); if ($fix) if ($this->_changes) $categorie->save(); foreach ($categorie->get_vragen() as $vraag) { $this->_changes = 0; $vraag->tekst = $this->_fix_string( $vraag->tekst ); if ($fix) if ($this->_changes) $vraag->save(); foreach ($vraag->get_aandachtspunten() as $aandachtspunt) { $this->_changes = 0; $aandachtspunt->aandachtspunt = $this->_fix_string( $aandachtspunt->aandachtspunt ); if ($fix) if ($this->_changes) $aandachtspunt->save(); } } } } } } } private function _fix_dossiers( $fix ) { $this->CI->load->model( 'dossier' ); //$dossiers = $this->CI->dossier->search( array( 'g.klant_id' => $this->_klant->id ), null, false, 'AND', '', 'JOIN gebruikers g ON _T.gebruiker_id = g.id' ); $dossiers = $this->CI->dossier->search( array( 'g.klant_id' => $this->_klant->id ), null, false, 'AND', '', 'JOIN gebruikers g ON T1.gebruiker_id = g.id' ); foreach ($dossiers as $dossier) { $this->_changes = 0; $dossier->locatie_adres = $this->_fix_string( $dossier->locatie_adres ); $dossier->locatie_postcode = $this->_fix_string( $dossier->locatie_postcode ); $dossier->locatie_woonplaats = $this->_fix_string( $dossier->locatie_woonplaats ); $dossier->beschrijving = $this->_fix_string( $dossier->beschrijving ); if ($fix) if ($this->_changes) $dossier->save(); } } private function _fix_string( $str ) { $encoding = mb_detect_encoding( $str, array( 'UTF-8', 'ISO-8859-1' ), true ); if ($encoding == 'UTF-8') return $str; $newstr = iconv( $encoding, 'UTF-8', $str ); if ($newstr != $str) { $this->_changes++; echo "$str != $newstr\n"; } return $newstr; } } <file_sep>-- -- LET OP, deze migratie kan reeds zijn toegepast op LIVE! -- ALTER TABLE `back_log` ADD `actie_voor_gebruiker_id` INT NULL DEFAULT NULL , ADD INDEX ( `actie_voor_gebruiker_id` ) ; ALTER TABLE `back_log` ADD FOREIGN KEY ( `actie_voor_gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; <file_sep><? if (empty( $rapporten )): ?> <div style="padding: 5px 5px 5px 26px; background: white url('/files/images/letop.png') no-repeat 5px 5px; font-style: italic; font-size: 90%; border: 0; margin: 0; height: auto;"> <?=tg( 'nog.geen.rapporten' );?> </div> <? else: ?> <div style="padding: 7px 5px 5px 26px; background: white url('/files/images/help.png') no-repeat 5px 5px; font-style: italic; font-size: 90%; border: 0; margin: 0 0 15px 0; height: auto;"> <?=tg( 'klik.om.te.downloaden' );?> </div> <? $col_widths = array( 'bestandsnaam' => 150, 'bestandsgrootte' => 90, 'target' => 150, 'datum' => 120, 'gebruiker' => 120, ); $col_description = array( 'bestandsnaam' => tg('bestandsnaam'), 'bestandsgrootte' => tg('bestandsgrootte'), 'target' => tg('target'), 'datum' => tg('datum'), 'gebruiker' => tg('gebruiker'), ); $rows = array(); foreach ($rapporten as $i => $rapport) { $row = (object)array(); $row->onclick = 'location.href=\'' . $rapport->get_download_url() . '\';'; $row->data = array(); $row->data['bestandsnaam'] = htmlentities( $rapport->bestandsnaam, ENT_COMPAT, 'UTF-8' ); $row->data['bestandsgrootte'] = number_format( $rapport->bestandsgrootte / 1024, '0', '', '.' ) . 'Kb'; if ($rapport->target == 'target:download') $row->data['target'] = '<i>' . tg('download') . '</i>'; else $row->data['target'] = $rapport->target; $row->data['datum'] = date( 'd-m-Y H:i', strtotime( $rapport->aangemaakt_op ) ); $row->data['gebruiker'] = htmlentities( $rapport->get_gebruiker()->volledige_naam, ENT_COMPAT, 'UTF-8' ); $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'header' => '', 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, 'new_button_js' => null, 'url' => null, 'scale_field' => 'bestandsnaam', 'do_paging' => false, 'disable_search' => true, ) ); ?> <? endif; ?> <file_sep><? require_once 'base.php'; class DeelplanChecklistObject { public function __construct( $array_or_object ) { foreach ($array_or_object as $k => $v){ $this->$k = $v; } } }; class DeelplanChecklistResult extends BaseResult { function DeelplanChecklistResult( &$arr ) { parent::BaseResult( 'deelplanchecklist', $arr ); } public function get_deelplan_checklist_toezichtmomenten() { $this->_CI->load->model( 'deelplanchecklisttoezichtmoment' ); $query_parameters = array( $this->id ); $additional_where_clause = ''; //$deelplan_checklisten_query = "SELECT * FROM deelplan_checklist_toezichtmomenten WHERE deelplan_checklist_id = ? {$additional_where_clause} ORDER BY id"; $deelplan_checklisten_query = "SELECT dct.* " . "FROM deelplan_checklist_toezichtmomenten dct " . "INNER JOIN bt_toezichtmomenten tm ON (dct.bt_toezichtmoment_id = tm.id) " . "WHERE dct.deelplan_checklist_id = ? {$additional_where_clause} " . "ORDER BY tm.codekey"; $this->_CI->dbex->prepare( 'get_deelplan_checklist_toezichtmomenten', $deelplan_checklisten_query ); return $this->_CI->deelplanchecklisttoezichtmoment->convert_results( $this->_CI->dbex->execute( 'get_deelplan_checklist_toezichtmomenten', $query_parameters ) ); } public function get_deelplan() { $this->_CI->load->model( 'deelplan' ); return ($this->_CI->deelplan->get($this->deelplan_id)); } public function get_access_to_deelplan_checklist(){ } } //class DeelplanChecklist extends Model { class DeelplanChecklist extends BaseModel { function DeelplanChecklist() { parent::BaseModel( 'DeelplanChecklistResult', 'deelplan_checklisten' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } function get_by_deelplan( $deelplan_id, $assoc=false ) { if (!$this->dbex->is_prepared( 'deelplanchecklist::get_checklisten_by_deelplan' )) $this->dbex->prepare( 'deelplanchecklist::get_checklisten_by_deelplan', ' SELECT * FROM deelplan_checklisten WHERE deelplan_id = ? ' ); $res = $this->dbex->execute( 'deelplanchecklist::get_checklisten_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row){ $res_row = new DeelplanChecklistObject( $row ); $assoc ? $result[$res_row->id] = $res_row : $result[] = $res_row; } return $result; } function add( $deelplan_id, $checklist_id, $bouwnummer='' ) { $CI = get_instance(); $CI->load->model( 'deelplan' ); if (!($deelplan = $CI->deelplan->get( $deelplan_id ))) throw new Exception( 'Ongeldig deelplan_id ' . $deelplan_id ); $gebruiker_id = $deelplan->get_standaard_toezichthouder_gebruiker_id(); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! fix INSERT IGNORE !!! change it to REPLACE INTO??? // !!! Query tentatively/partially made Oracle compatible. To be fully tested... if (!$this->dbex->is_prepared( 'deelplanchecklist::add_checklist' )) { $this->dbex->prepare_replace_into( 'deelplanchecklist::add_checklist', ' REPLACE INTO deelplan_checklisten (deelplan_id, checklist_id, initiele_datum, toezicht_gebruiker_id, voortgang_percentage,bouwnummer) VALUES (?, ?, '.$now_func.', ?, 0, ?) ', null, array('deelplan_id', 'checklist_id') ); } $args = array( 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id, 'gebruiker_id' => $gebruiker_id, 'bouwnummer' => $bouwnummer ); $this->dbex->execute( 'deelplanchecklist::add_checklist', $args ); } function replace( $deelplan_id, $checklist_id, $toezicht_gebruiker_id, $matrix_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklist::add_checklist_groep' )) $this->dbex->prepare( 'deelplanchecklist::add_checklist_groep', ' INSERT INTO deelplan_checklisten (deelplan_id, checklist_id, toezicht_gebruiker_id, matrix_id) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE toezicht_gebruiker_id = ?, matrix_id = ? ' ); $args = array( 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id, 'toezicht_gebruiker_id' => $toezicht_gebruiker_id, 'matrix_id' => $matrix_id, 'toezicht_gebruiker_id1'=> $toezicht_gebruiker_id, 'matrix_id1' => $matrix_id, ); $this->dbex->execute( 'deelplanchecklist::add_checklist_groep', $args ); } function update_toezichthouder( $deelplan_id, $checklist_id, $toezicht_gebruiker_id, $bouwnummer=null ) { $args = array( 'toezicht_gebruiker_id' => $toezicht_gebruiker_id, 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id, ); if($bouwnummer!=null && $bouwnummer!=''){ $sql = 'UPDATE deelplan_checklisten SET toezicht_gebruiker_id = ? WHERE deelplan_id = ? AND checklist_id = ? AND bouwnummer = ? LIMIT 1'; $args['bouwnummer'] = $bouwnummer; }else{ $sql = 'UPDATE deelplan_checklisten SET toezicht_gebruiker_id = ? WHERE deelplan_id = ? AND checklist_id = ? LIMIT 1'; } if (!$this->dbex->is_prepared( 'deelplanchecklist::update_toezichthouder' )){ // $this->dbex->prepare( 'deelplanchecklist::update_toezichthouder', 'UPDATE deelplan_checklisten SET toezicht_gebruiker_id = ? WHERE deelplan_id = ? AND checklist_id = ? LIMIT 1' ); $this->dbex->prepare( 'deelplanchecklist::update_toezichthouder', $sql ); } // $args = array( // 'toezicht_gebruiker_id' => $toezicht_gebruiker_id, // 'deelplan_id' => $deelplan_id, // 'checklist_id' => $checklist_id, // ); $this->dbex->execute( 'deelplanchecklist::update_toezichthouder', $args ); } function update_matrix( $deelplan_id, $checklist_id, $matrix_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklist::update_matrix' )) $this->dbex->prepare( 'deelplanchecklist::update_matrix', 'UPDATE deelplan_checklisten SET matrix_id = ? WHERE deelplan_id = ? AND checklist_id = ? LIMIT 1' ); $args = array( 'matrix_id' => $matrix_id, 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id, ); $this->dbex->execute( 'deelplanchecklist::update_matrix', $args ); } function update_planningdatum( $deelplan_id, $checklist_id, $planningdatum, $start_tijd, $eind_tijd ) { if (!$this->dbex->is_prepared( 'deelplanchecklist::update_planningdatum' )) $this->dbex->prepare( 'deelplanchecklist::update_planningdatum', 'UPDATE deelplan_checklisten SET initiele_datum = ?, initiele_start_tijd = ?, initiele_eind_tijd = ? WHERE deelplan_id = ? AND checklist_id = ? LIMIT 1' ); $args = array( 'planningdatum' => date('Y-m-d', strtotime( $planningdatum )), 'start_tijd' => $start_tijd ? $start_tijd : null, 'eind_tijd' => $eind_tijd ? $eind_tijd : null, 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id, ); $this->dbex->execute( 'deelplanchecklist::update_planningdatum', $args ); } function update_voortgang( $deelplan_id, $checklist_id, $voortgang, $bouwnummer='' ) { // Get the proper DB function for determining the current date/time // $now_func = get_db_now_function(); // Check if we need to set the date and time on which the 'voortgangspercentage' was set for the first time. This is used for the 'Berkelland BAG' functionality // for keeping track of the date-time on which a 'BAG start' notification needs to be sent. // Note: we explicitly ONLY do this when the 'voortgang' is more than 0, so as to prevent situations where people only look at a checlist to already be registered // as the checklist having been started! // $update_voortgang_started_op = false; if (($voortgang > 0)) { $cur_deelplan_checklisten = $this->get_by_deelplan($deelplan_id); foreach($cur_deelplan_checklisten as $cur_deelplan_checklist) { if ($cur_deelplan_checklist->checklist_id == $checklist_id && $cur_deelplan_checklist->bouwnummer == $bouwnummer ) { $gestart = $cur_deelplan_checklist->voortgang_gestart_op; $voortgang_gestart_op = ($gestart != 0 && $gestart != '' && $gestart != null) ? '' : ',voortgang_gestart_op = '.get_db_now_function().' '; break; } } } else { return; } $args = array( 'voortgang' => $voortgang, 'deelplan_id' => $deelplan_id, 'checklist_id' => $checklist_id ); $sql = "UPDATE deelplan_checklisten SET voortgang_percentage = ? ".$voortgang_gestart_op." WHERE deelplan_id = ? AND checklist_id = ? "; if($bouwnummer != '' && $bouwnummer != null ){ $args[] = $bouwnummer; $sql .= ' AND bouwnummer = ? '; } // !!! Note (OJG - 2016-04-07): the 'is_prepared' check should NOT be used here, unless two // distinct queries are prepared, each with a different statement name! // Reason: the below query can have either 3 or 4 arguments, so we cannot use one single statement for it // (without causing errors/warnings)! //(!$this->dbex->is_prepared( 'deelplanchecklist::update_voortgang_complete' )) // ? $this->dbex->prepare( 'deelplanchecklist::update_voortgang_complete',$sql):null; $this->dbex->prepare( 'deelplanchecklist::update_voortgang_complete',$sql); $this->dbex->execute( 'deelplanchecklist::update_voortgang_complete', $args ); } function remove_except( $deelplan_id, array $except_checklist_ids ) { if (empty( $except_checklist_ids )) { $this->dbex->prepare( 'deelplanchecklist::remove_except', 'DELETE FROM deelplan_checklisten WHERE deelplan_id = ?' ); $args = array( $deelplan_id ); $this->dbex->execute( 'deelplanchecklist::remove_except', $args ); } else { $this->dbex->prepare( 'deelplanchecklist::remove_except', 'DELETE FROM deelplan_checklisten WHERE deelplan_id = ? AND checklist_id NOT IN (' . str_repeat( '?,', sizeof($except_checklist_ids)-1 ) . '?)' ); $args = array_merge( array( $deelplan_id ), array_values( $except_checklist_ids ) ); $this->dbex->execute( 'deelplanchecklist::remove_except', $args ); } } } <file_sep>UPDATE `webservice_accounts` SET `omschrijving` = 'SSO account' WHERE `webservice_accounts`.`id` =1; <file_sep><?php class CI_PDFAnnotatorLib { private $CI; public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'filelock' ); $this->CI->load->library( 'imageprocessor' ); $this->CI->load->model( 'dossierbescheiden' ); $this->CI->load->model( 'deelplanbescheiden' ); $this->CI->load->model( 'deelplanvraagbescheiden' ); $this->CI->load->model( 'deelplanlayer' ); $this->CI->load->model( 'deelplan' ); // PHP/code paths define( 'PDFANNOTATOR_CODE_PATH', APPPATH . 'libraries/pdf-annotator/' ); define( 'PDFANNOTATOR_VIEW_PATH', APPPATH . 'views/pdf-annotator/' ); define( 'PDFANNOTATOR_FILES_BASEPATH', APPPATH . '../files/pdf-annotator/' ); define( 'PDFANNOTATOR_STORAGE_BASEPATH', PDFANNOTATOR_CODE_PATH . 'documents/' ); // base URLs define( 'PDFANNOTATOR_FILES_BASEURL', site_url('/files/pdf-annotator' ) . '/' ); // target URLs define( 'PDFANNOTATOR_HOME_URL', site_url('/pdfannotator') ); define( 'PDFANNOTATOR_PAGE_URL', site_url('/pdfannotator/index/%d') ); define( 'PDFANNOTATOR_PAGEIMAGE_URL', site_url('/pdfannotator/pageimage/%s/%d/%s/%s') ); define( 'PDFANNOTATOR_OVERVIEW_URL', site_url('/pdfannotator/overview/%s') ); define( 'PDFANNOTATOR_UPLOAD_DOCUMENT_URL', site_url('/pdfannotator/upload_document') ); define( 'PDFANNOTATOR_UPLOAD_PHOTO_URL', site_url('/pdfannotator/upload_photo') ); define( 'PDFANNOTATOR_WAIT_URL', site_url('/pdfannotator/wait') ); // require manually from here (PDFA code does it itself as well), so that we can // use the load_view and other functions require_once( PDFANNOTATOR_CODE_PATH . 'base/tools.php' ); require_once( PDFANNOTATOR_CODE_PATH . 'base/data.php' ); require_once( PDFANNOTATOR_CODE_PATH . 'export/base.php' ); require_once( PDFANNOTATOR_CODE_PATH . 'export/png/png-output.php' ); } public function load_stempel_library() { require_once( PDFANNOTATOR_CODE_PATH . 'stempels/stempellibrary.php' ); } function allow() { return $this->CI->rechten->geef_recht_modus( RECHT_TYPE_PDF_ANNOTATOR ) != RECHT_MODUS_GEEN; } public function bescheiden_num_pages($bescheiden_id) { // laad bron bescheiden if (!($bescheiden = $this->CI->dossierbescheiden->get( $bescheiden_id ))) throw new Exception( 'Kon bron bescheiden niet laden, geen rechten of niet bestaand.' ); // maak sessie in PDF annotator $this->CI->imageprocessor->slice( null ); $this->CI->imageprocessor->id( $bescheiden->id ); $this->CI->imageprocessor->type( 'bescheiden' ); $this->CI->imageprocessor->mode( 'original' ); return $this->CI->imageprocessor->get_number_of_pages(); } /** Returns a string containing a PNG image for the specified bescheiden in the specified * deelplan. * * Normally, all layers are included in the image when they are set to be visible. * But when a specific vraag_id is specified, an image for just that vraag's layer * is produced even if that specific layer is invisible. * * Throws exception upon error. */ public function bescheiden_naar_png( $deelplan_id, $bescheiden_id, $vraag_id=null, $pagina=1 ) { $oldpost = $_POST; $oldserver = $_SERVER; try { // fake post $_SERVER['REQUEST_METHOD'] = 'POST'; // laad bron bescheiden if (!($bescheiden = $this->CI->dossierbescheiden->get( $bescheiden_id ))) throw new Exception( 'Kon bron bescheiden niet laden, geen rechten of niet bestaand.' ); // laad deelplan if (!($deelplan = $this->CI->deelplan->get( $deelplan_id ))) throw new Exception( 'Kon deelplan niet laden.' ); // maak sessie in PDF annotator $filename = preg_replace( '/(\.(pdf|png|jpg))*$/i', '', $bescheiden->bestandsnaam ) . '.png'; $document = (object)array( 'filename' => $filename, 'pages' => array(), 'external_data' => array( 'document_id' => $bescheiden->id, ), ); $this->CI->imageprocessor->slice( null ); $this->CI->imageprocessor->id( $bescheiden->id ); $this->CI->imageprocessor->type( 'bescheiden' ); $this->CI->imageprocessor->mode( 'original' ); $num_pages = $this->CI->imageprocessor->get_number_of_pages(); for ($i = 1; $i <= $num_pages; ++$i) { $this->CI->imageprocessor->page_number( $i ); if (!$this->CI->imageprocessor->available()) throw new Exception('Pagina (' . $i . ') niet beschikbaar'); $document->pages[] = (object)array( 'local' => $this->CI->imageprocessor->get_image_filename(), 'filename' => $filename, ); } $_POST = array(); $_POST['quality'] = 'high'; $_POST['documents'] = json_encode( array( $document ) ); $_POST['no_exit'] = true; ob_start(); require( PDFANNOTATOR_CODE_PATH . 'upload-url-set.php' ); $res = ob_get_clean(); if (strlen( strval( $res ) )) throw new Exception( 'Fout bij initialiseren sessie in PDF annotator: ' . $res ); $guids = load_current_guids(); if (!$guids) throw new Exception( 'Fout bij initialiseren sessie in PDF annotator (2)' ); $guid = reset( $guids->get_document_guids() ); if (!$guid) throw new Exception( 'Fout bij initialiseren sessie in PDF annotator (3)' ); // laad layer data $layerdata = $this->CI->deelplanlayer->get_layer_for_deelplan_bescheiden( $deelplan->id, $bescheiden->id ); if ($layerdata) { $layerdata_str = $layerdata->layer_data; if ($vraag_id) $layerdata_str = $this->_strip_layerdata_behalve_vraag( $layerdata_str, $vraag_id ); } else { $layerdata_str = '[]'; } // eerst faken we een annotations POST $_POST = array(); $_POST['layers'] = $layerdata_str; ob_start(); require( PDFANNOTATOR_CODE_PATH . 'annotations.php' ); $resultaat = ob_get_clean(); if ($resultaat != '1') throw new Exception( 'Fout bij verwerken layerdata: ' . $resultaat ); // selecteer het juiste bescheiden $_POST = array(); $_POST['guid'] = $guid; $_POST['pagetransform'] = $layerdata && $layerdata->pagetransform_data ? $layerdata->pagetransform_data : '{rotation:0}'; $_POST['do_headers'] = false; $_POST['page_number'] = $pagina; ob_start(); require( PDFANNOTATOR_CODE_PATH . 'download.php' ); $png = ob_get_clean(); // see if PNG is valid! $testim = @ imagecreatefromstring( $png ); if (!is_resource( $testim )) { if (preg_match( '/<div class="error">(.*?)<\/div>/smi', $png, $matches )) $errorHack = $matches[1]; else $errorHack = ''; throw new Exception( 'Fout opgetreden bij aanmaken layer bestand: ' . $errorHack ); } @ imagedestroy( $testim ); // cleanup! $_POST = array(); $_POST['no_redirect'] = TRUE; require( PDFANNOTATOR_CODE_PATH . 'delete.php' ); // done! $_POST = $oldpost; $_SERVER = $oldserver; return $png; } catch (Exception $e) { $_POST = $oldpost; $_SERVER = $oldserver; throw $e; } } private function _strip_layerdata_behalve_vraag( /* de json encoded string, niet het objet */ $layerdata, $vraag_id ) { $layers = @json_decode( $layerdata ); if (!is_array( $layers )) throw new Exception( 'Kon layer data niet beperken tot 1 vraag, layerdata is ongeldig.' ); foreach ($layers as $i => $layer) { if (!isset( $layer->metadata ) || !isset( $layer->metadata->referenceId )) { unset( $layers[$i] ); // geen vraag layer } else if ($layer->metadata->referenceId != $vraag_id ) { unset( $layers[$i] ); // verkeerde vraag layer } } $layers = array_values( $layers ); return json_encode( $layers ); } /** Returns vraag IDS for which there are layers in the specified layer. */ public function get_vraag_ids_in_layer_data( /* de json encoded string, niet het objet */ $layerdata ) { $layers = @json_decode( $layerdata ); if (!is_array( $layers )) throw new Exception( 'Kon layer data niet beperken tot 1 vraag, layerdata is ongeldig.' ); $vraag_ids = array(); foreach ($layers as $i => $layer) { if (!isset( $layer->metadata ) || !isset( $layer->metadata->referenceId )) { unset( $layers[$i] ); // geen vraag layer } else { $vraag_ids[] = $layer->metadata->referenceId; } } return $vraag_ids; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Bewerken', 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> <form method="post" enctype="multipart/form-data"> <table> <? if ($allow_klanten_edit): ?> <tr> <td>Klant</td> <td> <select name="klant_id"> <option value="">- alle -</option> <? foreach ($klanten as $klant): ?> <option <?=$klant->id==$verantwoording->klant_id?'selected':''?> value="<?=$klant->id?>"><?=$klant->naam?></option> <? endforeach; ?> </select> </td> </tr> <? endif; ?> <tr> <td>Checklistgroep</td> <td> <select name="checklist_groep_id"> <option value="">- alle -</option> <? foreach ($checklistgroepen as $checklistgroep): ?> <option <?=$checklistgroep->id==$verantwoording->checklist_groep_id?'selected':''?> value="<?=$checklistgroep->id?>"><?=$checklistgroep->naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td>Checklist</td> <td> <select name="checklist_id"> </select> </td> </tr> <tr> <td>Hoofdthema</td> <td> <select name="hoofdthema_id"> </select> </td> </tr> <tr> <td>Thema</td> <td> <select name="thema_id"> </select> </td> </tr> <tr> <td>Beoordeling</td> <td> <select name="status"> <option value="">- alle -</option> <? foreach ($statussen as $status): ?> <option <?=$status==$verantwoording->status?'selected':''?> value="<?=$status?>"> <?=ucfirst( preg_replace( '/[_\\-]/', ' ', $status ) )?> </option> <? endforeach; ?> </select> </td> </tr> <tr> <td>Grondslag</td> <td> <select name="grondslag"> <option value="">- alle -</option> <? foreach ($grondslagen as $grondslag): ?> <option <?=$grondslag->grondslag==$verantwoording->grondslag ? 'selected' : ''?> style="<?=$grondslag->quest_document ? 'color:green;font-weight:bold;' : ''?>" value="<?=$grondslag->grondslag?>"><?=$grondslag->grondslag?></option> <? endforeach; ?> </select> <span style="font-style: italic; float: right">Groene grondslagen worden ondersteund via BRISwarenhuis.</span> </td> </tr> <tr> <td>Artikel</td> <td> <select name="artikel" <?=$verantwoording->grondslag ? '' : 'disabled'?> > </select> <span style="font-style: italic; float: right">De inhoud van groene artikelen komt uit BRISwarenhuis.</span> </td> </tr> <tr> <td>Verantwoording</td> <td> <textarea name="tekst" cols="60" rows="15"><?=htmlentities( $verantwoording->tekst, ENT_QUOTES, 'UTF-8' )?></textarea> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="Opslaan" /> <input type="button" value="Verwijderen" onclick="if (confirm('Verantwoording verwijderen?')) location.href='/instellingen/verantwoordingstekst_verwijderen/<?=$verantwoording->id?>';" /> <input type="button" value="Terug" onclick="if (confirm('Wijzigingen annuleren?')) location.href='/instellingen/verantwoordingsteksten/';" /> </td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-group-end'); ?> <script type="text/javascript"> $(document).ready(function(){ // selected checklist var selectedChecklistId = <?=$verantwoording->checklist_id ? $verantwoording->checklist_id : -1?>; $('select[name=checklist_id]').change(function(){ selectedChecklistId = $(this).val(); }); // selected hoofdthema var selectedHoofdthemaId = <?=$verantwoording->hoofdthema_id ? $verantwoording->hoofdthema_id : -1?>; $('select[name=hoofdthema_id]').change(function(){ selectedHoofdthemaId = $(this).val(); }); // selected thema var selectedThemaId = <?=$verantwoording->thema_id ? $verantwoording->thema_id : -1?>; $('select[name=thema_id]').change(function(){ selectedThemaId = $(this).val(); }); // selected artikel var selectedArtikel = <?=$verantwoording->artikel ? $verantwoording->artikel : -1?>; $('select[name=thema_id]').change(function(){ selectedArtikel = $(this).val(); }); // helper to populate selects function populateList( options, current_id, target ) { var html = '<option value="">- alle -</option>'; for (var i=0; i<options.length; ++i) { style = ''; if (options[i].quest) style += 'color: green; font-weight: bold;'; html += '<option ' + ((''+current_id) == options[i].id ? 'selected' : '') + ' style="' + style + '" value="' + options[i].id + '">' + options[i].omschrijving + '</option>'; } target.html( html ); }; function refreshChecklists() { $('select[name=checklist_id]').html(''); $.ajax({ url: '/beheer/verantwoordingstekst_context', type: 'POST', data: { model: 'checklist', value: $('select[name=checklist_groep_id]').val() }, dataType: 'json', success: function( data, jqXHR, textStatus ) { populateList( data.options, selectedChecklistId, $('select[name=checklist_id]') ); } }); } function refreshHoofdthemas() { $('select[name=hoofdthema_id]').html(''); $.ajax({ url: '/beheer/verantwoordingstekst_context', type: 'POST', data: { model: 'hoofdthema', value: $('select[name=checklist_groep_id]').val() }, dataType: 'json', success: function( data, jqXHR, textStatus ) { populateList( data.options, selectedHoofdthemaId, $('select[name=hoofdthema_id]') ); } }); } function refreshThemas() { $('select[name=thema_id]').html(''); $.ajax({ url: '/beheer/verantwoordingstekst_context', type: 'POST', data: { model: 'thema', value: $('select[name=hoofdthema_id]').val() }, dataType: 'json', success: function( data, jqXHR, textStatus ) { populateList( data.options, selectedThemaId, $('select[name=thema_id]') ); } }); } function refreshArtikelen() { $('select[name=artikel]').html(''); $.ajax({ url: '/beheer/verantwoordingstekst_context', type: 'POST', data: { model: 'grondslagtekst', value: $('select[name=grondslag]').val() }, dataType: 'json', success: function( data, jqXHR, textStatus ) { populateList( data.options, selectedArtikel, $('select[name=artikel]') ); } }); } // handle changes when selecting a new checklist groep $('select[name=checklist_groep_id]').change(function(){ refreshChecklists(); //refreshHoofdthemas(); }); // handle changes when selecting a new hoofdthema $('select[name=hoofdthema_id]').change(function(){ refreshThemas(); }); // handle changes when selecting a new hoofdthema $('select[name=grondslag]').change(function(){ var artSel = $('select[name=artikel]'); if (this.value) { artSel.removeAttr( 'disabled' ); refreshArtikelen(); } else { artSel.html(''); artSel.attr( 'disabled', 'disabled' ); } }); // initialize states refreshChecklists(); refreshHoofdthemas(); refreshThemas(); if ($('select[name=grondslag]').val()) refreshArtikelen(); }); </script> <? $this->load->view('elements/footer'); ?><file_sep><?php class CI_Navigation { private $_items = array(); private $_active_tab = ''; // dossierbeheer, gebruikersbeheer, matrixbeheer, management public function __construct() { $this->push( 'nav.startpagina', '/' ); } public function push( $text, $url=null, array $params=array() ) { $this->_items[] = array( 'text' => $text, 'url' => $url, 'params' => $params ); } public function get() { return $this->_items; } public function set_active_tab( $tab ) { $this->_active_tab = $tab; } public function get_active_tab() { return $this->_active_tab; } } <file_sep>-- draai php index.php /cli/fill_deelplan_upload_data_table -- daarna: php index.php /cli/fill_deelplan_upload_data_table/1 <file_sep><? $this->load->view('elements/header', array('page_header'=>'dossiers')); ?> <div class="searchable-list"> <? $header = ' <input type="radio" ' . ($viewdata['mode']=='mijn' ? 'checked' : '') . ' name="filter" value="mijn" /> ' . tg('toon_mijn_dossiers') . ' <input type="radio" ' . ($viewdata['mode']=='alle' ? 'checked' : '') . ' name="filter" value="alle" /> ' . tg('toon_alle_dossiers') . ' '; $header2 = ' <div style="height: auto; background-color: transparent; border: 0; padding: 0; margin: 0;"> <input type="text" value="' . htmlentities($viewdata['search'], ENT_COMPAT, 'UTF-8') . '" name="filter_text" size="20" /> <input name="search_button" type="button" value="' . tgng('form.zoeken') . '" /> <input name="reset_button" type="button" value="' . tgng('form.wissen') . '" /> </div> '; $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => $header, 'rightheader' => $header2, 'width' => '100%', 'height' => null, 'defunct' => true ) ); $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <div class="configuration hidden"> <!-- config elements --> <div config="search" value="<?=htmlentities( $viewdata['search'], ENT_QUOTES, 'UTF-8' )?>"></div> <div config="mode" value="<?=htmlentities( $viewdata['mode'], ENT_QUOTES, 'UTF-8' )?>"></div> <!-- url --> <div url="<?=site_url('/tablet/index/')?>" template="/mode/search"></div> </div> </div> <script type="text/javascript"> // filter stuff $(document).ready(function(){ // handle dossier filter by type/state $('input[type=radio][name=filter]').click(function(){ var listDiv = $('.searchable-list'); BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'mode', this.value ); }); }); // maps stuff $(document).ready(function(){ // bouw lijst van adressen op via de shared-code die dit doet <? $this->load->view( 'elements/nokiamaps-addressen-array' ); ?> // voeg de deelplan details toe <? $c=0; foreach (array_values($dossiers) as $i => $dossier): $volledig_adres = htmlentities( $dossier->locatie_adres . ', ' . $dossier->locatie_postcode . ', ' . $dossier->locatie_woonplaats, ENT_COMPAT, 'UTF-8' ); if ($volledig_adres == ', , ') // "empty" adres continue; $deelplannen = array_values( $dossier->get_deelplannen() ); ?> adressen[<?=$c++?>].deelplannen = [ <? foreach ($deelplannen as $j => $deelplan): $scopes = $deelplan->get_scopes(); ?> { naam: '<?=jsstr($deelplan->naam);?>', scopes: [ <? foreach ($scopes as $k => $scope): ?> { naam: '<?=jsstr($scope['naam'])?>', url: '<?=jsstr(site_url($scope['url']))?>' }<?=($k == sizeof($scopes)-1) ? '' : ','?> <? endforeach; ?> ] }<?=($j == sizeof($deelplannen)-1) ? '' : ','?> <? endforeach; ?> ]; <? endforeach; ?> NokiaMapsHelper.initialize( // insert the maps element after what element? $('table.group'), // array of addresses adressen, // after creation function( kaartElement ) { $(window).resize(function(){ var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { myHeight = document.body.clientHeight; } var top = kaartElement.offset().top; kaartElement.css({ height: (myHeight - top - 2) + 'px' }); }); }, // after adding maps elements function(kaartElement) { kaartElement.hide(); }, // when done loading function(kaartElement) { setTimeout(function(){ $(window).trigger('resize'); kaartElement.fadeIn(); }, 500); } ); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class RolRechtResult extends BaseResult { function RolRechtResult( &$arr ) { parent::BaseResult( 'rolrecht', $arr ); } public function get_rol() { return get_instance()->rol->get( $this->rol_id ); } public function get_rol_id() { return $this->rol_id; } public function get_recht() { return $this->recht; } public function get_modus() { return $this->modus; } } class RolRecht extends BaseModel { function RolRecht() { parent::BaseModel( 'RolRechtResult', 'rol_rechten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'rol', 'rol_id' ); } function replace( $rol_id, $recht, $modus ) { // !!! TODO: last insert ID handling bij een insert if (!$this->dbex->is_prepared( 'add_rolrecht' )) { //$this->dbex->prepare( 'add_rolrecht', 'REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (?, ?, ?)' ); $this->dbex->prepare_replace_into( 'add_rolrecht', 'REPLACE INTO rol_rechten (rol_id, recht, modus) VALUES (?, ?, ?)', null, array('id') ); } $args = array( 'rol_id' => $rol_id, 'recht' => $recht, 'modus' => $modus, ); $res = $this->dbex->execute( 'add_rolrecht', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( $args ); } public function get_for_logged_in_gebruiker() { return $this->get_for_gebruiker( $this->login->get_user_id() ); } public function get_for_gebruiker( $user_id ) { if (!$this->_CI->dbex->is_prepared( 'RolRecht::get_for_logged_in_gebruiker' )) $this->_CI->dbex->prepare( 'RolRecht::get_for_logged_in_gebruiker', ' SELECT rr.* FROM rol_rechten rr JOIN gebruikers g ON (rr.rol_id = g.rol_id) WHERE g.id = ? ' ); $res = $this->dbex->execute( 'RolRecht::get_for_logged_in_gebruiker', array( $user_id ) ); $result = array(); foreach ($res->result() as $row) $result[ $row->recht ] = $this->getr( $row ); return $result; } function get_by_rol( $rol_id ) { if (!$this->dbex->is_prepared( 'RolRecht::get_by_rol' )) $this->dbex->prepare( 'RolRecht::get_by_rol', 'SELECT * FROM '.$this->_table.' WHERE rol_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'RolRecht::get_by_rol', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[ $row->recht ] = $this->getr( $row ); return $result; } } <file_sep>UPDATE rollen SET is_lease = 1 WHERE naam LIKE '[BL]%'; <file_sep>ALTER TABLE deelplan_checklisten ADD COLUMN `voortgang_gestart_op` DATETIME DEFAULT NULL; ALTER TABLE deelplan_checklist_groepen ADD COLUMN `voortgang_gestart_op` DATETIME DEFAULT NULL; <file_sep>ALTER TABLE klanten ADD COLUMN dossierregels_rood_kleuren INT(11) DEFAULT 1; ALTER TABLE klanten ADD COLUMN dossiers_als_startpagina_openen INT(11) DEFAULT 0; ALTER TABLE klanten ADD COLUMN alleen_deelplannen_betrokkene INT(11) DEFAULT 1;<file_sep><? $tab = 200; ?> <form name="pago_pmo_form" id="pago_pmo_form" method="post" action="/dossiers/save_pago_pmo/<?=$dossier->id?>"> <input type="hidden" name="id" id="id" value="<?=isset($func->id)?$func->id:''?>" /> <table class="rapportage-filter pago_pmo_form_tbl"> <tr><td class="column"><?=tg('functie')?></td><td class="input"><input type="text" name="functie" id="functie" value="<?=isset($func->functie)?$func->functie:''?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('n_medewerkers')?></td><td class="input"><input type="text" name="n_medewerkers" id="n_medewerkers" value="<?=isset($func->n_medewerkers)?$func->n_medewerkers:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('beeldschermwerk')?></td><td class="input"><input type="text" name="beeldschermwerk" id="beeldschermwerk" value="<?=isset($func->beeldschermwerk)?$func->beeldschermwerk:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('biologische_agentia')?></td><td class="input"><input type="text" name="biologische_agentia" id="biologische_agentia" value="<?=isset($func->biologische_agentia)?$func->biologische_agentia:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('gevaarlijke_stoffen')?></td><td class="input"><input type="text" name="gevaarlijke_stoffen" id="gevaarlijke_stoffen" value="<?=isset($func->gevaarlijke_stoffen)?$func->gevaarlijke_stoffen:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('schadelijk_geluid')?></td><td class="input"><input type="text" name="schadelijk_geluid" id="schadelijk_geluid" value="<?=isset($func->schadelijk_geluid)?$func->schadelijk_geluid:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('fysieke_belasting')?></td><td class="input"><input type="text" name="fysieke_belasting" id="fysieke_belasting" value="<?=isset($func->fysieke_belasting)?$func->fysieke_belasting:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('werkdruk_belasting')?></td><td class="input"><input type="text" name="werkdruk_belasting" id="werkdruk_belasting" value="<?=isset($func->werkdruk_belasting)?$func->werkdruk_belasting:''?>" tabindex="<?=$tab++?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td><button type="submit">Opslaan</button></td><td><button type="button" onclick="cancel_pago_pmo_form();">Annuleren</button></td></tr> </table> </form> <script> $('#pago_pmo_form').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), dataType: 'json', success: function (data) { alert( '<?=tg('successfully_saved')?>' ); var target = $("#pago_pmo_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pago_pmo/' . $dossier->id)?>' ); }, error: function() { alert( '<?=tg('error_not_saved')?>' ); } }); }); function cancel_pago_pmo_form(){ var target = $("#pago_pmo_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pago_pmo/' . $dossier->id)?>' ); } </script><file_sep>-- draai php index.php /cli/zet_hoofd_en_sub_thema_voor_checklistgroep/139/Bouwen/Bouwen -- en daarna php index.php /cli/zet_hoofd_en_sub_thema_voor_checklistgroep/139/Bouwen/Bouwen/1 <file_sep><? $is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); ?> <!doctype html> <html> <head> <title>PDF annotator <?=PDFANNOTATOR_VERSION?></title> <? if ($is_Mobile): ?> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <? endif; ?> <? load_view( 'html-head.php' ); ?> <style type="text/css"> * { font-family: Arial; font-size: 8pt; } body { background-color: #fff; margin: 0; padding: 0; background: transparent url('<?=PDFANNOTATOR_FILES_BASEURL?>images/nlaf/page-background.png') repeat top left; margin: 50px; } </style> </head> <body> <? if (isset( $error ) && $error): ?> <div class="error"><?=htmlentities( $error, ENT_COMPAT, 'UTF-8' )?></div> <? endif; ?> <file_sep>ALTER TABLE `dossier_subjecten` ADD `gebruiker_id` INT NULL DEFAULT NULL , ADD INDEX ( `gebruiker_id` ) ; ALTER TABLE `dossier_subjecten` ADD FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; CREATE TABLE IF NOT EXISTS `deelplan_subject_vragen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `dossier_subject_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `dossier_subject_id` (`dossier_subject_id`), KEY `vraag_id` (`vraag_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; ALTER TABLE `deelplan_subject_vragen` ADD CONSTRAINT `deelplan_subject_vragen_ibfk_4` FOREIGN KEY (`dossier_subject_id`) REFERENCES `dossier_subjecten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_subject_vragen_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_subject_vragen_ibfk_3` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><? // browsers $CI = get_instance(); $CI->is_IE6or7 = preg_match( '/MSIE\s+[67]/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE6or7or8 = $CI->is_IE6or7 || preg_match( '/MSIE\s+8/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE = $CI->is_IE6or7or8 || preg_match( '/MSIE/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); // other $ver = 'v' . config_item('application_version'); if (config_item( 'development_version' )) $ver .= '&t=' . round(1000*microtime(true)); ?> <!doctype html> <html> <head> <title><?=@$extra_title ? $extra_title : APPLICATION_TITLE?></title> <meta http-equiv="expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <? if ($CI->is_Mobile): ?> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1" /> <? endif; ?> <!-- css --> <link rel="shortcut icon" href="<?=site_url('/files/images/favicon.png')?>" /> <link rel="stylesheet" href="<?=site_url('/files/jquery/jquery-ui.css')?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris.css?' . $ver)?>" type="text/css" /> <link rel="stylesheet" href="<?=site_url('/files/css/bris-telefoon.css?' . $ver)?>" type="text/css" /> <? $_gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $_leaseconfiguratie = $_gebruiker ? $_gebruiker->get_klant()->get_lease_configuratie() : null; ?> <? if ($_leaseconfiguratie): ?> <!-- overrides CSS files --> <style text="type/css"> #nlaf_NaarToezichtVoortgang { background-image: url(/files/images/nlaf/green-button-<?=$_leaseconfiguratie->naam?>.png); } #nlaf_GreenBar { color: #<?=$_leaseconfiguratie->voorgrondkleur?>; background-color: #<?=$_leaseconfiguratie->achtergrondkleur?>; } </style> <? endif; ?> <!-- javascript system libaries --> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-1.7.min.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/jquery/jquery-ui.min.js')?>"></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/modal.popup.js')?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/json.js')?>" ></script> <!-- BRIStoezicht libaries --> <script type="text/javascript"> var eventStopPropagation = function( e ) { if (typeof( e.stopPropagation ) == 'function') e.stopPropagation(); else if (typeof( e.cancelBubble ) != 'undefined') e.cancelBubble = true; } </script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/toezicht.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/core.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/dirtystatus.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/group.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/inlineedit.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/networkstatus.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/offlineklaar.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/tools.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/upload.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/telefoon.js?' . $ver)?>" ></script> <script type="text/javascript" language="javascript" src="<?=site_url('/files/js/bristoezicht/toets/specialimage.js?' . $ver)?>" ></script> </head> <body> <file_sep><? require_once 'base.php'; require_once(BASEPATH.'libraries/Password.php'); class GebruikerResult extends BaseResult { function GebruikerResult( &$arr ) { parent::BaseResult( 'gebruiker', $arr ); } function get_status() { $str = $this->volledige_naam ? $this->volledige_naam : $this->gebruikersnaam; return htmlentities( $str ); } function get_klant() { return $this->_CI->klant->get( $this->klant_id ); } function get_rol() { return $this->_CI->rol->get( $this->rol_id ); } function get_edit_fields() { $fields = array(); $fields[] = BaseResult::_edit_selectfield( 'Rol', 'rol_id', isset($this) ? $this->rol_id : @$_POST['rol_id'], get_instance()->rol, false, function( $v ) { static $toekenbare_rollen = null; if (!is_array( $toekenbare_rollen )) $toekenbare_rollen = get_instance()->rol->get_toekenbare_rollen_for_huidige_klant(); return isset( $toekenbare_rollen[$v->id] ); }, 'get_toekenbare_rollen_for_huidige_klant' ); $fields[] = BaseResult::_edit_textfield( 'Volledige naam', 'volledige_naam', isset($this) ? $this->volledige_naam : @$_POST['volledige_naam'] ); $fields[] = BaseResult::_edit_textfield('Email', 'email', isset($this) ? $this->email : @$_POST['email'] ); $fields[]= BaseResult::_edit_enumfield('De status', 'status', isset($this) ? $this->status : @$_POST['status'],array("actief"=>"actief","geblokkeerd"=>"geblokkeerd") ); if (!isset( $this )) { $fields[] = BaseResult::_edit_textfield( 'Gebruikersnaam', 'gebruikersnaam', @$_POST['gebruikersnaam'] ); } else { $fields[] = BaseResult::_edit_text_read_only( 'Gebruikersnaam', 'gebruikersnaam', isset($this) ? $this->gebruikersnaam : @$_POST['gebruikersnaam'] ); } $fields[] = BaseResult::_edit_passwordfield( isset( $this ) ? 'Nieuw wachtwoord (leeglaten als u geen nieuw wachtwoord wilt instellen)' : 'Wachtwoord', 'wachtwoord', '' ); /* $fields[] = BaseResult::_edit_textfield( 'Actieve periode 1 begin', 'active_period_1_begin', isset($this) ? $this->active_period_1_begin : @$_POST['active_period_1_begin'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 1 einde', 'active_period_1_end', isset($this) ? $this->active_period_1_end : @$_POST['active_period_1_end'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 2 begin', 'active_period_2_begin', isset($this) ? $this->active_period_2_begin : @$_POST['active_period_2_begin'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 2 einde', 'active_period_2_end', isset($this) ? $this->active_period_2_end : @$_POST['active_period_2_end'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 3 begin', 'active_period_3_begin', isset($this) ? $this->active_period_3_begin : @$_POST['active_period_3_begin'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 3 einde', 'active_period_3_end', isset($this) ? $this->active_period_3_end : @$_POST['active_period_3_end'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 4 begin', 'active_period_4_begin', isset($this) ? $this->active_period_4_begin : @$_POST['active_period_4_begin'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 4 einde', 'active_period_4_end', isset($this) ? $this->active_period_4_end : @$_POST['active_period_4_end'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 5 begin', 'active_period_5_begin', isset($this) ? $this->active_period_5_begin : @$_POST['active_period_5_begin'] ); $fields[] = BaseResult::_edit_textfield( 'Actieve periode 5 einde', 'active_period_5_end', isset($this) ? $this->active_period_5_end : @$_POST['active_period_5_end'] ); * */ return $fields; } function to_string() { return $this->volledige_naam; } function get_gebruiker() { return (@$this->gebruiker_id) ? get_instance()->gebruiker->get( $this->gebruiker_id ) : null; } function get_collegas() { $res = $this->_CI->db->query(' SELECT * FROM gebruikers g JOIN gebruiker_collegas gc ON g.id = gc.gebruiker1_id WHERE g.id = ' . $this->id . ' '); $result = array(); foreach ($res->result() as $row) { $gid = $row->gebruiker2_id; $result[$gid] = $this->_CI->gebruiker->getr( $row ); } return $result; } function update_collegas( $alle_gebruikers ) { $this->_CI->db->trans_start(); // cleanup current collega list $this->_CI->db->orwhere( 'gebruiker1_id', $this->id ); $this->_CI->db->delete( 'gebruiker_collegas' ); // setup new ones based on post data foreach ($alle_gebruikers as $gebruiker) { $var = 'collega_'.$gebruiker->id; if (isset($_POST[$var]) && $_POST[$var]=='on') $this->add_collega( $gebruiker->id ); } $this->_CI->db->trans_complete(); } function add_collega( $gebruiker_id ) { $this->_CI->db->set( 'gebruiker1_id', $this->id ); $this->_CI->db->set( 'gebruiker2_id', $gebruiker_id ); $this->_CI->db->insert( 'gebruiker_collegas' ); } function is_super_admin() { return $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_SITEBEHEER ) == RECHT_MODUS_ALLE; } // Some code is available only to VIIA users. This small method is to be used as a single point of // checking if a user belongs to VIIA or not. The current implementation is not final yet, as it uses // a brute check on the 'klant_id' value. When a nicer mechanism has been implemented for it, the below // code should be changed and made final accordingly. function is_viia_user() { //return true; return ($this->klant_id == 202); } function is_nijha_user() { //return true; return ($this->_CI->klant->get($this->klant_id)->naam == 'Nijha'); } // Some code is available only to Riepair users. This small method is to be used as a single point of // checking if a user belongs to Riepair or not. The current implementation is not final yet, as it uses // a brute check on the 'klant_id' value. When a nicer mechanism has been implemented for it, the below // code should be changed and made final accordingly. function is_riepair_user() { //return true; return ($this->klant_id == 155); } // Some code is available only to Arbode users (which is a subset of the Riepair users). This small method is // to be used as a single point of checking if a user belongs to Riepair or not. The current implementation is // not final yet, as it uses a brute check on the 'klant_id' value. When a nicer mechanism has been implemented // for it, the below code should be changed and made final accordingly. function is_arbode_user() { //return true; // For now specify the known (live) Arbode user IDs in a not-so-nice way, by simply listing their user IDs. $arbode_user_ids = array(469, 546, 556, 565, 409, 474, 467, 830, 831); return ($this->is_riepair_user() && in_array($this->id, $arbode_user_ids)); } public function hasLeaseRol() { $query = 'SELECT is_lease FROM rollen WHERE id = ' . $this->rol_id; return (bool) $this->_CI->db->query($query)->row(0)->is_lease; } public function isChildrenKlantenOnly(){ $children_org_roles = array(3,20); $has_children_orgs = $this->_CI->session->userdata( 'has_children_organisations' ); return $has_children_orgs && in_array($this->rol_id, $children_org_roles); } } class Gebruiker extends BaseModel { private $_skip_ckeck = false; function Gebruiker() { parent::BaseModel( 'GebruikerResult', 'gebruikers' ); } function is_external_user () { return $this->login->is_external_user(); } function get_external_user ($email, $password=<PASSWORD>, $check_password = true) { if (!$this->dbex->is_prepared( 'get_external_user' )) $this->dbex->prepare( 'get_external_user', " SELECT * FROM externe_gebruikers WHERE email = ? ; "); $res = $this->dbex->execute( 'get_external_user', array( $email) ); $result = array(); if ($res->num_rows) { $result = $this->gebruiker->getr( reset( $res->result() )); if ($check_password) { if ($this->verify_external_user_password($email, $password)) { $this->_table ='externe_gebruikers'; return $result; } } else { return true; } } return NULL; } function get_external_user_isblocked ($email) { if ($email) { if (!$this->dbex->is_prepared( 'get_external_user_isblocked' )) $this->dbex->prepare( 'get_external_user_isblocked', " SELECT `status` FROM `externe_gebruikers` WHERE `email` = ?; "); $res = $this->dbex->execute( 'get_external_user_isblocked', array( $email) ); if ($res) { $result = $res->row(); $status = $result->status; if ($status == 'geblokkeerd') { return true; } } } return NULL; } function verify_external_user_password ($email, $password) { if ($password) { if (!$this->dbex->is_prepared( 'get_external_user_password' )) $this->dbex->prepare( 'get_external_user_password', " SELECT `wachtwoord` FROM `externe_gebruikers` WHERE `email` = ?; "); $res = $this->dbex->execute( 'get_external_user_password', array( $email) ); $result = $res->row(); if ($result) { require_once(BASEPATH.'libraries/Password.php'); if (password_verify($password,$result->wachtwoord) == true) { return true; } } } return NULL; } function verify_external_user_token ($email, $token) { if ($token) { if (!$this->dbex->is_prepared( 'get_external_user_token' )) $this->dbex->prepare( 'get_external_user_token', " SELECT `token` FROM `externe_gebruikers` WHERE `email` = ?; "); $res = $this->dbex->execute( 'get_external_user_token', array( $email) ); $result = $res->row(); if ($result) { if (password_verify($token,$result->token) == true) { return true; } } } return NULL; } public function set_external_user_password($email, $password) { if (!$this->dbex->is_prepared( 'set_external_user_password' )) $this->dbex->prepare( 'set_external_user_password', " UPDATE `externe_gebruikers` SET `wachtwoord` = ?, `token` = null, `status` = 'actief' WHERE `email` = ?; "); $res = $this->dbex->execute( 'set_external_user_password', array( password_hash($password, PASSWORD_DEFAULT),$email )); if ($res) { return true; } return NULL; } public function get_opdrachtgevers($external_uid, $only_unfinished = true) { if (!$this->dbex->is_prepared( 'get_opdrachtgevers' )) $this->dbex->prepare( 'get_opdrachtgevers', " SELECT k.id AS id, k.volledige_naam AS klant_naam, d.id AS opdracht_id FROM `deelplan_opdrachten` d JOIN gebruikers g ON d.opdrachtgever_gebruiker_id = g.id JOIN klanten k ON g.klant_id = k.id JOIN dossier_subjecten ds ON d.dossier_subject_id = ds.id JOIN externe_gebruikers e ON ds.email = e.email WHERE e.id = ? ".( $only_unfinished ? ' AND d.status = \'nieuw\'' : '') . " ORDER BY d.gereed_datum;"); $res = $this->dbex->execute( 'get_opdrachtgevers', array( $external_uid) ); if ($res->num_rows) { return $res->result(); } return NULL; } public function check_access( BaseResult $object ) { global $class, $method; if ($class == 'gebruikers' && ($method == 'postlogin' || $method == 'inloggen') || HTTP_USER_AUTHENTICATION) return; if($this->_skip_ckeck) { return; } parent::check_access( $object ); } public function setSkipCheck() { $this->_skip_ckeck = true; } function get_logged_in_gebruiker() { // First try to determine whether we are being called from the inside of a webservice or not. // If such is the case, we do not have a logged in user, but possibly an overridden user has then be specified, in which // case we can try to get that user. if (defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_gebruiker_id'])) { // If a user ID was explicitely passed, use that for trying to get the proper user for setting the context. $overriden_gebruiker_id = (!empty($_POST['overridden_gebruiker_id'])) ? intval($_POST['overridden_gebruiker_id']) : 0; $gebruiker = null; if (!empty($overriden_gebruiker_id)) { // Get the proper user to specify the context that should be used. //$gebruiker = $this->_CI->gebruiker->get($overriden_gebruiker_id); $gebruiker = $this->get($overriden_gebruiker_id); } // Now return the retrieved user (or null if it was not found) return $gebruiker; } // if (defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_gebruiker_id'])) // If we are not being called from within a webservice, continue with the normal flow if ($this->login->logged_in()) { if ($this->login->is_external_user()) { //set the user table to external users $this->_table ='externe_gebruikers'; } $user = $this->get( $this->login->get_user_id() ); if ($user && $user->status) { if ($user->status == 'geblokkeerd') { global $class, $method; if ($class != 'gebruikers' || $method != 'licentie_probleem') redirect( '/gebruikers/licentie_probleem/AccountBlocked' ); } } $CI =& get_instance(); $CI->load->model("usergroupsrelation"); $user->groups=$CI->usergroupsrelation->get_groups_by_uid($this->login->get_user_id()); $CI->load->helper('array'); $CI->load->model("usergroupsrelation"); $user->groups_users=$CI->usergroupsrelation->get_users_by_uids(cut_array((array)$user->groups,'users_group_id')); return $user; } else { return null; } } function add( $klant_id, $volledige_naam, $rol_id, $kennis_id_unique_id, $email = null, $intern = KENNIS_ID_USER_INTERNAL ) { /* if (!$this->dbex->is_prepared( 'add_gebruiker' )) $this->dbex->prepare( 'add_gebruiker', 'INSERT INTO gebruikers (klant_id, volledige_naam, rol_id, kennis_id_unique_id) VALUES (?, ?, ?, ?)' ); $args = array( 'klant_id' => $klant_id, 'volledige_naam' => $volledige_naam, 'rol_id' => $rol_id, 'kennis_id_unique_id' => $kennis_id_unique_id, ); $res = $this->dbex->execute( 'add_gebruiker', $args ); if (!$res) return null; $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $args['id'] = $id; $args['status'] = 'actief'; return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'klant_id' => $klant_id, 'volledige_naam' => $volledige_naam, 'status' => 'actief', // Ook daadwerkelijk inserten, of vertrouwen op de DB default ?!? 'rol_id' => $rol_id, 'kennis_id_unique_id' => $kennis_id_unique_id, 'email' => $email, 'intern' => $intern ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function add_localdb( $klant_id, $gebruikersnaam, $wachtwoord, $volledige_naam, $rol_id, $email = null ) { if (!$gebruikersnaam) return false; for ($i=0; $i<strlen($gebruikersnaam); ++$i) if (!( ($gebruikersnaam[$i]>='a' && $gebruikersnaam[$i]<='z') || ($gebruikersnaam[$i]>='A' && $gebruikersnaam[$i]<='Z') || ($gebruikersnaam[$i]>='0' && $gebruikersnaam[$i]<='9') || $gebruikersnaam[$i]=='-' || $gebruikersnaam[$i]=='_')) return false; /* if (!$this->dbex->is_prepared( 'add_gebruiker' )) $this->dbex->prepare( 'add_gebruiker', 'INSERT INTO gebruikers (klant_id, gebruikersnaam, wachtwoord, volledige_naam, rol_id, kennis_id_unique_id) VALUES (?, ?, SHA1(?), ?, ?, ?)' ); $args = array( 'klant_id' => $klant_id, 'gebruikersnaam' => $gebruikersnaam, 'wachtwoord' => $wachtwoord, 'volledige_naam' => $volledige_naam, 'rol_id' => $rol_id, 'kennis_id_unique_id' => sha1( $gebruikersnaam . date( 'Y-m-d H:i:s' ) ), ); $res = $this->dbex->execute( 'add_gebruiker', $args, true ); // can fail! if (!$res) return null; $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. // 'wachtwoord' => $wachtwoord, $data = array( 'klant_id' => $klant_id, 'gebruikersnaam' => $gebruikersnaam, 'wachtwoord' => sha1($wachtwoord), 'volledige_naam' => $volledige_naam, 'rol_id' => $rol_id, 'email' => $email, 'kennis_id_unique_id' => sha1( $gebruikersnaam . date( 'Y-m-d H:i:s' ) ), ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function save( $object, $do_transaction=true, $alias=null, $error_on_no_changes=true ) { // Make sure to unset the 'groups' and 'groups_users' members as those are not present in the DB. unset($object->groups); unset($object->groups_users); // Store the DB record first $res = parent::save( $object, $do_transaction, $alias, $error_on_no_changes ); if( !$res ) { throw new Exception( 'Failed to save in DB. Inner Error.' ); } return $res; } public function get_by_klant( $klant_id, $only_active=false /* no longer doing anything */, $search=null, $gebruikers_id=null ) { //$gebruikers_id=""; if(!is_null($gebruikers_id)) $gebruikers_id=implode(',', $gebruikers_id); $gebruikerLookUpQuery = ' SELECT * FROM gebruikers WHERE klant_id = ? AND speciale_functie = \'geen\' ' . (!is_null( $search )? 'AND (gebruikersnaam LIKE ? OR volledige_naam LIKE ?)' : '') . ' ' . (!is_null( $gebruikers_id )? 'and id IN ('.$gebruikers_id.')' : '') .'ORDER BY volledige_naam '; $this->_CI->dbex->prepare( 'get_gebruikers_by_klant', $gebruikerLookUpQuery ); $args = array( $klant_id ); if (!is_null( $search )) { $args[] = '%' . $search . '%'; $args[] = '%' . $search . '%'; } $res = $this->dbex->execute( 'get_gebruikers_by_klant', $args ); $result = array(); foreach ($res->result() as $row) { // Use the 'false' value for the second parameter as otherwise // the id column of the logged in user is set as a string value instead // of as an int value! $result[ $row->id ] = $this->getr( $row, false ); } return $result; } public function get_by_kennisid_unique_id( $kennisid_unique_id ) { $this->_CI->dbex->prepare( 'get_by_kennisid_unique_id', 'SELECT * FROM gebruikers WHERE kennis_id_unique_id = ?' ); $res = $this->dbex->execute( 'get_by_kennisid_unique_id', array( $kennisid_unique_id ) ); if ($res->num_rows() <= 0) return null; $row = reset( $res->result() ); $gebruiker = $this->getr( $row ); $res->free_result(); return $gebruiker; } public function get_by_login( $login, $klant_id = null ) { $get_by_login_query = 'SELECT * FROM gebruikers WHERE (gebruikersnaam = ?)'; $parameters = array($login); if (!is_null($klant_id)) { $get_by_login_query .= ' AND (klant_id = ?)'; $parameters[] = $klant_id; } $this->_CI->dbex->prepare( 'get_by_login', $get_by_login_query ); $res = $this->dbex->execute( 'get_by_login', $parameters ); if ($res->num_rows() <= 0) return null; $row = reset( $res->result() ); $gebruiker = $this->getr( $row ); $res->free_result(); return $gebruiker; } } <file_sep><? require_once 'base.php'; class HoofdThemaResult extends BaseResult { function HoofdThemaResult( &$arr ) { parent::BaseResult( 'hoofdthema', $arr ); } public function get_klant() { $CI = get_instance(); return $CI->klant->get( $this->klant_id ); } function get_themas() { $CI = get_instance(); $CI->load->model( 'thema' ); return $CI->thema->search( array( 'hoofdthema_id' => $this->id ), null, false, 'AND', /*$order_by*/ 'thema' ); } } class HoofdThema extends BaseModel { function HoofdThema() { parent::BaseModel( 'HoofdThemaResult', 'bt_hoofdthemas' ); } public function check_access( BaseResult $object ) { return; } public function add( $hoofdthema, $nummer, $bron, $klant_id=null ) { /* $db = $this->get_db(); $this->dbex->prepare( 'HoofdThema::add', 'INSERT INTO bt_hoofdthemas (naam, nummer, bron, klant_id) VALUES (?, ?, ?, ?)', $db ); $args = array( 'naam' => $hoofdthema, 'nummer' => $nummer, 'bron' => $bron, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, ); $this->dbex->execute( 'HoofdThema::add', $args, false, $db ); $args['id'] = $db->insert_id(); return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'naam' => $hoofdthema, 'nummer' => $nummer, 'bron' => $bron, 'klant_id' => $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function find( $hoofdthema, $klant_id=null ) { $db = $this->get_db(); $this->dbex->prepare( 'HoofdThema::find', 'SELECT * FROM bt_hoofdthemas WHERE naam = ? AND klant_id = ?', $db ); $args = array( $hoofdthema, $klant_id ? $klant_id : $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $res = $this->dbex->execute( 'HoofdThema::find', $args, false, $db ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function get_by_checklist( $checklist_id ) { static $cache = null; if (!is_array( $cache )) { // execute only once per request! $CI = get_instance(); $CI->load->model( 'checklistgroep' ); $also_available = $CI->checklistgroep->get_also_beschikbaar_for_huidige_klant( true ); if (empty( $also_available )) $also_available = array( -1 => -1 ); $cache = array(); // Determine which "null function" should be used $null_func = get_db_null_function(); // Note: the "JOIN bt_vragen v ON (1=1)" part comes across as wildly odd. In fact, it is the joined in the WHERE clause. The '1=1' is done for compatibility with Oracle. $db = $this->get_db(); $res = $db->Query( ' SELECT DISTINCT(h.id), h.*, hg.checklist_id, h.nummer as sort_col1, h.naam as sort_col2 FROM bt_themas t JOIN bt_hoofdthemas h ON t.hoofdthema_id = h.id JOIN bt_vragen v ON (1=1) JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE ( 0=1 OR h.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' OR cl.checklist_groep_id IN (' . implode( ',', array_keys( $also_available ) ) . ') ) AND '.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id))) = t.id ORDER BY sort_col1, sort_col2 '); foreach ($res->result() as $row) { if (!isset( $cache[$row->checklist_id] )) $cache[$row->checklist_id] = array(); $cache[$row->checklist_id][] = $this->getr( $row ); } $res->free_result(); } if (isset( $cache[$checklist_id] )) return $cache[$checklist_id]; return array(); } public function get_by_checklistgroep( $checklist_groep_id ) { static $cache = null; if (!is_array( $cache )) { // execute only once per request! $CI = get_instance(); $CI->load->model( 'checklistgroep' ); $also_available = $CI->checklistgroep->get_also_beschikbaar_for_huidige_klant( true ); if (empty( $also_available )) $also_available = array( -1 => -1 ); $cache = array(); // Determine which "null function" should be used $null_func = get_db_null_function(); // Note: the "JOIN bt_vragen v ON (1=1)" part comes across as wildly odd. In fact, it is the joined in the WHERE clause. The '1=1' is done for compatibility with Oracle. $db = $this->get_db(); $res = $db->Query( ' SELECT DISTINCT(h.id), h.*, cl.checklist_groep_id, h.nummer as sort_col1, h.naam as sort_col2 FROM bt_themas t JOIN bt_hoofdthemas h ON t.hoofdthema_id = h.id JOIN bt_vragen v ON (1=1) JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE ( 0=1 OR h.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' OR cl.checklist_groep_id IN (' . implode( ',', array_keys( $also_available ) ) . ') ) AND '.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id))) = t.id ORDER BY sort_col1, sort_col2 '); foreach ($res->result() as $row) { if (!isset( $cache[$row->checklist_groep_id] )) $cache[$row->checklist_groep_id] = array(); $cache[$row->checklist_groep_id][] = $this->getr( $row ); } $res->free_result(); } if (isset( $cache[$checklist_groep_id] )) return $cache[$checklist_groep_id]; return array(); } //public function get_for_huidige_klant( $assoc=false, $klant_only=false, $sort='nummer, naam' ) public function get_for_huidige_klant( $assoc=false, $klant_only=false, $sort='h.nummer, h.naam' ) { // Create a sort string that's compatible with both MySQL and Oracle if ($sort == 'h.naam') { $safe_sort_select_part = 'h.naam as sort_col1'; $safe_sort_order_by_part = 'sort_col1'; } else { $safe_sort_select_part = 'h.nummer as sort_col1, h.naam as sort_col2'; $safe_sort_order_by_part = 'sort_col1, sort_col2'; } // Determine which "null function" should be used $null_func = get_db_null_function(); // execute only once per request! if (!$klant_only) { $CI = get_instance(); $CI->load->model( 'checklistgroep' ); $also_available = $CI->checklistgroep->get_also_beschikbaar_for_huidige_klant( true ); if (empty( $also_available )) $also_available = array( -1 => -1 ); } else $also_available = array( -1 => -1 ); $CI = get_instance(); // Note: the "JOIN bt_vragen v ON (1=1)" part comes across as wildly odd. In fact, it is the joined in the WHERE clause. The '1=1' is done for compatibility with Oracle. $query = ' SELECT DISTINCT(h.id), h.*, '.$safe_sort_select_part.' FROM bt_themas t JOIN bt_hoofdthemas h ON t.hoofdthema_id = h.id JOIN bt_vragen v ON (1=1) JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE ( 0=1 OR h.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' OR cl.checklist_groep_id IN (' . implode( ',', array_keys( $also_available ) ) . ') ) AND '.$null_func.'(v.thema_id,'.$null_func.'(hg.standaard_thema_id,'.$null_func.'(cl.standaard_thema_id,cg.standaard_thema_id))) = t.id UNION SELECT DISTINCT(h.id), h.*, '.$safe_sort_select_part.' FROM bt_hoofdthemas h WHERE h.klant_id = ' . $this->gebruiker->get_logged_in_gebruiker()->klant_id . ' ORDER BY ' . $safe_sort_order_by_part; $res = $this->db->Query($query); $result = array(); foreach ($res->result() as $row) { if (!$assoc) $result[] = $this->getr( $row, false ); else $result[$row->id] = $this->getr( $row, false ); } $res->free_result(); return $result; } } <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_subjecten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `dossier_subject_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `dossier_subject_id` (`dossier_subject_id`) ) ENGINE=InnoDB; ALTER TABLE `deelplan_subjecten` ADD CONSTRAINT `deelplan_subjecten_ibfk_2` FOREIGN KEY (`dossier_subject_id`) REFERENCES `dossier_subjecten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_subjecten_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><table width="100%"> <tr> <? $columns = 4; $index = 0; ?> <!-- goto parent block --> <? if (@$parent_map_id): ?> <? $parent = $this->dossierbescheidenmap->get( $parent_map_id )->get_parent(); ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <a href="javascript:void(0);" onclick="openBescheidenMap( <?=$parent ? $parent->id : 0?> );"> <img src="<?=site_url( '/files/images/bescheidenmap.png' )?>" /> </a> </div> <div style="display: inline-block; overflow:hidden; width:190px; height: 35px; padding: 5px; margin: 0; border: 0; background-color:#ddd; "> <b><?=tg('terug.naar.parent')?></b> </div> </td> <? ++$index; ?> <? endif; ?> <!-- mappen --> <? foreach ($mappen as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <a href="javascript:void(0);" onclick="openBescheidenMap( <?=$b->id?> );"> <img src="<?=site_url( '/files/images/bescheidenmap.png' )?>" /> </a> </div> <div style="display: inline-block; overflow:hidden; width:190px; height: 35px; padding: 5px; margin: 0; border: 0; background-color:#ddd; " title="<?=htmlentities( $b->naam, ENT_COMPAT, 'UTF-8' )?>"> <b><?=htmlentities( $b->naam, ENT_COMPAT, 'UTF-8' )?></b><br/> <input type="button" value="<?=tgng('form.alle')?>" onclick="selecteerAlleBescheidenInMap(<?=$b->id?>, 1);"/> <input type="button" value="<?=tgng('form.geen')?>" onclick="selecteerAlleBescheidenInMap(<?=$b->id?>, 0);"/> </div> </td> <? ++$index; ?> <? endforeach;?> <!-- bescheiden --> <? foreach ($bescheiden as $b): ?> <? if ($index && !($index % $columns)): ?> </tr> <tr> <? endif; ?> <td style="text-align:center; vertical-align:top; width:<?=round(100/$columns)?>%"> <div style="width:190px;height:110px;padding:4px;border:1px solid #ddd;margin:0; display:inline-block;"> <a target="_blank" href="<?=site_url('/dossiers/bescheiden_downloaden/' . $b->id)?>"> <img src="<?=site_url( '/pdfview/bescheiden/' . $b->id . '/1' )?>" /> </a> </div> <div style="display: inline-block; overflow:hidden; width:190px; height: 35px; padding: 5px; margin: 0; border: 0; background-color:#ddd; " title="<?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?>"> <input type="checkbox" bescheiden_id="<?=$b->id?>" onclick="updateBescheidenState( this, <?=$b->id?> );" /> <b><?=htmlentities( $b->omschrijving, ENT_COMPAT, 'UTF-8' )?></b> </div> </td> <? ++$index; ?> <? endforeach;?> <? for ($i=0; $i<($columns - $index); ++$i): ?> <td style="width:<?=round(100/$columns)?>%"></td> <? endfor; ?> </tr> </table> <file_sep>SELECT @rol_id:=id FROM rollen WHERE naam = 'Externe opdrachtnemer'; DELETE FROM rol_rechten WHERE (rol_id = @rol_id) AND (recht = 27); REPLACE INTO rol_rechten (rol_id, recht, modus) SELECT r.id ,27 ,2 FROM rollen r WHERE r.naam = 'Externe opdrachtnemer'; <file_sep><?php require_once('KMXLicenseSystem.php'); $licSys = new KMXLicenseSystem(); $licSys->magmaUrl = 'http://brismagma.intramax.eu/'; $licSys->magmaName = 'BRIStoezicht'; $licSys->magmaSecret = '<KEY>'; $licSys->magmaCalculationType = 'md5'; $licSys->cachePath = dirname(__FILE__) . '/token-licsys.cache'; $licSys->serviceUrl = 'http://licentie.bris.nl/'; // $licSys->licenseSystemLabel = 'bristoezicht'; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Lease beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Lease beheer', 'width' => '920px' ) ); ?> <table class="admintable lease" width="100%" cellpadding="0" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Naam</th> <th style="text-align:center; padding-left: 0px; border-bottom:2px solid #777;">Aantal klanten</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 500px; ">Status</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Opties</th> </tr> <? foreach ($alle_configuraties as $i => $config): ?> <? $status = $config->get_status(); ?> <tr class="<?=($i % 2)?'':'zebra'?>"> <td><h5><?=$config->naam?></h5></td> <td style="text-align:center"><?=sizeof($config->get_klanten())?></td> <td><div class="lease-status <?=$status===true?'good':'error'?>"><?=$status===true ? 'Configuratie in orde en alle bestanden aanwezig' : ('Fout: ' . $status)?></div></td> <td> <a href="<?=site_url('/admin/lease_bewerken/' . $config->id)?>"><img src="<?=site_url('/files/images/edit.png')?>"> Bewerken</a> </td> </tr> <? endforeach; ?> </table> <br/><br/> <div style="padding: 5px 5px 5px 26px; background: white url('/files/images/letop.png') no-repeat 5px 5px; font-style: italic; font-size: 90%; "> Let op! Sinds er bij het aanmaken van een nieuwe lease configuratie een aantal zaken komen kijken die ofwel niet automatisch kunnen (denk aan maken van nieuwe afbeeldingen), ofwel nu teveel tijd kosten om te automatiseren, is het aanmaken van een nieuwe configuratie via deze interface niet mogelijk. </div> <br/><br/> <form method="POST"> IP's voor lease beheer voor Imotep. <ul> <li>Een IP per regel!</li> <li>Geen andere tekst toevoegen!</li> <li>Gebruiker een * voor een wildcard!</li> </ul> <textarea type="text" name="ips" style="width: 30em; height: 10em;" maxlength="255"><?=implode( "\n", explode( ';', $this->klant->get(1)->lease_administratie_ips ) )?></textarea><br/> <input type="submit" value="Opslaan" /> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class BacklogUploadResult extends BaseResult { private $_checklisten = null; function BacklogUploadResult( &$arr ) { parent::BaseResult( 'backlogupload', $arr ); } function get_back_log() { $CI = get_instance(); $CI->load->model( 'backlogup' ); $results = $CI->backlogupload->search( array( 'id' => $this->back_log_id ) ); if (empty( $results )) throw new Exception( 'Kan backlog entry voor backlog upload niet vinden' ); return reset( $results ); } function get_download_url() { return site_url( '/admin/backlog_uploads_download/' . $this->id ); } public function laad_inhoud() { if (isset( $this->bestand )) return; $res = $this->_CI->db->query( 'SELECT bestand FROM back_log_uploads WHERE id = ' . intval( $this->id ) ); if (!$res) throw new Exception( 'Fout bij ophalen backlog upload inhoud (1).' ); if ($res->num_rows() != 1) throw new Exception( 'Fout bij ophalen backlog upload inhoud (2) (' . $res->num_rows . ').' ); $rows = $res->result(); $res->free_result(); $this->bestand = reset( $rows )->bestand; unset( $rows ); } public function geef_inhoud_vrij() { unset( $this->bestand ); } } class BacklogUpload extends BaseModel { function BacklogUpload() { parent::BaseModel( 'BacklogUploadResult', 'back_log_uploads' ); } public function check_access( BaseResult $object ) { // } public function add( $back_log_id, $bestandsnaam, $bestand ) { // determine content type $this->load->helper( 'file' ); // CI helper $content_type = get_mime_by_extension( $bestandsnaam ); // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. /* // prepare statements $this->dbex->prepare( 'BacklogUpload::add', 'INSERT INTO back_log_uploads (back_log_id, bestandsnaam, bestand, content_type, grootte) VALUES (?, ?, ?, ?, ?)' ); // lock, get max id, create new entries, and be done $args = array( 'back_log_id' => $back_log_id, 'bestandsnaam' => $bestandsnaam, 'bestand' => $bestand, 'content_type' => $content_type, 'grootte' => strlen( $bestand ), ); if (!($this->dbex->execute( 'BacklogUpload::add', $args ))) throw new Exception( 'Database fout bij toevoegen backlog upload.' ); $result = new $this->_model_class( $args ); $result->id = $this->db->insert_id(); return $result; */ // Use the base model's 'insert' method. $data = array( 'back_log_id' => $back_log_id, 'bestandsnaam' => $bestandsnaam, 'bestand' => $bestand, 'content_type' => $content_type, 'grootte' => strlen( $bestand ), ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'isbsi' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } public function get_aantallen_per_back_log() { $result = array(); $CI = get_instance(); $res = $CI->db->query( 'SELECT COUNT(*) AS count, back_log_id FROM back_log_uploads GROUP BY back_log_id' ); foreach ($res->result() as $row) $result[ $row->back_log_id ] = $row->count; $res->free_result(); return $result; } } <file_sep>-- -- -- LET OP: deze migratie is ws al op LIVE doorgevoerd! -- -- ALTER TABLE `back_log` ADD `is_wens` TINYINT NOT NULL DEFAULT '0'; UPDATE back_log SET `is_wens` = LENGTH(prioriteit) = 0; -- yes, now update to default 1! ALTER TABLE `back_log` CHANGE `is_wens` `is_wens` TINYINT( 4 ) NOT NULL DEFAULT '1'; <file_sep><? require_once 'base.php'; class KlantResult extends BaseResult { private $dossieroverzicht_velden; function KlantResult( &$arr ) { parent::BaseResult( 'klant', $arr ); } function get_edit_fields() { return array( $this->_edit_textfield('Klantnaam', 'naam', $this->naam ), $this->_edit_textfield('Bedrijfs/gemeente naam', 'volledige_naam', $this->volledige_naam ), $this->_edit_textfield('Contactpersoon', 'contactpersoon_naam', $this->contactpersoon_naam ), $this->_edit_textfield('... email', 'contactpersoon_email', $this->contactpersoon_email ), $this->_edit_textfield('... telefoon', 'contactpersoon_telefoon', $this->contactpersoon_telefoon ), $this->_edit_textfield('Klant kleur (HTML, zonder #)', 'kleur', $this->kleur ), $this->_edit_enumfield('Word export licentie', 'heeft_word_export_licentie', $this->heeft_word_export_licentie, array( 'nee'=>'Nee', 'ja'=>'Ja' ) ), $this->_edit_enumfield('BEL import licentie', 'heeft_bel_import_licentie', $this->heeft_bel_import_licentie, array( 'nee'=>'Nee', 'ja'=>'Ja' ) ), $this->_edit_enumfield('Fine and Kinney licentie', 'heeft_fine_kinney_licentie', $this->heeft_fine_kinney_licentie, array( 'nee'=>'Nee', 'ja'=>'Ja' ) ), $this->_edit_enumfield('Email question notification', 'email_question_notification', $this->email_question_notification, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Klant heeft Fine&Kinney licentie?', 'usergroup_activate', $this->usergroup_activate, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Standaard documenten?', 'standaard_documenten', $this->standaard_documenten, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Standaard Deelplannen?', 'standaard_deelplannen', $this->standaard_deelplannen, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Standaard brief?', 'letter', $this->letter, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Risico grafieken?', 'risico_grafieken', $this->risico_grafieken, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Toezichtmomenten licentie?', 'heeft_toezichtmomenten_licentie', $this->heeft_toezichtmomenten_licentie, array( 'nee'=>'Nee', 'ja'=>'Ja' ) ), $this->_edit_enumfield('Dossieroverzichten genereren?', 'kan_dossieroverzichten_genereren', $this->kan_dossieroverzichten_genereren, array( 'nee'=>'Nee', 'ja'=>'Ja' ) ), $this->_edit_enumfield('Automatic accountability text?', 'automatic_accountability_text', $this->automatic_accountability_text, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Sluit alle tabbladen met deelplannen?', 'deelplannen_tab_close', $this->deelplannen_tab_close, array( '0'=>'Nee', '1'=>'Ja' ) ), $this->_edit_enumfield('Deelplan out of_date red color?', 'deelplan_out_of_date_color', $this->deelplan_out_of_date_color, array( '0'=>'Nee', '1'=>'Ja' ) ), ); } function to_string() { return $this->volledige_naam; } function allow_bel_import() { return $this->heeft_bel_import_licentie=='ja'; } function allow_lease_administratie() { if (!isset( $this->_allow_lease_administratie )) { //$match_ip = $_SERVER['REMOTE_ADDR']; $match_ip = (empty($_SERVER["HTTP_X_FORWARDED_FOR"])) ? $_SERVER['REMOTE_ADDR'] : $_SERVER["HTTP_X_FORWARDED_FOR"]; $this->_allow_lease_administratie = false; if (!is_null( $this->lease_administratie_ips ) && strlen( $this->lease_administratie_ips )) { foreach (explode( ';', $this->lease_administratie_ips ) as $ip) { $regexp = '/^' . preg_replace( '/\*/', '[0-9\.]*', preg_replace( '/\./', '\.', $ip ) ) . '$/'; if (preg_match( $regexp, $match_ip )) { $this->_allow_lease_administratie = true; break; } } } } return $this->_allow_lease_administratie; } public function get_checklist_groepen() { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'get_checklist_groepen', 'SELECT * FROM ' . get_instance()->checklistgroep->get_table() . ' WHERE klant_id = ? ORDER BY naam', $db ); $res = $CI->dbex->execute( 'get_checklist_groepen', array( $this->id ), $db ); $result = array(); foreach ($res->result() as $row) $result[] = $CI->checklistgroep->getr( $row, false ); return $result; } public function get_gebruikers($active_only = false, $niet_speciale_only = true, $lease_only = false) { $CI = get_instance(); $db = $this->get_model()->get_db(); if($lease_only) { $query = 'SELECT g.* FROM ' . get_instance()->gebruiker->get_table() . ' g '. 'INNER JOIN rollen r ON r.id = g.rol_id '. 'WHERE g.klant_id = ? AND r.is_lease = 1'; } else { $query = 'SELECT * FROM ' . get_instance()->gebruiker->get_table() . ' WHERE klant_id = ?'; } $CI->dbex->prepare( 'get_gebruikers', $query, $db ); $res = $CI->dbex->execute( 'get_gebruikers', array( $this->id ), $db ); $result = array(); foreach( $res->result() as $row ) { if (!$active_only || $row->status == 'actief') { if (!$niet_speciale_only || $row->speciale_functie=='geen') { $result[] = $CI->gebruiker->getr( $row, false ); } } } $res->free_result(); return $result; } public function get_gebruikers_by_speciale_functie( $functie ) { $CI = get_instance(); // regular $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'get_gebruikers_by_speciale_functie', 'SELECT * FROM ' . get_instance()->gebruiker->get_table() . ' WHERE klant_id = ? AND speciale_functie = ?', $db ); $res = $CI->dbex->execute( 'get_gebruikers_by_speciale_functie', array( $this->id, $functie ), $db ); $result = array(); foreach ($res->result() as $row) $result[] = $CI->gebruiker->getr( $row, false ); $res->free_result(); return $result; } public function get_dossieroverzicht_velden() { return $this->dossieroverzicht_velden; } public function get_dossieroverzicht ($gearchiveerd = '0') { switch ($gearchiveerd) { case '0': $mysql_array = array ( '#dossier_id' => '`d`.`id`', '#deelplan_id' => '`dp`.`id`', '#dossier_opmerkingen' => '`d`.`opmerkingen`', 'Adres' =>'`d`.`locatie_adres`', 'Kenmerk' => '`d`.`kenmerk`', 'dd. Besluit' => 'FROM_UNIXTIME(`d`.`aanmaak_datum`, \'%d-%m-%Y\')', 'Project omschrijving' => '`d`.`beschrijving`', 'Deelplan omschrijving' => '`dp`.`naam`', 'DH_Grondslag' => 'null', 'Categorie' => '`cl`.`naam`', 'Checklistgroep' => '`clg`.`naam`', 'DH_Beschikking' => 'null', 'Toezichthouder' => '`tz`.`volledige_naam`', 'DH_BAG id' => 'null', 'Status Scope' => '`dc`.`voortgang_percentage`' // If Checklists need to be combined, use: //'Categorie' => 'SUBSTRING_INDEX (GROUP_CONCAT(`cl`.`naam` ORDER BY dc.checklist_id DESC),\',\', 1)', //'Status Scope' => 'SUM(`dc`.`voortgang_percentage`)' ); break; case '1': $mysql_array = array ( '#dossier_id' => '`d`.`id`', '#deelplan_id' => '`dp`.`id`', '#dossier_opmerkingen' => '`d`.`opmerkingen`', 'Adres' =>'`d`.`locatie_adres`', 'Kenmerk' => '`d`.`kenmerk`', 'dd. Besluit' => 'FROM_UNIXTIME(`d`.`aanmaak_datum`, \'%d-%m-%Y\')', 'Project omschrijving' => '`d`.`beschrijving`', 'Deelplan omschrijving' => '`dp`.`naam`', 'Categorie' => '`cl`.`naam`', 'Checklistgroep' => '`clg`.`naam`', 'DH_Beschikking' => 'null', 'Toezichthouder' => '`tz`.`volledige_naam`', 'dd. afgedaan' => 'IF( `d`.`gearchiveerd` = \'1\', DATE_FORMAT(`d`.`laatst_bijgewerkt_op`, \'%d-%m-%Y\'), NULL )' // If Checklists need to be combined, use: //'Categorie' => 'SUBSTRING_INDEX (GROUP_CONCAT(`cl`.`naam` ORDER BY dc.checklist_id DESC),\',\', 1)', ); break; } // Put all the keys and values in a temporary array to create the mysql string later on $temp_array = array(); foreach ($mysql_array as $key=>$value) { $temp_array[] = "$value '$key'"; } // For the dossieroverzicht_velden array we only need the keys $this->dossieroverzicht_velden = array_keys($mysql_array); $query_dossieroverzicht = 'SELECT '.implode (',',$temp_array).' '. 'FROM gebruikers g INNER JOIN dossiers d ON g.id = d.gebruiker_id LEFT JOIN deelplannen dp ON dp.dossier_id = d.id LEFT JOIN deelplan_checklisten dc ON dc.deelplan_id = dp.id LEFT JOIN bt_checklisten cl ON cl.id = dc.checklist_id LEFT JOIN bt_checklist_groepen clg ON clg.id = cl.checklist_groep_id LEFT JOIN gebruikers tz ON tz.id = dc.toezicht_gebruiker_id WHERE g.klant_id = ? AND d.gearchiveerd = ? AND d.verwijderd = 0 AND `d`.`aanmaak_datum` >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 YEAR)) ORDER BY \'dd. Besluit\' DESC'; /* * If there needs to be grouping on checklist, change ORDER BY \'dd. Besluit\' DESC'; to the following: * GROUP BY dp.id * ORDER BY 'dd. Besluit' DESC; */ $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'get_dossieroverzicht', $query_dossieroverzicht, $db ); $res= $CI->dbex->execute( 'get_dossieroverzicht', array( $this->id, $gearchiveerd ), $db ); $dossiers = array(); foreach($res->result() as $row) { $dossier = array(); foreach ($this->dossieroverzicht_velden as $field) { $value = $row->$field; if ($value) { $dossier[$field] = $value; } else { $dossier[$field] = ''; } } $dossiers[] = $dossier; } $res->free_result(); return $dossiers; } public function get_dossiers() { $CI = get_instance(); return $CI->dossier->convert_results( $CI->db->query( ' SELECT d.* FROM dossiers d JOIN gebruikers g ON d.gebruiker_id = g.id WHERE g.klant_id = ' . $this->id . ' AND d.gearchiveerd = 0 AND d.verwijderd = 0 ' )); } public function get_lease_configuratie() { if (!$this->lease_configuratie_id) return null; $CI = get_instance(); $CI->load->model( 'leaseconfiguratie' ); return $CI->leaseconfiguratie->get( $this->lease_configuratie_id ); } public function get_toezicht_momenten() { // !!! Note: to the contrary of MySQL, in Oracle the 'GROUP BY' clause is not allowed to use the aliases like 'toezicht_moment1'. Use the real column names instead. $query = ' SELECT v.toezicht_moment AS toezicht_moment1, h.standaard_toezicht_moment AS toezicht_moment2, cl.standaard_toezicht_moment AS toezicht_moment3, cg.standaard_toezicht_moment AS toezicht_moment4 FROM bt_vragen v RIGHT JOIN bt_categorieen c ON v.categorie_id = c.id RIGHT JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id RIGHT JOIN bt_checklisten cl ON h.checklist_id = cl.id RIGHT JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE cg.klant_id = ' . intval($this->id) . ' GROUP BY v.toezicht_moment, h.standaard_toezicht_moment, cl.standaard_toezicht_moment, cg.standaard_toezicht_moment '; $res = $this->_CI->db->query($query); $toezicht_momenten = array(); foreach ($res->result() as $row) { if (!is_null( $row->toezicht_moment1 )) $toezicht_momenten[] = $row->toezicht_moment1; if (!is_null( $row->toezicht_moment2 )) $toezicht_momenten[] = $row->toezicht_moment2; if (!is_null( $row->toezicht_moment3 )) $toezicht_momenten[] = $row->toezicht_moment3; if (!is_null( $row->toezicht_moment4 )) $toezicht_momenten[] = $row->toezicht_moment4; } $res->free_result(); if (!in_array( 'Algemeen', $toezicht_momenten )) $toezicht_momenten[] = 'Algemeen'; return array_unique( $toezicht_momenten ); } public function get_fases() { // !!! Note: to the contrary of MySQL, in Oracle the 'GROUP BY' clause is not allowed to use the aliases like 'fase1'. Use the real column names instead. $res = $this->_CI->db->query( ' SELECT v.fase AS fase1, h.standaard_fase AS fase2, cl.standaard_fase AS fase3, cg.standaard_fase AS fase4 FROM bt_vragen v RIGHT JOIN bt_categorieen c ON v.categorie_id = c.id RIGHT JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id RIGHT JOIN bt_checklisten cl ON h.checklist_id = cl.id RIGHT JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE cg.klant_id = ' . intval($this->id) . ' GROUP BY v.fase, h.standaard_fase, cl.standaard_fase, cg.standaard_fase '); $fases = array(); foreach ($res->result() as $row) { if (!is_null( $row->fase1 )) $fases[] = $row->fase1; if (!is_null( $row->fase2 )) $fases[] = $row->fase2; if (!is_null( $row->fase3 )) $fases[] = $row->fase3; if (!is_null( $row->fase4 )) $fases[] = $row->fase4; } $res->free_result(); if (!in_array( 'Algemeen', $fases )) $fases[] = 'Algemeen'; return array_unique( $fases ); } public function get_mappingen( $isFreeOnly=FALSE, $assoc=FALSE ) { $CI = get_instance(); $CI->load->model( 'matrixmapping' ); return $CI->matrixmapping->get_dmms( $this->id, $isFreeOnly, $assoc ); } public function get_map_checklisten(){ $CI = get_instance(); $CI->load->model( 'checklist' ); return $CI->checklist->get_map_checklisten_by_klant( $this->id ); } } class Klant extends BaseModel { function Klant() { parent::BaseModel( 'KlantResult', 'klanten', true ); } public function check_access( BaseResult $object ) { global $class, $method; if (!isset( $this->rechten )) // during init return; if ($this->rechten->geef_recht_modus( RECHT_TYPE_GEBRUIKERS_BEHEREN ) != RECHT_MODUS_GEEN) return; if (!$this->is_object_security_active()) return; if ($class == 'gebruikers' && $method == 'inloggen') return; if ($class == 'lease' && $method == 'do_lease') return; if (!isset( $object->id )) // during add! return; if ($object->id != $this->session->userdata('kid')) $this->throw_no_access_error( $object, $object->get_model() ); } function get_logged_in_klant() { // klant die hoort bij ingelogde gebruiker, of NULL if ($this->login->logged_in()) { return get_instance()->klant->get( get_instance()->session->userdata('kid') ); } else return null; } function add( $klantnaam, $kennis_id_unique_id ) { /* if (!$this->dbex->is_prepared( 'add_klant' )) $this->dbex->prepare( 'add_klant', 'INSERT INTO klanten (naam, volledige_naam, status, kennis_id_unique_id) VALUES (?, ?, ?, ?)' ); $args = array( 'naam' => $klantnaam, 'volledige_naam' => $klantnaam, 'status' => 'geaccepteerd', 'kennis_id_unique_id' => $kennis_id_unique_id, ); $this->dbex->execute( 'add_klant', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return nul; return new $this->_model_class( array_merge( array( 'id' => $id ), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'naam' => $klantnaam, 'volledige_naam' => $klantnaam, 'status' => 'geaccepteerd', 'kennis_id_unique_id' => $kennis_id_unique_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function add_localdb( $klantnaam, $cp_naam, $cp_email, $cp_telefoon, $gebruikersnaam, $ww1, $ww2, $volledige_naam ) { // check ww's if (!$ww1 || $ww1!=$ww2) return 1; // check klantnaam for ($i=0; $i<strlen($klantnaam); ++$i) if (!( ($klantnaam[$i]>='a' && $klantnaam[$i]<='z') || ($klantnaam[$i]>='A' && $klantnaam[$i]<='Z') || ($klantnaam[$i]>='0' && $klantnaam[$i]<='9') || $klantnaam[$i]=='-' || $klantnaam[$i]=='_') ) return 5; // start transaction $this->db->trans_start(); // !!! TODO: implement properly. Use the basemodel's insert, use a name suffix, and handle properly /* if (!$this->dbex->is_prepared( 'add_klant' )) $this->dbex->prepare( 'add_klant', 'INSERT INTO klanten (naam, volledige_naam, contactpersoon_email, contactpersoon_naam, contactpersoon_telefoon, status, kennis_id_unique_id) VALUES (?, ?, ?, ?, ?, ?, ?)' ); $args = array( 'naam' => $klantnaam, 'volledige_naam' => $klantnaam, 'contactpersoon_email' => $cp_email, 'contactpersoon_naam' => $cp_naam, 'contactpersoon_telefoon' => $cp_telefoon, 'status' => 'geaccepteerd', 'kennis_id_unique_id' => sha1( date('Y-m-d H:i:s') ), ); $this->dbex->execute( 'add_klant', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) { $this->db->trans_rollback(); return 4; } $klant = new $this->_model_class( $args ); $klant->id = $id; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. $CI = get_instance(); $has_children_orgs = $CI->session->userdata( 'has_children_organisations' ); $kid = $CI->session->userdata( 'kid' ); $lease_configuratie_id = $CI->session->_loginSystem->get_lease_configuratie_id(); if( APPLICATION_LOGIN_SYSTEM == 'LocalDB' && $this->login->verify( 'admin', 'parentadmin' ) ) { $parent_id = $kid; $cf_id = $lease_configuratie_id; } else { $cf_id = $parent_id = null; } // Use the base model's 'insert' method. $data = array( 'naam' => $klantnaam, 'volledige_naam' => $klantnaam, 'contactpersoon_email' => $cp_email, 'contactpersoon_naam' => $cp_naam, 'contactpersoon_telefoon' => $cp_telefoon, 'status' => 'geaccepteerd', 'kennis_id_unique_id' => sha1( date('Y-m-d H:i:s') ), 'parent_id' => $parent_id, 'lease_configuratie_id' => $cf_id ); // Call the normal 'insert' method of the base record. $klant = $this->insert( $data ); $id = $klant->id; if (!is_numeric($id)) { $this->db->trans_rollback(); return 4; } if(!isset($this->rol)){ $this->_CI->load->model('rol'); $this->rol = $this->_CI->rol; } $gebruikers = $klant->get_gebruikers( true ); if (sizeof( $gebruikers ) == 0) $rol = $this->rol->get_beheer_default(); else $rol = $this->rol->get_toezichthouder_default(); // add gebruiker, if it fails, rollback and fail $gebruiker = $this->gebruiker->add_localdb( $klant->id, $gebruikersnaam, $ww1, $volledige_naam, $rol->id ); if (!$gebruiker) { $this->db->trans_rollback(); return 6; // invalid gebruikersnaam } if (!$this->db->_trans_status || $gebruiker===null) { $this->db->trans_rollback(); return 3; } // finish transaction if (!$this->db->trans_complete()) { $this->db->trans_rollback(); return 4; } // done! return 0; } function get_by_naam( $naam ) { if (!$this->dbex->is_prepared( 'get_klanten_by_naam' )) $this->dbex->prepare( 'get_klanten_by_naam', ' SELECT * FROM klanten WHERE naam = ? ' ); $res = $this->dbex->execute( 'get_klanten_by_naam', array( $naam ) ); $result = array(); if ($res->num_rows) return $this->klant->getr( reset( $res->result() ) ); return NULL; } public function get_by_kennisid_unique_id( $kennisid_unique_id ) { $this->_CI->dbex->prepare( 'get_by_kennisid_unique_id', 'SELECT * FROM klanten WHERE kennis_id_unique_id = ?' ); $res = $this->dbex->execute( 'get_by_kennisid_unique_id', array( $kennisid_unique_id ) ); if ($res->num_rows() <= 0) return null; $klanten = $res->result(); $row = reset( $klanten ); $klant = $this->getr($row); $res->free_result(); return $klant; } public function get_last_requests() { // The below query is fully Oracle compatible $res = $this->db->query( ' SELECT k.id AS klant_id, MAX(g.laatste_request) AS tijdstip FROM gebruikers g JOIN klanten k ON g.klant_id = k.id GROUP BY k.id ' ); $result = array(); foreach ($res->result() as $row) $result[$row->klant_id] = $row->tijdstip; $res->free_result(); return $result; } public function getAllPairs() { $stmt = $this->db->query('SELECT id, naam FROM klanten'); $res = $stmt->result(); $result = array(); foreach($res as $row) { $result[$row->id] = $row->naam; } $stmt->free_result(); return $result; } public function getDataforOverview($client_id, $year) { $year++; // !!! TODO: REQUIRES ORACLE FIX UP!!!! $query_dossier_deelplan = 'SELECT d.id dossier_id, FROM_UNIXTIME(d.aanmaak_datum) dossier_creation_date, '. 'dp.id deelplan_id, dp.aangemaakt_op deelplan_creation_date '. 'FROM gebruikers g '. 'INNER JOIN dossiers d ON g.id = d.gebruiker_id '. 'LEFT JOIN deelplannen dp ON dp.dossier_id = d.id AND dp.aangemaakt_op < "' . $year . '" '. 'WHERE g.klant_id = ' . $client_id . ' AND d.aanmaak_datum < '.strtotime($year.'-01').' '. 'ORDER BY dossier_creation_date DESC'; $stmt = $this->db->query($query_dossier_deelplan); $res = $stmt->result(); $dossiers = $clg = $result = array(); foreach($res as $row) { $dossier_creation_date = date('Y-n', strtotime($row->dossier_creation_date)); list($dossier_year, $dossier_month) = explode('-', $dossier_creation_date); if( !isset($dossiers[$row->dossier_id]) ) { $result['dossiers'][$dossier_year][$dossier_month] = isset($result['dossiers'][$dossier_year][$dossier_month]) ? ++$result['dossiers'][$dossier_year][$dossier_month] : 1; $dossiers[$row->dossier_id] = true; } if( is_null($row->deelplan_id) ) { continue; } $deelplan_year = date('Y', strtotime($row->deelplan_creation_date)); $deelplan_month = date('n', strtotime($row->deelplan_creation_date)); $result['deelplans'][$deelplan_year][$deelplan_month] = isset($result['deelplans'][$deelplan_year][$deelplan_month]) ? ++$result['deelplans'][$deelplan_year][$deelplan_month] : 1; } $query_clg_cl = 'SELECT bt_clg.id bt_clg_id, bt_clg.created_at bt_clg_creation_date, bt_cl.created_at bt_cl_creation_date '. 'FROM bt_checklist_groepen bt_clg '. 'INNER JOIN bt_checklisten bt_cl ON bt_cl.checklist_groep_id = bt_clg.id AND bt_cl.created_at < "' . $year . '-01-01" '. 'WHERE bt_clg.klant_id = ' . $client_id .' AND bt_clg.created_at IS NOT NULL AND bt_clg.created_at < "' . $year . '-01-01" '. 'ORDER BY bt_clg_creation_date DESC'; $stmt = $this->db->query($query_clg_cl); $res = $stmt->result(); foreach($res as $row) { if( !isset($clg[$row->bt_clg_id]) ) { $bt_clg_creation_date = date('Y-n', strtotime($row->bt_clg_creation_date)); list($checklist_grp_year, $checklist_grp_month) = explode('-', $bt_clg_creation_date); $result['checklist_grp'][$checklist_grp_year][$checklist_grp_month] = isset($result['checklist_grp'][$checklist_grp_year][$checklist_grp_month]) ? ++$result['checklist_grp'][$checklist_grp_year][$checklist_grp_month] : 1; $clg[$row->bt_clg_id] = true; } if( isset($row->bt_cl_creation_date) ) { $bt_cl_creation_date = date('Y-n', strtotime($row->bt_cl_creation_date)); list($checklist_year, $checklist_month) = explode('-', $bt_cl_creation_date); $result['checklist'][$checklist_year][$checklist_month] = isset($result['checklist'][$checklist_year][$checklist_month]) ? ++$result['checklist'][$checklist_year][$checklist_month] : 1; } } $stmt->free_result(); return $result; } function allow_lease_administratie() { $gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker(); if (!$gebruiker) return false; return $gebruiker->get_klant()->allow_lease_administratie(); } } <file_sep>ALTER TABLE bt_vragen ADD COLUMN naam VARCHAR(255) DEFAULT NULL AFTER email_config;<file_sep><? $this->load->view('elements/header', array('page_header'=>'toezichtmomenten.monenten','map_view'=>true)); ?> <h1><?=tgg('toezichtmomenten.headers.monenten')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list"> <tr> <td> <div class="button new" style="margin-left: 10px;"> <i class="icon-plus" style="font-size: 12pt"></i> <span><?=tgg('toezichtmomenten.button.new')?></span> </div> <?=htag('new')?> </td> </tr> </table> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==sizeof($list)-1) ? 'bottom' : ''; ?> <li class="entry top left right <?=$bottom?>" entry_id="<?=$entry->id ?>"> <img style="margin-left: 3px; padding-top: 10px; vertical-align: bottom;" src="<?=$image_url ?>"> <div class="list-entry" style="margin-top: 3px; vertical-align: bottom;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> </div> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = '<?=site_url('/toezichtmomenten/hoofdgroepen/').'/'.$checklistgroep_id.'/'.$checklist_id.'/'?>'+$(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $('div.main div.button.new').click(function(){ location.href = '<?=site_url('/toezichtmomenten/hoofdgroepen/').'/'.$checklistgroep_id.'/'.$checklist_id?>'; }); </script><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account accepteren')); ?> <form method="post" name="form"> <table> <tr> <td id="form_header">Klantnaam*:</td> </tr> <tr> <td id="form_value"><input name="klantnaam" value="<?=$klantnaam?>" type="text" size="40" maxlength="32"/><br/><i>Let op, deze naam moet uniek zijn!</i></td> </tr> <tr> <td id="form_header">Contacpersoon:</td> </tr> <tr> <td id="form_value">Naam*: <input name="contactpersoon_naam" value="<?=$contactpersoon_naam?>" type="text" size="40" maxlength="64"/></td> </tr> <tr> <td id="form_value">E-mail: <input name="contactpersoon_email" value="<?=$contactpersoon_email?>" type="text" size="40" maxlength="128"/></td> </tr> <tr> <td id="form_value">Telefoon: <input name="contactpersoon_telefoon" value="<?=$contactpersoon_telefoon?>" type="text" size="32" maxlength="32"/></td> </tr> <tr> <td id="form_header">Gebruiker:</td> </tr> <tr> <td id="form_value">Gebruikersnaam*: <input name="gebruikersnaam" value="<?=$gebruikersnaam?>" type="text" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_value">Volledige naam*: <input name="volledige_naam" value="<?=$volledige_naam?>" type="text" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_header">Wachtwoord*:</td> </tr> <tr> <td id="form_value"><input name="wachtwoord1" value="" type="password" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_value"><input name="wachtwoord2" value="" type="password" size="40" maxlength="32"/> <i>(nogmaals)</i></td> </tr> <tr> <td id="form_button"><input type="submit" value="Toevoegen"/></td> </tr> </table> </form> <? $this->load->view('elements/footer'); ?><file_sep><script type="text/javascript"> function annuleren() { closePopup(); } function verwijderen() { document.location.href = "<?=site_url('/dossiers/verwijderen/'.$dossier->id.'/confirm')?>"; } </script> <table width="100%" cellspacing="0" cellpadding="5"> <tr> <td colspan="2"><h2>Checklist verwijderen</h2></td> </tr> <tr> <td colspan="2" id="form"> Weet u zeker dat u dit dossier wilt verwijderen? U kunt deze actie niet ongedaan maken! </td> </tr> <tr> <td id="form"><input type="button" onclick="verwijderen();" value="<?=tgng('form.verwijderen')?>" /></td> <td id="form" style="text-align:right"><input type="button" onclick="annuleren();" value="<?=tgng('form.annuleren')?>" /></td> </tr> </table> <file_sep><?php function imagettfbbox2a( $text, $fontfile, $fontsize, $fontangle=0 ) { /************ simple function that calculates the *exact* bounding box (single pixel precision). The function returns an associative array with these keys: left, top: coordinates you will pass to imagettftext width, height: dimension of the image you have to create *************/ $rect = imagettfbbox( $fontsize, $fontangle, $fontfile, $text ); $minX = min( array( $rect[0], $rect[2], $rect[4], $rect[6] ) ); $maxX = max( array( $rect[0], $rect[2], $rect[4], $rect[6] ) ); $minY = min( array( $rect[1], $rect[3], $rect[5], $rect[7] ) ); $maxY = max( array( $rect[1], $rect[3], $rect[5], $rect[7] ) ); return (object)array( "left" => $minX, "top" => $minY, "width" => $maxX - $minX, "height" => $maxY - $minY, "box" => $rect ); } /** Main annotation afbeelding processor class. When instantiating it, $checklist_id is the only * parameter than can be null. $deelplan_id and $checklist_groep_id must always be set! * If you set $log_enabled to true, the class will output a lot of debug information to indicate * what it is doing. * * In theory you could call run() multiple times. Do not do that though, it's untested. Call it once. */ class AnnotatieAfbeeldingProcessorImpl { private $annotaties = array(); // Note: the $annotation_data_set and $overview_data_set parameters are intentionally passed by reference so we can use them to add to existing sets (if so desired). public function __construct($deelplan_id, $checklist_groep_id, $checklist_id, $padding=50, $log_enabled=false, $output_path = '') { $this->CI = get_instance(); $this->deelplan_id = $deelplan_id; $this->checklist_groep_id = $checklist_groep_id; $this->checklist_id = $checklist_id; $this->padding = $padding; $this->log_enabled = $log_enabled; $this->output_path = $output_path; $this->annotation_data_set = array(); // Can be used for filling it with the desired (if any) annotation data in the respective callback function $this->overview_data_set = array(); // Can be used for filling it with the desired (if any) overview data in the respective callback function $this->CI->load->library('pdfannotatorlib'); $this->CI->load->library('imageprocessor'); $this->CI->load->model('dossierbescheiden'); $this->CI->load->model('deelplanlayer'); $this->CI->load->model('dossier'); $this->CI->load->model('deelplan'); $this->CI->load->model('checklistgroep'); $this->CI->load->model('checklist'); $this->CI->load->model('hoofdgroep'); $this->CI->load->model('categorie'); $this->CI->load->model('vraag'); } public function log($msg) { if ($this->log_enabled) { $time = microtime(true); //echo sprintf("[%s.%03d] %s\n", date('Y-m-d H:i:s'), round(1000 * ($time - floor($time))), $msg); echo nl2br(sprintf("[%s.%03d] %s\n", date('Y-m-d H:i:s'), round(1000 * ($time - floor($time))), $msg)); } } public function run(AnnotatieAfbeeldingProcessorCallback $callback, $question_specific_annotations = false) { $this->_initialize_objects(); $this->_load_layers(); $this->_load_bescheiden(); $this->_create_annotatie_images($callback); $this->_create_bescheiden_images($callback, $question_specific_annotations); } private function _initialize_objects() { $this->deelplan = $this->CI->deelplan->get($this->deelplan_id); if (!$this->deelplan) throw new Exception('Deelplan ID ' . $this->deelplan_id . ' is niet geldig'); $this->dossier = $this->CI->dossier->get($this->deelplan->dossier_id); $this->klant = $this->dossier->get_gebruiker()->get_klant()->volledige_naam; $this->checklistgroep = $this->CI->checklistgroep->get($this->checklist_groep_id); if (!$this->checklistgroep) throw new Exception('Checklistgroep ID ' . $this->checklist_groep_id . ' is niet geldig'); $this->checklist = $this->checklist_id ? $this->CI->checklist->get($this->checklist_id) : null; if ($this->checklist_id && !$this->checklist) throw new Exception('Checklist ID ' . $this->checklist_id . ' is niet geldig'); if ($this->checklist && $this->checklist->checklist_groep_id != $this->checklist_groep_id) throw new Exception('Checklist ID ' . $this->checklist_id . ' hoort niet bij checklistgroep ID ' . $this->checklist_groep_id); $this->log('Loaded data objects'); } private function _load_layers() { $res = $this->CI->db->query('SELECT * FROM deelplan_layers WHERE deelplan_id = ' . $this->deelplan->id); $this->bescheiden_ids = array(); $this->layers = array(); foreach ($res->result() as $row) { $layers = Layers::import(json_decode($row->layer_data)); $has_actual_data = false; foreach ($layers->get_layers() as $layer) if (sizeof($layer->get_annotations()->get_annotations_for_page(1))) $has_actual_data = true; if ($has_actual_data) { if (!in_array($row->dossier_bescheiden_id, $this->bescheiden_ids)) $this->bescheiden_ids[] = $row->dossier_bescheiden_id; $this->layers[] = (object)array( 'bescheiden_id' => $row->dossier_bescheiden_id, 'deelplan_id' => $row->deelplan_id, 'layers' => $layers, 'pagetransform' => json_decode($row->pagetransform_data) ); } } $res->free_result(); $this->log('Loaded ' . sizeof($this->bescheiden_ids) . ' bescheiden ids'); $this->log('Loaded ' . sizeof($this->layers) . ' layers'); } private function _load_bescheiden() { $this->bescheiden = array(); $this->CI->imageprocessor->mode('original'); $this->CI->imageprocessor->type('bescheiden'); foreach ($this->bescheiden_ids as $id) { // get binary contents of image $this->CI->imageprocessor->slice(null); $this->CI->imageprocessor->id($id); try { $numpages = $this->CI->imageprocessor->get_number_of_pages(); for ($i = 1; $i <= $numpages; ++$i) { $this->CI->imageprocessor->page_number( $i ); $filename = $this->CI->imageprocessor->get_image_filename(); // get size $res = @getimagesize($filename); if ($res === false) throw new Exception('Failed to get image size of ' . $filename); list($w, $h) = $res; // set if (!isset($this->bescheiden[$id])) $this->bescheiden[$id] = array(); $this->bescheiden[$id][$i] = (object)array( 'w' => $w, 'h' => $h, 'filename' => $filename, 'id' => $id, ); } } catch (Exception $e) { $bescheiden = $this->CI->dossierbescheiden->get($id); if (!$bescheiden) throw new Exception('Failed to load bescheiden ' . $id . ' for error processing: ' . $e->getMessage()); if (preg_match('/\.(jpe?g|png|pdf)$/i', $bescheiden->bestandsnaam)) $this->log('Failed to obtain image data for id ' . $id . ': ' . $e->getMessage()); } } $this->log('Loaded ' . sizeof($this->bescheiden) . ' bescheiden'); } private function _create_annotatie_images(AnnotatieAfbeeldingProcessorCallback $callback) { //$next_number = 1; foreach ($this->layers as $i => $layers) { $this->log('Layer set ' . $i); // get pagetransform data $pagetransform = $layers->pagetransform; foreach ($layers->layers->get_layers() as $j => $layer) { $this->log('Layer ' . $j); //$vraag_id = $layer->get_metadata()->referenceId; $vraag_id = (isset($layer->get_metadata()->referenceId)) ? $layer->get_metadata()->referenceId : 0; if (!$vraag_id) { $this->log('Layer heeft geen vraag ID'); // this is not an error situation, the web version makes a "Algemene Laag" layer not belonging to a vraag } else { $vraag = $this->CI->vraag->get($vraag_id); if (!$vraag) { $this->log('Layer heeft ongeldig vraag ID ' . $vraag_id); continue; // The below exception brutally breaks the process of generating a report. Instead, we now log this situation and skip this question //throw new Exception('Layer heeft ongeldig vraag ID ' . $vraag_id); } $categorie = $vraag->get_categorie(); $hoofdgroep = $categorie->get_hoofdgroep(); // $checklist = $hoofdgroep->get_checklist(); $checklist_id = $hoofdgroep->get_checklist_id(); $this->log('Vraag ' . $vraag->id . ' geladen: ' . $vraag->tekst); //check if the layer is applicable to the current checklist if ($this->checklist_id == $checklist_id) { // loop over all annotations foreach ($layer->get_annotations()->get_page_numbers() as $pagina_nummer) { /* $type = @$ann->export()->type; $data = new AnnotatieAfbeeldingData($bescheiden->id, $this->dossier->id, $this->deelplan->id, $this->checklistgroep->id, $this->checklist ? $this->checklist->id : null, $vraag->get_categorie()->hoofdgroep_id, $vraag->id, $type); if ($callback->ShouldProcessAnnotation($data)) */ $this->log('... page number: ' . $pagina_nummer); // get bescheiden info $bescheiden = $this->bescheiden[$layers->bescheiden_id][$pagina_nummer]; if (!$bescheiden) throw new Exception('Interne fout, bescheiden ' . $layers->bescheiden_id . ' niet geladen'); $this->log('Bescheiden geladen: ' . $layers->bescheiden_id . ' afbeelding is ' . $bescheiden->w . 'x' . $bescheiden->h); // determine initial image width/height if ($pagetransform->rotation == '90' || $pagetransform->rotation == '-90' ) { $img_width = $bescheiden->h * $pagetransform->zoomLevel; $img_height = $bescheiden->w * $pagetransform->zoomLevel; } else { $img_width = $bescheiden->w * $pagetransform->zoomLevel; $img_height = $bescheiden->h * $pagetransform->zoomLevel; } // check page orientation if ($img_width < $img_height) { $bescheiden_orientation = 'portrait'; } else { $bescheiden_orientation = 'landscape'; } // create fake PDFAnnotator document $this->log('Bestandsnaam: ' . $bescheiden->filename); $document = new Document( array($bescheiden->filename), // source file, must be array otherwise PDF annotator thinks it needs PDF->png processing pathinfo($bescheiden->filename, PATHINFO_BASENAME), // filename to use, must be without path info 'high'); // quality $this->log('PDF annotator document gemaakt'); foreach ($layer->get_annotations()->get_annotations_for_page($pagina_nummer) as $annotatie_index => $ann) { $include = false; $type = @$ann->export()->type; $data = new AnnotatieAfbeeldingData($bescheiden->id, $this->dossier->id, $this->deelplan->id, $this->checklistgroep->id, $this->checklist ? $this->checklist->id : null, $vraag->get_categorie()->hoofdgroep_id, $vraag->id, $type, $pagina_nummer, $bescheiden_orientation); if ($callback->ShouldProcessAnnotation($data)) { // MJ (02-07-2015): included a check to determine if the upload that the layer is bound to still exists $upload_exists = $this->CI->db->query('SELECT `id` from `dossier_bescheiden` WHERE `id` = '. $bescheiden->id .';'); if (count($upload_exists->result())>0) { $this->log('Annotatie ' . $annotatie_index); // create fake Layers object with just this single annotation $annotations = new Annotations(); $annotations->add(1, $ann); $layerData = new Layers(); $layerData->add_layer(new Layer($layer->get_name(), $layer->get_metadata(), $layer->get_visibility(), $layer->get_filter(), $annotations)); $this->log('... annotations en layers objecten aangemaakt'); // get dimensions $bb = $ann->get_bounding_box(); // Check if the bounding box exceeds the canvas edges // If it does, calculate the extra amount of canvas to add $x1 = $bb->get_position()->x; $x2 = $x1 + $bb->get_size()->x; $y1 = $bb->get_position()->y; $y2 = $y1 + $bb->get_size()->y; $w = abs($x2 - $x1); $h = abs($y2 - $y1); $additional_width= $additional_height = 0; //get additional image widths and heights in case of text annotation if ($type == 'text'){ $h = $h + 7;// padding = 4, borderwidth = 3 $w = $w + 7;// padding = 4, borderwidth = 3 } if ($bescheiden_orientation == 'landscape') { $additional_height = (($w/4*3-$h)/2); } else { $additional_width = (($h/3*4-$w)/2); } $padding_x= $this->padding; $padding_y = $this->padding/4*3; $dim_x = $bb->get_position()->x - $padding_x - $additional_width; $dim_y = $bb->get_position()->y - $padding_y - $additional_height; $dim_w = $bb->get_size()->x + 2* $padding_x + 2 * $additional_width; $dim_h = $bb->get_size()->y + 2* $padding_y + 2 * $additional_height; $canvas_border = max(0, 0 - $dim_y , $dim_y + $dim_h - $img_height, 0 - $dim_x, $dim_x + $dim_w - $img_width); $pagetransform->additionalCanvas= $canvas_border; $dimensions = (object)array( 'x' => $dim_x + $canvas_border, 'y' => $dim_y + $canvas_border, 'w' => $dim_w, 'h' => $dim_h, ); $this->log('... bounding box is from ' . $bb->get_x1() . 'x' . $bb->get_y1() . ' to ' . $bb->get_x2() . 'x' . $bb->get_y2() ); $this->log('... dimensions are ' . $dimensions->x . 'x' . $dimensions->y . ' size ' . $dimensions->w . 'x' . $dimensions->h ); // create output object if ($this->klant != 'VIIA' || ($type != 'line' && $type != 'measureline' && $type != 'path')) { $include = true; $this->log('... PNG creeeren'); $output = new PNGSingleOutputString($document, $layerData); $png = $output->run($pagetransform, $dimensions); $this->log('... Output ophalen'); $png = $output->output(); $this->log('... Callback aanroepen'); } // setup object completely //check if a number has already been assigned $ann_number = ''; $arr_ann_number = $this->CI->db->query('SELECT annotatie_id FROM annotatie_ids WHERE deelplan_id = ' . $this->deelplan->id .' AND vraag_id = '.$data->GetVraagId() .' AND dossier_bescheiden_id = '. $bescheiden->id .' AND x1 = '.intval($bb->get_position()->x) .' AND y1 = '.intval($bb->get_position()->y).' AND type = "'.$type.'";'); foreach ($arr_ann_number->result() as $row) { $ann_number = $row->annotatie_id; } if (!$ann_number){//if not, get the hightest number in use $arr_ann_number = $this->CI->db->query('SELECT @max := MAX( annotatie_id ) +1 AS annotatie_id FROM annotatie_ids WHERE deelplan_id = ' . $this->deelplan->id.';'); foreach ($arr_ann_number->result() as $row) { $ann_number = $row->annotatie_id; } if (!$ann_number) $ann_number = 1; //update the table $this->CI->db->query('INSERT INTO `annotatie_ids` ( `annotatie_id`, `deelplan_id` , `vraag_id` , `dossier_bescheiden_id` , `x1` , `y1` , `type` ) VALUES ('. $ann_number .', ' . $this->deelplan->id .', ' . $data->GetVraagId().', ' . $bescheiden->id .', ' . intval($bb->get_position()->x) .', ' . intval($bb->get_position()->y).', "' . $type.'");' ); } $data->SetAnnotatieNummer($ann_number); $data->SetAnnotatieObject($ann); $data->SetBoundingBox($bb); // call callback function //$callback->ProcessAnnotationImage($data, $png); if ($include) { $callback->ProcessAnnotationImage($data, $png, $this->output_path, $this->annotation_data_set); } // register annotatie if (empty($this->annotaties[$bescheiden->id][$pagina_nummer]) || !$this->annotaties[$bescheiden->id][$pagina_nummer]) { $this->annotaties[$bescheiden->id][$pagina_nummer] = array(); } $this->annotaties[$bescheiden->id][$pagina_nummer][] = $data; } else { $this->log('... corresponding bescheiden not found for annotation ' . $annotatie_index . ' for vraag ' . $vraag->id); } } else { $this->log('... ignoring annotation ' . $annotatie_index . ' for vraag ' . $vraag->id); } } // remove data $this->log('... Opruimen'); unset($png); unset($output); unset($layerData); unset($annotations); } } //end check if layer applies to current checklist } } // remove data unset($document); unset($bescheiden); unset($vraag); } } private function _create_bescheiden_images(AnnotatieAfbeeldingProcessorCallback $callback, $hoofdgroep_specific_annotations = false) { foreach ($this->annotaties as $bescheiden_id => $bescheiden_set) { foreach($bescheiden_set as $pagina_nummer => $bescheiden_annotaties) { // get PNG for this bescheiden_id $this->CI->imageprocessor->mode('original'); $this->CI->imageprocessor->type('bescheiden'); $this->CI->imageprocessor->slice(null); $this->CI->imageprocessor->id($bescheiden_id); $this->CI->imageprocessor->page_number($pagina_nummer); $original_png_filename = $this->CI->imageprocessor->get_image_filename(); // import PNG $filesize = filesize($original_png_filename); $format = $filesize > 512*1024 ? 'jpeg' : 'png'; $img = @imagecreatefromstring(file_get_contents($original_png_filename)); $annotation_combinations = array(); if (is_resource($img)) { $zoom_level = 1; $img = $this->_apply_transforms($img, $bescheiden_id, $zoom_level); if ($hoofdgroep_specific_annotations) { $hoofdgroepen = array(); } //create references to all annotations per image if ($bescheiden_annotaties ) { //set annotation size based on scale and orientation //TODO: pass correct scaling information from docx.php ($max_overview_image_width/height) $max_overview_image_width = 1398; $max_overview_image_height = 900; if (imagesy($img) > imagesx($img)) { //portrait $scaled_fontsize = floatval (max(1,imagesy($img)/ $max_overview_image_height)); } else { //landscape $scaled_fontsize = floatval (max(1,imagesx($img)/ $max_overview_image_width)); } $img = $this->_add_bescheiden($img, $bescheiden_annotaties, $callback, $zoom_level, $scaled_fontsize, $annotation_combinations); // output ob_start(); $imagefunc = 'image' . $format; $imagefunc($img); $png_contents = ob_get_clean(); // call callback function $callback->ProcessBescheidenOverview($bescheiden_id.'_'.$pagina_nummer, $png_contents, $format, $this->output_path, $this->overview_data_set); foreach ($bescheiden_annotaties as $data) { if ($hoofdgroep_specific_annotations) { $hoofdgroep_id = $data->GetHoofdgroepId(); $hoofdgroepen[$hoofdgroep_id][] = $data; } } }//if ($bescheiden_annotaties ) if ($hoofdgroep_specific_annotations) { foreach($hoofdgroepen as $hoofdgroep=>$annotations){ //make sure we get a blank image. Using a copy of the original image created before adding the annotations did not work (somehow they are linked) $img = @imagecreatefromstring(file_get_contents($original_png_filename)); $img = $this->_apply_transforms($img, $bescheiden_id, $zoom_level); //set annotation size based on scale and orientation $max_thumb_overview_image_width = 934; $max_thumb_overview_image_height = 570; if (imagesx($img) > imagesy($img)) { //landscape $scaled_fontsize = floatval (imagesy($img)/$max_thumb_overview_image_height); } else { //portrait $scaled_fontsize = floatval (imagesx($img)/$max_thumb_overview_image_height); } $img = $this->_add_bescheiden($img, $annotations, $callback, $zoom_level, $scaled_fontsize,$annotation_combinations); // output ob_start(); $imagefunc = 'image' . $format; $imagefunc($img); $png_contents = ob_get_clean(); // call callback function $callback->ProcessBescheidenOverview($bescheiden_id.'_'.$pagina_nummer.'_'.$hoofdgroep, $png_contents, $format, $this->output_path, $this->overview_thumbs_data_set); }//foreach($hoofdgroepen as $hoofdgroep=>$annotations){ }//if ($hoofdgroep_specific_annotations) } //if (is_resource($img)) }//foreach($bescheiden_set as $pagina_nummer => $bescheiden_annotaties) } //foreach ($this->annotaties as $bescheiden_id => $bescheiden_set) } private function _apply_transforms ($img, $bescheiden_id, &$zoom_level) { //check if there are page transforms $arr_layers= array_filter($this->layers, function ($obj) use ($bescheiden_id){ if (isset($obj->bescheiden_id)) { if($obj->bescheiden_id != $bescheiden_id) return false; } return true; }); //apply transforms if (count($arr_layers) > 0){ //there can be only one transform so take the first entry foreach ($arr_layers as $layer){ // apply page transformations if ($layer) { $transform = $layer->pagetransform; if ($transform->rotation) { $img = imagerotate( $img, 360 - $transform->rotation, 0 ); } if ($transform->flipH) $img = imageflipped( $img, 2 ); if ($transform->flipV) $img = imageflipped( $img, 1 ); $w = imagesx( $img ); $h = imagesy( $img ); if ($transform->zoomLevel && $transform->zoomLevel != 1) $zoom_level = $transform->zoomLevel ; } } } return $img ; } private function _add_bescheiden($img, $dataset, $callback, $zoom_level, $scaled_fontsize, &$annotation_combinations) { //set sizes $fontsize = 9 * $scaled_fontsize; $padding = 3 * $scaled_fontsize; $bordersize = 1 * $scaled_fontsize; $combination_padding = 20 * $scaled_fontsize; //set colors $bg_color = imagecolorallocate ($img, 255,255,255); $color = imagecolorallocate ($img, 0,0,255); //create coordinates array to check if annotation numbers need to be combined $existing_annotations = array(); $base_annotations = array(); $texts = array(); if (count($annotation_combinations) == 0) { $combination_letter = "A"; } else { $combination_letter = key (array_slice($annotation_combinations,-1,1)); $combination_letter++; } foreach ($dataset as $data) { // write annotatie number $nummer = $data->GetAnnotatieNummer(); $center = $data->GetBoundingBox()->get_center(); $type = $data->GetAnnotatieType(); if ($this->klant == 'VIIA' && $type == 'text' ) { $nummer = "T-$nummer"; $ann = $data->GetAnnotatieObject(); $texts[$nummer] = $ann->get_text(); } $positions = $this->_get_positions($nummer, $fontsize, $padding, $zoom_level, $center); //check if an annotation already exists at the given location $location_occupied = false; $assigned_combination_letter = ""; //if customer is not VIIA or is not in a "base annotations type", check if the location is already occupied if ($this->klant != 'VIIA' || ($type != 'line' && $type != 'measureline' && $type != 'photo' && $type != 'path')) { foreach ($existing_annotations as $nr=>$coordinates) { // check if space is unoccupied. If any of the following tests is true, the annotations do NOT overlap. if ($positions["x1"] > $coordinates["x2"] == true|| $positions["x2"] < $coordinates["x1"]== true || $positions["y1"] > $coordinates["y2"] == true || $positions["y2"] < $coordinates["y1"]== true) { $location_occupied = false; } else { $existing_annotation_nr = $nr; $location_occupied = true; break; } } //foreach ($existing_annotations as $nr=>$coordinates) //assign the number to print and add the coordinates of the current annotation to the array if ($location_occupied) { //check if the existing position was taken by an annotation or a combination letter if (is_numeric($existing_annotation_nr) || preg_match("/T-\d/", $existing_annotation_nr)) { foreach ($annotation_combinations as $combination_id=>$annotations) { if (array_search($existing_annotation_nr, $annotations)) { $assigned_letter = $combination_id; break; } } } else { $assigned_letter = $existing_annotation_nr; } if (isset($assigned_letter)) { //if there is an entry already, assign this annotation to the existing letter $annotation_combinations[$assigned_letter][] = $nummer; $nummer = $assigned_letter; } else { //if it is the second item in this spot, assign this one and the first to a letter $annotation_combinations[$combination_letter][] = $nummer; $annotation_combinations[$combination_letter][] = $existing_annotation_nr; //change the assigned character in the annotation array , recalculating the text size $positions = $this->_get_positions($combination_letter, $fontsize, $padding, $zoom_level, $center); $existing_annotations[$combination_letter] = array('x1'=>$positions["x1"],'y1'=>$positions["y1"],'x2'=>$positions["x2"],'y2'=>$positions["y2"],'cx'=>$positions["cx"],'cy'=>$positions["cy"]); unset ($existing_annotations[$existing_annotation_nr]); $combination_letter++; } } else { $existing_annotations[$nummer] = array('x1'=>$positions["x1"],'y1'=>$positions["y1"],'x2'=>$positions["x2"],'y2'=>$positions["y2"],'cx'=>$positions["cx"],'cy'=>$positions["cy"]); } //if ($location_occupied) } //if ($klant != 'VIIA' || $type != 'line') else { $base_annotations[$nummer] = array('x1'=>$positions["x1"],'y1'=>$positions["y1"],'x2'=>$positions["x2"],'y2'=>$positions["y2"],'cx'=>$positions["cx"],'cy'=>$positions["cy"], 'type'=>$type, 'data'=>$data); } } //foreach ($dataset as $data) //If there are combinations, add them to the image $combination_text = ''; foreach ($annotation_combinations as $id=>$annotations) { //check if the annotation was in fact used on this overview image if (array_key_exists($id,$existing_annotations)) { sort($annotations); $combination_text .= $id .': '.implode(', ',$annotations)."\n"; } } //If there are additional texts, add them to the image too foreach ($texts as $id=>$annotation) { $combination_text .= $id .':'.$annotation."\n"; } //empty the texts array $texts = array(); if ($combination_text) { //calculate the space to add $tbox = imagettfbbox2a($combination_text, 'arialb.ttf', $fontsize); //Create new canvas and place original in top left corner $imnew = imagecreatetruecolor(imagesx($img), imagesy($img) + $tbox->height + 2*$combination_padding); imagefill($imnew,0,0,$bg_color); imagecopyresampled($imnew, $img, 0, 0, 0, 0, imagesx($img), imagesy($img), imagesx($img),imagesy($img)); //Write text (x1 is the lower left corner!) imagettftext($imnew, $fontsize, 0, $combination_padding, imagesy($img)+ $combination_padding + $fontsize, $color, "arialb.ttf", $combination_text); $img = $imnew; } //add the base annotations foreach ($base_annotations as $id=>$annotation) { $ann = $annotation['data']->GetAnnotatieObject(); imagesetthickness ($img, $bordersize); if ($annotation['type'] == 'photo') { $x1 = ($ann->get_x() + $ann->get_imagesizew() / 2) / $zoom_level; $y1 = ($ann->get_y() + $ann->get_imagesizeh() / 2) / $zoom_level; $x2 = ($x1 + ($ann->get_dirlength() * $zoom_level) * cos( $ann->get_direction() )); $y2 = ($y1 - ($ann->get_dirlength() * $zoom_level) * sin( $ann->get_direction() )); $this->_draw_line ($img, $x1, $y1, $x2, $y2, $color, false, true ); // Draw rectangle for annotation number // Create background for text imagefilledrectangle($img, $annotation["x1"], $annotation["y1"], $annotation["x2"], $annotation["y2"], $bg_color); // Create border around text area imagerectangle($img, $annotation["x1"], $annotation["y1"], $annotation["x2"], $annotation["y2"], $color); // Add the annotation number imagettftext($img, $fontsize, 0, $annotation["x1"] + $padding, $annotation["y1"] + $padding + $fontsize, $color, 'arialb.ttf', $id); // Draw the direction line } elseif ($annotation['type'] == 'line') { $annotation_color = $ann->get_color(); $annotation_color = imagecolorallocate( $img, $annotation_color[0], $annotation_color[1], $annotation_color[2] ); $x1 = $ann->get_x1() / $zoom_level; $y1 = $ann->get_y1() / $zoom_level; $x2 = $ann->get_x2() / $zoom_level; $y2 = $ann->get_y2() / $zoom_level; $this->_draw_line ($img, $x1, $y1, $x2, $y2, $annotation_color ); } elseif ($annotation['type'] == 'measureline') { $annotation_color = $ann->get_color(); $annotation_color = imagecolorallocate( $img, $annotation_color[0], $annotation_color[1], $annotation_color[2] ); $x1 = $ann->get_x1() / $zoom_level; $y1 = $ann->get_y1() / $zoom_level; $x2 = $ann->get_x2() / $zoom_level; $y2 = $ann->get_y2() / $zoom_level; $this->_draw_line ($img, $x1, $y1, $x2, $y2, $annotation_color ,true, true ); // render text if ($ann->has_eigen_tekst()) { $text = $ann->get_eigen_tekst(); } else { $text = $ann->get_length() . 'mm'; } $tx = ($x1+$x2)/2; $ty = ($y1+$y2)/2; $bbox = imagettfbbox2a ( $text, 'arialb.ttf', $fontsize); imagettftext( $img, $fontsize, 0, $tx, $ty + $bbox->height, $annotation_color,"arialb.ttf", $text ); } elseif ($annotation['type'] == 'path') { $annotation_color = $ann->get_kleur(); $annotation_color = imagecolorallocate( $img, $annotation_color[0], $annotation_color[1], $annotation_color[2] ); $locaties = $ann->get_decoded_locaties(); $last = null; for ($i=0; $i<sizeof($locaties); ++$i) { if ($last) { $x1 = $last->x / $zoom_level; $y1 = $last->y / $zoom_level; $x2 = $locaties[$i]->x / $zoom_level; $y2 = $locaties[$i]->y / $zoom_level; $this->_draw_line ($img, $x1, $y1, $x2, $y2, $annotation_color); } $last = $locaties[$i]; } } } // print all other annotations foreach ($existing_annotations as $id=>$coordinates) { imagesetthickness ($img, $bordersize); if (is_numeric($id) || preg_match("/T-\d/", $id)) { //Draw rectangle for annotation number //Create background for text imagefilledrectangle($img, $coordinates["x1"], $coordinates["y1"], $coordinates["x2"], $coordinates["y2"], $bg_color); //Create border around text area imagerectangle($img, $coordinates["x1"], $coordinates["y1"], $coordinates["x2"], $coordinates["y2"], $color); } elseif (!is_numeric($id)) { //Draw imagearc for combination letter. Use center position for of x1/y1. //Create background for text imagefilledellipse($img, $coordinates["cx"], $coordinates["cy"], $coordinates["x2"] - $coordinates["x1"], $coordinates["y2"] - $coordinates["y1"], $bg_color); //Create border around text area. Can't use imageellipse because of a but, ignoring border thickness. imagearc($img, $coordinates["cx"], $coordinates["cy"], $coordinates["x2"] - $coordinates["x1"], $coordinates["y2"] - $coordinates["y1"], 0, 359, $color); } //Write text (x1 is the lower left corner!) imagettftext($img, $fontsize, 0, $coordinates["x1"] + $padding, $coordinates["y1"] + $padding + $fontsize, $color, 'arialb.ttf', $id); } return $img; } // private function _add_bescheiden($img, $dataset, $callback, $zoom_level, $scaled_fontsize, &$annotation_combinations) private function _get_positions ($string='', $fontsize=8, $padding=1, $zoom_level, $center) { //TODO: move to helper $bbox = imagettfbbox2a($string, 'arialb.ttf', $fontsize); // Get position information $pos = $center->subtracted(new Vector2($bbox->width / 2, - $bbox->height/2)); $pos = $pos->added(new Vector2($bbox->left, $bbox->top)); //get the corners and center of the textbox $x1 = max($pos->x / $zoom_level,$padding); $y1 = max($pos->y / $zoom_level,$padding); $x2 = $x1 + $bbox->width + 2* $padding; $y2 = $y1 + $bbox->height + 2* $padding; $cx = $x1 + (($x2-$x1)/2); $cy = $y1 + (($y2-$y1)/2); return array ('x1'=>$x1,'x2'=>$x2,'y1'=>$y1,'y2'=>$y2, 'cx' =>$cx , 'cy'=>$cy); } // private function _get_positions ($string='', $fontsize=8, $padding=1, $zoom_level, $center) private function _draw_line ( $im,$x1, $y1, $x2, $y2, $color, $arrow_start = false, $arrow_end = false) { imageline( $im, $x1, $y1, $x2, $y2, $color ); if ($arrow_start) { // render arrow heads $headlength = 25; $rotation = 30; $dirvec = new Vector2( $x2 - $x1, $y2 - $y1 ); $dirvec = $dirvec->normalized(); $arrowvec = $dirvec->rotated( ((180.0 - $rotation) / 180.0) * M_PI )->multiplied( $headlength ); $ax = $x2 + $arrowvec->x; $ay = $y2 + $arrowvec->y; imageline( $im, $x2, $y2, $ax, $ay, $color ); $arrowvec = $dirvec->rotated( ((180.0 + $rotation) / 180.0) * M_PI )->multiplied( $headlength ); $ax = $x2 + $arrowvec->x; $ay = $y2 + $arrowvec->y; imageline( $im, $x2, $y2, $ax, $ay, $color ); } if ($arrow_end) { // render arrow heads $headlength = 25; $rotation = 30; $dirvec = new Vector2( $x2 - $x1, $y2 - $y1 ); $dirvec = $dirvec->normalized(); $arrowvec = $dirvec->rotated( ((180.0 - $rotation) / 180.0) * M_PI )->multiplied( $headlength ); $ax = $x2 + $arrowvec->x; $ay = $y2 + $arrowvec->y; imageline( $im, $x2, $y2, $ax, $ay, $color ); $arrowvec = $dirvec->rotated( ((180.0 + $rotation) / 180.0) * M_PI )->multiplied( $headlength ); $ax = $x2 + $arrowvec->x; $ay = $y2 + $arrowvec->y; imageline( $im, $x2, $y2, $ax, $ay, $color ); } } } <file_sep>// add outerHTML function to jquery (function($) { $.fn.outerHTML = function() { return $(this).clone().wrap('<div></div>').parent().html(); } })(jQuery); // add trim function if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } // zero pad function var zp = function( val, zeroes ) { val = '' + val; while (val.length < zeroes) val = '0' + val; return val; }; // add destroyed event to jquery (function( $ ) { /** * @attribute destroyed * @parent specialevents * @download http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/dom/destroyed/destroyed.js * @test jquery/event/destroyed/qunit.html * Provides a destroyed event on an element. * <p> * The destroyed event is called when the element * is removed as a result of jQuery DOM manipulators like remove, html, * replaceWith, etc. Destroyed events do not bubble, so make sure you don't use live or delegate with destroyed * events. * </p> * <h2>Quick Example</h2> * @codestart * $(".foo").bind("destroyed", function(){ * //clean up code * }) * @codeend * <h2>Quick Demo</h2> * @demo jquery/event/destroyed/destroyed.html * <h2>More Involved Demo</h2> * @demo jquery/event/destroyed/destroyed_menu.html */ var oldClean = jQuery.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) !== undefined; i++ ) { $(elem).triggerHandler("destroyed"); //$.event.remove( elem, 'destroyed' ); } oldClean(elems); }; })(jQuery) // we have to support IE8 which doesn't have indexOf... // if we add indexOf to the prototype of Array, every object // gets it too :X teh f...? and since we "for (var i in ...)" a // lot, this causes unsuspected behaviour in IE8 function indexOfArray( arr, val ) { if (arr.indexOf) return arr.indexOf( val ); for (var i=0; i<arr.length; ++i) if (arr[i] == val) return i; return -1; } <file_sep><?php class RiepairImporter { private $CI; private $_path = '/home/foddex/Riepair checklisten 19-09-2013'; private $_checklistgroepen = array(); private $_hoofdthema = null; private $_override = false; private $_parser; public function __construct() { $this->CI = get_instance(); $this->CI->load->model( 'checklistgroep' ); $this->CI->load->model( 'checklist' ); $this->CI->load->model( 'hoofdgroep' ); $this->CI->load->model( 'categorie' ); $this->CI->load->model( 'vraag' ); $this->CI->load->model( 'thema' ); $this->CI->load->model( 'hoofdthema' ); $this->CI->load->model( 'klant' ); $this->_parser = new Parser( $this ); $this->_parser->add_regexp( 'thema', '#<h2.*?><a.*?>(.*?)</a></h2>#msi' ); $this->_parser->add_regexp( 'hoofdgroep', '#<h3.*?><a.*?>(.*?)</a></h3>#msi' ); $this->_parser->add_regexp( 'vraag', '#<h4.*?><a.*?>(.*?)</a></h4>#msi' ); $this->_parser->add_regexp( 'standaardwaardeoordeel', '#<p class="message emphasis">(.*?)</p>#msi' ); $this->_parser->add_regexp( 'aandachtspunt', '#<p>(.*?)</p>#msi' ); } public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } public function run( $override=false ) { $this->_override = $override; $this->CI->db->trans_start(); try { $this->_login_as_riepair(); $files = $this->_load_files(); foreach ($files as $file) { $contents = @file_get_contents( $this->_path . '/' . $file ); if ($contents === false) throw new Exception( 'Kon bestand niet inlezen: ' . $file ); $checklistnaam = $this->_bepaal_checklistnaam( $file ); $checklistgroep = $this->_maak_checklistgroep( $checklistnaam ); $checklist = $this->_maak_checklist( $checklistnaam, $checklistgroep ); if (!$checklist) continue; // bestaat reeds $this->_import_checklist( $contents, $checklist ); } if (!$this->CI->db->trans_complete()) throw new Exception( 'Fout bij database commit' ); } catch (Exception $e) { $this->CI->db->_trans_status = false; $this->CI->db->trans_complete(); $this->log( 'EXCEPTION: ' . $e->getMessage() ); } } private function _login_as_riepair() { $klant = $this->CI->klant->search( array( 'naam' => 'riepair' ) ); if (empty( $klant )) throw new Exception( 'Kan klant riepair niet vinden' ); $gebruikers = $klant[0]->get_gebruikers( true ); if (empty( $gebruikers )) throw new Exception( 'Kan geen actieve gebruiker vinden in klant riepair' ); $this->CI->login( $klant[0]->id, $gebruikers[0]->id ); $this->_hoofdthema = $this->CI->hoofdthema->find( 'rie.nl' ); if (!$this->_hoofdthema) { $this->_hoofdthema = $this->CI->hoofdthema->add( 'rie.nl', 0, 'Eigen' ); if (!$this->_hoofdthema) throw new Exception( 'Kon hoofdthema rie.nl niet toevoegen voor klant riepair' ); } } private function _load_files() { if (!is_dir( $this->_path )) throw new Exception( 'Geen geldig pad: ' . $this->_path ); $files = array(); foreach (scandir( $this->_path ) as $file) if (preg_match( '/.html?$/i', $file )) $files[] = $file; if (!sizeof( $files )) throw new Exception( 'Geen bestanden gevonden in: ' . $this->_path ); $this->log( sizeof($files) . ' bestanden gevonden voor import' ); return $files; } private function _bepaal_checklistnaam( $filename ) { if (!preg_match( '/^(.*?)\.html?$/i', $filename, $matches )) throw new Exception( 'Kon checklistnaam niet bepalen uit: ' . $filename ); $checklistnaam = $matches[1]; if (strlen( $checklistnaam ) > 128) throw new Exception( 'Te lange checklistnaam: ' . $checklistnaam ); return $checklistnaam; } private function _maak_checklistgroep( $checklistnaam ) { if (empty( $checklistnaam )) throw new Exception( 'Checklistnaam leeg, kan geen checklistgroepnaam extraheren' ); $checklistgroepnaam = strtoupper( $checklistnaam[0] ); if ($checklistgroepnaam < 'A' || $checklistgroepnaam > 'Z') throw new Exception( 'Onverwachte eerste letter in checklistnaam: ' . $checklistnaam ); if (!isset( $_checklistgroepen[$checklistgroepnaam] )) { $cg = $this->CI->checklistgroep->search( array( 'naam' => $checklistgroepnaam ) ); if (!empty( $cg )) $_checklistgroepen[$checklistgroepnaam] = $cg[0]; else { $cg = $this->CI->checklistgroep->add( $checklistgroepnaam ); if (!$cg) throw new Exception( 'Fout bij toevoegen van checklistgroep: ' . $checklistgroepnaam ); $_checklistgroepen[$checklistgroepnaam] = $cg; } $cg = $_checklistgroepen[$checklistgroepnaam]; $cg->standaard_wo_tekst_00 = 'Nog niet beoordeeld'; $cg->standaard_wo_kleur_00 = 'oranje'; $cg->standaard_wo_is_leeg_00 = 1; $cg->standaard_wo_in_gebruik_00 = 1; $cg->standaard_wo_tekst_01 = 'Niet van toepassing'; $cg->standaard_wo_kleur_01 = 'groen'; $cg->standaard_wo_in_gebruik_01 = 1; $cg->standaard_wo_is_leeg_01 = 0; $cg->standaard_wo_tekst_02 = 'Nader onderzoek nodig'; $cg->standaard_wo_kleur_02 = 'oranje'; $cg->standaard_wo_in_gebruik_02 = 1; $cg->standaard_wo_is_leeg_02 = 0; $cg->standaard_wo_tekst_03 = NULL; $cg->standaard_wo_kleur_03 = NULL; $cg->standaard_wo_is_leeg_03 = NULL; $cg->standaard_wo_in_gebruik_03 = 0; $cg->standaard_wo_tekst_04 = NULL; $cg->standaard_wo_kleur_04 = NULL; $cg->standaard_wo_is_leeg_04 = NULL; $cg->standaard_wo_in_gebruik_04 = 0; $cg->standaard_wo_tekst_10 = 'JA'; $cg->standaard_wo_kleur_10 = 'groen'; $cg->standaard_wo_is_leeg_10 = 0; $cg->standaard_wo_in_gebruik_10 = 1; $cg->standaard_wo_tekst_11 = NULL; $cg->standaard_wo_kleur_11 = NULL; $cg->standaard_wo_is_leeg_11 = NULL; $cg->standaard_wo_in_gebruik_11 = 0; $cg->standaard_wo_tekst_12 = NULL; $cg->standaard_wo_kleur_12 = NULL; $cg->standaard_wo_is_leeg_12 = NULL; $cg->standaard_wo_in_gebruik_12 = 0; $cg->standaard_wo_tekst_13 = NULL; $cg->standaard_wo_kleur_13 = NULL; $cg->standaard_wo_is_leeg_13 = NULL; $cg->standaard_wo_in_gebruik_13 = 0; $cg->standaard_wo_tekst_20 = 'NEE'; $cg->standaard_wo_kleur_20 = 'rood'; $cg->standaard_wo_is_leeg_20 = 0; $cg->standaard_wo_in_gebruik_20 = 1; $cg->standaard_wo_tekst_21 = NULL; $cg->standaard_wo_kleur_21 = NULL; $cg->standaard_wo_is_leeg_21 = NULL; $cg->standaard_wo_in_gebruik_21 = 0; $cg->standaard_wo_tekst_22 = NULL; $cg->standaard_wo_kleur_22 = NULL; $cg->standaard_wo_is_leeg_22 = NULL; $cg->standaard_wo_in_gebruik_22 = 0; $cg->standaard_wo_tekst_23 = NULL; $cg->standaard_wo_kleur_23 = NULL; $cg->standaard_wo_is_leeg_23 = NULL; $cg->standaard_wo_in_gebruik_23 = 0; $cg->standaard_wo_standaard = 'w00'; $cg->standaard_wo_steekproef = 'w00'; $cg->standaard_wo_steekproef_tekst = $cg->standaard_wo_tekst_00; if (!$cg->save( 0, 0, 0)) throw new Exception( 'Fout bij configureren van checklistgroep: ' . $cg->naam ); } return $_checklistgroepen[$checklistgroepnaam]; } private function _maak_checklist( $checklistnaam, ChecklistGroepResult $checklistgroep ) { $cl = $this->CI->checklist->search( array( 'naam' => $checklistnaam, 'checklist_groep_id' => $checklistgroep->id ) ); if (!empty( $cl )) { if (!$this->_override) { $this->log( 'Checklist ' . $checklistnaam . ' bestaat reeds!' ); return NULL; } else { foreach ($cl as $c) $c->delete(); } } $cl = $this->CI->checklist->add( $checklistgroep->id, $checklistnaam ); if (!$cl) throw new Exception( 'Fout bij toevoegen van checklist: ' . $checklistnaam ); return $cl; } private function _import_checklist( $contents, ChecklistResult $checklist ) { $this->log( 'Importeren van ' . $checklist->naam ); $this->_parser->load_text( $contents ); $offset = 0; $cur_thema = null; $cur_hoofdgroep = null; $cur_vraag = null; while ($match = $this->_parser->next( $offset )) { $offset = $match->next; switch ($match->type) { case 'thema': $cur_thema = $this->_maak_thema( $match->matches[1][0] ); break; case 'hoofdgroep': $cur_hoofdgroep = $this->_maak_hoofdgroep( $match->matches[1][0], $checklist ); break; case 'vraag': if (!$cur_hoofdgroep) { if (!$cur_thema) throw new Exception( 'Vraag gevonden voordat er een hoofdgroep of thema was: ' . $match->matches[1][0] ); $cur_hoofdgroep = $this->_maak_hoofdgroep( $cur_thema->thema, $checklist ); } $cur_vraag = $this->_maak_vraag( $match->matches[1][0], $cur_hoofdgroep, $cur_thema ); break; case 'aandachtspunt': if (!$cur_vraag) throw new Exception( 'Aandachtspunt gevonden voordat er een vraag was: ' . $match->matches[1][0] ); $this->_maak_vraag_aandachtspunt( $match->matches[1][0], $cur_vraag ); break; case 'standaardwaardeoordeel': break; } } } private function _maak_thema( $thema ) { $thema = trim( preg_replace( '/\s+/', ' ', $thema ) ); if (strlen( $thema ) > 128) { if (preg_match( '/^(.*)\?/', $thema, $matches )) { $this->log( '... verander te lange thema naam "' . $thema . '" in "' . $matches[0] . '"' ); $thema = $matches[0]; } if (strlen( $thema ) > 128) throw new Exception( 'Thema naam te lang: ' . $thema ); } if (empty( $thema )) throw new Exception( 'Lege thema naam niet toegestaan' ); $t = $this->CI->thema->find( $thema, null, $this->_hoofdthema->id ); if (!$t) { $t = $this->CI->thema->add( $thema, 0, $this->_hoofdthema->id ); if (!$t) throw new Exception( 'Fout bij toevoegen thema: ' . $thema ); } return $t; } private function _maak_hoofdgroep( $hoofdgroepnaam, ChecklistResult $checklist ) { $hoofdgroepnaam = trim( preg_replace( '/\s+/', ' ', $hoofdgroepnaam ) ); if (strlen( $hoofdgroepnaam ) > 512) throw new Exception( 'Hoofdgroep naam te lang: ' . $hoofdgroepnaam ); if (empty( $hoofdgroepnaam )) throw new Exception( 'Lege hoofdgroep naam niet toegestaan' ); $hg = $this->CI->hoofdgroep->add( $checklist->id, $hoofdgroepnaam ); if (!$hg->id) throw new Exception( 'Fout bij toevoegen hoofdgroep: ' . $hoofdgroepnaam ); return $hg; } private function _maak_vraag( $vraag, HoofdgroepResult $hoofdgroep, ThemaResult $thema ) { $vraag = trim( preg_replace( '/\s+/', ' ', $vraag ) ); if (empty( $vraag )) throw new Exception( 'Lege vraag niet toegestaan' ); $categorieen = $hoofdgroep->get_categorieen(); if (empty( $categorieen )) { $categorieen = array( $this->CI->categorie->add( $hoofdgroep->id, '...' ) ); if (!$categorieen[0]->id) throw new Exception( 'Fout bij toevoegen van categorie' ); } $v = $this->CI->vraag->add( $categorieen[0]->id, $vraag, $thema->id ); if (!$v->id) throw new Exception( 'Fout bij toevoegen vraag: ' . $vraag ); return $v; } private function _maak_vraag_aandachtspunt( $aandachtspunt, VraagResult $vraag ) { $aandachtspunt = trim( preg_replace( '/\s+/', ' ', $aandachtspunt ) ); if (empty( $aandachtspunt )) return; if (!$vraag->gebruik_ndchtspntn) { $vraag->gebruik_ndchtspntn = 1; if (!$vraag->save(0,0,0)) throw new Exception( 'Fout bij configureren vraag: ' . $vraag->tekst ); } $checklist = $vraag->get_categorie()->get_hoofdgroep()->get_checklist(); if (!$this->CI->db->query( sprintf( 'INSERT INTO bt_vraag_ndchtspntn (vraag_id, checklist_groep_id, checklist_id, aandachtspunt) VALUES (%d, %d, %d, %s)', $vraag->id, $checklist->checklist_groep_id, $checklist->id, $this->CI->db->escape( $aandachtspunt ) ) )) throw new Exception( 'Fout bij toevoegen aandachtspunt' ); } } class Parser { private $importer; private $regexps = array(); private $text; public function __construct( $importer ) { $this->importer = $importer; } public function add_regexp( $type, $regexp ) { $this->regexps[$type] = $regexp; } public function load_text( $text ) { $this->text = $text; } public function next( $offset=0 ) { $closestdist = strlen( $this->text ); $closestregexp = null; $closestmatches = array(); foreach ($this->regexps as $name => $regexp) { if (preg_match( $regexp, $this->text, $matches, PREG_OFFSET_CAPTURE, $offset )) { $current_offset = $matches[0][1]; if ($closestdist > $current_offset) { $closestdist = $current_offset; $closestregexp = $name; $closestmatches = $matches; } } } if (!$closestregexp) return null; foreach ($closestmatches as $i => $match) { // fix encoding als dat nodig is $encoding = mb_detect_encoding( $match[0] ); if ($encoding != 'UTF-8') { $match[0] = iconv( $encoding, 'UTF-8', $match[0] ); if ($match[0] === false) throw new Exception( 'Kon tekst niet van ' . $encoding . ' naar UTF-8 converteren: "' . $match[0] . '"' ); } // sla weer op in array, geen references gebruiken, die zuigen $closestmatches[$i][0] = html_entity_decode( $match[0] ); } return $closestregexp ? (object)array( 'type' => $closestregexp, 'offset' => $closestdist, 'matches' => $closestmatches, 'next' => $closestdist + strlen($closestmatches[0][0]), ) : null; } } <file_sep><?php class UpdatePlanningTables { public function run() { $CI = get_instance(); $CI->db->trans_start(); // Get the proper DB function for determining the current date $date_now_func = get_db_date_now_function(); // // Voor deelplannen met integreerbare checklisten (dus geen toezicht per checklist), // zet in de plannings tabel het deelplan_id, checklist_groep_id en ***eerste hercontrole datum*** // $CI->db->query( 'DELETE FROM deelplan_checklistgroep_plnng' ); // eerst toekomst (>=now(), MIN) // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $CI->db->query( ' INSERT INTO deelplan_checklistgroep_plnng SELECT dv.deelplan_id, cl.checklist_groep_id, MIN(dv.hercontrole_datum) AS eerste_hercontrole_datum FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE dv.hercontrole_datum IS NOT NULL AND cg.modus != \'niet-combineerbaar\' AND dv.hercontrole_datum >= '.$date_now_func.' GROUP BY dv.deelplan_id, cl.checklist_groep_id ' ); $rows = $CI->db->affected_rows(); // dan verleden (<now(), MAX) $CI->db->query( ' INSERT INTO deelplan_checklistgroep_plnng SELECT dv.deelplan_id, cl.checklist_groep_id, MAX(dv.hercontrole_datum) AS eerste_hercontrole_datum FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE dv.hercontrole_datum IS NOT NULL AND cg.modus != \'niet-combineerbaar\' AND (dv.deelplan_id, cl.checklist_groep_id) NOT IN (SELECT deelplan_id, checklist_groep_id FROM deelplan_checklistgroep_plnng) GROUP BY dv.deelplan_id, cl.checklist_groep_id ' ); $rows += $CI->db->affected_rows(); echo 'deelplan_checklistgroep_plnng: ' . $rows . ' rows added' . "\n"; // // Voor deelplannen met NIET integreerbare checklisten (dus een toezicht per checklist), // zet in de plannings tabel het deelplan_id, checklist_id en ***eerste hercontrole datum*** // $CI->db->query( 'DELETE FROM deelplan_checklist_planning' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... // eerst toekomst (>=now(), MIN) $CI->db->query( ' INSERT INTO deelplan_checklist_planning SELECT dv.deelplan_id, cl.id, MIN(dv.hercontrole_datum) AS eerste_hercontrole_datum FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE dv.hercontrole_datum IS NOT NULL AND cg.modus = \'niet-combineerbaar\' AND dv.hercontrole_datum >= '.$date_now_func.' GROUP BY dv.deelplan_id, cl.id ' ); $rows = $CI->db->affected_rows(); // dan verleden (<now(), MAX) $CI->db->query( ' INSERT INTO deelplan_checklist_planning SELECT dv.deelplan_id, cl.id, MAX(dv.hercontrole_datum) AS eerste_hercontrole_datum FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE dv.hercontrole_datum IS NOT NULL AND cg.modus = \'niet-combineerbaar\' AND (dv.deelplan_id, cl.id) NOT IN (SELECT deelplan_id, checklist_id FROM deelplan_checklist_planning) GROUP BY dv.deelplan_id, cl.id ' ); $rows += $CI->db->affected_rows(); echo 'deelplan_checklist_planning: ' . $rows . ' rows added' . "\n"; // Determine which "null function" should be used $null_func = get_db_null_function(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... // !!! NOTE: the below insert query will currently fail in Oracle, at least becaue the 'having' clause does not work with the alias! // Instead, the entire aggregate data MUST be repeated. :S // A nicer work-around for this is desired. // // Combineer deelplannen met bovenstaande twee tabellen, en bekijk per deelplan // wat de eerst volgende datum is: de initiele datum uit het deelplan, of de eerstvolgende // datum uit een van de subtabellen // $CI->db->query( 'DELETE FROM deelplan_planning' ); $CI->db->query( ' INSERT INTO deelplan_planning SELECT deelplan_id, IF ( LEAST( '.$null_func.'(a.eerste_checklist_groep_hercontrole_datum, \'9999-12-31\'), '.$null_func.'(a.eerste_checklist_hercontrole_datum, \'9999-12-31\'), '.$null_func.'(a.checklist_groep_initiele_datum, \'9999-12-31\'), '.$null_func.'(a.checklist_initiele_datum, \'9999-12-31\') )!=\'9999-12-31\', LEAST( '.$null_func.'(a.eerste_checklist_groep_hercontrole_datum, \'9999-12-31\'), '.$null_func.'(a.eerste_checklist_hercontrole_datum, \'9999-12-31\'), '.$null_func.'(a.checklist_groep_initiele_datum, \'9999-12-31\'), '.$null_func.'(a.checklist_initiele_datum, \'9999-12-31\') ), GREATEST( '.$null_func.'(a.laatste_checklist_groep_hercontrole_datum, \'0000-00-00\'), '.$null_func.'(a.laatste_checklist_hercontrole_datum, \'0000-00-00\'), '.$null_func.'(a.laatste_checklist_groep_initiele_datum, \'0000-00-00\'), '.$null_func.'(a.laatste_checklist_initiele_datum, \'0000-00-00\') ) ) AS gepland_datum FROM ( SELECT z.deelplan_id, MIN(z.eerste_checklist_groep_hercontrole_datum) AS eerste_checklist_groep_hercontrole_datum, MIN(z.eerste_checklist_hercontrole_datum) AS eerste_checklist_hercontrole_datum, MIN(z.checklist_groep_initiele_datum) AS checklist_groep_initiele_datum, MIN(z.checklist_initiele_datum) AS checklist_initiele_datum, MAX(z.laatste_checklist_groep_hercontrole_datum) AS laatste_checklist_groep_hercontrole_datum, MAX(z.laatste_checklist_hercontrole_datum) AS laatste_checklist_hercontrole_datum, MAX(z.laatste_checklist_groep_initiele_datum) AS laatste_checklist_groep_initiele_datum, MAX(z.laatste_checklist_initiele_datum) AS laatste_checklist_initiele_datum FROM ( SELECT dcg.deelplan_id, IF(dcgp.eerste_hercontrole_datum<'.$date_now_func.',NULL,dcgp.eerste_hercontrole_datum) AS eerste_checklist_groep_hercontrole_datum, IF(dclp.eerste_hercontrole_datum<'.$date_now_func.',NULL,dclp.eerste_hercontrole_datum) AS eerste_checklist_hercontrole_datum, IF(dcg.initiele_datum<'.$date_now_func.',NULL,dcg.initiele_datum) AS checklist_groep_initiele_datum, IF(dcl.initiele_datum<'.$date_now_func.',NULL,dcl.initiele_datum) AS checklist_initiele_datum, dcgp.eerste_hercontrole_datum AS laatste_checklist_groep_hercontrole_datum, dclp.eerste_hercontrole_datum AS laatste_checklist_hercontrole_datum, dcg.initiele_datum AS laatste_checklist_groep_initiele_datum, dcl.initiele_datum AS laatste_checklist_initiele_datum FROM deelplan_checklist_groepen dcg LEFT JOIN deelplan_checklistgroep_plnng dcgp ON (dcg.deelplan_id = dcgp.deelplan_id AND dcg.checklist_groep_id = dcgp.checklist_groep_id) RIGHT JOIN deelplan_checklisten dcl ON (dcg.deelplan_id = dcl.deelplan_id) LEFT JOIN deelplan_checklist_planning dclp ON (dcl.deelplan_id = dclp.deelplan_id AND dcl.checklist_id = dclp.checklist_id) HAVING ( eerste_checklist_groep_hercontrole_datum IS NOT NULL OR eerste_checklist_hercontrole_datum IS NOT NULL OR checklist_groep_initiele_datum IS NOT NULL OR checklist_initiele_datum IS NOT NULL OR laatste_checklist_groep_hercontrole_datum IS NOT NULL OR laatste_checklist_hercontrole_datum IS NOT NULL OR laatste_checklist_groep_initiele_datum IS NOT NULL OR laatste_checklist_initiele_datum IS NOT NULL ) ) z GROUP BY z.deelplan_id ) a HAVING gepland_datum != \'0000-00-00\' ' ); echo 'deelplan_planning: ' . $CI->db->affected_rows() . ' rows added' . "\n"; // // Bekijk per dossier wat de eerstevolgende datum is, van alle deelplannen // $CI->db->query( 'DELETE FROM dossier_planning' ); // eerst toekomst (>=now(), MIN) // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $CI->db->query( ' INSERT INTO dossier_planning SELECT dossier_id, MIN(hc.gepland_datum) AS gepland_datum FROM deelplannen d LEFT JOIN deelplan_planning hc ON d.id = hc.deelplan_id WHERE hc.gepland_datum >= '.$date_now_func.' GROUP BY dossier_id HAVING MIN(hc.gepland_datum) IS NOT NULL ' ); $rows = $CI->db->affected_rows(); // dan verleden (<now(), MAX) $CI->db->query( ' INSERT INTO dossier_planning SELECT dossier_id, MAX(hc.gepland_datum) AS gepland_datum FROM deelplannen d LEFT JOIN deelplan_planning hc ON d.id = hc.deelplan_id WHERE dossier_id NOT IN (SELECT dossier_id FROM dossier_planning) GROUP BY dossier_id HAVING MAX(hc.gepland_datum) IS NOT NULL ' ); $rows += $CI->db->affected_rows(); echo 'dossier_planning: ' . $rows . ' rows added' . "\n"; if (!$CI->db->trans_complete()) throw new Exception( 'Failed to commit database transaction.' ); } } <file_sep><?php abstract class BRIS_AbstractSupervisionMoments { protected $_deelplan_id; protected $_supervisor_user_id; protected $_progress; protected $_current_time; /** * @var BaseModel */ protected $_model; private static $_instances; protected static $_model_name; public function __construct() { $this->_current_time = date('Y-m-d H:i:s'); $controller_instance = get_instance(); $controller_instance->load->model(static::$_model_name); $this->_model = $controller_instance->{static::$_model_name}; } public function setDeelplan($deelplan) { $this->_deelplan_id = $deelplan; return $this; } public function setSupervisorUserId($supervisor_user_id) { $this->_supervisor_user_id = $supervisor_user_id; return $this; } public function setProgress($progress) { $this->_progress = $progress; return $this; } abstract public function saveMoment(); /** * @return $this */ public static function getInstance() { $class = get_called_class(); if( is_null(self::$_instances[$class]) ) { self::$_instances[$class] = new $class; } return self::$_instances[$class]; } protected function _checkValues() { $fields = get_object_vars($this); foreach($fields as $field => $field_value) { if( is_null($field_value) ) { throw new Exception('Value not setted: ' . $field); } } } }<file_sep>-- As issues occurred with key names etc. when trying to drop the primary key and creating a new one, -- along with doing other table manipulation work, we now rename the current table (to have a back-up) -- and create a new one with the columns and structure we need, and select the data back into that. RENAME TABLE deelplan_vragen TO bck_20150211_deelplan_vragen; -- Create the table, using the new structure CREATE TABLE `deelplan_vragen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, `status` varchar(100) DEFAULT NULL, `toelichting` text, `seconden` int(11) NOT NULL, `gebruiker_id` int(11) NOT NULL, `last_updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `hercontrole_datum` date DEFAULT NULL, `hercontrole_start_tijd` char(8) DEFAULT NULL, `hercontrole_eind_tijd` char(8) DEFAULT NULL, `flags` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK__deelplan_vragen__d_id__v_id` (`deelplan_id`,`vraag_id`), KEY `gebruiker_id` (`gebruiker_id`), KEY `last_updated_at` (`last_updated_at`), KEY `deelplan_id` (`deelplan_id`), KEY `vraag_id` (`vraag_id`), CONSTRAINT `FK__deelplan_vragen__gebruikers` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE, CONSTRAINT `FK__deelplan_vragen__bt_vragen` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK__deelplan_vragen__deelplannen` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB; -- Now fill the table with the data from the back-up table INSERT INTO deelplan_vragen ( `id` , `deelplan_id` , `vraag_id` , `status` , `toelichting` , `seconden` , `gebruiker_id` , `last_updated_at` , `hercontrole_datum` , `hercontrole_start_tijd` , `hercontrole_eind_tijd` , `flags` ) SELECT NULL , `deelplan_id` , `vraag_id` , `status` , `toelichting` , `seconden` , `gebruiker_id` , `last_updated_at` , `hercontrole_datum` , `hercontrole_start_tijd` , `hercontrole_eind_tijd` , `flags` FROM bck_20150211_deelplan_vragen; -- Clean-up DROP TABLE bck_20150211_deelplan_vragen; -- Table for queueing and maintaining history of the sent emails CREATE TABLE `deelplan_vraag_emails` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_vraag_id` int(11) NOT NULL, `gebruiker_id` int(11) NOT NULL, `status` varchar(100) DEFAULT NULL, `toelichting` text DEFAULT NULL, `datum_entered` datetime DEFAULT NULL, `datum_sent` datetime DEFAULT NULL, `recipient` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK__max_1_unsent_dpv_recipient` (`deelplan_vraag_id`, `recipient`, `datum_sent`), KEY `deelplan_vraag_id` (`deelplan_vraag_id`), KEY `gebruiker_id` (`gebruiker_id`), CONSTRAINT `FK__dveh__deelplan_vragen` FOREIGN KEY (`deelplan_vraag_id`) REFERENCES `deelplan_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK__dveh__gebruikers` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB; <file_sep>DROP TABLE IF EXISTS `bt_checklist_groep_verantwtkstn`; CREATE TABLE `bt_checklist_groep_verantwtkstn` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_groep_id` int(11) NOT NULL, `verantwoordingstekst` VARCHAR(1024) NOT NULL, `status` ENUM('groen', 'geel', 'rood') NULL, PRIMARY KEY (`id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `bt_checklist_groep_verantwtkstn` ADD CONSTRAINT FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; DROP TABLE IF EXISTS `bt_checklist_verantwtkstn`; CREATE TABLE IF NOT EXISTS `bt_checklist_verantwtkstn` ( `id` int(11) NOT NULL AUTO_INCREMENT, `checklist_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `verantwoordingstekst` VARCHAR(1024) NOT NULL, `status` ENUM('groen', 'geel', 'rood') NULL, PRIMARY KEY (`id`), KEY `checklist_id` (`checklist_id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; ALTER TABLE `bt_checklist_verantwtkstn` ADD CONSTRAINT FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; DROP TABLE IF EXISTS `bt_hoofdgroep_verantwtkstn`; CREATE TABLE IF NOT EXISTS `bt_hoofdgroep_verantwtkstn` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hoofdgroep_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `verantwoordingstekst` VARCHAR(1024) NOT NULL, `status` ENUM('groen', 'geel', 'rood') NULL, PRIMARY KEY (`id`), KEY `hoofdgroep_id` (`hoofdgroep_id`), KEY `checklist_groep_id` (`checklist_groep_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; ALTER TABLE `bt_hoofdgroep_verantwtkstn` ADD CONSTRAINT FOREIGN KEY (`hoofdgroep_id`) REFERENCES `bt_hoofdgroepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; DROP TABLE IF EXISTS `bt_vraag_verantwtkstn`; CREATE TABLE IF NOT EXISTS `bt_vraag_verantwtkstn` ( `id` int(11) NOT NULL AUTO_INCREMENT, `vraag_id` int(11) NOT NULL, `checklist_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `verantwoordingstekst` VARCHAR(1024) NOT NULL, `status` ENUM('groen', 'geel', 'rood') NULL, PRIMARY KEY (`id`), KEY `vraag_id` (`vraag_id`), KEY `checklist_groep_id` (`checklist_groep_id`), KEY `checklist_id` (`checklist_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; ALTER TABLE `bt_vraag_verantwtkstn` ADD CONSTRAINT FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `bt_checklisten` ADD `standaard_gebruik_verantwtkstn` TINYINT NULL DEFAULT NULL AFTER `standaard_gebruik_opdrachten` ; ALTER TABLE `bt_hoofdgroepen` ADD `standaard_gebruik_verantwtkstn` TINYINT NULL DEFAULT NULL AFTER `standaard_gebruik_opdrachten` ; ALTER TABLE `bt_vragen` ADD `gebruik_verantwtkstn` TINYINT NULL DEFAULT NULL AFTER `gebruik_opdrachten` ; <file_sep><?php if(isset($context->email_config)){ $jsonObj =json_decode($context->email_config); } $choseen_email_option_style = 'background-color:#2EB099; color: #ffffff'; $default_email_option_style = 'background-color:#fcfcfc'; $email_options_values = array(EMAIL_OPT_QUESTION, EMAIL_OPT_QUESTION_STATUS, EMAIL_OPT_SUPERVISOR, EMAIL_OPT_DATE, EMAIL_OPT_ANWSER, EMAIL_OPT_DOSSIER_DATA, EMAIL_OPT_LETTER); $style = $checkbox = array(); if( isset($jsonObj->email_address, $jsonObj->email_content, $jsonObj->email_status_for_send) ) { $email_address = $jsonObj->email_address; $email_content = $jsonObj->email_content; $status_for_send = $jsonObj->email_status_for_send; } else { $email_address = $email_content = $status_for_send = ''; } foreach( $email_options_values as $value ) { if( isset($jsonObj->email_options) && in_array($value, $jsonObj->email_options) ) { $style[$value] = $choseen_email_option_style; $checkbox[$value] = ' checked'; } else { $style[$value] = $default_email_option_style; $checkbox[$value] = ''; } } ?> <div class="main hidden" id="email"> <ul class="list"> <li class="entry top left right"> <div class="header"><?=tgg('email_address')?></div> <?= htag('email_address', 'email') ?> <div class="content"> <input type="text" name="email_address" value="<?= $email_address ?>" size="90" /> </div> </li> <li style="height: auto; background: url('/files/checklistwizard/pixel.png') repeat"> <div style="width: 161px" class="header"><?=tgg('email_content')?></div> <?=htag('email_content', 'email')?> <div style="padding: 13px"> <textarea name="email_content" style="width: 100%; height: 115px"><?= $email_content ?></textarea> </div> </li> <li style="height: auto; background: url('/files/checklistwizard/pixel.png')"> <div style="width: 161px" class="header"><?=tgg('checklistwizard.section.email.email_options')?></div> <?= htag('email_options', 'email') ?> <div id="email_options" style="padding: 13px"> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_QUESTION] ?>"> <?= tgg('question') ?> <input name="email_options[]" value="<?= EMAIL_OPT_QUESTION ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_QUESTION] ?>> </label> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_QUESTION_STATUS] ?>"> <?= tgg('question_status') ?> <input name="email_options[]" value="<?= EMAIL_OPT_QUESTION_STATUS ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_QUESTION_STATUS] ?>> </label> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_SUPERVISOR] ?>"> <?= tgg('supervisor') ?> <input name="email_options[]" value="<?= EMAIL_OPT_SUPERVISOR ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_SUPERVISOR] ?>> </label> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_DATE] ?>"> <?= tgg('date') ?> <input name="email_options[]" value="<?= EMAIL_OPT_DATE ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_DATE] ?>> </label> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_ANWSER] ?>"> <?= tgg('anwser') ?> <input name="email_options[]" value="<?= EMAIL_OPT_ANWSER ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_ANWSER] ?>> </label> <label style="display: block; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_DOSSIER_DATA] ?>"> <?= tgg('checklistwizard.section.email.dossier_data') ?> <input name="email_options[]" value="<?= EMAIL_OPT_DOSSIER_DATA ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_DOSSIER_DATA] ?>> </label> <label style="display: <?= ($klant->letter) ? 'block' : 'none' ?>; width: 110px; text-align: center; padding: 4px; margin: 5px; <?= $style[EMAIL_OPT_LETTER] ?>"> <?= tgg('checklistwizard.section.email.letter') ?> <input name="email_options[]" value="<?= EMAIL_OPT_LETTER ?>" style="display: none" type="checkbox"<?= $checkbox[EMAIL_OPT_LETTER] ?>> </label> <script> $('input', '#email_options').click(function() { if( this.checked ) { $(this).parent().css({"background-color":"#2EB099", "color": "#ffffff"}); } else { $(this).parent().css({"background-color":"#fcfcfc", "color": ""}); } }); </script> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('question_status')?></div> <?=htag('question_status', 'email')?> <div class="content"> <select name="email_status_for_send" style="width: 300px"> <option <?= $status_for_send == STATUS_ALL_COLORS ? 'selected' : ''?> value="<?= STATUS_ALL_COLORS ?>">-- Bij alle waardeoordelen --</option> <option <?= $status_for_send == STATUS_RED ? 'selected' : ''?> value="<?= STATUS_RED ?>">Rood</option> <option <?= $status_for_send == STATUS_ORANGE ? 'selected' : ''?> value="<?= STATUS_ORANGE ?>">Oranje</option> <option <?= $status_for_send == STATUS_GREEN ? 'selected' : ''?> value="<?= STATUS_GREEN ?>">Groen</option> </select> </div> </li> </ul> </div><file_sep>BRISToezicht.NetworkStatus = { div: null, // null, or jQuery collection of divs that contain the status (might be more than one) updateHandle: null, // setTimeout result isOnline: true, // online state isLoggedIn: true, // logged in state iframe: null, // session test iframe mode: null, initialize: function() { this.div = $('div.network-status'); if (this.div.size() == 0) return; this.mode = this.div.attr( 'standaard-mode' ); $('div.network-status img').click(function(){ if (BRISToezicht.NetworkStatus.mode == 'wifi') BRISToezicht.NetworkStatus.mode = '3g'; else BRISToezicht.NetworkStatus.mode = 'wifi'; BRISToezicht.NetworkStatus.setState( BRISToezicht.NetworkStatus.getState() ); BRISToezicht.Toets.Form.attemptStore(); }); $('div.network-status span').click(function(){ BRISToezicht.NetworkStatus.updateConnectedState(); }); this.setOnline(); this.setLoggedIn(); this.scheduleUpdate(); this.iframe = $('#online-check'); this.iframe.load(function(){ BRISToezicht.NetworkStatus.updateComplete(); }); }, getMode: function() { return this.mode; }, setOnline: function() { this.setState( true ); }, setOffline: function() { this.setState( false ); }, setState: function( online ) { // remember old state var oldState = this.isOnline; // store new state this.isOnline = online; // update all online/offline visual indicators this.div.removeClass( online ? 'offline' : 'online' ); this.div.addClass( online ? 'online' : 'offline' ); this.div.children('span').text( (!this.isLoggedIn) ? 'Uitgelogd' : (online ? 'Online' : 'Offline') ); // hide/show all elements that require a specific state if (online) { $('.require_offline, .require_online').hide(); $('.require_online.' + this.mode).show(); } else { $('.require_online, .require_offline').hide(); $('.require_offline.' + this.mode).show(); } // if we WERE offline, and are now online, then start store! if (!oldState && this.isOnline) BRISToezicht.Toets.Form.attemptStore(); }, getState: function() { return this.isOnline; }, setLoggedIn: function() { this.setLoggedInState( true ); }, setLoggedOut: function() { this.setLoggedInState( false ); }, setLoggedInState: function( logged_in ) { // store new state this.isLoggedIn = logged_in; // update all online/offline visual indicators if (logged_in) { this.div.removeClass( 'loggedout' ); } else { this.div.addClass( 'loggedout' ); } this.setState( this.isOnline ); }, updateConnectedState: function( sync ) { $.ajax({ url: '/root/online_check/', type: 'GET', async: !sync, success: function( data, textStatus, jqXHR ) { BRISToezicht.NetworkStatus.setOnline(); // we are online, now check the session by refreshing our iframe BRISToezicht.NetworkStatus.iframe.attr( 'src', "/root/session_check" ); }, error: function( jqXHR, textStatus, errorThrown ) { // we are not online BRISToezicht.NetworkStatus.setOffline(); BRISToezicht.NetworkStatus.setLoggedIn(); // this hides the note, we have no idea! BRISToezicht.NetworkStatus.scheduleUpdate(); } }); }, updateComplete: function( success ) { if (this.getLoggedInStateFromIframeText()) BRISToezicht.NetworkStatus.setLoggedIn(); else BRISToezicht.NetworkStatus.setLoggedOut(); BRISToezicht.NetworkStatus.scheduleUpdate(); }, getLoggedInStateFromIframeText: function() { try { return this.getIframeText().match( /BTZ Logged in/ ) ? true : false; } catch (err) { // exception means: we are in system.kennisid.nl !! return false; } }, getIframeText: function() { return this.iframe.contents().find('body').html(); }, scheduleUpdate: function( alttimeout ) { if (this.updateHandle) { clearTimeout( this.updateHandle ); this.updateHandle = null; } this.updateHandle = setTimeout( 'BRISToezicht.NetworkStatus.updateConnectedState();', alttimeout || (20*1000) /* 20 seconds */ ); } }; <file_sep>ALTER TABLE `dossiers` ADD COLUMN `dossier_hash` varchar(40) DEFAULT NULL; <file_sep>DROP TABLE IF EXISTS project_mappen; DROP TABLE IF EXISTS artikel_vraag_mappen; DROP TABLE IF EXISTS risicoprofiel_mappingen; DROP TABLE IF EXISTS matrix_mappingen; CREATE TABLE matrix_mappingen ( id int(11) NOT NULL AUTO_INCREMENT, naam varchar(255) DEFAULT NULL, klant_id int(11) NOT NULL, bt_matrix_id int(11) DEFAULT NULL, checklist_id int(11) DEFAULT NULL, type enum ('main', 'derivative') NOT NULL DEFAULT 'main', parent_matrix_mapping_id int(11) DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT FK_matrix_mappingen_bt_checklisten_id FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE SET NULL ON UPDATE SET NULL, CONSTRAINT FK_matrix_mappingen_klanten_id FOREIGN KEY (klant_id) REFERENCES klanten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_matrix_mappingen_matrix_mappingen_id FOREIGN KEY (parent_matrix_mapping_id) REFERENCES matrix_mappingen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE artikel_vraag_mappen ( id int(11) NOT NULL AUTO_INCREMENT, matrix_id int(11) DEFAULT NULL, bt_riskprofiel_id int(11) DEFAULT NULL, artikel_id int(11) DEFAULT NULL, vraag_id int(11) DEFAULT NULL, is_active tinyint(1) NOT NULL DEFAULT TRUE, PRIMARY KEY (id), UNIQUE INDEX UK_artikel_vraag_mappen (matrix_id, bt_riskprofiel_id, artikel_id, vraag_id), CONSTRAINT FK_artikel_vraag_mappen_bt_vragen_id FOREIGN KEY (vraag_id) REFERENCES bt_vragen (id) ON DELETE SET NULL ON UPDATE SET NULL, CONSTRAINT FK_artikel_vraag_mappen_matrix_mappingen_id FOREIGN KEY (matrix_id) REFERENCES matrix_mappingen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci; -- ------------------------------------------------------------------ CREATE TABLE `project_mappen` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `deelpan_id` INT(11) NOT NULL, `vraag_map_id` INT(11) NOT NULL, `is_active` TINYINT(1) NOT NULL DEFAULT TRUE, PRIMARY KEY (`id`), INDEX `FK_project_mappen__artikel_vraag_mappen` (`vraag_map_id`), INDEX `FK_project_mappen__deelplannen` (`deelpan_id`), CONSTRAINT `FK_project_mappingen_artikel_vraag_mappen` FOREIGN KEY (`vraag_map_id`) REFERENCES `artikel_vraag_mappen` (`id`), CONSTRAINT `FK_project_mappingen_deelplannen` FOREIGN KEY (`deelpan_id`) REFERENCES `deelplannen` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ) COLLATE='utf8_general_ci' ENGINE=InnoDB ; <file_sep>CREATE TABLE IF NOT EXISTS `kennisid_tijden` ( `id` int(11) NOT NULL AUTO_INCREMENT, `duur_in_ms` int(11) NOT NULL, `type` enum('kennis-id-balk','wsdl-ophalen','sessie-verifieren') NOT NULL, `url` varchar(512) NOT NULL, `ip` varchar(15) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; <file_sep>-- draai: -- php index.php /cli/cleanup_wetteksten -- php index.php /cli/cleanup_wetteksten/1 -- php index.php /cli/update_quest_koppeling/1 <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.checklistgroepen')?></h1> <? $this->load->view( 'checklistwizard/_lijst', array( 'entries' => $checklistgroepen, 'get_id' => function( $cg ) { return $cg->id; }, 'get_image' => function( $cg ) { return $cg->get_image(); }, 'get_naam' => function( $cg ) { return $cg->naam; }, 'delete_url' => '/checklistwizard/checklistgroep_verwijderen', 'add_url' => '/checklistwizard/checklistgroep_toevoegen', 'add_uitgebreid_url' => '/checklistwizard/checklistgroep_uitgebreid_toevoegen', 'copy_url' => '/checklistwizard/checklistgroep_kopieren', 'defaults_url' => '/checklistwizard/checklistgroep_bewerken', ) ); ?> <div class="button"> <a href="<?=site_url('/checklistwizard/checklistgroep_volgorde')?>"><?=tgg('checklistwizard.buttons.wijzig_volgorde')?></a> </div> <?=htag('wijzig-volgorde')?> <div style="float:right; margin-left: 5px;"> <?=htag('toon-alle-toggle')?> </div> <div class="button" style="float:right"> <a href="<?=site_url('/checklistwizard/checklistgroepen_toon_alle_toggle_beschikbare')?>"> <? if ($toon_alle_beschikbare_checklistgroepen): ?> <?=tgg('checklistwizard.buttons.toon_alleen_eigen_checklistgroepen')?> <? else: ?> <?=tgg('checklistwizard.buttons.toon_alle_beschikbare_checklistgroepen')?> <? endif; ?> </a> </div> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = '<?=site_url('/checklistwizard/checklisten/')?>/' + $(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->model( 'matrix' ); $this->load->model( 'hoofdthema' ); $this->load->model( 'thema' ); // bepaal klant $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $have_risico_model = $klant->heeft_fine_kinney_licentie == 'ja'; $is_automatic_accountability_text= $klant->automatic_accountability_text==1; // bepaal hier de waarden die in de velden getoond moeten worden if ($modus == 'nieuw' && $model == 'checklistgroep') { // // !!!dit zijn de defaults gelijk aan de database!!! // $Vnaam = @$naam; $Vlogo = null; $Vactief = 'open'; // niet actief $Vmodus = 'niet-combineerbaar'; // integreerbaar $Vthemas_automatisch_selecteren = 1; $Vrisico_model = 'generiek'; $Vmatrix_id = null; $Vvraag_type = 'meerkeuzevraag'; $Vaanwezigheid = 31; $_thema = resolve_thema( 'new', 'Algemeen', 'Algemeen' ); $Vhoofdthema_id = $_thema->hoofdthema_id; $Vthema_id = $_thema->id; $Vtoezicht_moment = 'Algemeen'; $Vfase = 'Algemeen'; $Vtekst = array( array( 'Niet van toepassing', 'Voldoet', 'Voldoet niet' ), array( 'Geen waardeoordeel', '', '' ), array( '', '', '' ), array( '', '', '' ), array( '' ) ); $Vleeg = array( array( 0, 0, 0 ), array( 1, 0, 0 ), array( 0, 0, 0 ), array( 0, 0, 0 ), array( 0 ) ); $Vkleur = array( array( 'oranje', 'groen', 'rood' ), array( 'oranje', '', '' ), array( '', '', '' ), array( '', '', '' ), array( '' ) ); $Vingebruik = array( array( 1, 1, 1 ), array( 1, 0, 0 ), array( 0, 0, 0 ), array( 0, 0, 0 ), array( 0 ) ); $Vwo_standaard = 'w01'; $Vwo_steekproef = 'w01'; $Vwo_steekproef_tekst = 'Niet gecontroleerd ivm steekproef'; $Vgrondslagteksten = array(); $Vrichtlijnen = array(); $Vaandachtspunten = array(); $Vopdrachten = array(); $Vverantwoordingsteksten = array(); $Vgebruik_grndslgn = false; $Vgebruik_rchtlnn = false; $Vgebruik_ndchtspntn = false; $Vgebruik_verantwoordingsteksten = false; } else // bij elk ander modus en/of model is de context ofwel het te editen object, ofwel het object waar we de defaults uit moeten halen! { if ($model == 'vraag') $Vvraagtekst = ($modus == 'nieuw') ? @$tekst : $context->tekst; else $Vnaam = ($modus == 'nieuw') ? @$naam : $context->naam; $Vlogo = $checklistgroep->get_image(); if ($context instanceof ChecklistGroepResult) { $Vactief = $context->standaard_checklist_status; $Vmodus = $context->modus; $Vthemas_automatisch_selecteren = $context->themas_automatisch_selecteren; $Vmatrix_id = get_instance()->matrix->geef_standaard_matrix_voor_checklist_groep( $context )->id; $Vrisico_model = $context->risico_model; } else if ($context instanceof ChecklistResult) { $Vactief = $context->status; if (is_null( $Vactief )) $Vactief = $context->get_checklistgroep()->standaard_checklist_status; } $Vvraag_type = $context->get_wizard_veld_recursief( 'vraag_type' ); $Vaanwezigheid = $context->get_wizard_veld_recursief( 'aanwezigheid' ); $Vthema_id = $context->get_wizard_veld_recursief( 'thema_id' ); if (!$Vthema_id) $Vthema_id = resolve_thema( 'new', 'Algemeen', 'Algemeen' )->id; $Vhoofdthema_id = get_instance()->thema->get( $Vthema_id )->hoofdthema_id; $Vtoezicht_moment = $context->get_wizard_veld_recursief( 'toezicht_moment' ); $Vfase = $context->get_wizard_veld_recursief( 'fase' ); $Vtekst = array( array( $context->get_wizard_veld_recursief( 'wo_tekst_00' ), $context->get_wizard_veld_recursief( 'wo_tekst_10' ), $context->get_wizard_veld_recursief( 'wo_tekst_20' ) ), array( $context->get_wizard_veld_recursief( 'wo_tekst_01' ), $context->get_wizard_veld_recursief( 'wo_tekst_11' ), $context->get_wizard_veld_recursief( 'wo_tekst_21' ) ), array( $context->get_wizard_veld_recursief( 'wo_tekst_02' ), $context->get_wizard_veld_recursief( 'wo_tekst_12' ), $context->get_wizard_veld_recursief( 'wo_tekst_22' ) ), array( $context->get_wizard_veld_recursief( 'wo_tekst_03' ), $context->get_wizard_veld_recursief( 'wo_tekst_13' ), $context->get_wizard_veld_recursief( 'wo_tekst_23' ) ), array( $context->get_wizard_veld_recursief( 'wo_tekst_04' ), ), ); $Vleeg = array( array( $context->get_wizard_veld_recursief( 'wo_is_leeg_00' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_10' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_20' ) ), array( $context->get_wizard_veld_recursief( 'wo_is_leeg_01' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_11' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_21' ) ), array( $context->get_wizard_veld_recursief( 'wo_is_leeg_02' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_12' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_22' ) ), array( $context->get_wizard_veld_recursief( 'wo_is_leeg_03' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_13' ), $context->get_wizard_veld_recursief( 'wo_is_leeg_23' ) ), array( $context->get_wizard_veld_recursief( 'wo_is_leeg_04' ), ), ); $Vkleur = array( array( $context->get_wizard_veld_recursief( 'wo_kleur_00' ), $context->get_wizard_veld_recursief( 'wo_kleur_10' ), $context->get_wizard_veld_recursief( 'wo_kleur_20' ) ), array( $context->get_wizard_veld_recursief( 'wo_kleur_01' ), $context->get_wizard_veld_recursief( 'wo_kleur_11' ), $context->get_wizard_veld_recursief( 'wo_kleur_21' ) ), array( $context->get_wizard_veld_recursief( 'wo_kleur_02' ), $context->get_wizard_veld_recursief( 'wo_kleur_12' ), $context->get_wizard_veld_recursief( 'wo_kleur_22' ) ), array( $context->get_wizard_veld_recursief( 'wo_kleur_03' ), $context->get_wizard_veld_recursief( 'wo_kleur_13' ), $context->get_wizard_veld_recursief( 'wo_kleur_23' ) ), array( $context->get_wizard_veld_recursief( 'wo_kleur_04' ), ), ); $Vingebruik = array( array( $context->get_wizard_veld_recursief( 'wo_in_gebruik_00' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_10' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_20' ) ), array( $context->get_wizard_veld_recursief( 'wo_in_gebruik_01' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_11' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_21' ) ), array( $context->get_wizard_veld_recursief( 'wo_in_gebruik_02' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_12' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_22' ) ), array( $context->get_wizard_veld_recursief( 'wo_in_gebruik_03' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_13' ), $context->get_wizard_veld_recursief( 'wo_in_gebruik_23' ) ), array( $context->get_wizard_veld_recursief( 'wo_in_gebruik_04' ), ), ); $Vwo_standaard = $context->get_wizard_veld_recursief( 'wo_standaard' ); $Vwo_steekproef = $context->get_wizard_veld_recursief( 'wo_steekproef' ); $Vwo_steekproef_tekst = $context->get_wizard_veld_recursief( 'wo_steekproef_tekst' ); $Vgrondslagteksten = wizard_get_grondslagen( $context ); $Vrichtlijnen = wizard_get_richtlijnen( $context ); $Vaandachtspunten = wizard_get_aandachtspunten( $context ); $Vopdrachten = wizard_get_opdrachten( $context ); $Vverantwoordingsteksten = $is_automatic_accountability_text && $model == 'vraag' ? wizard_get_automatic_verantwoordingsteksten($context) : wizard_get_verantwoordingsteksten( $context ); if(!$Vverantwoordingsteksten) $Vverantwoordingsteksten=array(); $Vgebruik_grndslgn = $modus == 'nieuw' ? false : (@$context->gebruik_grndslgn || @$context->standaard_gebruik_grndslgn); $Vgebruik_rchtlnn = $modus == 'nieuw' ? false : (@$context->gebruik_rchtlnn || @$context->standaard_gebruik_rchtlnn); $Vgebruik_ndchtspntn = $modus == 'nieuw' ? false : (@$context->gebruik_ndchtspntn || @$context->standaard_gebruik_ndchtspntn); $Vgebruik_opdrachten = $modus == 'nieuw' ? false : (@$context->gebruik_opdrachten || @$context->standaard_gebruik_opdrachten); $Vgebruik_verantwoordingsteksten = $modus == 'nieuw' ? false : (@$context->gebruik_verantwtkstn || @$context->standaard_gebruik_verantwtkstn); } ?> <? if ($headers) $this->load->view('elements/header', array('page_header'=>'wizard.main', 'extra_scripts' => array( 'pagescripts/uitgebreide_editor.js' ))); ?> <h1><?=tgg('checklistwizard.headers.' . $model . '_' . $modus)?></h1> <? if (isset( $checklist ) && $checklist && $checklist->is_in_gebruik()): ?> <div style="border: 1px solid #ddd; padding: 15px 10px; font-weight: bold;"> <i class="icon-warning-sign" style="font-size: 20pt; color: #ff9c00; float: left; margin: 5px; position: relative; top: -10px; "></i> <?=tgg('checklistwizard.pas.op.reeds.in.gebruik')?> </div> <br/><br/> <? endif; ?> <iframe class="hidden" name="submit_frame"></iframe> <form method="POST" enctype="multipart/form-data" target="submit_frame"> <? $this->load->view( 'checklistwizard/_checklist_status' ) ?> <ul class="tabbar"> <li tag="algemeen"><?=tgg('checklistwizard.section.algemeen')?></li> <li tag="vragen"><?=tgg('checklistwizard.section.vragen')?></li> <li tag="achtergrondinformatie"><?=tgg('checklistwizard.section.achtergrondinformatie')?></li> <li tag="verantwoordingen"><?=tgg('checklistwizard.section.verantwoordingen')?></li> <li tag="opdrachten"><?=tgg('checklistwizard.section.opdrachten')?></li> <? if( $model == 'vraag' && $klant->email_question_notification ) { ?> <li tag="email"><?=tgg('checklistwizard.section.email')?></li> <? } ?> </ul> <div class="main hidden" id="algemeen"> <ul class="list"> <? if ($model != 'vraag'): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.naam')?></div> <div class="content"> <input type="text" name="naam" value="<?=$Vnaam?>" size="90" /> <?=htag('naam', 'algemeen')?> </div> </li> <? else: ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.tekst')?></div> <div class="content"> <input type="text" name="tekst" value="<?=$Vvraagtekst?>" size="90" /> <?=htag('vraagtekst', 'algemeen')?> </div> </li> <? endif; ?> <? if ($model == 'checklistgroep'): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.logo')?></div> <div class="content"> <? if ($Vlogo): ?> <img src="<?=site_url($Vlogo->get_url())?>" style="vertical-align: middle;" /> <? endif; ?> <input type="file" name="logo"> <?=htag('logo', 'algemeen')?> </div> </li> <? endif; ?> <? if ($model == 'checklistgroep' || $model == 'checklist'): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.status')?></div> <div class="content"> <select name="actief" style="width: 300px"> <option <?=$Vactief == 'afgerond' ? 'selected' : ''?> value="afgerond">Actief</option> <option <?=$Vactief == 'open' ? 'selected' : ''?> value="open">Niet actief</option> </select> <?=htag('actief', 'algemeen')?> </div> </li> <? endif; ?> <? if ($model == 'checklistgroep'): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.integreerbaar')?></div> <div class="content"> <select name="modus" style="width: 300px"> <option <?=$Vmodus == 'niet-combineerbaar' ? 'selected' : ''?> value="niet-combineerbaar">Niet integreerbaar</option> <option <?=$Vmodus == 'combineerbaar' ? 'selected' : ''?> value="combineerbaar">Integreerbaar (op hoofdthema)</option> <option <?=$Vmodus == 'combineerbaar-op-checklist' ? 'selected' : ''?> value="combineerbaar-op-checklist">Integreerbaar (op checklist)</option> </select> <?=htag('integreerbaar', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.themas_automatisch_selecteren')?></div> <div class="content"> <select name="themas_automatisch_selecteren" style="width: 300px"> <option <?=$Vthemas_automatisch_selecteren == 0 ? 'selected' : ''?> value="0">Thema's niet automatisch selecteren</option> <option <?=$Vthemas_automatisch_selecteren == 1 ? 'selected' : ''?> value="1">Thema's automatisch selecteren</option> </select> <?=htag('themas-automatisch-selecteren', 'algemeen')?> </div> </li> <? if ($context): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.standaardmatrix')?></div> <div class="content"> <select name="matrix_id" style="width: 300px"> <? foreach ($this->matrix->geef_matrices_voor_checklist_groep( $context, true ) as $matrix): ?> <option <?=$Vmatrix_id == $matrix->id ? 'selected' : ''?> value="<?=$matrix->id?>"><?=htmlentities( $matrix->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <?=htag('standaardmatrix', 'algemeen')?> </div> </li> <? endif; ?> <? if ($have_risico_model): ?> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.risico_model')?></div> <div class="content"> <select name="risico_model" style="width: 300px"> <option <?=$Vrisico_model == 'generiek' ? 'selected' : ''?> value="generiek">Generiek</option> <option <?=$Vrisico_model == 'fine_kinney' ? 'selected' : ''?> value="fine_kinney">Fine &amp; Kinney</option> </select> <?=htag('themas-automatisch-selecteren', 'algemeen')?> </div> </li> <? endif; ?> <? endif; ?> </ul> </div> <div class="main hidden" id="vragen"> <ul class="list"> <li class="entry top left right"> <div class="content"> <select name="vraag_type" style="width: 300px"> <option <?=$Vvraag_type == 'meerkeuzevraag' ? 'selected' : ''?> value="meerkeuzevraag">Meerkeuzevraag</option> <option <?=$Vvraag_type == 'invulvraag' ? 'selected' : ''?> value="invulvraag">Invulvraag</option> </select> <?=htag('vraagtype', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.aanwezigheid')?></div> <div class="content"> <? foreach (array( '1' => 'S', 2=>'1', 4=>'2', 8=>'3', 16=>'4' ) as $k => $v): ?> <? $checked = ($Vaanwezigheid & $k) ? 'checked' : ''; ?> <div class="checkbox <?=$checked?>"><?=$v?></div> <input type="checkbox" name="aanwezigheid[]" value="<?=$k?>" <?=$checked?> class="hidden" /> <? endforeach; ?> <?=htag('aanwezigheid', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.hoofdthema')?></div> <div class="content"> <select name="hoofdthema_id" style="width: 250px"> <? foreach ($this->hoofdthema->get_for_huidige_klant( false, true, 'h.naam' ) as $hoofdthema): ?> <option <?=$Vhoofdthema_id == $hoofdthema->id ? 'selected' : ''?> value="<?=$hoofdthema->id?>"><?=htmlentities( $hoofdthema->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-hoofdthema"></i> <?=htag('hoofdthema', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.thema')?></div> <div class="content"> <select name="thema_id" style="width: 250px"> <? foreach ($this->thema->get_for_huidige_klant( false, true, false ) as $thema): ?> <option <?=$Vthema_id == $thema->id ? 'selected' : ''?> value="<?=$thema->id?>" hoofdthema_id="<?=$thema->hoofdthema_id?>"><?=htmlentities( $thema->thema, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-thema"></i> <?=htag('thema', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.toezicht_moment')?></div> <div class="content"> <select name="toezicht_moment" style="width: 250px" beschrijving="toezichtmoment"> <? foreach ($klant->get_toezicht_momenten() as $toezicht_moment): ?> <option <?=$Vtoezicht_moment == $toezicht_moment ? 'selected' : ''?> value="<?=htmlentities($toezicht_moment, ENT_COMPAT, 'UTF-8')?>"><?=htmlentities($toezicht_moment, ENT_COMPAT, 'UTF-8')?></option> <? endforeach; ?> </select> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-toezicht-moment" beschrijving="toezichtmoment"></i> <?=htag('toezicht_moment', 'algemeen')?> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.fase')?></div> <div class="content"> <select name="fase" style="width: 250px" beschrijving="fase"> <? foreach ($klant->get_fases() as $fase): ?> <option <?=$Vfase == $fase ? 'selected' : ''?> value="<?=htmlentities($fase, ENT_COMPAT, 'UTF-8')?>"><?=htmlentities($fase, ENT_COMPAT, 'UTF-8')?></option> <? endforeach; ?> </select> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-fase" beschrijving="fase"></i> <?=htag('fase', 'algemeen')?> </div> </li> <li class="entry top left right <?=$Vvraag_type == 'invulvraag' ? 'hidden' : ''?>"> <div class="header"><?=tgg('checklistwizard.waardeoordelen')?> <?=htag('waardeoordelen', 'algemeen')?></div> </li> <li class="entry top left right bottom <?=$Vvraag_type == 'invulvraag' ? 'hidden' : ''?>" style="height: auto; background-color: #e4e3e3; background-image: none;"> <input type="hidden" name="wo_standaard" value="<?=$Vwo_standaard?>"> <input type="hidden" name="wo_steekproef" value="<?=$Vwo_steekproef?>"> <input type="hidden" name="wo_steekproef_tekst" value="<?=$Vwo_steekproef_tekst?>" /> <table class="toezicht"> <? for ($y=0; $y<5; ++$y): ?> <tr> <? for ($x=0; $x<3; ++$x): if ($x > 0 && $y > 3) continue; $tag = 'w' . $x . $y; ?> <td width="33%" tag="w<?=$x.$y?>"> <input type="hidden" name="wo_tekst_<?=$x?><?=$y?>" value="<?=htmlentities( $Vtekst[$y][$x], ENT_COMPAT, 'UTF-8' )?>" /> <input type="hidden" name="wo_kleur_<?=$x?><?=$y?>" value="<?=$Vkleur[$y][$x]?>" /> <input type="hidden" name="wo_is_leeg_<?=$x?><?=$y?>" value="<?=intval($Vleeg[$y][$x])?>" /> <input type="hidden" name="wo_in_gebruik_<?=$x?><?=$y?>" value="<?=intval($Vingebruik[$y][$x])?>" /> <div class="rounded10 toezicht-button <?=$y == 0 ? 'hoofd' : ''?>"><?=htmlentities( $Vtekst[$y][$x], ENT_COMPAT, 'UTF-8' )?></div> <input type="button" class="wis-button <?=$Vingebruik[$y][$x] ? '' : 'hidden'?>" value="<?=tgng('checklistwizard.wis')?>"> <div class="default-button" style="<?=$Vwo_standaard == $tag ? '' : 'display: none;'?>">D</div> <div class="steekproef-button" style="<?=$Vwo_steekproef == $tag ? '' : 'display: none;'?>">S</div> </td> <? endfor; ?> </tr> <? endfor; ?> </table> </li> </ul> </div> <div class="main hidden" id="achtergrondinformatie"> <ul class="list"> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.wettelijke_grondslagen')?> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-grondslag"></i> <?=htag('wettelijke_grondslagen', 'algemeen')?></div> <? if ($Vgebruik_grndslgn): ?> <div class="header" style="float:right; width: 200px; text-align: right;"> <label><input type="checkbox" name="gebruik_grndslgn" value="nee"><?=tgg('checklistwizard.herstel-standaard-set')?></label> <?=htag('herstel-grondslagen', 'algemeen')?> </div> <? endif; ?> </li> <li class="entry top left right" style="height: auto; min-height: 50px; background-color: #e4e3e3; background-image: none;"> <? $document_width = $this->is_Mobile ? 249 : 331; $rest_width = $this->is_Mobile ? 110 : 140; ?> <table class="table-header" cellpadding="0" cellspacing="0" style="table-layout: fixed; overflow:hidden; white-space: nowrap; width: 0px;"> <tr> <td width="<?=$document_width?>" class="center">Document</td> <td width="<?=$rest_width?>" class="center">Hoofdstuk</td> <td width="<?=$rest_width?>" class="center">Afdeling</td> <td width="<?=$rest_width?>" class="center">Paragraaf</td> <td width="<?=$rest_width?>" class="center">Artikel</td> <td width="<?=$rest_width?>" class="center">Lid</td> <td width="50" class="last">&nbsp;</td> </tr> </table> <div class="table-wrapper"> <table class="table-contents" cellpadding="0" cellspacing="0" style="table-layout: fixed; overflow: hidden; white-space: nowrap; width: 0px;"> <tr class="hidden new-row"> <td width="<?=$document_width?>" class="center document"></td> <td width="<?=$rest_width?>" class="center hoofdstuk"></td> <td width="<?=$rest_width?>" class="center afdeling"></td> <td width="<?=$rest_width?>" class="center paragraaf"></td> <td width="<?=$rest_width?>" class="center artikel"></td> <td width="<?=$rest_width?>" class="center lid"></td> <td width="50" class="last"> <input type="hidden" name="grondslag_tekst_ids[]" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? foreach ($Vgrondslagteksten as $grondslagtekst): ?> <tr> <td width="<?=$document_width?>" class="center document" style="overflow:hidden"><?=$grondslagtekst->get_grondslag()->grondslag?></td> <td width="<?=$rest_width?>" class="center hoofdstuk"><?=$grondslagtekst->display_hoofdstuk?></td> <td width="<?=$rest_width?>" class="center afdeling"><?=$grondslagtekst->display_afdeling?></td> <td width="<?=$rest_width?>" class="center paragraaf"><?=$grondslagtekst->display_paragraaf?></td> <td width="<?=$rest_width?>" class="center artikel"><?=$grondslagtekst->display_artikel?></td> <td width="<?=$rest_width?>" class="center lid"><?=$grondslagtekst->display_lid?></td> <td width="50" class="last"> <input type="hidden" name="grondslag_tekst_ids[]" value="<?=$grondslagtekst->id?>" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? endforeach; ?> </table> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.richtlijnen')?> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-richtlijn"></i> <?=htag('richtlijnen', 'algemeen')?></div> <? if ($Vgebruik_rchtlnn): ?> <div class="header" style="float:right; width: 200px; text-align: right;"> <label><input type="checkbox" name="gebruik_rchtlnn" value="nee"><?=tgg('checklistwizard.herstel-standaard-set')?></label> <?=htag('herstel-richtlijnen', 'algemeen')?> </div> <? endif; ?> </li> <li class="entry top left right hidden" style="height: auto; min-height: 50px; background-color: #e4e3e3; background-image: none;"> <? $tekst_width = $this->is_Mobile ? 854 : 1086; $rest_width = 50; ?> <table class="table-header" cellpadding="0" cellspacing="0" width="100%" style="table-layout: fixed; overflow:hidden; white-space: nowrap; width: 0px;"> <tr> <td width="<?=$tekst_width?>">Bestand</td> <td width="<?=$rest_width?>" class="last">&nbsp;</td> </tr> </table> <div class="table-wrapper"> <table class="table-contents" cellpadding="0" cellspacing="0" width="100%" style="table-layout: fixed; overflow:hidden; white-space: nowrap; width: 0px;"> <tr class="hidden new-row"> <td width="<?=$tekst_width?>" class="richtlijn"></td> <td width="<?=$rest_width?>" class="last"> <input type="hidden" name="richtlijn_ids[]" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-richtlijn"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? foreach ($Vrichtlijnen as $richtlijn): ?> <tr> <td width="<?=$tekst_width?>" class="richtlijn <?=isset( $richtlijn->url ) ? 'is_url' : ''?>"> <?= htmlentities( isset( $richtlijn->url ) ? ($richtlijn->url_beschrijving ? $richtlijn->url_beschrijving . ' [' . $richtlijn->url . ']' : $richtlijn->url) : $richtlijn->filename, ENT_COMPAT, 'UTF-8' )?> </td> <td width="<?=$rest_width?>" class="last"> <input type="hidden" name="richtlijn_ids[]" value="<?=$richtlijn->id?>" /> <? if (isset( $richtlijn->url )): ?> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-richtlijn"></i> <? else: ?> <i style="font-size: 12pt; vertical-align: middle; color: #777; opacity: 0.5;" class="icon-edit"></i> <? endif; ?> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? endforeach; ?> </table> </div> </li> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.aandachtspunten')?> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-aandachtspunt"></i> <?=htag('aandachtspunten', 'algemeen')?></div> <? if ($Vgebruik_ndchtspntn): ?> <div class="header" style="float:right; width: 200px; text-align: right;"> <label><input type="checkbox" name="gebruik_ndchtspntn" value="nee"><?=tgg('checklistwizard.herstel-standaard-set')?></label> <?=htag('herstel-aandachtspunten', 'algemeen')?> </div> <? endif; ?> </li> <li class="entry top left right bottom hidden" style="height: auto; min-height: 50px; background-color: #e4e3e3; background-image: none;"> <? $tekst_width = $this->is_Mobile ? 854 : 1086; $rest_width = 50; ?> <table class="table-header" cellpadding="0" cellspacing="0" width="100%" style="table-layout: fixed; overflow: hidden; white-space: nowrap; width: 0px;"> <tr> <td width="<?=$tekst_width?>">Tekst</td> <td width="<?=$rest_width?>" class="last">&nbsp;</td> </tr> </table> <div class="table-wrapper"> <table class="table-contents" cellpadding="0" cellspacing="0" width="100%" style="table-layout: fixed; overflow: hidden; white-space: nowrap; width: 0px;"> <tr class="hidden new-row"> <td width="<?=$tekst_width?>" class="aandachtspunt"></td> <td width="<?=$rest_width?>" class="last"> <input type="hidden" name="aandachtspunten[]" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-aandachtspunt"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? foreach ($Vaandachtspunten as $aandachtspunt): ?> <tr> <td width="<?=$tekst_width?>" class="aandachtspunt"><?=str_replace("\n", "<br>",$aandachtspunt->aandachtspunt)?></td> <td width="<?=$rest_width?>" class="last"> <input type="hidden" name="aandachtspunten[]" value="<?=htmlentities( $aandachtspunt->aandachtspunt, ENT_COMPAT, 'UTF-8' )?>" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-aandachtspunt"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? endforeach; ?> </table> </div> </li> </ul> </div> <div class="main" id="verantwoordingen"> <ul class="list"> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.verantwtkstn')?> <?php $is_automatic_accountability_text && $model=="vraag" ? print "<i style='font-size: 12pt; vertical-align: middle' onclick='open_automatic_verantwoordingstekst_popup(".$context->id.");' class='icon-plus add-automatic-verantwoordingstekst'></i>" : print "<i style='font-size: 12pt; vertical-align: middle' class='icon-plus add-verantwoordingstekst'></i>";?> <?=htag('verantwtkstn', 'algemeen')?></div> <!-- <? if ($Vgebruik_verantwoordingsteksten): ?> <div class="header" style="float:right; width: 200px; text-align: right;"> <label><input type="checkbox" name="gebruik_verantwtkstn" value="nee"><?=tgg('checklistwizard.herstel-standaard-set')?></label> <?=htag('herstel-verantwtkstn', 'algemeen')?> </div> <? endif; ?> --> </li> <li class="entry top left right bottom" style="height: auto; min-height: 50px; background-color: #e4e3e3; background-image: none;"> <? if ($is_automatic_accountability_text && $model=="vraag" ) :?> <table class="table-header" cellpadding="0" cellspacing="0" width="100%"> <tr> <td width="600">Tekst</td> <td width="300">Waardeoordeel</td> <td width="150">Automatisch</td> <td class="last">&nbsp;</td> </tr> </table> <?php else : ?> <table class="table-header" cellpadding="0" cellspacing="0" width="100%"> <tr> <td width="890">Tekst</td> <td width="100">Bij status</td> <td class="last">&nbsp;</td> </tr> </table> <?php endif;?> <div class="table-wrapper"> <table class="table-contents" cellpadding="0" cellspacing="0" width="100%"> <? if ($is_automatic_accountability_text && $model=="vraag" ) :?> <tr class="hidden new-row"> <td style="white-space: normal" width="600" class="verantwoordingstekst"></td> <td style="white-space: normal" width="300" class="waardeoordeel"></td> <td style="text-align:center; white-space: normal" width="150" class="automatish_status"> <input id="automatish_status" readonly disabled="disabled" type="checkbox"> </td> <td style="white-space: normal" class="last"> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-automatic-verantwoordingstekst" onclick='open_automatic_verantwoordingstekst_popup();'></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delet-eautomatic-table-row" onclick='delete_automatic_verantwoordingstekst();'></i> </td> </tr> <? foreach ($Vverantwoordingsteksten as $verantwoordingstekst): ?> <tr class="content"> <td style="white-space: normal" width="600" class="verantwoordingstekst"><?=htmlentities( $verantwoordingstekst['verantwoordingsteksten'], ENT_COMPAT, 'UTF-8' )?></td> <td style="white-space: normal" width="300" class="automatish_status"> <? foreach ($verantwoordingstekst['button_naam'] as $button_naam) :?> <p><?=$button_naam?></p> <? endforeach; ?> </td> <td style="text-align:center; white-space: normal" width="150" class="automatish_status"> <input id="automatish_status" readonly disabled="disabled" type="checkbox" <? $verantwoordingstekst['automatish_generate'] ? print "checked" : "" ?>> </td> <td style="white-space: normal" class="last"> <i style="font-size: 12pt; vertical-align: middle" id="<?=$verantwoordingstekst['id']?>" class="icon-edit edit-automatic-verantwoordingstekst" onclick='open_automatic_verantwoordingstekst_popup("<?=$context->id?>","<?=$verantwoordingstekst['id']?>");'></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delet-eautomatic-table-row" onclick='delete_automatic_verantwoordingstekst("<?=$context->id?>","<?=$verantwoordingstekst['id']?>");'></i> </td> </tr> <? endforeach; ?> <?php else : ?> <tr class="hidden new-row"> <td style="white-space: normal" width="890" class="verantwoordingstekst"></td> <td style="white-space: normal" width="100" class="status"></td> <td style="white-space: normal" class="last"> <input type="hidden" name="verantwoordingstekst[]" /> <input type="hidden" name="status[]" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-verantwoordingstekst"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? foreach ($Vverantwoordingsteksten as $verantwoordingstekst): ?> <tr> <td style="white-space: normal" width="890" class="verantwoordingstekst"><?=htmlentities( $verantwoordingstekst->verantwoordingstekst, ENT_COMPAT, 'UTF-8' )?></td> <td style="white-space: normal" width="100" class="status"><?=$verantwoordingstekst->status ?: 'alle'?></td> <td style="white-space: normal" class="last"> <input type="hidden" name="verantwoordingstekst[]" value="<?=htmlentities( $verantwoordingstekst->verantwoordingstekst, ENT_COMPAT, 'UTF-8' )?>" /> <input type="hidden" name="status[]" value="<?=$verantwoordingstekst->status?>" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-verantwoordingstekst"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? endforeach; ?> <?php endif;?> </table> </div> </li> </ul> </div> <div class="main hidden" id="opdrachten"> <ul class="list"> <li class="entry top left right"> <div class="header"><?=tgg('checklistwizard.opdrachten')?> <i style="font-size: 12pt; vertical-align: middle" class="icon-plus add-opdracht"></i> <?=htag('opdrachten', 'algemeen')?></div> <? if (!empty($Vgebruik_opdrachten)): ?> <div class="header" style="float:right; width: 200px; text-align: right;"> <label><input type="checkbox" name="gebruik_opdrachten" value="nee"><?=tgg('checklistwizard.herstel-standaard-set')?></label> <?=htag('herstel-opdrachten', 'algemeen')?> </div> <? endif; ?> </li> <li class="entry top left right bottom" style="height: auto; min-height: 50px; background-color: #e4e3e3; background-image: none;"> <table class="table-header" cellpadding="0" cellspacing="0" width="100%"> <tr> <td width="990">Tekst</td> <td class="last">&nbsp;</td> </tr> </table> <div class="table-wrapper"> <table class="table-contents" cellpadding="0" cellspacing="0" width="100%"> <tr class="hidden new-row"> <td width="990" class="opdracht"></td> <td class="last"> <input type="hidden" name="opdrachten[]" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-opdracht"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? foreach ($Vopdrachten as $opdracht): ?> <tr> <td width="990" class="opdracht"><?=htmlentities( $opdracht->opdracht, ENT_COMPAT, 'UTF-8' )?></td> <td class="last"> <input type="hidden" name="opdrachten[]" value="<?=htmlentities( $opdracht->opdracht, ENT_COMPAT, 'UTF-8' )?>" /> <i style="font-size: 12pt; vertical-align: middle" class="icon-edit edit-opdracht"></i> <i style="font-size: 12pt; vertical-align: middle" class="icon-trash delete-table-row"></i> </td> </tr> <? endforeach; ?> </table> </div> </li> </ul> </div> <? if( $model == 'vraag' && $klant->email_question_notification ) { $this->load->view( 'checklistwizard/_email_config.php', array('klant' => $klant)); } ?> <input type="hidden" class="active_tab" value="<?=@$active_tab?>" /> <input type="hidden" class="return_url" value="<?=htmlentities( site_url($return_url), ENT_COMPAT, 'UTF-8' )?>" /> <? if (!($context instanceof VraagResult)): ?> <label><input type="checkbox" beschrijving="<?=tgng('recursief_vraagconfig.kort')?>" name="recursief_vraagconfig" style="vertical-align:middle"> <?=tgg('recursief.vraagconfiguratie', tgn('hierachie.lijst'))?></label><br/> <label><input type="checkbox" beschrijving="<?=tgng('recursief_achtergrondinformatie.kort')?>" name="recursief_achtergrondinformatie" style="vertical-align:middle"> <?=tgg('recursief.achtergrondinformatie', tgn('hierachie.lijst'))?></label><br/> <label><input type="checkbox" beschrijving="<?=tgng('recursief_verantwoordingen.kort')?>" name="recursief_verantwoordingen" style="vertical-align:middle"> <?=tgg('recursief.verantwoordingen', tgn('hierachie.lijst'))?></label><br/> <label><input type="checkbox" beschrijving="<?=tgng('recursief_opdrachten.kort')?>" name="recursief_opdrachten" style="vertical-align:middle"> <?=tgg('recursief.opdrachten', tgn('hierachie.lijst'))?></label><br/> <? endif; ?> <div class="button opslaan_en_afsluiten"> <a href="javascript:void(0);" style="font-weight: bold; font-size: 120%; "><?=tgng('form.opslaan_en_afsluiten')?></a> </div> <div class="button opslaan"> <a href="javascript:void(0);" style="font-weight: bold; font-size: 120%; "><?=tgng('form.opslaan')?></a> </div> </form> <? if ($headers) $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('backlog-uploads'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <table class="BacklogUploads"> <tr> <th style="text-align:left">Bestand</th> <th style="text-align:left">Content-Type</th> <th style="text-align:left">Grootte</th> <th style="text-align:left">Ge&uuml;pload op</th> </tr> <? foreach ($uploads as $i => $upload): ?> <tr style="background-color: <?=($i % 2) ? '#fff' : '#eee'?>;"> <td><?=htmlentities( $upload->bestandsnaam, ENT_COMPAT, 'UTF-8' )?></td> <td><?=htmlentities( $upload->content_type, ENT_COMPAT, 'UTF-8' )?></td> <td><?=round( $upload->grootte / (1024*1024), 1 )?> MB</td> <td><?=date( 'd-m-Y H:i:s', strtotime( $upload->aangemaakt_op ) )?></td> <td> <a href="<?=$upload->get_download_url()?>"><img src="/files/images/magnifier.png"> Download nu</a> <a href="javascript:void(0);" onclick="if (confirm('Upload verwijderen?')) location.href='<?=site_url('/admin/backlog_uploads_delete/' . $upload->id)?>';"><img src="/files/images/delete.png"> Verwijderen</a> </td> </tr> <? endforeach; ?> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <p> <input type="button" value="Naar backlog item" onclick="location.href='/admin/backlog_edit/<?=$backlog->id?>';" /> </p> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('backlog-upload-new'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <form method="POST" enctype="multipart/form-data"> <input type="file" name="file"><br/> <br/> <input type="submit" value="Uploaden" /> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? require_once 'base.php'; class DossierBescheidenMapResult extends BaseResult { function DossierBescheidenMapResult( &$arr ) { parent::BaseResult( 'dossierbescheidenmap', $arr ); } function get_parent() { return $this->parent_dossier_besch_map_id ? $this->get_model()->get( $this->parent_dossier_besch_map_id ) : null; } function get_aantal_bescheiden_in_map( $ook_recursief=true ) { $res = $this->_CI->db->query( 'SELECT COUNT(*) AS count FROM dossier_bescheiden WHERE dossier_bescheiden_map_id = ' . intval($this->id) ); $count = $res->row_object()->count; $res->free_result(); if ($ook_recursief) foreach ($this->get_model()->get_by_dossier( $this->dossier_id, $this->id ) as $map) $count += $map->get_aantal_bescheiden_in_map( $ook_recursief ); return $count; } function get_bescheiden( $ook_recursief=false ) { $CI = get_instance(); $result = $CI->dossierbescheiden->get_by_dossier( $this->dossier_id, false, $this->id ); if ($ook_recursief) foreach ($this->get_mappen( false ) as $map) $result = array_merge( $result, $map->get_bescheiden( $ook_recursief ) ); return $result; } function get_mappen( $ook_recursief=false ) { $result = $this->get_model()->get_by_dossier( $this->dossier_id, $this->id ); if ($ook_recursief) foreach ($result as $map) $result = array_merge( $result, $map->get_mappen( $ook_recursief ) ); return $result; } function get_pad( $separator=' / ' ) { $pad = $this->naam; $parent = $this->get_parent(); return $parent ? $parent->get_pad() . $separator . $pad : $pad; } } class DossierBescheidenMap extends BaseModel { function DossierBescheidenMap() { parent::BaseModel( 'DossierBescheidenMapResult', 'dossier_bescheiden_mappen' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } public function get_by_dossier( $dossier_id, $parent_id=0 ) { $args = array( 'dossier_id' => $dossier_id ); if ($parent_id) { $args['parent_dossier_besch_map_id'] = $parent_id; $extra_query = null; } else $extra_query = 'parent_dossier_besch_map_id IS NULL'; return $this->search( $args, $extra_query, $assoc=false, $operator='AND', $order_by='naam' ); } public function add( DossierResult $dossier, $mapnaam, $parent_map_id ) { $data = array( 'dossier_id' => $dossier->id, 'naam' => $mapnaam, 'parent_dossier_besch_map_id' => $parent_map_id ? $parent_map_id : null, ); return $this->insert( $data ); } } <file_sep><?php class CI_CSSImagePreloader { private $_paths = array(); // paths we need to check for CSS files private $_files = array(); // CSS files we've found private $_urls = array(); // unique set of clean URL paths to preload public function __construct() { $this->_paths[] = APPPATH . '/../files/css/'; $this->_paths[] = APPPATH . '/../files/pdf-annotator/css'; foreach ($this->_paths as $path) foreach (scandir( $path ) as $file) if (preg_match( '/\.css$/i', $file )) $this->_files[] = $path . '/' . $file; foreach ($this->_files as $file) if (false !== ($contents = file_get_contents( $file ))) { $basepath = dirname( str_replace( '/..', '', str_replace( '//', '/', preg_replace( '#' . preg_quote(APPPATH) . '#', '', $file ) ) ) ) . '/'; if (preg_match_all( '/url\(["\']?(.*?)["\']?\)/i', $contents, $matches )) { foreach ($matches[1] as $url) { if (preg_match( '/^\.\./', $url )) $path = $basepath . $url; else $path = $url; $cleanpath = preg_replace( '#/([a-z0-9_-]+)/\.\./#', '/', $path ); $this->_urls[] = $cleanpath; } } } $this->_urls = array_unique( $this->_urls ); } public function process() { $str = '<div style="position:absolute; left: -9999px; top: -9999px;">' . "\n"; foreach ($this->_urls as $url) $str .= "\t" . '<img src="/files/images/s.gif" target_url="' . $url . '">' . "\n"; $str .= '</div>'; echo $str; } public function add_url( $url ) { $this->_urls[] = $url; } } <file_sep><? require_once 'base.php'; class BijwoonmomentenmapResult extends BaseResult { public function BijwoonmomentenmapResult( &$arr ){ parent::BaseResult( 'bijwoonmomentenmap', $arr ); } } class Bijwoonmomentenmap extends BaseModel { public function Bijwoonmomentenmap(){ parent::BaseModel( 'BijwoonmomentenmapResult', 'bijwoonmomenten_map' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function add( $dmmId, $tmomentId ){ $CI = get_instance(); $tbl = $this->_table; $data = array( 'matrix_id' => $dmmId, 'toezichtmoment_id' => $tmomentId ); $result = $this->db->select() ->where('matrix_id',$dmmId) ->where('toezichtmoment_id',$tmomentId) ->get( $tbl, 1 ) ->result() ; return ( !(bool)count($result) ) ? $this->insert( $data ) : $result[0]; } // public function delete_by_toezichtmoment( $tmomentId ){ // $CI = get_instance(); // $tbl = $this->_table; // $this->db // ->where('toezichtmoment_id', $tmomentId) // ->delete( $tbl ) // ; // return true; // } // public function is_bw( $dmmId, $tmomentId ){ // $CI = get_instance(); // $tbl = $this->_table; // $result = $this->db->select() // ->where('matrix_id', $dmmId ) // ->where('toezichtmoment_id', $tmomentId ) // ->get( $tbl, 1 ) // ->result() // ; // return (bool)count($result); // } // public function get_by_ public function get_by_toezichtmoment( $tmomentId, $dmmId ) { $result = $this->db->select() ->where('toezichtmoment_id', $tmomentId ) ->where('matrix_id', $dmmId ) ->get( $this->_table ) ->result() ; if(isset($result[0])) return $this->getr($result[0]); else return false; } }// Class end <file_sep><? if (!@$exclude_jquery): ?> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script> <? endif; ?> <? if (file_exists( $fullfn = (PDFANNOTATOR_FILES_BASEPATH . 'js/PDFAnnotator-' . PDFANNOTATOR_VERSION . '.js') )): ?> <script type="text/javascript" src="/<?=$fullfn?>"></script> <? else: ?> <? /* leave this list in this format, or compress-js will not work anymore */ foreach (array( 'jquery.event.drag-2.2.js', 'jquery-additions.js', 'modal.popup.js', 'json.js', 'Base/Engine.js', 'Base/Observable.js', 'PDFAnnotator/Base.js', 'PDFAnnotator/Upload.js', 'PDFAnnotator/Window.js', 'PDFAnnotator/Math/Vector2.js', 'PDFAnnotator/Math/IntVector2.js', 'PDFAnnotator/Server.js', 'PDFAnnotator/HelperWindow.js', 'PDFAnnotator/Tool.js', 'PDFAnnotator/Tool/Camera.js', 'PDFAnnotator/Tool/CameraAssignment.js', 'PDFAnnotator/Tool/Circle.js', 'PDFAnnotator/Tool/Image.js', 'PDFAnnotator/Tool/Measure.js', 'PDFAnnotator/Tool/Quad.js', 'PDFAnnotator/Tool/SingleLine.js', 'PDFAnnotator/Tool/Text.js', 'PDFAnnotator/Tool/HandleTool.js', 'PDFAnnotator/Tool/Delete.js', 'PDFAnnotator/Tool/Move.js', 'PDFAnnotator/Tool/Resize.js', 'PDFAnnotator/Tool/Pan.js', 'PDFAnnotator/Tool/Download.js', 'PDFAnnotator/Tool/DownloadAlles.js', 'PDFAnnotator/Tool/DownloadScherm.js', 'PDFAnnotator/Tool/ChangeVraag.js', 'PDFAnnotator/Line.js', 'PDFAnnotator/AttachedRotatedLine.js', 'PDFAnnotator/Handle.js', 'PDFAnnotator/Handle/Delete.js', 'PDFAnnotator/Handle/Move.js', 'PDFAnnotator/Handle/Resize.js', 'PDFAnnotator/Handle/LineMove.js', 'PDFAnnotator/Handle/LineDelete.js', 'PDFAnnotator/Handle/QuadResize.js', 'PDFAnnotator/Handle/CircleResize.js', 'PDFAnnotator/Handle/MeasureFinish.js', 'PDFAnnotator/Handle/MeasureDelete.js', 'PDFAnnotator/Handle/OverviewMove.js', 'PDFAnnotator/Handle/OverviewHide.js', 'PDFAnnotator/Handle/ChangeVraag.js', 'PDFAnnotator/GUI.js', 'PDFAnnotator/GUI/Menu.js', 'PDFAnnotator/GUI/Menu/Panel.js', 'PDFAnnotator/GUI/Menu/Colors.js', 'PDFAnnotator/GUI/Menu/Drawing.js', 'PDFAnnotator/GUI/Menu/Text.js', 'PDFAnnotator/GUI/Menu/ImageList.js', 'PDFAnnotator/GUI/Menu/Layers.js', 'PDFAnnotator/GUI/Menu/Layers/LayerEntry.js', 'PDFAnnotator/GUI/Tools.js', 'PDFAnnotator/GUI/Zoom.js', 'PDFAnnotator/Editable.js', 'PDFAnnotator/EditableContainer.js', 'PDFAnnotator/EditableEditor.js', 'PDFAnnotator/Layer.js', 'PDFAnnotator/LayerReference.js', 'PDFAnnotator/Engine.js', 'PDFAnnotator/Engine/Platform.js', 'PDFAnnotator/OverviewWindow.js', 'PDFAnnotator/Editable/Text.js', 'PDFAnnotator/Editable/Image.js', 'PDFAnnotator/Editable/Line.js', 'PDFAnnotator/Editable/Photo.js', 'PDFAnnotator/Editable/PhotoAssignment.js', 'PDFAnnotator/Editable/Quad.js', 'PDFAnnotator/Editable/Circle.js', 'PDFAnnotator/Editable/MeasureLine.js', 'PDFAnnotator/Editable/Path.js', 'PDFAnnotator/Editable/Compound.js', // BTZ specific 'PDFAnnotator/Server/PDFAnnotatorBTZ.js', 'PDFAnnotator/Server/BTZVraag.js', ) as $filename): ?> <script type="text/javascript" src="<?=PDFANNOTATOR_FILES_BASEURL?>js/<?=$filename?>?<?=PDFANNOTATOR_VERSION?>"></script> <? endforeach; ?> <? endif; ?> <link rel="stylesheet" type="text/css" href="<?=PDFANNOTATOR_FILES_BASEURL?>css/site.css?<?=PDFANNOTATOR_VERSION?>" /><file_sep>ALTER TABLE `deelplan_opdrachten` ADD `deelplan_upload_id` INT NULL DEFAULT NULL , ADD INDEX ( `deelplan_upload_id` ) ; ALTER TABLE `deelplan_opdrachten` ADD FOREIGN KEY ( `deelplan_upload_id` ) REFERENCES `deelplan_uploads` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; <file_sep><? require_once 'base.php'; class ColectivematrixResult extends BaseResult{ function ColectivematrixResult( &$arr ){ parent::BaseResult( 'colectivematrix', $arr ); } public function getRisicoprofiel( $id ) { $profiel = array( 'id' => $id, 'naam' => '' ); $afdelingen = array(); foreach( $this->afdelingen as $afdeling ) { $artikelen = array(); foreach( $afdeling->artikelen as $artikel ) { foreach( $artikel->risicoProfielen as $risicoprofiel ) { if( $risicoprofiel->risicoProfielId == $id ) { $profiel['naam'] = $risicoprofiel->naam; $artikelen[] = array( 'id' => $artikel->artikelId, 'naam' => $artikel->naam, 'active' => $artikel->actief, 'beschrijving' => $artikel->beschrijving ); break; } } } $count = count($artikelen); if( $count ) { $afdelingen[] = array( 'id' => $afdeling->afdelingId, 'naam' => $afdeling->naam, 'active'=> $afdeling->actief, 'beschrijving'=> $afdeling->beschrijving, 'count'=> $count, 'artikelen'=> $artikelen ); } } $profiel['afdelingen'] = $afdelingen; return $profiel; } public function get_artikal( $artikalId ){ foreach( $this->afdelingen as $afdeling ){ foreach($afdeling->artikelen as $artikel ){ if($artikel->artikelId == $artikalId ){ return $artikel; } } } return null; } //------------------------------------------------------------------------------ }// Class end class Colectivematrix extends BaseModel{ private $soap_data = array( 'licentieNaam' => 'WB_woningborg_usr', 'licentieWachtwoord' => 'WB_woningborg_pwd', 'collectieveMatrixId' => null ); function Colectivematrix(){ parent::BaseModel( 'ColectivematrixResult', 'bt_toezichtmomenten' );//TODO: Name of this table is used as dummy naam. $this->load->helper( 'soapclient' ); } //------------------------------------------------------------------------------ public function check_access( BaseResult $object ){ // } //------------------------------------------------------------------------------ public function get( $id, $assoc=false ){ $result = null; $this->soap_data['collectieveMatrixId'] = $id; $result = $this->all( array(), $assoc ); if($assoc) { $result = $result[0]; } else { $result = new $this->_model_class( $result[0] ); } return $result; } private function convertCollectiveMatricesToArray( $matrices ) { $result_matrices = array(); foreach( $matrices as $matrix ) { $result_afdelingen = array(); foreach( $matrix->afdelingen as $afdeling ) { $result_artikelen = array(); foreach( $afdeling->artikelen as $artikel ) { $result_risicoprofielen = array(); foreach($artikel->risicoProfielen as $risicoprofiel ) { $result_risicoprofielen[] = array( 'id' => $risicoprofiel->risicoProfielId, 'naam' => $risicoprofiel->naam ); } $result_artikelen[] = array( 'id' => $artikel->artikelId, 'naam' => $artikel->naam, 'active' => $artikel->actief, 'beschrijving' => $artikel->beschrijving, 'risicoprofielen'=> $result_risicoprofielen ); } $result_afdelingen[] = array( 'id' => $afdeling->afdelingId, 'naam' => $afdeling->naam, 'active' => $afdeling->actief, 'beschrijving' => $afdeling->beschrijving, 'artikelen' => $result_artikelen ); } $result_matrices[] = array( 'id' => $matrix->collectieveMatrixId, 'naam' => $matrix->naam, 'active' => $matrix->actief, 'beschrijving' => $matrix->beschrijving, 'afdelingen' => $result_afdelingen ); } return $result_matrices; } private function get_debug_mutrixes($assoc){ $collectieveMatrices = array( (object)array( 'collectieveMatrixId' => 1, 'naam' => 'Collectivematrix 1', 'beschrijving' => 'Collectivematrix 1 Beschrijving', 'actief' => TRUE, 'afdelingen'=> array( (object)array( 'afdelingId' => '1.1', 'naam' => '1.1 Afdeling', 'beschrijving' => '1.1 Afdeling', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 111, 'actief'=>TRUE, 'naam' => '1.1.1', 'beschrijving' => 'Artikel 1.1.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3') )), (object)array('artikelId' => 112, 'actief'=>TRUE, 'naam' => '1.1.2', 'beschrijving' => 'Artikel 1.1.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 2, 'naam' => 'Risicoprofiel 2'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 113, 'actief'=>TRUE, 'naam' => '1.1.3', 'beschrijving' => 'Artikel 1.1.3', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 114, 'actief'=>TRUE, 'naam' => '1.1.4', 'beschrijving' => 'Artikel 1.1.4', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => '<NAME>'), (object)array('risicoProfielId' => 2, 'naam' => '<NAME>') )) ) ), (object)array( 'afdelingId' => '1.3', 'naam' => 'Afdeling 1.3', 'beschrijving' => 'Afdeling 1.3', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 131, 'actief'=>TRUE, 'naam' => '1.3.1', 'beschrijving' => 'Artikel 1.3.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 4, 'naam' => '<NAME>') )), (object)array('artikelId' => 132, 'actief'=>FALSE, 'naam' => '1.3.2', 'beschrijving' => 'Artikel 1.3.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 3, 'naam' => '<NAME>') )) ) ) ) ),// Matrix end (object)array( 'collectieveMatrixId' => 2, 'naam' => 'Collectivematrix 2', 'beschrijving' => 'Collectivematrix 2 Beschrijving', 'actief' => TRUE, 'afdelingen'=> array( (object)array( 'afdelingId' => '1.1', 'naam' => '1.1 Afdeling', 'beschrijving' => '1.1 Afdeling', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 211, 'actief'=>TRUE, 'naam' => '1.1.1', 'beschrijving' => 'Artikel 1.1.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3') )), (object)array('artikelId' => 212, 'actief'=>TRUE, 'naam' => '1.1.2', 'beschrijving' => 'Artikel 1.1.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 2, 'naam' => 'Risicoprofiel 2'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 213, 'actief'=>TRUE, 'naam' => '1.1.3', 'beschrijving' => 'Artikel 1.1.3', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )) ) ), (object)array( 'afdelingId' => '1.3', 'naam' => 'Afdeling 1.3', 'beschrijving' => 'Afdeling 1.3', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 231, 'actief'=>TRUE, 'naam' => '1.3.1', 'beschrijving' => 'Artikel 1.3.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 232, 'actief'=>FALSE, 'naam' => '1.3.2', 'beschrijving' => 'Artikel 1.3.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3') )), (object)array('artikelId' => 332, 'actief'=>FALSE, 'naam' => '1.3.3', 'beschrijving' => 'Artikel 1.3.3', 'risicoProfielen' => array( (object)array('risicoProfielId' => 2, 'naam' => 'Risicoprofiel 2') )) ) ) ) )// Matrix end ,(object)array( 'collectieveMatrixId' => 3, 'naam' => 'Collectivematrix 3', 'beschrijving' => 'Collectivematrix 3 Beschrijving', 'actief' => TRUE, 'afdelingen'=> array( (object)array( 'afdelingId' => '1.1', 'naam' => '1.1 Afdeling', 'beschrijving' => '1.1 Afdeling', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 311, 'actief'=>TRUE, 'naam' => '1.1.1', 'beschrijving' => 'Artikel 1.1.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3') )), (object)array('artikelId' => 312, 'actief'=>TRUE, 'naam' => '1.1.2', 'beschrijving' => 'Artikel 1.1.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 2, 'naam' => 'Risicoprofiel 2'), (object)array('risicoProfielId' => 3, 'naam' => 'Risicoprofiel 3'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 313, 'actief'=>TRUE, 'naam' => '1.1.3', 'beschrijving' => 'Artikel 1.1.3', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => 'Risicoprofiel 1'), (object)array('risicoProfielId' => 4, 'naam' => 'Risicoprofiel 4') )), (object)array('artikelId' => 314, 'actief'=>TRUE, 'naam' => '1.1.4', 'beschrijving' => 'Artikel 1.1.4', 'risicoProfielen' => array( (object)array('risicoProfielId' => 1, 'naam' => '<NAME>'), (object)array('risicoProfielId' => 2, 'naam' => '<NAME>') )), (object)array('artikelId' => 315, 'actief'=>TRUE, 'naam' => '1.1.5', 'beschrijving' => 'Artikel 1.1.5', 'risicoProfielen' => array( (object)array('risicoProfielId' => 2, 'naam' => '<NAME>'), (object)array('risicoProfielId' => 4, 'naam' => '<NAME>') )) ) ), (object)array( 'afdelingId' => '1.3', 'naam' => 'Afdeling 1.3', 'beschrijving' => 'Afdeling 1.3', 'actief'=>TRUE, 'artikelen' => array( (object)array('artikelId' => 331, 'actief'=>TRUE, 'naam' => '1.3.1', 'beschrijving' => 'Artikel 1.3.1', 'risicoProfielen' => array( (object)array('risicoProfielId' => 4, 'naam' => '<NAME>') )), (object)array('artikelId' => 332, 'actief'=>FALSE, 'naam' => '1.3.2', 'beschrijving' => 'Artikel 1.3.2', 'risicoProfielen' => array( (object)array('risicoProfielId' => 3, 'naam' => '<NAME>') )) ) ) ) )// Matrix end ); /** collectieveMatrixId */ if( $this->soap_data['collectieveMatrixId'] != null ){ foreach( $collectieveMatrices as $key=>$collectieveMatrix ){ if($collectieveMatrix->collectieveMatrixId != $this->soap_data['collectieveMatrixId'] ){ unset($collectieveMatrices[$key]); } } } $collectieveMatrices = array_values($collectieveMatrices); return $assoc ? $this->convertCollectiveMatricesToArray( $collectieveMatrices ) : $collectieveMatrices; } public function all( $sort_fields=array(), $assoc=false, $usecache=true ){ if( 1 ){// Debug matrix data return $this->get_debug_mutrixes( $assoc ); } $this->load->helper( 'soapclient' ); // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); $remoteSoapWsdl = $this->config->item('ws_url_wsdl_bt_soapdossier'); $soapMethodName = 'soapGetCollectieveMatrices'; $wrappedSoapClient = getWrappedSoapClientHelper($remoteSoapWsdl."&{$randval}", $soapMethodName, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $this->soap_data ); if (empty($wsResult)) { $errorMessage = "De BT Coolective Matrix webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } } } // if (empty($wrappedSoapClient->soapErrors)) else { $errorMessage = "Foutmelding(en) bij maken connectie naar BT Coolective Matrix webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } } // else of clause: if (empty($wrappedSoapClient->soapErrors)) // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar BT Coolective Matrix webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } } // if (!empty($errorsDuringCall)) else { // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult) && isset($wsResult->success) && $wsResult->success) { // The call succeeded so signal that. $is_success = true; // If dossiers were retrieved, extract them and store them in the dataset that we will be using later. if (!empty($wsResult->results->collectieveMatrices)) { $collectieveMatrices = $wsResult->results->collectieveMatrices; } } // if (!empty($wsResult)) } // else of clause: if (!empty($errorsDuringCall)) return $assoc ? $this->convertCollectiveMatricesToArray( $collectieveMatrices ) : $collectieveMatrices; } //------------------------------------------------------------------------------ private function prepareProjectMatrix( $projectMatrix ){ $collective_matrix = $this->get($projectMatrix['collective_matrix_id']); $projectMatrix['naam'] = $collective_matrix->naam; $profile = $collective_matrix->getRisicoprofiel( $projectMatrix['risk_profiel_id'] ); $projectMatrix['profiel_naam'] = $profile['naam']; foreach( $projectMatrix['afdelingen'] as &$pj_afdeling ){ foreach( $collective_matrix->afdelingen as $dflt_afdeling ){ if($pj_afdeling['id'] == $dflt_afdeling->afdelingId) { $pj_afdeling['naam'] = $dflt_afdeling->naam; foreach($pj_afdeling['artikelen'] as &$pj_artikel) { foreach($dflt_afdeling->artikelen as $dflt_artikel ) { if($pj_artikel['id'] == $dflt_artikel->artikelId) { $pj_artikel['naam'] = $dflt_artikel->naam; $pj_artikel['beschrijving'] = $dflt_artikel->beschrijving; if($pj_artikel['active'] && $dflt_artikel->actief) { $pj_artikel['status'] = 'S'; } elseif($pj_artikel['active'] && !$dflt_artikel->actief) { $pj_artikel['status'] = 'P'; } else { $pj_artikel['status'] = '&#8212;'; } break; } } } $pj_afdeling['count'] = count($pj_afdeling['artikelen']); break; } } } return $projectMatrix; } //------------------------------------------------------------------------------ private function convertProjectSpecifiekeMappingToArray( $spMap ) { $result_afdelingen = array(); foreach($spMap->afdelingen as $afdeling ) { $result_artikelen = array(); foreach( $afdeling->artikelen as $artikel ) { $result_artikelen[] = array( 'id'=> $artikel->artikelId, 'active'=> $artikel->actief ); } $result_afdelingen[] = array( 'id' => $afdeling->afdelingId, // 'naam' => $afdeling->naam, 'active' => $afdeling->actief, 'artikelen' => $result_artikelen ); } $result_sp_map = array( 'collective_matrix_id' => $spMap->collectieveMatrixId, 'risk_profiel_id' => $spMap->risicoProfielId, 'afdelingen'=> $result_afdelingen ); return $result_sp_map; } public function getProjectSpecifiekeMapping( $bt_dossier_id, $bt_dossier_hash='', $assoc=true ){ $sp_map = array(); // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); $remoteSoapWsdl = $this->config->item('ws_url_wsdl_bt_soapdossier'); $soapMethodName = 'soapGetProjectSpecifiekeMapping'; $wrappedSoapClient = getWrappedSoapClientHelper($remoteSoapWsdl."&{$randval}", $soapMethodName, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $input_data = array( 'licentieNaam' => 'WB_woningborg_usr', 'licentieWachtwoord' => '<PASSWORD>', 'dossierHash' => $bt_dossier_hash, 'dossierId' => $bt_dossier_id ); $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $input_data ); if (empty($wsResult)) { $errorMessage = "De BT Coolective Matrix webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } } } // if (empty($wrappedSoapClient->soapErrors)) else { $errorMessage = "Foutmelding(en) bij maken connectie naar BT Coolective Matrix webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } } // else of clause: if (empty($wrappedSoapClient->soapErrors)) // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar BT Coolective Matrix webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } } // if (!empty($errorsDuringCall)) else { // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult) && isset($wsResult->success) && $wsResult->success) { // The call succeeded so signal that. $is_success = true; // If dossiers were retrieved, extract them and store them in the dataset that we will be using later. if (!empty($wsResult->results->projectSpecifiekeMapping)) { $sp_map = $wsResult->results->projectSpecifiekeMapping; } } // if (!empty($wsResult)) } // else of clause: if (!empty($errorsDuringCall)) $result_sp_map = $this->convertProjectSpecifiekeMappingToArray($sp_map); $result_sp_map = $this->prepareProjectMatrix( $result_sp_map ); return $result_sp_map; /* $bt_project_matrix = array( 'collective_matrix_id' => 2, // Collectivematrix 2 'risk_profiel_id' => 1152, // Risicoprofiel 2 // 'active' => TRUE, 'afdelingen'=> array( array( 'id' => 21, // 'naam' => 'Afdeling 2.1', 'active'=>TRUE, // TRUE 'artikelen' => array( // array('id' => 211, 'active'=>TRUE, 'naam' => 'Artikel 2.1.1', // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>'), // )), array('id' => 212, 'active'=>TRUE//, 'naam' => 'Artikel 2.1.2', // FALSE // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>'), // array('id' => 1152, 'naam' => '<NAME>') // ) ), array('id' => 213, 'active'=>FALSE//, 'naam' => 'Artikel 2.1.3', // FALSE // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>'), // array('id' => 1152, 'naam' => '<NAME>'), // array('id' => 1153, 'naam' => '<NAME>') // ) ), array('id' => 214, 'active'=>TRUE//, 'naam' => 'Artikel 2.1.4', // TRUE // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>'), // array('id' => 1152, 'naam' => '<NAME>'), // array('id' => 1153, 'naam' => '<NAME>'), // array('id' => 1164, 'naam' => '<NAME>') // ) ), // array('id' => 215, 'active'=>TRUE, 'naam' => 'Artikel 2.1.5', // 'risicoprofielen' => array( // array('id' => 1164, 'naam' => '<NAME>') // )), // array('id' => 216, 'active'=>FALSE, 'naam' => 'Artikel 2.1.6', // 'risicoprofielen' => array( // array('id' => 1153, 'naam' => '<NAME>'), // array('id' => 1164, 'naam' => '<NAME>') // )) ) ), array( 'id' => 22, // 'naam' => 'Afdeling 2.2', 'active'=>TRUE, // TRUE 'artikelen' => array( // array('id' => 221, 'active'=>TRUE, 'naam' => 'Artikel 2.2.1', // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>') // )), array('id' => 222, 'active'=>FALSE//, 'naam' => 'Artikel 2.2.2', // FALSE // 'risicoprofielen' => array( // array('id' => 1152, 'naam' => '<NAME>') // ) ), // array('id' => 223, 'active'=>TRUE, 'naam' => 'Artikel 2.2.3', // 'risicoprofielen' => array( // array('id' => 1153, 'naam' => '<NAME>') // )), // array('id' => 224, 'active'=>FALSE, 'naam' => 'Artikel 2.2.4', // 'risicoprofielen' => array( // array('id' => 1164, 'naam' => '<NAME>') // )) ) ), array( 'id' => 23, // 'naam' => 'Afdeling 2.3', 'active'=>TRUE, // TRUE 'artikelen' => array( // array('id' => 231, 'active'=>TRUE, 'naam' => 'Artikel 2.3.1', // 'risicoprofielen' => array( // array('id' => 1164, 'naam' => '<NAME>') // )), // array('id' => 232, 'active'=>FALSE, 'naam' => 'Artikel 2.3.2', // 'risicoprofielen' => array( // array('id' => 1153, 'naam' => '<NAME>') // )), array('id' => 233, 'active'=>TRUE//, 'naam' => 'Artikel 2.3.3', // TRUE // 'risicoprofielen' => array( // array('id' => 1151, 'naam' => '<NAME>'), // array('id' => 1152, 'naam' => '<NAME>') // ) ) ) ) ) )// Matrix end ; $bt_project_matrix = $this->prepareProjectMatrix($bt_project_matrix); return $bt_project_matrix; */ } //------------------------------------------------------------------------------ }// Class end <file_sep>DROP TABLE IF EXISTS supervision_moments_executed; DROP TABLE IF EXISTS supervision_moments_cl; DROP TABLE IF EXISTS supervision_moments_clg; CREATE TABLE IF NOT EXISTS `supervision_moments_cl` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `checklist_id` int(11) NOT NULL, `supervision_start` datetime NOT NULL, `supervision_end` datetime DEFAULT NULL, `progress_start` float NOT NULL, `progress_end` float DEFAULT NULL, `supervisor_user_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `supervisor_user_id` (`supervisor_user_id`), KEY `checklist_id` (`checklist_id`), KEY `deelplan_id` (`deelplan_id`), CONSTRAINT `FK_s_m_cl__cl_id` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_s_m_cl__d_id` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_s_m_cl__g_id` FOREIGN KEY (`supervisor_user_id`) REFERENCES `gebruikers` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS supervision_moments_clg ( id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, deelplan_id INT(11) NOT NULL, checklist_group_id INT(11) NOT NULL, supervision_start datetime NOT NULL, supervision_end datetime DEFAULT NULL, progress_start FLOAT NOT NULL, progress_end FLOAT DEFAULT NULL, supervisor_user_id INT(11) NOT NULL, PRIMARY KEY(id), KEY supervisor_user_id(supervisor_user_id), KEY deelplan_id(deelplan_id), KEY checklist_group_id(checklist_group_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE supervision_moments_clg ADD CONSTRAINT FK_s_m_clg__clg_id FOREIGN KEY(checklist_group_id) REFERENCES bt_checklist_groepen(id) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FK_s_m_clg__d_id FOREIGN KEY(deelplan_id) REFERENCES deelplannen(id) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT FK_s_m_clg__g_id FOREIGN KEY(supervisor_user_id) REFERENCES gebruikers(id) ON DELETE RESTRICT ON UPDATE RESTRICT; <file_sep><? if (false): // re-enable this to get a new list! $CI = get_instance(); $CI->load->library( 'cssimagepreloader' ); $CI->cssimagepreloader->process(); ?> <? else: ?> <div style="position:absolute; left: -9999px; top: -9999px;"> <!-- manual entries --> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/edit-handle-resize.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/edit-handle-move.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/edit-handle-measure-finish.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/edit-handle-measure-delete.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/edit-handle-delete.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/stempels/_hidden/camera.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-visible.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-invisible.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-filter-none.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-filter-groen.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-filter-geel.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-filter-rood.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-icon-layers.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-delete.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-add.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-icon-colors.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-icon-images.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-icon-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/regular-button-small.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-rotate0.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-rotate90.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-rotate180.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-rotate270.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-flip-horizontal.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-background-flip-vertical.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-icon-text.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-0-0-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/127-127-127-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/136-0-21-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/237-28-36-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-127-39-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-242-0-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/34-177-76-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/0-162-232-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/63-72-204-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/163-73-164-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-255-255-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/195-195-195-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/185-122-87-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-174-201-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/255-201-14-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/239-228-176-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/181-230-29-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/153-217-234-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/112-146-190-256down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-1up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-1down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-2up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-2down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-4up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-4down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-8up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-8down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-16up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-16down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-32up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-32down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-64up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-64down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-128up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-128down.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-256up.gif"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/line/cache/200-191-231-256down.gif"> <!-- generated list, copy/paste output from above code below --> <img src="/files/images/s.gif" target_url="/files/images/background-bottom.png"> <img src="/files/images/s.gif" target_url="/files/images/background-bottomleft.png"> <img src="/files/images/s.gif" target_url="/files/images/background-bottomright.png"> <img src="/files/images/s.gif" target_url="/files/images/background-green-topbar.png"> <img src="/files/images/s.gif" target_url="/files/images/background-left.png"> <img src="/files/images/s.gif" target_url="/files/images/background-right.png"> <img src="/files/images/s.gif" target_url="/files/images/graybutton-left.png"> <img src="/files/images/s.gif" target_url="/files/images/graybutton-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/graybutton-right.png"> <img src="/files/images/s.gif" target_url="/files/images/greenbutton-left.png"> <img src="/files/images/s.gif" target_url="/files/images/greenbutton-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/greenbutton-right.png"> <img src="/files/images/s.gif" target_url="/files/images/groupleft.png"> <img src="/files/images/s.gif" target_url="/files/images/groupmid.png"> <img src="/files/images/s.gif" target_url="/files/images/groupright.png"> <img src="/files/images/s.gif" target_url="/files/images/list-collapsed.png"> <img src="/files/images/s.gif" target_url="/files/images/list-expanded.png"> <img src="/files/images/s.gif" target_url="/files/images/list-item.png"> <img src="/files/images/s.gif" target_url="/files/images/list2-left.png"> <img src="/files/images/s.gif" target_url="/files/images/list2-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/list2-right.png"> <img src="/files/images/s.gif" target_url="/files/images/listheaderbackground.png"> <img src="/files/images/s.gif" target_url="/files/images/midbarleft.png"> <img src="/files/images/s.gif" target_url="/files/images/midbarmid.png"> <img src="/files/images/s.gif" target_url="/files/images/midbarright.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/aandachtspunten-pdf.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/aandachtspunten-subtab-achtergrond-selected.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/aandachtspunten-subtab-achtergrond.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/arrow-left-simple-disabled.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/arrow-left-simple.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/arrow-right-simple-disabled.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/arrow-right-simple.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button-gemiddeld.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button-hoog.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button-laag.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button-zeer_hoog.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button-zeer_laag.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/doorzichtige-achtergrond.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/green-button-mouseover.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/green-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/header-background.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/lijst-kolom-header.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/lijst-title-header-inverted.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/lijst-title-header.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/notificaties.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/popup-background.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bar-left.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bar-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bar-right.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bg-left.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bg-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/progressbar-bg-right.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/regular-button-small.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/regular-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/relevante-documenten-button-120.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/relevante-documenten-button-160.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/row-background1.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/row-background2.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/tabcontents-background.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/verantwoording.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/waardeoordeel-geel-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/waardeoordeel-groen-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/waardeoordeel-normal-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/waardeoordeel-rood-button.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/waardeoordeel-wit-button.png"> <img src="/files/images/s.gif" target_url="/files/images/redbutton-left.png"> <img src="/files/images/s.gif" target_url="/files/images/redbutton-mid.png"> <img src="/files/images/s.gif" target_url="/files/images/redbutton-right.png"> <img src="/files/images/s.gif" target_url="/files/images/tabbackground.png"> <img src="/files/images/s.gif" target_url="/files/images/tableft-selected.png"> <img src="/files/images/s.gif" target_url="/files/images/tableft.png"> <img src="/files/images/s.gif" target_url="/files/images/tabmid-selected.png"> <img src="/files/images/s.gif" target_url="/files/images/tabmid.png"> <img src="/files/images/s.gif" target_url="/files/images/tabright-selected.png"> <img src="/files/images/s.gif" target_url="/files/images/tabright.png"> <img src="/files/images/s.gif" target_url="/files/images/nlaf/briswarenhuis-button.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/label-panels.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/label-tools.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-arrow-expanded.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-arrow.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-imagelist-header0-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-imagelist-header1-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-geel-depressed.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-geel.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-groen-depressed.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-groen.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-none-depressed.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-none.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-rood-depressed.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-filter-rood.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-background-active.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-layers-layer-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-left-selected.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-left.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-mid-selected.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-mid.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-right-selected.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/menu-text-button-right.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/page-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-background.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-camera.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-circle.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-delete.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-download.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-image.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-measure.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-move.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-pan.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-quad.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-resize.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-single-line.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-tool-text.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-camera.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-circle.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-delete.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-download.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-image.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-measure.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-move.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-pan.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-quad.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-resize.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-single-line.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/tools-toolselected-text.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/compound-have-photo.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/compound-have-no-photo.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/compound-groen.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/compound-geel.png"> <img src="/files/images/s.gif" target_url="/files/pdf-annotator/images/nlaf/compound-rood.png"> </div> <? endif; ?><file_sep>-- zet in de crontab: -- php index.php /cli/outlooksynchronizer/verbose,real -- -- -- LET OP: alle huidige deelplannen uitsluiten via outlook_synchronisatie veld? <file_sep>PDFAnnotator.GUI.Menu = PDFAnnotator.Base.extend({ init: function( gui, menuconfig ) { this._super(); /* store menu config */ this.gui = gui; this.menuconfig = menuconfig; /* create more instance variables */ this.selectedMenuHeader = null; /* install resize handler to resize when window resizes */ this.installResizeHandler(); /* install menu item expand/collapse handlers */ this.installOpenCloseEvents(); /* handle sub components */ this.colors = new PDFAnnotator.GUI.Menu.Colors( this, this.menuconfig.panels.colors ); this.drawing = new PDFAnnotator.GUI.Menu.Drawing( this, this.menuconfig.panels.drawing ); this.text = new PDFAnnotator.GUI.Menu.Text( this, this.menuconfig.panels.text ); this.imagelist = new PDFAnnotator.GUI.Menu.ImageList( this, this.menuconfig.panels.imagelist ); this.layers = new PDFAnnotator.GUI.Menu.Layers( this, this.menuconfig.panels.layers ); }, /* initialize as soon as all subsystems are setup */ initialize: function() { this.layers.initialize(); this.drawing.initialize(); }, /* resets the state of the various panels */ resetPanels: function() { this.colors.reset(); this.drawing.reset(); this.text.reset(); this.imagelist.reset(); this.layers.reset(); }, getGUI: function() { return this.gui; }, installResizeHandler: function() { var thiz = this; // handle resizing dom and tool panels PDFAnnotator.Window.prototype.getInstance().on( 'resize', function( window, data ){ thiz.menuconfig.mainContainer.css( 'height', data.height + 'px' ); thiz.menuconfig.mainContainer.parent().css( 'top', data.top + 'px' ); }); }, installOpenCloseEvents: function() { var thiz = this; /* toggle submenu's opening and closing */ this.menuconfig.headers.click(function(){ var isSame = thiz.selectedMenuHeader && thiz.selectedMenuHeader.size() && thiz.selectedMenuHeader[0] == this; if (thiz.selectedMenuHeader) { thiz.selectedMenuHeader.removeClass( 'Expanded' ); thiz.selectedMenuHeader.next().slideUp(); } if (!isSame) { thiz.selectedMenuHeader = $(this); thiz.selectedMenuHeader.next().slideDown(); thiz.selectedMenuHeader.addClass( 'Expanded' ); } else thiz.selectedMenuHeader = null; }); /* toggle entire menu opening and closing */ this.menuconfig.handle.click(function(){ thiz.toggle(); }); /* toggle now */ thiz.toggle(); }, toggle: function() { if (this.menuconfig.mainContainer.is( ':visible' )) this.hide(); else this.show(); }, hide: function() { this.menuconfig.mainContainer.hide(); }, show: function() { this.menuconfig.mainContainer.show(); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'handleiding')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => $label, 'width' => '40em' )); ?> <form method="post" > <table> <tr> <td style="font-size:13px; text-align:left"><?=tg('organisatie')?>:</td> <td style="text-align:right"><input type="text" name="klantnaam" value="" maxlength="32"></td> </tr> <tr> <td style="font-size:13px; text-align:left"><?=tg('gebruikersnaam')?>:</td> <td style="text-align:right"><input type="text" name="gebruikersnaam" value="" maxlength="32"></td> </tr> <tr> <td style="font-size:13px; text-align:left"><?=tg('wachtwoord')?>:</td> <td style="text-align:right"><input type="password" name="wachtwoord" value="" maxlength="32"></td> </tr> <tr> <td style="text-align:left"></td> <td style="text-align:right"><input type="submit" name="" value="Inloggen"></td> </tr> </table> <input type="hidden" name="post_login_location" value="<?=$post_login_location?>"> </form> <script type="text/javascript"> $(document).ready(function(){ document.forms[0].klantnaam.focus(); }); </script> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class DeelplanChecklistGroepObject { public function __construct( $array_or_object ) { foreach ($array_or_object as $k => $v) $this->$k = $v; } }; class DeelplanChecklistGroep extends Model { function get_by_deelplan( $deelplan_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::get_checklist_groepen_by_deelplan' )) $this->dbex->prepare( 'deelplanchecklistgroep::get_checklist_groepen_by_deelplan', ' SELECT * FROM deelplan_checklist_groepen WHERE deelplan_id = ? ' ); $res = $this->dbex->execute( 'deelplanchecklistgroep::get_checklist_groepen_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) $result[ $row->checklist_groep_id ] = new DeelplanChecklistGroepObject( $row ); return $result; } function add( $deelplan_id, $checklist_groep_id ) { $CI = get_instance(); $CI->load->model( 'deelplan' ); if (!($deelplan = $CI->deelplan->get( $deelplan_id ))) throw new Exception( 'Ongeldig deelplan_id ' . $deelplan_id ); $gebruiker_id = $deelplan->get_standaard_toezichthouder_gebruiker_id(); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! fix INSERT IGNORE !!! change it to REPLACE INTO??? // !!! Query tentatively/partially made Oracle compatible. To be fully tested... if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::add_checklist_groep' )) { /* $this->dbex->prepare( 'deelplanchecklistgroep::add_checklist_groep', ' INSERT IGNORE INTO deelplan_checklist_groepen (deelplan_id, checklist_groep_id, initiele_datum, toezicht_gebruiker_id) VALUES (?, ?, '.$now_func.', ?) ' ); * */ $this->dbex->prepare_replace_into( 'deelplanchecklistgroep::add_checklist_groep', ' REPLACE INTO deelplan_checklist_groepen (deelplan_id, checklist_groep_id, initiele_datum, toezicht_gebruiker_id, voortgang_percentage) VALUES (?, ?, '.$now_func.', ?, 0) ', null, array('deelplan_id', 'checklist_groep_id') ); } $args = array( 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, 'gebruiker_id' => $gebruiker_id, ); $this->dbex->execute( 'deelplanchecklistgroep::add_checklist_groep', $args ); } function replace( $deelplan_id, $checklist_groep_id, $toezicht_gebruiker_id, $matrix_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::add_checklist_groep' )) $this->dbex->prepare( 'deelplanchecklistgroep::add_checklist_groep', ' INSERT INTO deelplan_checklist_groepen (deelplan_id, checklist_groep_id, toezicht_gebruiker_id, matrix_id) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE toezicht_gebruiker_id = ?, matrix_id = ? ' ); $args = array( 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, 'toezicht_gebruiker_id' => $toezicht_gebruiker_id, 'matrix_id' => $matrix_id, 'toezicht_gebruiker_id1'=> $toezicht_gebruiker_id, 'matrix_id1' => $matrix_id, ); $this->dbex->execute( 'deelplanchecklistgroep::add_checklist_groep', $args ); } function update_toezichthouder( $deelplan_id, $checklist_groep_id, $toezicht_gebruiker_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::update_toezichthouder' )) $this->dbex->prepare( 'deelplanchecklistgroep::update_toezichthouder', 'UPDATE deelplan_checklist_groepen SET toezicht_gebruiker_id = ? WHERE deelplan_id = ? AND checklist_groep_id = ? LIMIT 1' ); $args = array( 'toezicht_gebruiker_id' => $toezicht_gebruiker_id, 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, ); $this->dbex->execute( 'deelplanchecklistgroep::update_toezichthouder', $args ); } function update_matrix( $deelplan_id, $checklist_groep_id, $matrix_id ) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::update_matrix' )) $this->dbex->prepare( 'deelplanchecklistgroep::update_matrix', 'UPDATE deelplan_checklist_groepen SET matrix_id = ? WHERE deelplan_id = ? AND checklist_groep_id = ? LIMIT 1' ); $args = array( 'matrix_id' => $matrix_id, 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, ); $this->dbex->execute( 'deelplanchecklistgroep::update_matrix', $args ); } function update_planningdatum( $deelplan_id, $checklist_groep_id, $planningdatum, $start_tijd, $eind_tijd ) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::update_planningdatum' )) $this->dbex->prepare( 'deelplanchecklistgroep::update_planningdatum', 'UPDATE deelplan_checklist_groepen SET initiele_datum = ?, initiele_start_tijd = ?, initiele_eind_tijd = ? WHERE deelplan_id = ? AND checklist_groep_id = ? LIMIT 1' ); $args = array( 'planningdatum' => date('Y-m-d', strtotime( $planningdatum )), 'start_tijd' => $start_tijd ? $start_tijd : null, 'eind_tijd' => $eind_tijd ? $eind_tijd : null, 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, ); $this->dbex->execute( 'deelplanchecklistgroep::update_planningdatum', $args ); } function update_voortgang( $deelplan_id, $checklist_groep_id, $voortgang ) { // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // Check if we need to set the date and time on which the 'voortgangspercentage' was set for the first time. This is used for the 'Berkelland BAG' functionality // for keeping track of the date-time on which a 'BAG start' notification needs to be sent. // Note: we explicitly ONLY do this when the 'voortgang' is more than 0, so as to prevent situations where people only look at a checlist to already be registered // as the checklist having been started! $update_voortgang_started_op = false; if (($voortgang > 0)) { $cur_deelplan_checklistgroepen = $this->get_by_deelplan($deelplan_id); foreach($cur_deelplan_checklistgroepen as $cur_deelplan_checklistgroep_id => $cur_deelplan_checklistgroep) { if ( ($cur_deelplan_checklistgroep_id == $checklist_groep_id) && ($cur_deelplan_checklistgroep->voortgang_percentage == 0) ) { $update_voortgang_started_op = true; } } } $args = array( 'voortgang' => $voortgang, 'deelplan_id' => $deelplan_id, 'checklist_groep_id' => $checklist_groep_id, ); if ($update_voortgang_started_op) { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::update_voortgang_complete' )) { $this->dbex->prepare( 'deelplanchecklistgroep::update_voortgang_complete', 'UPDATE deelplan_checklist_groepen SET voortgang_percentage = ?, voortgang_gestart_op = '.$now_func.' WHERE deelplan_id = ? AND checklist_groep_id = ?' ); } $this->dbex->execute( 'deelplanchecklistgroep::update_voortgang_complete', $args ); } else { if (!$this->dbex->is_prepared( 'deelplanchecklistgroep::update_voortgang' )) { $this->dbex->prepare( 'deelplanchecklistgroep::update_voortgang', 'UPDATE deelplan_checklist_groepen SET voortgang_percentage = ? WHERE deelplan_id = ? AND checklist_groep_id = ?' ); } $this->dbex->execute( 'deelplanchecklistgroep::update_voortgang', $args ); } } function remove_except( $deelplan_id, array $except_checklist_groep_ids ) { if (empty( $except_checklist_groep_ids )) { $this->dbex->prepare( 'deelplanchecklistgroep::remove_except', 'DELETE FROM deelplan_checklist_groepen WHERE deelplan_id = ?' ); $args = array( $deelplan_id ); $this->dbex->execute( 'deelplanchecklistgroep::remove_except', $args ); } else { $this->dbex->prepare( 'deelplanchecklistgroep::remove_except', 'DELETE FROM deelplan_checklist_groepen WHERE deelplan_id = ? AND checklist_groep_id NOT IN (' . str_repeat( '?,', sizeof($except_checklist_groep_ids)-1 ) . '?)' ); $args = array_merge( array( $deelplan_id ), array_values( $except_checklist_groep_ids ) ); $this->dbex->execute( 'deelplanchecklistgroep::remove_except', $args ); } } } <file_sep><?php class CI_RisicoAnalyse { private $db; private $cache = array(); public function __construct() { $CI = get_instance(); $this->db = $CI->db; $this->dbex = $CI->dbex; $CI->load->model( 'checklistgroep' ); $CI->load->model( 'checklist' ); } // loads all available risicoanalyses at once, for overview pages public function lookup_all($matrix_id=NULL) { $klant_id = get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id; $db_order_by_null_clause = get_db_order_by_null_clause(); $sub_where = $matrix_id ? " and ra.matrix_id=".$matrix_id :''; $res = $this->db->query( ' SELECT ra.*, c.id AS existing_checklist_id FROM bt_risicoanalyses ra RIGHT JOIN bt_checklisten c ON (ra.checklist_id = c.id AND ra.klant_id = ' . $klant_id . ') JOIN bt_checklist_groepen cg ON c.checklist_groep_id = cg.id WHERE cg.klant_id = ' . $klant_id .$sub_where. ' ORDER BY ra.checklist_id ' . $db_order_by_null_clause ); foreach ($res->result() as $row) { $matrix_id = $row->matrix_id; if ($matrix_id) { // not yet any data for this matrix? then load it now if (!isset( $this->cache[ $matrix_id ] )) $this->cache[ $matrix_id ] = array(); // if this checklist ID already has a loaded prioriteitstelling, skip this row if (isset( $this->cache[ $matrix_id ][ $row->existing_checklist_id ] )) continue; if ($row->checklist_id) $this->cache[ $matrix_id ][ $row->existing_checklist_id ] = new RisicoAnalyse( $row->id, $row->checklist_id, $row->gemaakt_op, $row->matrix_id ); else $this->cache[ $matrix_id ][ $row->existing_checklist_id ] = null; } else { // we've come to the list of existing checklist's that don't have any prioriteitstelling at all foreach ($this->cache as $matrix_id => $prioriteitstellingen) $this->cache[$matrix_id][ $row->existing_checklist_id ] = null; } } $res->free_result(); // now make sure that all checklist ID's are available in all matrix arrays, // so that we won't accidentally make any new ones automatically where such is // not required foreach ($this->cache as $matrix_id => $risicoanalyses) foreach ($risicoanalyses as $checklist_id => $unused) foreach ($this->cache as $matrix_id2 => $risicoanalyses2) if ($matrix_id != $matrix_id2) if (!isset( $this->cache[$matrix_id2][$checklist_id] )) $this->cache[$matrix_id2][$checklist_id] = null; } // finds or creates new risicoanalyse for checklist public function lookup_or_create( $matrix_id, $checklist_id, $create_if_not_exists=true ) { if (!$checklist_id) return NULL; $matrix_id = intval( $matrix_id ); $checklist_id = intval( $checklist_id ); if (!array_key_exists( $matrix_id, $this->cache )) $this->cache[$matrix_id] = array(); if (!array_key_exists( $checklist_id, $this->cache[$matrix_id] ) || $create_if_not_exists) { $this->cache[$matrix_id][ $checklist_id ] = $this->_lookup( $matrix_id, $checklist_id ); if (!$this->cache[$matrix_id][ $checklist_id ]) { if (!$create_if_not_exists) return null; $this->cache[$matrix_id][ $checklist_id ] = $this->_create( $matrix_id, $checklist_id ); } } return $this->cache[$matrix_id][ $checklist_id ]; } // finds risicoanalyse for checklist, returns null when not in database public function lookup( $matrix_id, $checklist_id ) { if (!$checklist_id) return NULL; $matrix_id = intval( $matrix_id ); $checklist_id = intval( $checklist_id ); if (!array_key_exists( $matrix_id, $this->cache )) $this->cache[$matrix_id] = array(); if (!array_key_exists( $checklist_id, $this->cache[$matrix_id] )) { $this->cache[$matrix_id][ $checklist_id ] = $this->_lookup( $matrix_id, $checklist_id ); } return $this->cache[$matrix_id][ $checklist_id ]; } // lookup, returns null when non-existent // NOTE: does NOT read from or write to $this->cache private function _lookup( $matrix_id, $checklist_id ) { $stmt = 'RisicoAnalyse::_lookup'; $this->dbex->prepare( $stmt, 'SELECT * FROM bt_risicoanalyses WHERE checklist_id = ? AND klant_id = ? AND matrix_id = ?', $this->db ); $res = $this->dbex->execute( $stmt, array( $checklist_id, get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, $matrix_id ), false, $this->db ); if ($res->num_rows() == 0) { $res->free_result(); return null; } else { $data = reset( $res->result() ); $res->free_result(); return new RisicoAnalyse( $data->id, $data->checklist_id, $data->gemaakt_op, $data->matrix_id ); } } // creates new risicoanalyse in db, throws exception on failure. // NOTE: does NOT read from or write to $this->cache private function _create( $matrix_id, $checklist_id ) { // The below query is now "Oracle-safe" // create in database $stmt = 'RisicoAnalyse::_create1'; $this->dbex->prepare( $stmt, 'INSERT INTO bt_risicoanalyses (checklist_id, klant_id, matrix_id) VALUES (?, ?, ?)', $this->db ); $this->dbex->prepare_with_insert_id( $stmt, 'INSERT INTO bt_risicoanalyses (checklist_id, klant_id, matrix_id) VALUES (?, ?, ?)', $this->db, $last_insert_id ); $res = $this->dbex->execute( $stmt, array( $checklist_id, get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, $matrix_id ), false, $this->db ); if (!$res) throw new Exception( 'Fout bij aanmaken risicoanalyse in de database.' ); $risicoanalyse_id = (get_db_type() == 'oracle') ? $last_insert_id : $this->db->insert_id(); // create default effecten in database $stmt = 'RisicoAnalyse::_create2'; $this->dbex->prepare( $stmt, 'INSERT INTO bt_risicoanalyse_effecten (risicoanalyse_id, effect, waarde, sortering) VALUES (?, ?, 1, ?)', $this->db ); $effecten = array( 'Letsel', 'Gebouwbeschadiging', 'Schoonheid', 'Gezondheid', 'Overlast van en naar derden', 'Sociale achteruitgang', 'Milieu', 'Ruimtelijke ordening', 'Naleefgedrag' , ); foreach ($effecten as $i => $effect) $this->dbex->execute( $stmt, array( $risicoanalyse_id, $effect, $i+1 ), false, $this->db ); // lookup regularly $ra = $this->_lookup( $matrix_id, $checklist_id ); if (!$ra) throw new Exception( 'Fout bij ophalen nieuw aangemaakte risicoanalyse.' ); return $ra; } public function delete( $matrix_id, $checklist_id ) { $stmt = 'RisicoAnalyse::delete'; $this->dbex->prepare( $stmt, 'DELETE FROM bt_risicoanalyses WHERE checklist_id = ? AND klant_id = ? AND matrix_id = ? LIMIT 1', $this->db ); $args = array( $checklist_id, get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, $matrix_id ); $res = $this->dbex->execute( $stmt, $args, false, $this->db ); if (!$res) throw new Exception( 'Fout bij verwijderen risicoanalyse uit de database.' ); unset( $this->cache[$matrix_id][$checklist_id] ); } public function get_db() { return $this->db; } } class RisicoAnalyse { private $id; private $checklist_id; private $checklist = null; private $matrix_id; private $gemaakt_op; private $effecten = null; // becomes array after first get_ call private $waarden = null; // becomes array after first get_ call private $waarden_dirty = array(); private $kansen = null; // becomes array after first get_ call private $kansen_dirty = array(); private $model; private $handler = null; public function __construct( $id, $checklist_id, $gemaakt_op, $matrix_id ) { $this->id = $id; $this->checklist_id = $checklist_id; $this->gemaakt_op = $gemaakt_op; $this->matrix_id = $matrix_id; $checklist = $this->get_checklist(); if (!$checklist) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id . ' in risicoanalyse.' ); $this->model = $checklist->get_checklistgroep()->risico_model; $this->handler = RisicoAnalyseHandlerFactory::create($this->model, $this->id); } public function get_model() { return $this->model; } public function get_handler() // risico analyse handler, see RisicoAnalyseHandler interface { return $this->handler; } public function is_complete( array $hoofdgroepen) { // make sure all data is loaded locally $this->get_waarde( -1, -1 ); $this->get_kans( -1 ); // check if all waarden are set and valid foreach ($hoofdgroepen as $hoofdgroep) foreach ($this->get_effecten() as $effect) if ($this->get_waarde( $hoofdgroep->id, $effect->get_id() ) <= 0) return false; // check if all kansen are set and valid foreach ($hoofdgroepen as $hoofdgroep) { $kans = $this->handler->kans_data_to_kans_value($this->get_kans( $hoofdgroep->id )); if ($kans <= 0) return false; } // complete! return true; } public function get_gemaakt_op() { return $this->gemaakt_op; } public function get_checklist_id() { return $this->checklist_id; } public function get_matrix_id() { return $this->matrix_id; } public function get_checklist() { if (is_null( $this->checklist )) $this->checklist = get_instance()->checklist->get( $this->checklist_id ); return $this->checklist; } public function get_effecten() { if (!is_array( $this->effecten )) { $this->effecten = array(); $db = get_instance()->risicoanalyse->get_db(); $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyse::get_effecten'; $dbex->prepare( $stmt, 'SELECT * FROM bt_risicoanalyse_effecten WHERE risicoanalyse_id = ? ORDER BY sortering', $db ); $res = $dbex->execute( $stmt, array( $this->id ), false, $db ); foreach ($res->result() as $row) $this->effecten[ $row->id ] = new RisicoAnalyseEffect( $row->id, $row->effect, $row->waarde, $row->sortering ); $res->free_result(); } return $this->effecten; } public function delete_effect( $id ) { $this->get_effecten(); $db = get_instance()->risicoanalyse->get_db(); $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyse::get_effecten'; $dbex->prepare( $stmt, 'DELETE FROM bt_risicoanalyse_effecten WHERE id = ?', $db ); $res = $dbex->execute( $stmt, array( $id ), false, $db ); if (!$res) throw new Exception( 'Fout bij verwijderen risico analyse effect.' ); unset( $this->effecten[$id] ); } public function add_effect( $effect, $waarde ) { $this->get_effecten(); $sortering = empty( $this->effecten ) ? 1 : (reset( array_reverse( $this->effecten ) )->get_sortering() + 1); // The below query is now "Oracle-safe" $db = get_instance()->risicoanalyse->get_db(); $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyse::get_effecten'; $dbex->prepare_with_insert_id( $stmt, 'INSERT INTO bt_risicoanalyse_effecten (risicoanalyse_id, effect, waarde, sortering) VALUES (?, ?, ?, ?)', $db, $last_insert_id ); $res = $dbex->execute( $stmt, array( $this->id, $effect, $waarde, $sortering ), false, $db ); if (!$res) throw new Exception( 'Fout bij opslaan nieuwe risico analyse effect.' ); $id = (get_db_type() == 'oracle') ? $last_insert_id : $db->insert_id(); $this->effecten[ $id ] = new RisicoAnalyseEffect( $id, $effect, $waarde, $sortering ); } function get_risico( $hoofdgroep_id ) { $kans = $this->handler->kans_data_to_kans_value($this->get_kans( $hoofdgroep_id )); return $kans * $this->get_gemiddelde( $hoofdgroep_id ); } function get_kansen() { if (!is_array( $this->kansen )) $this->get_kans( null ); return $this->kansen; } function get_kans( $hoofdgroep_id ) { if (!is_array( $this->kansen )) { $this->kansen = $this->handler->get_kansen(); } if (isset( $this->kansen[ $hoofdgroep_id ] )) return $this->kansen[ $hoofdgroep_id ]; return 0; } function get_gemiddelde( $hoofdgroep_id ) { $effecten = $this->get_effecten(); $totaal = 0; $delen_door = 0; foreach ($effecten as $effect) { $val = $this->get_waarde( $hoofdgroep_id, $effect->get_id() ); if (strlen( strval( $val ) )) { $totaal += $val * $effect->get_waarde(); $delen_door += $effect->get_waarde(); } } if ($delen_door) return $totaal / $delen_door; return 0; } function get_waarden() { if (!is_array( $this->waarden )) $this->get_waarde( null, null ); return $this->waarden; } function get_waarde( $hoofdgroep_id, $effect_id ) { if (!is_array( $this->waarden )) { $this->waarden = array(); $db = get_instance()->risicoanalyse->get_db(); $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyse::get_waarde'; $dbex->prepare( $stmt, 'SELECT hoofdgroep_id, risicoanalyse_effect_id, waarde FROM bt_risicoanalyse_waardes WHERE risicoanalyse_id = ?', $db ); $res = $dbex->execute( $stmt, array( $this->id ), false, $db ); foreach ($res->result() as $row) { if (!isset( $this->waarden[ $row->hoofdgroep_id ] )) $this->waarden[ $row->hoofdgroep_id ] = array(); $this->waarden[ $row->hoofdgroep_id ][ $row->risicoanalyse_effect_id ] = $row->waarde; } $res->free_result(); } if (isset( $this->waarden[ $hoofdgroep_id ] )) if (isset( $this->waarden[ $hoofdgroep_id ][ $effect_id ] )) return $this->waarden[ $hoofdgroep_id ][ $effect_id ]; return ''; } function set_waarde( $hoofdgroep_id, $effect_id, $waarde ) { if (!isset( $this->waarden[ $hoofdgroep_id ] )) $this->waarden[ $hoofdgroep_id ] = array(); if (!isset( $this->waarden[ $hoofdgroep_id ][ $effect_id ] ) || $this->waarden[ $hoofdgroep_id ][ $effect_id ] != $waarde) { // store in list that keeps track of changes to DB if (!isset( $this->waarden_dirty[ $hoofdgroep_id ] )) $this->waarden_dirty[ $hoofdgroep_id ] = array(); $this->waarden_dirty[ $hoofdgroep_id ][ $effect_id ] = $waarde; // store locally $this->waarden[ $hoofdgroep_id ][ $effect_id ] = $waarde; } } function delete_waarde( $hoofdgroep_id, $effect_id ) { if (isset( $this->waarden[ $hoofdgroep_id ][ $effect_id ] )) { // set to remove in DB $this->waarden_dirty[ $hoofdgroep_id ][ $effect_id ] = null; // remove locally unset( $this->waarden[ $hoofdgroep_id ][ $effect_id ] ); } } function set_kans( $hoofdgroep_id, $kans ) { if (!isset( $this->kansen[ $hoofdgroep_id ] ) || $this->kansen[ $hoofdgroep_id ] != $kans) { // store in list that keeps track of changes to DB $this->kansen_dirty[ $hoofdgroep_id ] = $kans; // store locally $this->kansen[ $hoofdgroep_id ] = $kans; } } function update_db_waarden( $db ) { if (!empty( $this->waarden_dirty )) { $db = get_instance()->risicoanalyse->get_db(); $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyse::update_db_waarden'; //$dbex->prepare( $stmt, 'REPLACE INTO bt_risicoanalyse_waardes (waarde, risicoanalyse_id, hoofdgroep_id, risicoanalyse_effect_id) VALUES (?,?,?,?)', $db ); $dbex->prepare_replace_into( $stmt, 'REPLACE INTO bt_risicoanalyse_waardes (waarde, risicoanalyse_id, hoofdgroep_id, risicoanalyse_effect_id) VALUES (?,?,?,?)', $db, array('id', 'risicoanalyse_id', 'hoofdgroep_id', 'risicoanalyse_effect_id') ); $stmtdel = 'RisicoAnalyse::update_db_waarden::delete'; $dbex->prepare( $stmtdel, 'DELETE FROM bt_risicoanalyse_waardes WHERE risicoanalyse_id = ? AND hoofdgroep_id = ? AND risicoanalyse_effect_id = ?', $db ); if (is_array($this->waarden_dirty)) foreach ($this->waarden_dirty as $hoofdgroep_id => $effecten) foreach ($effecten as $effect_id => $waarde ) // if $waarde is null, then perform delete! if (is_null( $waarde )) { if (!$dbex->execute( $stmtdel, array( $this->id, $hoofdgroep_id, $effect_id ), false, $db )) throw new Exception( 'Fout bij verwijderen van een ingevoerde waarde uit risicoanalyse in database.' ); } else { if (!$dbex->execute( $stmt, array( $waarde, $this->id, $hoofdgroep_id, $effect_id ), false, $db )) throw new Exception( 'Fout bij opslaan van ingevoerde waarden van risicoanalyse in database.' ); } $this->waarden_dirty = array(); } } function update_db_kansen( $db ) { if (!empty( $this->kansen_dirty )) { $this->handler->store_kansen($this->kansen_dirty); $this->kansen_dirty = array(); } } function get_prioriteit( $hoofdgroep_id ) { $risico = $this->get_risico( $hoofdgroep_id ); return $this->handler->get_risico_classificatie( $risico ); } function create_prioriteitstelling( $matrix_id, $db ) { $ps = get_instance()->prioriteitstelling->lookup_or_create( $matrix_id, $this->get_checklist_id() ); $ps->get_waarde( -1 ); // make sure all data is loaded, so DB can be updated better foreach ($this->get_checklist()->get_hoofdgroepen() as $hoofdgroep) { foreach ($hoofdgroep->get_hoofdthemas() as $hoofdthema) $ps->set_waarde( $hoofdgroep->id, $hoofdthema['hoofdthema']->id, $this->get_prioriteit( $hoofdgroep->id ) ); } $ps->update_db( $db ); } } class RisicoAnalyseEffect { private $id; private $effect; private $waarde; private $sortering; public function __construct( $id, $effect, $waarde, $sortering ) { $this->id = intval( $id ); $this->effect = strval( $effect ); $this->waarde = floatval( $waarde ); $this->sortering = intval( $sortering ); } public function get_id() { return $this->id; } public function get_effect() { return $this->effect; } public function get_waarde() { return $this->waarde; } public function get_sortering() { return $this->sortering; } public function update_db( $db, $new_effect=null, $new_waarde=null, $new_sortering=null ) { if ((is_null( $new_effect ) || $this->effect == $new_effect) && (is_null( $new_waarde ) || $this->waarde == $new_waarde) && (is_null( $new_sortering ) || $this->sortering == $new_sortering)) return; $dbex = get_instance()->dbex; $stmt = 'RisicoAnalyseEffect::update_db'; if (!$dbex->is_prepared( $stmt )) $dbex->prepare( $stmt, 'UPDATE bt_risicoanalyse_effecten SET effect = ?, waarde = ?, sortering = ? WHERE id = ?', $db ); $res = $dbex->execute( $stmt, array( is_null( $new_effect ) ? $this->effect : $new_effect, is_null( $new_waarde ) ? $this->waarde : $new_waarde, is_null( $new_sortering ) ? $this->sortering : $new_sortering, $this->get_id(), ), false, $db ); if (!$res) throw new Exception( 'Fout bij opslaan wijzigingen aan risico analyse effect.' ); } } class RisicoAnalyseHandlerFactory { static public function create($risico_model, $ra_id=null) { switch ($risico_model) { case 'generiek': $handler = new RisicoAnalyseGeneriek(); break; case 'fine_kinney': $handler = new RisicoAnalyseFineKinney(); break; default: throw new Exception( 'RisicoAnalyseHandlerFactory: onbekend risico model "' . $risico_model . '".' ); } if ($risico_model != $handler->get_risico_model()) throw new Exception( 'RisicoAnalyseHandlerFactory: risico model "' . $risico_model . '" mismatch.' ); if ($ra_id) $handler->set_risico_analyse_id($ra_id); return $handler; } } interface RisicoAnalyseHandler { /* General purpose */ function set_risico_analyse_id($ra_id); function get_risico_model(); /* RA library functions */ function get_kansen(); function kans_data_to_kans_value($kans_data); /* View functions */ function get_effect_values(); function get_kans_values(); function get_risico_shortnames(); function get_naleefgedrag(); /* Prioriteit functions */ function get_risico_classificatie($risico); } class RisicoAnalyseGeneriek implements RisicoAnalyseHandler { private $ra_id; private $CI; public function __construct() { $this->CI = get_instance(); } function set_risico_analyse_id($ra_id) { $this->ra_id = $ra_id; } function get_risico_model() { return 'generiek'; } function get_kansen() { $dbex = $this->CI->dbex; $stmt = 'RisicoAnalyse::get_kans'; $dbex->prepare( $stmt, 'SELECT hoofdgroep_id, kans FROM bt_risicoanalyse_kansen WHERE risicoanalyse_id = ?' ); $res = $dbex->execute( $stmt, array($this->ra_id) ); $kansen = array(); foreach ($res->result() as $row) $kansen[ $row->hoofdgroep_id ] = $row->kans; $res->free_result(); return $kansen; } function store_kansen(array $hoofdgroep_to_kansen_data) { if (!empty($hoofdgroep_to_kansen_data)) { $dbex = $this->CI->dbex; $stmt = 'RisicoAnalyse::update_db_kansen'; $dbex->prepare_replace_into( $stmt, 'REPLACE INTO bt_risicoanalyse_kansen (kans, risicoanalyse_id, hoofdgroep_id) VALUES (?, ?, ?)', null, array('id', 'risicoanalyse_id', 'hoofdgroep_id') ); foreach ($hoofdgroep_to_kansen_data as $hoofdgroep_id => $kans) if (!$dbex->execute( $stmt, array( $kans, $this->ra_id, $hoofdgroep_id ))) throw new Exception( 'Fout bij opslaan van kansen van risicoanalyse in database.' ); $this->kansen_dirty = array(); } } function kans_data_to_kans_value($kans_data) { return $kans_data; } function get_effect_values() { return null; } function get_kans_values() { return null; } function get_risico_shortnames() { return array( 'zeer_laag' => 'S', 'laag' => '1', 'gemiddeld' => '2', 'hoog' => '3', 'zeer_hoog' => '4', ); } function get_risico_classificatie($risico) { if ($risico <= 3) return 'zeer_laag'; if ($risico <= 6) return 'laag'; if ($risico <= 12) return 'gemiddeld'; if ($risico <= 20) return 'hoog'; return 'zeer_hoog'; } function get_naleefgedrag() { return 'Kans uit naleefgedrag'; } } class RisicoAnalyseFineKinney implements RisicoAnalyseHandler { private $ra_id; private $CI; public function __construct() { $this->CI = get_instance(); } function set_risico_analyse_id($ra_id) { $this->ra_id = $ra_id; } function get_risico_model() { return 'fine_kinney'; } function get_kansen() { $dbex = $this->CI->dbex; $stmt = 'RisicoAnalyse::get_kans'; $dbex->prepare( $stmt, 'SELECT hoofdgroep_id, fine_kinney_waarschijnlijkheid, fine_kinney_blootstelling FROM bt_risicoanalyse_kansen WHERE risicoanalyse_id = ?' ); $res = $dbex->execute( $stmt, array($this->ra_id) ); $kansen = array(); foreach ($res->result() as $row) $kansen[ $row->hoofdgroep_id ] = array( 'waarschijnlijkheid' => $row->fine_kinney_waarschijnlijkheid, 'blootstelling' => $row->fine_kinney_blootstelling, ); $res->free_result(); return $kansen; } function store_kansen(array $hoofdgroep_to_kansen_data) { if (!empty($hoofdgroep_to_kansen_data)) { $dbex = $this->CI->dbex; $stmt = 'RisicoAnalyse::update_db_kansen'; $dbex->prepare_replace_into( $stmt, 'REPLACE INTO bt_risicoanalyse_kansen (fine_kinney_waarschijnlijkheid, fine_kinney_blootstelling, risicoanalyse_id, hoofdgroep_id) VALUES (?, ?, ?, ?)', null, array('id', 'risicoanalyse_id', 'hoofdgroep_id') ); foreach ($hoofdgroep_to_kansen_data as $hoofdgroep_id => $kans) { if (!$dbex->execute( $stmt, array( $kans['waarschijnlijkheid'], $kans['blootstelling'], $this->ra_id, $hoofdgroep_id ))) throw new Exception( 'Fout bij opslaan van kansen van risicoanalyse in database (F&K).' ); } $this->kansen_dirty = array(); } } function kans_data_to_kans_value($kans_data) { $w = floatval($kans_data['waarschijnlijkheid']); $b = floatval($kans_data['blootstelling']); return $w * $b; } function get_effect_values() { return array( '' => '', '100' => 'catastrofaal', '40' => 'ramp', '15' => 'zeer ernstig', '7' => 'aanzienlijk', '3' => 'belangrijk', '1' => 'gering_hinder', ); } function get_kans_values() { return array( 'waarschijnlijkheid' => array( '' => '', '10' => 'zeer_groot_bijna_zeker', '6' => 'groot_zeer_wel_mogelijk', '3' => 'gemiddeld_ongewoon_maar_mogelijk', '1' => 'klein_mogelijke_op_langere_termijn', '0.5' => 'zeer_klein_onwaarschijnlijk', '0.2' => 'vrijwel_onmogelijk_wel_denkbaar', '0.1' => 'zeer_onwaarschijnlijk_bijna_niet_denkbaar', ), 'blootstelling' => array( '' => '', '10' => 'voortdurend', '6' => 'regelmatig_dagelijks_tijdens_de_werkuren', '3' => 'af_en_toe_wekelijks_of_incidenteel', '2' => 'soms_maandelijks_meerdere_malen_per_jaar', '1' => 'zelden_enkele_malen_per_jaar', '0.5' => 'zeer_zelden_minder_dan_eens_per_jaar', ) ); } function get_risico_shortnames() { return array( 'zeer_laag' => 'A', 'laag' => 'M', 'gemiddeld' => 'B', 'hoog' => 'H', 'zeer_hoog' => 'Z', ); } function get_risico_classificatie($risico) { if ($risico < 20) return 'zeer_laag'; if ($risico < 70) return 'laag'; if ($risico < 200) return 'gemiddeld'; if ($risico < 400) return 'hoog'; return 'zeer_hoog'; } function get_naleefgedrag() { return 'Waarschijnlijkheid uit naleefgedrag'; } } <file_sep>-- voeg veld toe voor gebruiker_id, initieel NULL is toegestaan ALTER TABLE `deelplan_vraag_geschiedenis` ADD `gebruiker_id` INT NULL DEFAULT NULL, ADD INDEX ( `gebruiker_id` ); ALTER TABLE `deelplan_vraag_geschiedenis` ADD FOREIGN KEY ( `gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE ; -- werk database bij UPDATE `deelplan_vraag_geschiedenis` SET `gebruiker_id` = ( SELECT DISTINCT(do.gebruiker_id) FROM deelplannen de JOIN dossiers do ON de.dossier_id = do.id WHERE de.id = deelplan_vraag_geschiedenis.deelplan_id ); -- haal mogelijk tot zetten van NULL weer weg ALTER TABLE `deelplan_vraag_geschiedenis` CHANGE `gebruiker_id` `gebruiker_id` INT( 11 ) NOT NULL ; <file_sep><? load_view( 'header.php' ); ?> <h2>PDF import verzoek mislukt.</h2> Helaas kan uw verzoek momenteel niet verwerkt worden... onze excuses. <? load_view( 'footer.php' ); ?> <file_sep>BRISToezicht.Toets.Form = { storing: false, autoStoreHandle: null, form: null, nextUnique: 0, externalUploads: $(), initialize: function() { this.form = $('form[name=form]'); this.startAutoStore(); this.updateSyncOverview(); var window_width=$(window).width(); var window_height=$(window).height(); if(window_width>992){ $("#nlaf_ViewImage").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("#nlaf_PDFAnnotator").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("#nlaf_ToezichtVoortgangPanel").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("div#nlaf_ToezichtVoortgangPanel>div:nth-child(2)").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); } $( window ).resize(function() { if(window_width>992){ $("#nlaf_ViewImage").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("#nlaf_PDFAnnotator").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("#nlaf_ToezichtVoortgangPanel").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); $("div#nlaf_ToezichtVoortgangPanel>div:nth-child(2)").height($(window).height()-$('div#nlaf_Header').outerHeight()-$("#nlaf_GreenBar").outerHeight()); } else { $("#nlaf_ViewImage").height("inherit"); $("#nlaf_PDFAnnotator").height("inherit"); $("#nlaf_ToezichtVoortgangPanel").height("inherit"); } }); }, startAutoStore: function() { if (this.autoStoreHandle) { clearTimeout( this.autoStoreHandle ); this.autoStoreHandle = null; } this.autoStoreHandle = setTimeout( function() { BRISToezicht.Toets.Form.attemptStore( false ); }, 30*1000 /* auto-store every 30 seconds */ ); }, addStoreOnceData: function( value ) { var name = 'extra_commands[' + (++this.nextUnique) + ']'; var target = this.form.find('.store-once'); var input = $(document.createElement( 'input' )); input.attr( 'name', name ); input.attr( 'type', 'hidden' ); input.attr( 'value', value ); target.append( input ); BRISToezicht.DirtyStatus.updateState(); this.updateSyncOverview(); }, haveStoreOnceData: function() { return this.form.find('.store-once').children().size() > 0; }, haveUploads: function() { return this.getUploads().size() > 0; }, getUploads: function() { // walk over the list of external uploads, and see if they are still inside the DOM // if one is not, it's been succesfully uploaded! elementInDOM = function(e) { if (e) { while (e = e.parentNode) { if (e == document) { return true; } } } return false; }; var newExternalUploads = $(); this.externalUploads.each(function(){ if (elementInDOM( this )) newExternalUploads = newExternalUploads.add( $(this) ); }); this.externalUploads = newExternalUploads; return this.form.find('input[type=file][action]').add( this.externalUploads ); }, /* specified input should have an 'action' attribute which may be safely set into its form. */ registerExternalUpload: function( input ) { this.externalUploads = this.externalUploads.add( input ); BRISToezicht.DirtyStatus.updateState(); this.updateSyncOverview(); }, removeStoreOnceData: function() { this.form.find('.store-once').html( '' ); }, getFormPostData: function( root ) { if (!root) root = this.form; var postdata = {}; root.find( 'input, select' ).each(function(){ // het NAME element moet aanwezig zijn (sommigen hebben dat bewust niet) if (this.name) { // als er een type is (dus geen select!) if (this.type) { // sla niet-geselecteerde radio buttons over if (this.type.toUpperCase()=='RADIO' && !this.checked) return; // sla files over if (this.type.toUpperCase()=='FILE') return; } // geef DEBUG waarschuwing als er dubbele postdata elementen zijn /* if (typeof( postdata[ this.name ] ) != 'undefined') alert( 'Waarschuwing: dubbel element naam ' + this.name + ' in form!' ); */ // sla element op postdata[ this.name ] = $(this).val(); } }); return postdata; }, startNextUpload: function( user_started ) { //jd('--- function: startNextUpload --- '); // we gaan het FORM posten in een iframe, maar om te voorkomen dat alles in 1x gepost // wordt en potentieel PHP/server limieten raakt, doen we ze stuk voor stuk; // als we een <input type="file">-element op DISABLED zetten, wordt ie niet gesubmit; // zodoende zetten we ze allemaal op DISABLED, behalve de eerste // bij succes wordt dit element vervolgens verwijderd, bij een fout proberen we het // later nog eens var allUploads = this.getUploads(); if (!allUploads.size()) { return; } var currentUpload = $(allUploads[0]); // do disable magic allUploads.attr( 'disabled', 'disabled' ); currentUpload.removeAttr( 'disabled' ); // stel het formulier in op de juiste action target var form = currentUpload.parents('form[name=form]'); var action = currentUpload.attr( 'action' ) .replace( '#vraag_ids', currentUpload.attr( 'vraag_ids' ) ) .replace( '#deelplan_id', currentUpload.attr( 'deelplan_id' ) ) .replace( '#checklist_groep_id', currentUpload.attr( 'checklist_groep_id' ) ) .replace( '#checklist_id', currentUpload.attr( 'checklist_id' ) ) .replace( '#bouwnummer', currentUpload.attr( 'bouwnummer' ) ) ; form.attr( 'action', action ); // get extra attributes var onderwerp_id = currentUpload.attr( 'onderwerp_id' ); var vraag_ids = currentUpload.attr( 'vraag_ids' ); vraag_ids = vraag_ids.split( ',' ); // start nu de upload! BRISToezicht.Upload.start( form[0], function( result ){ //jd('+++ result +++'); //jd(result); form.removeAttr('action'); form.removeAttr('target'); result = result.split(";"); for (var j=0; j<result.length; j++){ if(result[j]){ if (!result[j].match( /^\d+\:(.*?)$/ ) && result[j] != 'OK') { /* if (user_started) { jd('+++ Fout user_started +++'); alert( 'Fout bij upload: ' + result ); } else { jd('+++ Fout not user_started +++'); alert( 'Fout bij upload: ' + result ); } */ // Return an error and remove the upload from DOM! // If we don't remove the upload from the DOM, the attemptStore call will in rapid succession continuously keep hammering at this // same error. Possibly we need to make a distinction in the way this is handled when a user explicitly tried to store something, vs. when it // gets called from the synchroniser, but for now we'll handle it this way. alert( 'Fout bij upload: ' + result[j] ); currentUpload.parent().remove(); } else { if (result != 'OK') { var description = RegExp.$1; // first match from last regexp var data = $.parseJSON( description ); // bouw nieuwe deelplanupload object var du = { vraagupload_id: data.id, filename: data.filename, url: data.url, thumbnail_url: data.thumbnail_url, has_thumbnail: data.has_thumbnail, delete_url: data.delete_url, uploaded_at: data.uploaded_at, auteur: data.auteur, datatype: 'foto/video' }; // werk de juiste vraag data bij var first = true; for (var i in vraag_ids) if (typeof( vraag_ids[i] ) != 'function') { vraag_id = vraag_ids[i]; vraagData = BRISToezicht.Toets.Vraag.getVraagData( onderwerp_id, vraag_id ); vraagData.deelplanuploads[data.id] = du; if (first) { // only register once if this upload is for more than one vraag! BRISToezicht.Toets.data.vraaguploads[data.id] = du; first = false; } } // voeg img toe voor deze foto $('<img class="bestand" width="430">') .appendTo( '.nlaf_TabContent .image-set' ) .attr( 'vraagupload_id', data.id ) .attr( 'src', data.url ) .data( 'image', du ); // remove upload from DOM! currentUpload.parent().remove(); // reselect vraag BRISToezicht.Toets.Vraag.reselect(); } else { // remove upload from DOM! currentUpload.parent().remove(); } } } } // update visuele status BRISToezicht.DirtyStatus.updateState(); // probeer meteen weer te storen! volgende file! BRISToezicht.Toets.Form.attemptStore(); }, function( result ) { // remove upload from DOM! currentUpload.parent().remove(); if ($.browser.msie) alert( 'Er is iets fout gegaan met uploaden vanwege een security probleem in Internet Explorer.' ); else alert( 'Er is iets fout gegaan met uploaden.' ); }); }, attemptStore: function( user_started ) { jd('--- function: attemptStore --- '); this.updateSyncOverview(); this.updateCurrentAction( '' ); // hoe we hier ook zijn terecht gekomen (automatisch of via gebruiker klik), // herstart de 30 seconden auto-store timer meteen this.startAutoStore(); // check if we may store right now var message = null; if (!BRISToezicht.NetworkStatus.getState()) message = 'Er is geen netwerk verbinding, u kunt nu niet opslaan.'; else if (BRISToezicht.Upload.uploading) message = 'Er is een upload bezig (foto of video), even geduld a.u.b.'; else if (this.storing) message = 'Uw werk wordt momenteel opgeslagen, even geduld a.u.b.'; // als er een fout is, dan stoppen we hier, afhankelijk van of de gebruiker // geklikt heeft, of dat dit een automatisch store actie is, tonen we wel // of niet een foutmelding. if (message) { if (user_started) alert( message ); return; } // als we niks te doen hebben, dan nu kappen var haveDirtyData = BRISToezicht.DirtyStatus.getState(); if (!haveDirtyData) return; // haal huidige netwerk modus op var mode = BRISToezicht.NetworkStatus.mode; // is '3g' of 'wifi' // zijn er file uploads te doen? zo ja, dan die nu eerst doen! if (BRISToezicht.Toets.Form.haveUploads() && mode == 'wifi') { // we gaan uploaden, dus zet "storing now" status BRISToezicht.DirtyStatus.setStateStoringNow(); // start file upload this.startNextUpload( user_started ); // ga voor nu niet verder in deze functie! this.updateCurrentAction( 'Foto uploaden ...' ); return; } // als we alleen maar 'dirty' zijn omdat er file uploads zijn, verder // niks, dan niks doen nu! wachten totdat netwerk modus 3g wordt! if (!BRISToezicht.DirtyStatus.getStateExceptUploads()) return; // bouw form data en url postdata = this.getFormPostData(); url = location.href; //debugger; // markeer als niet langer dirty, zodat de gebruiker TIJDENS het storen gewoon door kan // klikken, en de "dirty" flag geldig blijft als de gebruiker dit inderdaad doet; als // we pas NA het storen dirty terug op false zetten, kan het wezen dat we data "missen", // dat wil zeggen, data als niet-dirty markeren die het wel is! en dan niet opslaan! // // als er iets mis gaat met opslaan, wordt de dirty flag weer aan gezet! BRISToezicht.Toets.Vraag.markDirty( false ); BRISToezicht.DirtyStatus.setStateStoringNow(); this.updateCurrentAction( 'Vraaginformatie verzenden ...' ); // store! this.storing = true; $.ajax({ url: url, type: 'POST', data: postdata, dataType: 'json', success: function( data, jqXHR, textStatus ){ if (!user_started) { jd('+++ sitation 1 +++ '); BRISToezicht.Toets.Form.handleStoreResult( data.success ); } else { jd('+++ sitation 2 +++ '); BRISToezicht.Toets.Form.handleStoreResult( data.success, data.error || 'Opslagfout zonder nadere details.' ); } }, error: function() { if (user_started) { jd('+++ sitation 3 +++ '); BRISToezicht.Toets.Form.handleStoreResult( false, 'Fout bij communicatie met server.' ); } else { jd('+++ sitation 4 +++ '); BRISToezicht.Toets.Form.handleStoreResult( false ); } } }); }, handleStoreResult: function( success, error ) { this.updateCurrentAction( '' ); // whatever the result, we're no longer storing data this.storing = false; // show (optional) error message on failure, do nothing else if (!success) { // mark dirty, to be sure we will retry in the future BRISToezicht.Toets.Vraag.markDirty( true ); // error kan leeg gelaten worden om geen popups te geven bij automatische opslag if (error) alert( error ); } // success! else { // remove store once data this.removeStoreOnceData(); } // update storage state visually BRISToezicht.DirtyStatus.updateState(); BRISToezicht.Toets.Form.updateSyncOverview(); }, updateSyncOverview: function() { // haal data op var aantalOpdrachten = this.form.find('.store-once input').size(); var aantalFotos = this.getUploads().size(); var heeftVraagData = BRISToezicht.DirtyStatus.getStateExceptUploads(); // bouw string var kleur = aantalFotos > 0 ? 'red' : 'inherited'; var str = '<span style="color:' + kleur + '">' + aantalFotos + ' foto\'s</span> | ' + aantalOpdrachten + ' opdrachten' + (heeftVraagData ? ' | vraaginformatie' : ''); // zet het $('#nlaf_SyncOverview').html( str ); }, updateCurrentAction: function( actie ) { $('#nlaf_SyncCurrent').html( actie ); /* html(), niet text(), zodat we &uuml; kunnen gebruiken */ } }; <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.risicoanalyse_effecten::acties', 'Acties', '2013-10-18 15:45:22', 0), ('beheer.risicoanalyse_effecten::effect', 'Effect', '2013-09-17 15:47:39', 0), ('beheer.risicoanalyse_effecten::effecten', 'Effecten', '2013-09-17 15:47:35', 0), ('beheer.risicoanalyse_effecten::factor', 'Factor', '2013-09-17 15:48:00', 0), ('intro.index::opties', 'Opties', '2013-09-17 13:47:40', 0), ('prioriteit.gemiddeld', '2', '2013-09-17 15:45:20', 0), ('prioriteit.hoog', '3', '2013-09-17 15:45:20', 0), ('prioriteit.laag', '1', '2013-09-17 15:45:20', 0), ('prioriteit.zeer_hoog', '4', '2013-09-17 15:45:20', 0), ('prioriteit.zeer_laag', 'S', '2013-09-17 15:45:20', 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('beheer.risicoanalyse_effecten::acties', 'Acties', '2013-10-18 15:45:22', 0), ('toon.invul.vragen', 'Toon invulvragen', '2013-09-17 19:55:35', 0); <file_sep><div class="page"> <div id="header" class="menubar"> <span>BRISToezicht - Afsluiten</span> </div> <div class="objects"> <?=$objecten['result'] ?> </div> <div id="footer" class="menubar"> <form method="post"> <input type="hidden" name="page" value="dossiers"> <input id="dossiers" type="submit" value="Dossiers" hidden /> <label for="dossiers">Dossiers</label> </form> </div> </div><file_sep><?php class CI_SimpleMail { private $CI; private $_sender; public function __construct() { $this->CI = get_instance(); $this->_sender = config_item( 'mail_sender' ); } public function send( $subject, $text, array $recipients, array $cc=array(), array $bcc=array(), $content_type='text/plain', array $extra_headers=array(), $sender = null, $x_mailer = null) { if (empty( $recipients )) { throw new Exception( 'SimpleMail: lijst van ontvangers is leeg' ); } $headers = array( 'From: ' . ($sender ? $sender : $this->_sender), 'Reply-To: ' . ($sender ? $sender : $this->_sender), 'X-Mailer: '. ( isset($x_mailer) ? $x_mailer : 'BRIStoezicht/' . BRIS_TOEZICHT_VERSION), 'MIME-Version: 1.0', 'Content-type: ' . $content_type . '; charset=utf-8', ); if (!empty( $cc )) $headers[] = 'Cc: ' . implode( ', ', $cc ); if (!empty( $bcc )) $headers[] = 'Bcc: ' . implode( ', ', $bcc ); foreach ($extra_headers as $h) $headers[] = $h; return mail( implode( ', ', $recipients ), $subject, $text, implode( "\r\n", $headers ) ); } public function send_with_attachments( $subject, $text, array $recipients, array $cc=array(), array $bcc=array(), $sender=null, array $attachments=array() ) { $this->CI->load->library( 'email' ); if (empty( $recipients )) throw new Exception( 'SimpleMail: lijst van ontvangers is leeg' ); $this->CI->email->from( $sender ? $sender : $this->_sender ); $this->CI->email->reply_to( $sender ? $sender : $this->_sender ); $this->CI->email->to( $recipients ); $this->CI->email->cc( $cc ); $this->CI->email->bcc( $bcc ); $this->CI->email->subject( $subject ); $this->CI->email->message( $text ); $this->CI->email->set_mailtype( 'text' ); $tmpdir = '/tmp/bristoezicht-sendmail-temp-' . time() . '-' . mt_rand() . '/'; foreach ($attachments as $attachment) { if (!is_array( $attachment ) || !isset( $attachment['type'] )) throw new Exception( 'send_with_attachments: attachment is geen array' ); switch ($attachment['type']) { case 'contents': if (!is_dir( $tmpdir )) if (!(mkdir( $tmpdir, 0777, true ))) throw new Exception( 'send_with_attachments: fout bij aanmaken tijdelijke directory: ' . $tmpdir ); if (file_exists( $tmpdir . $attachment['filename'] )) throw new Exception( 'send_with_attachments: dubbele filenames in attachments niet toegestaan' ); if (!file_put_contents( $tmpdir . $attachment['filename'], $attachment['contents'] )) throw new Exception( 'send_with_attachments: fout bij wegschrijven tijdelijk bestand: ' . $tmpdir . $attachment['filename'] ); $this->CI->email->attach( $tmpdir . $attachment['filename'] ); break; case 'localfile': $this->CI->email->attach( $attachment['filename'] ); break; } } $res = $this->CI->email->send(); exec( 'rm -rf ' . escapeshellarg( $tmpdir ) ); return $res; } } <file_sep><? require_once 'base.php'; class VraagOpdrachtResult extends BaseResult { public function VraagOpdrachtResult( &$arr ){ parent::BaseResult( 'vraagopdracht', $arr ); } } class VraagOpdracht extends BaseModel { public function VraagOpdracht(){ parent::BaseModel( 'VraagOpdrachtResult', 'bt_vraag_opdrachten' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_by_vraag( $vraagId /* , $checklistGroepId, $checklistId */ ) { $vraagopdrachten = $this->db ->where('vraag_id', $vraagId ) // ->where('checklist_groep_id', $checklistGroepId ) // ->where('checklist_id', $checklistId ) ->order_by('opdracht') ->get( $this->_table ) ->result(); $result = array(); foreach( $vraagopdrachten as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } }// Class end <file_sep><? require_once 'base.php'; class WebserviceApplicatieBescheidenResult extends BaseResult { function WebserviceApplicatieBescheidenResult( &$arr ) { parent::BaseResult( 'webserviceapplicatiebescheiden', $arr ); } } class WebserviceApplicatieBescheiden extends BaseModel { function WebserviceApplicatieBescheiden() { parent::BaseModel( 'WebserviceApplicatieBescheidenResult', 'webservice_applicatie_bschdn', true ); } function get_for_webapplicatie_id( $webapplicatie_id ) { $stmt_name = 'WebserviceApplicatieBescheiden::get_for_webapplicatie_id'; $result = array(); $CI = get_instance(); $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE webservice_applicatie_id = ?' ); foreach ($this->convert_results( $CI->dbex->execute( $stmt_name, array( $webapplicatie_id ) ) ) as $wad) $result[ $wad->dossier_bescheiden_id ] = $wad; return $result; } function zet( $webservice_applicatie_id, $dossier_bescheiden_id, $laatst_bijgewerk_op ) { $stmt_name = 'webserviceapplicatiebescheiden::zet'; $CI = get_instance(); //$CI->dbex->prepare( $stmt_name, 'REPLACE INTO webservice_applicatie_bschdn (webservice_applicatie_id, dossier_bescheiden_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)' ); $CI->dbex->prepare_replace_into( $stmt_name, 'REPLACE INTO webservice_applicatie_bschdn (webservice_applicatie_id, dossier_bescheiden_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)', null, array('id', 'webservice_applicatie_id', 'dossier_bescheiden_id') ); return $CI->dbex->execute( $stmt_name, array( $webservice_applicatie_id, $dossier_bescheiden_id, $laatst_bijgewerk_op ) ); } } <file_sep><?php error_reporting(E_ALL ^ (E_STRICT|E_NOTICE) ); set_exception_handler(function($e){ echo $e->getTraceAsString() . "\n"; die( 'UNCAUGHT EXCEPTION: ' . $e->getMessage() . "\n" ); }); set_error_handler(function($errno, $errstr, $errfile, $errline) { if (error_reporting() & $errno) { if ($errno == 2 && preg_match( '/session/i', $errstr )) return; echo( 'PHP MESSAGE: ' . $errfile . ':' . $errline . ': ' . $errno . ' ' . $errstr . "\n" ); // debug_print_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); } }); require_once( APPPATH . '/controllers/cli/checkchecklist.php' ); require_once( APPPATH . '/controllers/cli/checkthemas.php' ); require_once( APPPATH . '/controllers/cli/checkutf8.php' ); require_once( APPPATH . '/controllers/cli/ssosynchronizer.php' ); require_once( APPPATH . '/controllers/cli/outlooksynchronizer.php' ); require_once( APPPATH . '/controllers/cli/planning-updater.php' ); require_once( APPPATH . '/controllers/cli/vraagupload2bescheidenconverter.php' ); require_once( APPPATH . '/controllers/cli/fillgrondslagtekstentabel.php' ); require_once( APPPATH . '/controllers/cli/annotatieschaler.php' ); require_once( APPPATH . '/controllers/cli/cleanup_verlopen_tokens.php' ); require_once( APPPATH . '/controllers/cli/opdrachtprocessor.php' ); require_once( APPPATH . '/controllers/cli/riepairimporter.php' ); require_once( APPPATH . '/controllers/cli/exportchecklistgroep.php' ); require_once( APPPATH . '/controllers/cli/databaseidcleanup.php' ); require_once( APPPATH . '/controllers/cli/wettekstfetcher.php' ); require_once( APPPATH . '/controllers/cli/dossiergeolocatieupdater.php' ); require_once( APPPATH . '/controllers/cli/foddextest.php' ); class Cli extends Controller { private $_checklistgroep = 'Slopen'; private $_kid = 1; // 1 (dev-Imotep), or 79 (dev-Lexerta) private $_uid = 1; // 1 (dev-foddie), or 137 (dev-Lexerta) // Set the following values globally, as two methods make use of them. private $max_allowed_convert_bescheiden_instances = 1; private $lock_file_convert_bescheiden_base = 'convert-bescheiden-instance-'; private $lock_file_convert_pdfa = 'convert-pdfa-run'; private $system_load_threshold = 3.00; public function __construct() { parent::__construct(); if (!IS_CLI) redirect(); while (ob_get_level()) ob_end_flush(); } public function oracletest() { echo "\n\nDBex Oracle specific test stuff:\n\n"; $this->CI = get_instance(); // Doesn't work: $this->CI->dbex->prepare( 'find', "SELECT * FROM bt_grondslag_teksten WHERE grondslag_id = ? AND artikel = ?" ); $res = $this->CI->dbex->execute( 'find', array( 1, '4.57' ) ); // $exists = $res->num_rows() > 0; echo "\n+ 1 Raw before:\n"; d($res); //echo "\n\n+ 2a Assoc:\n"; //d($res->_fetch_assoc()); //d($res->_fetch_assoc()); echo "\n\n+ 2b Object:\n"; d($res->_fetch_object()); d($res->_fetch_object()); echo "\n\n+ 3 Raw after:\n"; d($res); } public function cl_clg_lookup($vraag_id = 0) { echo "\n\nChecklist look-up voor vraag met ID: {$vraag_id}\n\n"; $this->CI = get_instance(); $query = "SELECT bl.checklist_groep_id AS checklist_groep_id, bl.id AS checklist_id FROM bt_vragen bv INNER JOIN bt_categorieen bc ON (bv.categorie_id = bc.id) INNER JOIN bt_hoofdgroepen bh ON (bc.hoofdgroep_id = bh.id) INNER JOIN bt_checklisten bl ON (bh.checklist_id = bl.id) WHERE bv.id = ?"; $this->CI->dbex->prepare( 'find', $query ); $res = $this->CI->dbex->execute( 'find', array( $vraag_id ) ); $cl_id = $clg_id = 0; foreach ($res->result() as $row) { $cl_id = $row->checklist_id; $clg_id = $row->checklist_groep_id; } echo "\nChecklist ID: {$cl_id} - checklistgroep ID: {$clg_id}\n\n"; } public function checklist_export($checklistGroepId, $checklistId = 0) { echo "Checklist exporter...\n"; echo "Exporting checklistgroep with ID: {$checklistGroepId}\n"; if ($checklistId > 0) { echo "Limiting to checklist with ID: {$checklistId}\n"; } $this->CI = get_instance(); // Prepare the main query that gets all of the data, with exception of the 'grondslagen' and 'artikelen'. $query_params = array($checklistGroepId); $query = "SELECT bg.naam AS checklist_groep_naam, bl.naam AS checklist_naam, bh.naam AS hoofdgroep_naam, bv.tekst AS vraag_tekst, COALESCE(bv.aanwezigheid, 0) AS prio, bht.naam AS hoofdthema, bt.thema AS thema, br.filename AS richtlijn, bva.aandachtspunt AS aandachtspunt, bv.toezicht_moment, bv.fase, bv.id AS vraag_id FROM bt_vragen bv INNER JOIN bt_categorieen bc ON (bv.categorie_id = bc.id) INNER JOIN bt_hoofdgroepen bh ON (bc.hoofdgroep_id = bh.id) INNER JOIN bt_checklisten bl ON (bh.checklist_id = bl.id) INNER JOIN bt_checklist_groepen bg ON (bl.checklist_groep_id = bg.id) LEFT JOIN bt_themas bt ON (bv.thema_id = bt.id) LEFT JOIN bt_hoofdthemas bht ON (bt.hoofdthema_id = bht.id) LEFT JOIN bt_vraag_rchtlnn bvr ON ((bv.gebruik_rchtlnn = 1) AND (bvr.vraag_id = bv.id)) LEFT JOIN bt_richtlijnen br ON (bvr.richtlijn_id = br.id) LEFT JOIN bt_vraag_ndchtspntn bva ON ((bv.gebruik_ndchtspntn = 1) AND (bva.vraag_id = bv.id)) WHERE bl.checklist_groep_id = ?"; if ($checklistId > 0) { $query .= " AND bl.id = ?"; $query_params[] = $checklistId; } $this->CI->dbex->prepare( 'find', $query ); $res = $this->CI->dbex->execute( 'find', $query_params ); // Prepare the helper query that gets the 'grondslagen' and 'artikelen'. This will be executed from within the loop that processes the results of the main query. $grondslagenQuery = "SELECT bg.grondslag, bgt.artikel FROM bt_vraag_grndslgn bvg INNER JOIN bt_grondslag_teksten bgt ON (bvg.grondslag_tekst_id = bgt.id) INNER JOIN bt_grondslagen bg ON (bgt.grondslag_id = bg.id) WHERE bvg.vraag_id = ?"; $this->CI->dbex->prepare( 'find_grondslagen', $grondslagenQuery ); $dataToExport = array(); foreach ($res->result() as $row) { // First initialise the row data set $dataRowToExport = array(); $dataRowToExport['Checklistgroep'] = ''; $dataRowToExport['Checklist'] = ''; $dataRowToExport['Hoofdgroep'] = ''; $dataRowToExport['Categorie'] = '?'; $dataRowToExport['Vraag'] = ''; $dataRowToExport['Prio S'] = ''; $dataRowToExport['Prio 1'] = ''; $dataRowToExport['Prio 2'] = ''; $dataRowToExport['Prio 3'] = ''; $dataRowToExport['Prio 4'] = ''; $dataRowToExport['Hoofdthema'] = ''; $dataRowToExport['Thema'] = ''; $dataRowToExport['Richtlijn'] = ''; $dataRowToExport['Aandachtspunt'] = ''; for ($i = 1 ; $i <= 10 ; $i++) { $dataRowToExport["Grondslag {$i}"] = ''; $dataRowToExport["Artikel {$i}"] = ''; } $dataRowToExport['Toezichtmoment'] = ''; $dataRowToExport['Fase'] = ''; // Then proceed to process and store the results. Start with the straightforward columns that require no manipulation. $dataRowToExport['Checklistgroep'] = strval($row->checklist_groep_naam); $dataRowToExport['Checklist'] = strval($row->checklist_naam); $dataRowToExport['Hoofdgroep'] = strval($row->hoofdgroep_naam); $dataRowToExport['Vraag'] = strval($row->vraag_tekst); $dataRowToExport['Hoofdthema'] = strval($row->hoofdthema); $dataRowToExport['Thema'] = strval($row->thema); $dataRowToExport['Richtlijn'] = strval($row->richtlijn); $dataRowToExport['Aandachtspunt'] = strval($row->aandachtspunt); $dataRowToExport['Toezichtmoment'] = strval($row->toezicht_moment); $dataRowToExport['Fase'] = strval($row->fase); //d($row); // Properly determine which 'prioriteiten' should be set and store them $prio = $row->prio; $prio_s = $prio_1 = $prio_2 = $prio_3 = $prio_4 = 0; //$prio_s = $prio_1 = $prio_2 = $prio_3 = $prio_4 = $prio; if ($prio > 0) { $prio_s = (($prio & 0x01) > 0); $prio_1 = (($prio & 0x02) > 0); $prio_2 = (($prio & 0x04) > 0); $prio_3 = (($prio & 0x08) > 0); $prio_4 = (($prio & 0x10) > 0); /* echo "Prioriteiten {$prio}:"; d($prio_s); d($prio_1); d($prio_2); d($prio_3); d($prio_4); * */ } /* $dataRowToExport['Prio S'] = intval($prio_s); $dataRowToExport['Prio 1'] = intval($prio_1); $dataRowToExport['Prio 2'] = intval($prio_2); $dataRowToExport['Prio 3'] = intval($prio_3); $dataRowToExport['Prio 4'] = intval($prio_4); * */ $dataRowToExport['Prio S'] = ($prio_s) ? 'S' : ''; $dataRowToExport['Prio 1'] = ($prio_1) ? '1' : ''; $dataRowToExport['Prio 2'] = ($prio_2) ? '2' : ''; $dataRowToExport['Prio 3'] = ($prio_3) ? '3' : ''; $dataRowToExport['Prio 4'] = ($prio_4) ? '4' : ''; // The 'Grondslagen' and 'Artikelen' require a helper query, as they have a variable amount of occurences. unset($resGrondslagen); /* for ($i = 1 ; $i <= 10 ; $i++) { $grondslag_str = "grondslag_{$i}"; $artikel_str = "artikel_{$i}"; $$grondslag_str = $$artikel_str = ''; } * */ $resGrondslagen = $this->CI->dbex->execute( 'find_grondslagen', array($row->vraag_id) ); $i = 0; foreach ($resGrondslagen->result() as $rowGrondslagen) { //d($rowGrondslagen); $i++; /* $grondslag_str = "grondslag_{$i}"; $artikel_str = "artikel_{$i}"; $$grondslag_str = $rowGrondslagen->grondslag; $$artikel_str = $rowGrondslagen->artikel; * */ // Careful here! // Some questions have more than 10 grondslagen defined, but the import file only allows 10, so limit it! if ($i <= 10) { $dataRowToExport["Grondslag {$i}"] = strval($rowGrondslagen->grondslag); $dataRowToExport["Artikel {$i}"] = strval($rowGrondslagen->artikel); } } /* if (!empty($grondslag_1)) { for ($i = 1 ; $i <= 10 ; $i++) { $grondslag_str = "grondslag_{$i}"; $artikel_str = "artikel_{$i}"; echo "Grondslag {$i}: " . $$grondslag_str . "\n"; echo "Artikel {$i}: " . $$artikel_str . "\n"; } } * */ // Finally add the properly constructed row data to the set of complete data. $dataToExport[] = $dataRowToExport; } // Now that we have properly constructed the entire data set write it out to a CSV file. //d($dataToExport); if (!empty($dataToExport)) { // Brute-force create (or truncate) a file. $filename = "checklistgroep_{$checklistGroepId}_export.csv"; echo "Creating CSV file {$filename}\n"; $fp = fopen($filename, 'w'); // Specify a CSV delimiter $delimiter = "\t"; $enclosed_by = '"'; // Write a row with headers for the export. Simply use the array keys of the first row for this. fputcsv($fp, array_keys($dataToExport[0]), $delimiter); // Now add the data of the retrieved rows. foreach ($dataToExport as $dataRowToExport) { //$values_to_write = array_values($dataRowToExport); fputcsv($fp, array_values($dataRowToExport), $delimiter, $enclosed_by); } // Close the file fclose($fp); } echo "Done.\n"; } // This method was developed specifically for Berkelland (live klantId value = 86), but who knows... Maybe someday it is desired for other clients too (or just for // testing it), so we pass the klantId as an optional parameter public function bag_data_export($klantId = 86) { echo "BAG data exporter...\n"; $this->CI = get_instance(); // Set the various paths etc. that we will need. Make sure they exist or can be created, //$base_import_path = APPPATH . '../sql-dump/import/Bunnik/'; $base_export_path = APPPATH . '../files/csv_export/'; $csv_file_name = $base_export_path . "bag_data_{$klantId}_export.csv"; if (!is_dir( $base_export_path )) { if (!mkdir( $base_export_path, 0755, true )) { die( "Couldn't create directory: $base_export_path\n" ); } } // The main query that is constructed down below should implement the main logic in a generic way for all clients, but for some clients we (may) have to // implement specific additional conditions. We do so here, by constructing an 'additional where clause' when needed. $additionalWhereConditions = ''; if ($klantId == 86) { // Berkelland requested to only include 'deelplannen' that were added on or after November 1st. We can do this precisely as requested, but we can also include // those of which the progress was started after that date. For now, the former is done. //$additionalWhereConditions = " AND ( (t4.voortgang_gestart_op > '2014-10-31 23:59:59') OR (t3.aangemaakt_op > '2014-10-31 23:59:59') ) "; $additionalWhereConditions = " AND (t3.aangemaakt_op > '2014-10-31 23:59:59') "; } // Prepare the main query that gets all of the data. // Note that at present we have no distinction between 'verantwoordelijke_deelplan_start' and 'verantwoordelijke_deelplan_gereed'. At a later time (i.e. after // the data model has been extended) we should be able to properly fill these two fields. // The following two conditions are used for properly limiting the data to the set that should trigger a notification. Basically this means that the // set is limited to the dossiers/deelplannen/checklists for which an 'afmeldings' notification should be send (i.e. the first row of conditions) and // those for which an 'aanmeldings' notification should be send (i.e. the second row of conditions). // AND ( ((t2.gearchiveerd = 1) OR (t3.afgemeld = 1) OR (t4.voortgang_percentage = 100)) -- = afmeldconditie // OR ((t4.voortgang_percentage > 0) AND (t4.datum_voortgang_voor_het_eerst_groter_dan_0 IS NOT NULL)) ) -- BAG start aanmeldconditie $query_params = array($klantId); $query = "SELECT t2.id AS dossier_id, t2.laatst_bijgewerkt_op AS dossier_laatst_bewerkt_op, t1.volledige_naam AS dossier_eigenaar, t2.kenmerk AS dossier_kenmerk, t3.id AS deelplan_id, t3.naam AS deelplan_naam, t2.locatie_adres, t2.locatie_postcode, t2.locatie_woonplaats, t2.gearchiveerd AS dossier_gearchiveerd, t4.voortgang_percentage, t4.voortgang_gestart_op, t5.naam AS checklist_naam, t3.aangemaakt_op AS deelplan_aangemaakt_op, t3.afgemeld AS deelplan_afgemeld, t3.afgemeld_op AS deelplan_afgemeld_op, t6.volledige_naam AS verantwoordelijke_deelplan_start, t6.volledige_naam AS verantwoordelijke_deelplan_gereed FROM gebruikers t1 INNER JOIN dossiers t2 ON (t1.id = t2.gebruiker_id) LEFT JOIN deelplannen t3 ON (t2.id = t3.dossier_id) LEFT JOIN deelplan_checklisten t4 ON (t3.id = t4.deelplan_id) INNER JOIN bt_checklisten t5 ON (t5.id = t4.checklist_id) LEFT JOIN gebruikers t6 ON (t6.id = t4.toezicht_gebruiker_id) WHERE (t1.klant_id = ?) AND ( ((t2.gearchiveerd = 1) OR (t3.afgemeld = 1) OR (t4.voortgang_percentage = 100)) OR ((t4.voortgang_percentage > 0) AND (t4.voortgang_gestart_op IS NOT NULL)) ) {$additionalWhereConditions} ORDER BY t2.kenmerk, t3.naam"; $this->CI->dbex->prepare( 'bag_export_data', $query ); $res = $this->CI->dbex->execute( 'bag_export_data', $query_params ); // Initialise the header titles that should appear above the columns. Make sure to use a 'default' DB value as it is selected back as a key for each of the column names. //Rij 1: kolomhoofden beschrijven: √ dossierkenmerk, √ deelplankenmerk, √ adres, √ huisnummer, √ postcode, √ huisletter, √ woonplaats, datum gestart, datum gereed, verantwoordelijke deelplan start, verantwoordelijke deelplan gereed $headerColumns = array('dossier_kenmerk' => 'Dossierkenmerk', 'deelplan_naam' => 'Deelplankenmerk', 'checklist_naam' => 'Checklistnaam', 'locatie_adres' => 'Adres', 'locatie_postcode' => 'Postcode', 'locatie_woonplaats' => 'Woonplaats', 'voortgang_gestart_op' => 'Datum gestart', 'deelplan_afgemeld_op' => 'Datum gereed', 'verantwoordelijke_deelplan_start' => 'Verantwoordelijke deelplan start', 'verantwoordelijke_deelplan_gereed' => 'Verantwoordelijke deelplan gereed'); // Now extract the keys of the column names, since these are DB fields (or aliases) we can easily use them to quickly set-up each row with largely correct automatically // filled data, and we then only need to apply specific overrids afterwards in order to fix it up. $dataKeys = array_keys($headerColumns); // Now start filling the rows. Do this as much as possible in an automatic way and only apply overrides where necessary. $dataToExport = array(); foreach ($res->result() as $row) { // First initialise the row data set with automatically filled data. This should already cover most of the data we need to export. $dataRowToExport = array(); foreach($dataKeys as $dataKey) { $dataRowToExport["$dataKey"] = $row->$dataKey; } // Now apply specific overrides where necessary. if (is_null($dataRowToExport['voortgang_gestart_op'])) { $dataRowToExport['voortgang_gestart_op'] = 'Geen start geregistreerd'; } if (is_null($dataRowToExport['deelplan_afgemeld_op'])) { if ($row->dossier_gearchiveerd) { // NOTE: Using the last modification date of the dossier is dangerous as it is not completely guaranteed to be correct, since it's a DB field // that automatically gets updated upon every update. But, it's the best fallback value we have present at this time, so for now it'll have to do. $dataRowToExport['deelplan_afgemeld_op'] = $row->dossier_laatst_bewerkt_op; } else { $dataRowToExport['deelplan_afgemeld_op'] = 'Geen einde geregistreerd'; } } //d($dataRowToExport); // Finally add the properly constructed row data to the set of complete data. $dataToExport[] = $dataRowToExport; } // Now that we have properly constructed the entire data set write it out to a CSV file. //d($dataToExport); if (!empty($dataToExport)) { // Brute-force create (or truncate) a file. //$filename = "bag_data_{$klantId}_export.csv"; echo "Creating CSV file {$csv_file_name}\n"; $fp = fopen($csv_file_name, 'w'); // Specify a CSV delimiter $delimiter = "\t"; $enclosed_by = '"'; // Write a row with headers for the export. Simply use the array keys of the first row for this. //fputcsv($fp, array_keys($dataToExport[0]), $delimiter); fputcsv($fp, array_values($headerColumns), $delimiter); // Now add the data of the retrieved rows. foreach ($dataToExport as $dataRowToExport) { //$values_to_write = array_values($dataRowToExport); fputcsv($fp, array_values($dataRowToExport), $delimiter, $enclosed_by); } // Close the file fclose($fp); // Now that the file has been created and we know it to not be empty, we send it to the proper destination. // Note: this will definitely have a client specific handling! $this->CI->load->helper( 'ftpclient' ); // For Berkelland, we FTP the file to the same server as is being used for the SSO folder based synchronisation if ($klantId == 86) { try { // FTP specific settings for Berkelland $this->ftp = null; $this->ftp_host_name = '172.16.58.3'; $this->ftp_user_name = 'lexerta'; $this->ftp_password = '<PASSWORD>'; $this->ftp_directories_to_synchronise = array(); $this->ftp_dirs_to_sync_auto_determine = false; $this->ftp_start_directory = 'Werkmap/BAG_CSV'; $this->ftp_dir_style = 'linux'; $this->ftp_use_passive_mode = true; $this->refresh_export_files = true; # Open an FTP connection to the location where the export files are stored $this->ftp = new FtpClientHelper($this->ftp_host_name, $this->ftp_user_name, $this->ftp_password, $this->ftp_use_passive_mode); # This connection requires specific directory settings, so pass them along $this->ftp->initialise_directory_settings($this->ftp_directories_to_synchronise, $this->ftp_dirs_to_sync_auto_determine, $this->ftp_start_directory, $this->ftp_dir_style); # !!! temp, debug. show current directory contents. $this->ftp->ftp_list_dir_contents(); # Remove any and all .xls files from the target directory. if ($this->refresh_export_files) { $this->ftp->delete_files_from_directory($this->ftp_start_directory, '.csv'); } # Define the set of files to send. //$files_to_send = array($this->xls_output_file_name_locatie_dossiers, $this->xls_output_file_name_toezicht_zaken, $this->xls_output_file_name_handhaaf_zaken); $files_to_send = array($csv_file_name); # Send the files. $this->ftp->send_files($files_to_send); # Close the connnection when we are done. $this->ftp->close(); } catch (Exception $e) { echo "EXCEPTION when trying to send the export file by FTP: " . $e->getMessage() . "\n"; } } // if ($klantId == 86) } // if (!empty($dataToExport)) echo "Done.\n"; } public function bunniktellingen() { // Load the 'vraag' model $this->load->model( 'vraag' ); // Get the questions and other data that we need // For the task at hand, we need to consider the following two bt_checklist_groepen // 138: <NAME>, 1 dec 2012 // 139: <NAME>, 1 jan 2013 $clg_ids = array(138 => '<NAME>, 1 dec 2012', 139 => '<NAME>, 1 jan 2013'); // Define the filter criteria handily, so we can loop over it for our countings. // Structure: "hoofdgroep filter" => "question filter" $filter_criteria = array('Orienteringsgesprek' => 'mededeling start', 'Eindcontrole' => 'Gereedmelding ingediend'); foreach ($filter_criteria as $hg_filter_value => $question_filter_value) { // Loop over the required checklistgroepen and gather and count the data as needed for the respective hoofdgroep - question foreach ($clg_ids as $clg_id => $clg_naam) { echo "\n\n\nResultaten voor checklistgroep {$clg_naam} ($clg_id) - hoofdgroep '{$hg_filter_value}':\n\n"; // Get the 'checklisten' and 'hoofdgroepen' for the current 'checklistgroep' $clg_cl_hg_dataset_str = "clg_{$clg_id}_cl_hg_".strtolower($hg_filter_value); //$clg_138_cl_hg_orienteringsgesprek = array(); //$clg_139_cl_hg_orienteringsgesprek = array(); $clg_cl_hg_dataset = array(); // Data query, filtered by the hoogfdgroep filter value $clg_data_query = " SELECT clg.id AS clg_id, clg.naam AS clg_naam, cl.id AS cl_id, cl.naam AS cl_naam, cl.status AS cl_status, cl.sortering AS cl_sortering, hg.id AS hg_id, hg.checklist_id AS hg_cl_id, hg.naam AS hg_naam, hg.sortering AS hg_sortering FROM bt_hoofdgroepen hg INNER JOIN bt_checklisten cl ON (hg.checklist_id = cl.id) INNER JOIN bt_checklist_groepen clg ON (cl.checklist_groep_id = clg.id) WHERE (cl.checklist_groep_id = {$clg_id}) AND (hg.naam like '%{$hg_filter_value}%') ORDER BY clg.id, cl.sortering, hg.sortering"; $res = $this->db->query($clg_data_query); foreach ($res->result() as $row) { // Get the hoofdgroep ID $hg_id = $row->hg_id; // Now gather the data for that hoofdgroep and perform the counting $row->tellingen = array('Niet ingevuld' => 0); // For this set of data, we gather the questions and answers, get the proper 'status' (= 'waarde oordeel') text and perform our counts based on that $dv_data_query = " SELECT dv.status AS dv_status, dv.last_updated_at AS dv_date, v.id AS v_id, v.tekst AS v_tekst FROM deelplan_vragen dv INNER JOIN bt_vragen v ON (dv.vraag_id = v.id) WHERE dv.vraag_id IN ( SELECT v1.id FROM bt_vragen v1 WHERE v1.categorie_id IN ( SELECT c.id FROM bt_categorieen c WHERE c.hoofdgroep_id = {$hg_id} ) AND v1.tekst like '%{$question_filter_value}%' ) AND (YEAR(dv.last_updated_at) = 2013)"; $res2 = $this->db->query($dv_data_query); //echo "\n\n{$dv_data_query}\n\n"; //d($res2->result); foreach ($res2->result() as $row2) { if (is_null($row2->dv_status)) { $row->tellingen['Niet ingevuld']++; } else { // Get the vraag for the current row $vraag = $this->vraag->get($row2->v_id); $waarde_oordeel = $vraag->get_waardeoordeel( false, $row2->dv_status ); if (empty($row->tellingen["$waarde_oordeel"])) { $row->tellingen["$waarde_oordeel"] = 0; } $row->tellingen["$waarde_oordeel"]++; } } $res2->free_result(); // Directly echo the results echo "\n\nTellingen voor: {$row->clg_naam} - {$row->cl_naam}:\n"; foreach ($row->tellingen as $wo => $count) { echo "{$wo}: {$count} keer\n"; } // Store the row, including the counts, in the result set $clg_cl_hg_dataset[] = $row; } $res->free_result(); // Register the temporary array under the corresponding variable name that contains the checklistgroep ID $$clg_cl_hg_dataset_str = $clg_cl_hg_dataset; //d($$clg_cl_hg_orienteringsgesprek_str); } // foreach ($clg_ids as $clg_id => $clg_naam) } // foreach ($filter_criteria as $hg_filter_value => $question_filter_value) /* echo "\n\nAfter loop:\n\n"; d($clg_138_cl_hg_orienteringsgesprek); d($clg_139_cl_hg_orienteringsgesprek); d($clg_138_cl_hg_eindcontrole); d($clg_139_cl_hg_eindcontrole); * */ } public function login( $kid=null, $uid=null, $noisy=true ) { if ($this->login->logged_in()) $this->login->logout(); if (!is_null( $kid )) $this->_kid = intval( $kid ); if (!is_null( $uid )) $this->_uid = intval( $uid ); if ($noisy) echo ">>> LOGGING IN kid={$this->_kid} uid={$this->_uid} <<<\n"; if (!$this->login->login( $this->_uid, 0 )) throw new Exception( 'Login library call failed.' ); $this->session->set_userdata( 'kid', $this->_kid ); $this->session->set_userdata( 'klant_volledige_naam', 'kvolledige_naam' ); $this->session->set_userdata( 'do_inline_editing', false ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); if (!$gebruiker) throw new Exception( 'Successful login, but no logged in user!' ); if ($noisy) echo ">>> LOGIN CHECK: kid=" . $gebruiker->klant_id . ", uid=" . $gebruiker->id . "\n"; } public function checkchecklist( $checklist_id=null, $fix=false ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'categorie' ); $this->load->model( 'vraag' ); $this->load->model( 'deelplanvraagbescheiden' ); $this->load->model( 'thema' ); if (!$checklist_id) throw new Exception( 'Geen checklist ID opgegeven.' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldige checklist ID opgegeven.' ); $ccl = new CheckChecklist( $checklist ); $ccl->run( $fix ); } public function checkallechecklisten( $fix=false ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'categorie' ); $this->load->model( 'vraag' ); $this->load->model( 'deelplanvraagbescheiden' ); $this->load->model( 'thema' ); foreach ($this->checklist->all() as $checklist) { if ($checklist->beschikbaarheid == 'publiek-voor-iedereen') { $ccl = new CheckChecklist( $checklist ); $ccl->run( $fix ); } } } public function export_dossier() { $this->load->model( 'dossier' ); if (!($dossier = $this->dossier->get( 2119 ))) throw new Exception( 'Failed to load dossier 2119' ); $result = $dossier->export( 'standaard' ); echo 'Filename: ' . $result->get_filename() . "\n"; echo 'Content-Type: ' . $result->get_contenttype() . "\n"; echo 'File-Length: ' . strlen( $result->get_contents() ) . " bytes\n"; } public function export_all_dossiers() { $this->load->model( 'dossier' ); // get all dossiers $dossiers = array(); foreach ($this->dossier->all() as $dossier) if (!$dossier->gearchiveerd && !$dossier->verwijderd) $dossiers[] = $dossier; // close DB connection $this->db->close(); // foreach dossier, fork foreach ($dossiers as $dossier) { switch (pcntl_fork()) { case 0: // child! $this->db->initialize(); // login user for this dossier $gebruiker = $this->gebruiker->get( $dossier->gebruiker_id ); $this->login( $gebruiker->klant_id, $gebruiker->id ); // set default filter data $filter_data = array( 'onderdeel' => array( 'inleiding' => 'on', 'dossiergegevens' => 'on', 'documenten' => 'on', 'deelplannen' => 'on', 'samenvatting' => 'on', 'bevindingen' => 'on', 'bijlage-fotos' => 'on', 'bijlage-documenten-tekeningen' => 'on', 'bijlage-juridische-grondslag' => 'on', ), 'deelplan' => array( ), 'grondslag' => array( ), 'show-revisions' => 'on', ); $checklisten = array(); foreach ($dossier->get_deelplannen() as $j => $deelplan) { $filter_data['deelplan'][$deelplan->id] = 'on'; foreach ($deelplan->get_checklisten() as $checklist) { $checklisten[] = $checklist->checklist_id; $cg_id = $checklist->checklist_groep_id; if (!isset( $this->checklistgroep_grondslagen[$cg_id] )) foreach ($deelplan->get_grondslagen( $cg_id ) as $vraaggrondslagen) foreach ($vraaggrondslagen as $grondslag) if (!in_array( $grondslag->grondslag, $filter_data['grondslag'] )) $filter_data['grondslag'][$grondslag->grondslag] = 'on'; } } // export! echo 'DOSSIER: ' . $dossier->id . ' (user_id:' . $dossier->gebruiker_id . ')' . "\n"; echo 'DEELPLANNEN: ' . implode( ', ', array_keys( $filter_data['deelplan'] ) ) . "\n"; echo 'CHECKLISTEN: ' . implode( ', ', $checklisten ) . "\n"; $result = $dossier->export( 'standaard', $filter_data ); echo 'Filename: ' . $result->get_filename() . "\n"; echo 'Content-Type: ' . $result->get_contenttype() . "\n"; echo 'File-Length: ' . strlen( $result->get_contents() ) . " bytes\n"; echo "\n"; file_put_contents( 'Dossier ' . $dossier->id . ' - ' . $result->get_filename(), $result->get_contents() ); exit(0); case -1: // failed to fork :/ echo( "FAILED TO FORK :/\n" ); break; default: pcntl_wait( $status ); break; } } } // This can be called with the values 1, 5 and 15, giving the average loads of respectively the last 1, 5 or 15 minutes public function get_current_system_load($interval = 1, $silent = false) { // Assert an unsuccessful outcome of the call. $return_value = -1; if (!$silent) { echo "Obtaining current average server load for the past {$interval} minute(s).\n"; } // Use the "uptime" command for obtaining the load averages $uptime_cmd = "uptime"; $exec_return_value = shell_exec($uptime_cmd); // Parse the output. Note that on OS-X the text to look for is 'load averages:' whereas on Ubuntu it is 'load average:'. In order to have a version that is compatible with // both, we simply search for 'load average' and strip the known starts off the output. $pos = strpos(strtolower($exec_return_value), 'load average'); if ($pos === false) { // For some reason the 'load average' text was not found in the output, return with a -1 error return code. //return -1; if (!$silent) { echo "Failed to determine the server load values.\n"; } } else { // Get the last part of the output, starting at the 'load average' text. $load_averages_str = substr($exec_return_value, 0-(strlen($exec_return_value)-$pos)); //d($load_averages_str); // Now strip off the known starts of the output text. Also strip off any and all commas; Ubuntu does use commas, but OS-X for example does not. $load_averages_str = str_ireplace(array('load average: ', 'load averages: ', ','), '', $load_averages_str); //d($load_averages_str); // Now extract the three load values $load_averages = explode(' ', trim($load_averages_str)); // Now get the desired load average. Assume the caller passed a valid value. If not, simply revert to returning the value of the last minute. if ($interval == 15) { // Return the average load of the past 15 minutes $return_value = $load_averages[2]; } else if ($interval == 5) { // Return the average load of the past 5 minutes $return_value = $load_averages[1]; } else { // Return the average load of the past minute $return_value = $load_averages[0]; } if (!$silent) { echo "Determined load averages: 1 minute: {$load_averages[0]}, 5 minutes: {$load_averages[1]}, 15 minutes: {$load_averages[2]}\n"; echo "Returning requested value: {$return_value}\n"; } } // Finally, return the determined value return $return_value; } // public function get_current_system_load($interval = 1, $silent = false) // This method is intended to be run from a cron job, using a suitable 'limit' value. public function convert_pdf_to_pdfa( $limit = 0 ) { echo "\n\n>>> Starting PDF -> PDFA conversion at: " . date("Y-m-d H:i:s") . " <<<\n"; // Get the average system load of the last minute $current_system_load = $this->get_current_system_load(1); if ((float)$current_system_load > $this->system_load_threshold) { echo "The system load is currently {$current_system_load}. The maximum allowed load in order for this script to run is {$this->system_load_threshold}. Aborting current run.\n"; exit; } // Load the dossierbescheiden model $this->load->model( 'dossierbescheiden' ); // load filelock system $this->load->library( 'filelock' ); // See if we can obtain a filelock, if not, this process is already running, in which case we bail out. //$filelock = $this->filelock->create( 'convert-pdfa-run' ); $filelock = $this->filelock->create( $this->lock_file_convert_pdfa ); if ($filelock->try_lock() == LOCKFILE_SUCCESS) { // Check if any instance of the convert_bescheiden run is active. If it is, stand off and bail out. $convert_bescheiden_locks = array(); $outer_file_lock_name = ''; for ($i = 1 ; $i <= $this->max_allowed_convert_bescheiden_instances ; $i++) { //$outer_file_lock_name = 'convert-bescheiden-instance-' . $i; $outer_file_lock_name = $this->lock_file_convert_bescheiden_base . $i; echo "Attempting to obtain bescheiden conversion lock {$i} (file: {$outer_file_lock_name}). Status: "; // See if we can obtain a filelock, if not, the convert_bescheiden process is already running, in which case we bail out. $outer_filelock_str = 'outer_filelock_' . $i; $$outer_filelock_str = $this->filelock->create( $outer_file_lock_name ); if ($$outer_filelock_str->try_lock() == LOCKFILE_SUCCESS) { // We obtained the lock, store the lockfile object in the array. $convert_bescheiden_locks[] = $$outer_filelock_str; } else { // We could not obtain at least one of the locks, flag that the bescheiden conversion is probably running, clear all of the locks and exit. $filelock->unlock(); foreach ($convert_bescheiden_locks as $convert_bescheiden_lock) { $convert_bescheiden_lock->unlock(); } echo "Bescheiden conversion appears to be running. Skipping this convert_pdfa run...\n"; exit; } } echo ">>> Obtained all of the required locks. Performing PDF/A-1a conversion <<<\n\n"; // Find all PDF files for which no PDF/A copy exists yet $limit_str = (empty($limit)) ? '' : " LIMIT {$limit}"; $pdf_files_without_pdfa_query = "SELECT id, bestandsnaam, LOWER(SUBSTRING(bestandsnaam, -4)) AS file_extension FROM dossier_bescheiden WHERE has_pdfa_copy = 0 HAVING file_extension = '.pdf'" . $limit_str; $res = $this->db->query( $pdf_files_without_pdfa_query ); // Now loop over the results. Try to convert each one of them to PDF/A-1a format. echo ">>> Amount of files to convert: " . sizeof($res->result()) . " <<<\n\n"; $cnt = 0; foreach ($res->result() as $row) { // First get the dossierbescheiden as an object. $dossierbescheiden = $this->dossierbescheiden->get($row->id); // For now, we only generate 100% graphical PDF files for the VIIA users. Get the "klant ID" of the dossier and only force fully graphical PDFs // for the VIIA dossiers. //$generate_graphical_version = ($dossierbescheiden->get_dossier()->get_gebruiker()->klant_id == 202); $generate_graphical_version = true; $cnt++; echo ">>> Converting file {$cnt}: '{$dossierbescheiden->bestandsnaam}' with location: '" . $dossierbescheiden->get_file_location() . "'\n"; //d($dossierbescheiden->bestandsnaam); //d($dossierbescheiden->get_file_location()); // Convert the PDF file. Do not use 'force' and do not use the 'silent' mode. //$file_converted_succesfully = $this->dossierbescheiden->convert_pdf_to_optimised_pdfa($dossierbescheiden, false, false); $file_converted_succesfully = $this->dossierbescheiden->convert_pdf_to_optimised_pdfa($dossierbescheiden, $generate_graphical_version, false, false); //$file_converted_succesfully = $this->dossierbescheiden->convert_pdf_to_optimised_pdfa($dossierbescheiden, true, true, false); // !!! during development stage: force the conversion // If the file was successfully converted, we update the 'has_pdfa_copy' status to reflect this. if ($file_converted_succesfully) { $dossierbescheiden->has_pdfa_copy = 1; $dossierbescheiden->save(); } } $res->free_result(); // As a last step unconditionally remove the filelock when we're done $filelock->unlock(); // Unconditionalle unlock all of the convert_bescheiden loccks too. foreach ($convert_bescheiden_locks as $convert_bescheiden_lock) { $convert_bescheiden_lock->unlock(); } } else { echo "De PDF -> PDFA conversie of bescheiden conversie draait reeds. Deze PDFA conversie run wordt nu niet uitgevoerd.\n"; } echo "\n\n>>> Ending PDF -> PDFA conversion at: " . date("Y-m-d H:i:s") . " <<<\n"; } public function convert_bescheiden( $force=0 , $process_debilt=false ) { //mj 05-08-2015: record start time to determine if De Bilt can be run as well later in the script $timestart = time(); echo "\n\n>>> Starting bescheiden conversion at: " . date("Y-m-d H:i:s") . " <<<\n"; // Get the average system load of the last minute $current_system_load = $this->get_current_system_load(1); if ((float)$current_system_load > $this->system_load_threshold) { echo "The system load is currently {$current_system_load}. The maximum allowed load in order for this script to run is {$this->system_load_threshold}. Aborting current run.\n"; exit; } // load filelock system $this->load->library( 'filelock' ); // Specify how many instances of this script may run maximally at the same time. Note that this code will limit the amount of instances that are allowed to perform // a COMPLETE run. Within the body of such a run further individual locking (on a 'dossierbescheiden' level) also takes place to prevent simultaneously running tasks // from trying to convert the same files simulatenously. // Note that we can take this code further, if needed, for example by also adding checks to the maximum allowed lifetime of the lockfile (e.g. 15 minutes or so). This // Has not yet been implemented as we may not need it. //$max_allowed_instances = 3; //$max_allowed_instances = 1; // OJG (13-4-2015): Due to several occurences of extreme loads coming from the convert_bescheiden call, for now we only allow one active run at a time! $max_allowed_lifetime = 15; $outer_file_lock_success = false; $outer_file_lock_name = ''; //for ($i = 1 ; $i <= $max_allowed_instances ; $i++) for ($i = 1 ; $i <= $this->max_allowed_convert_bescheiden_instances ; $i++) { //$outer_file_lock_name = 'convert-bescheiden-instance-' . $i; $outer_file_lock_name = $this->lock_file_convert_bescheiden_base . $i; echo "Attempting to obtain outer lock {$i} (file: {$outer_file_lock_name}). Status: "; // See if we can obtain a filelock, if not, this process is already running, in which case we continue to check if we can get a lock with a higher number, // until we either succeed or the maximum allowed lock files have been exhausted. $outer_filelock = $this->filelock->create( $outer_file_lock_name ); if ( ($outer_filelock->try_lock() == LOCKFILE_SUCCESS) || $force) { // We obtained the lock, flag that status such that the script is allowed to do its real work and exit this loop. echo "SUCCESS\n"; $outer_file_lock_success = true; break; } else { echo "FAILED\n"; } } // If we successfully obtained the outer lock, we continue if ($outer_file_lock_success) { // Before starting the actual conversion, we try to get a lock with the name that is used for the PDF/A conversion. This is done to make reasonably sure the PDF/A // call stands off when we are converting bescheiden. This is done since both tasks are heavy. This way the server load is better spread. It is known that there // are all sorts of potential glitch situations in which case this locking trick doesn't work, and the both conversion calls can run at the same time, but most of the times // it is expected to work as planned, and that is sufficient for now. // Note: as both tasks are normally started from cron, we intentionally wait for 5 seconds first, so as to give precedence to the PDF/A conversion task, which is called // much less frequently than the convert_bescheiden call and which (to the contrary of convert_bescheiden) will exit very quickly if nothing needs to be done. sleep(5); echo "Attempting to obtain PDF/A-1a conversion file lock (file: {$this->lock_file_convert_pdfa}). Status: "; // See if we can obtain a filelock, if not, the PDF/A-1a conversion process is already running, in which case we bail out. $pdfa_conversion_filelock = $this->filelock->create( $this->lock_file_convert_pdfa ); if (!$force) { if ($pdfa_conversion_filelock->try_lock() != LOCKFILE_SUCCESS) { // We could not obtain the lock, flag that the PDF/A conversion is probably running, clear the convert_bescheiden lock and exit. $outer_filelock->unlock(); echo "PDF/A-1a conversion appears to be running. Skipping this convert_bescheiden run...\n"; exit; } } // init image processor (and data) $this->load->library( 'imageprocessor' ); $ip_modes = array( 'original', 'thumbnail', 'overview' ); // clear output buffers while (ob_get_level()) ob_end_flush(); // find all bescheiden zonder PNG $this->load->model( 'dossierbescheiden' ); // $bescheidenlijst = $this->dossierbescheiden->all(); $bescheidenlijst = array(); //$res = $this->db->query( 'SELECT id, bestandsnaam, png_status, length(bestand) as datasize FROM dossier_bescheiden' ); //MJ, 05-08-2015: changed the following line to exclude Gemeente De Bilt unless no other files are present. If Gemeente De Bilt is used, limit the number to 10 so it doesn't exceed 5 minutes runtime. //$res = $this->db->query('SELECT id, dossier_id, bestandsnaam, png_status FROM dossier_bescheiden ORDER BY id DESC'); //$process_debilt = false; if ($process_debilt) { // if (0) { echo "De Bilt Proces is van toepassing, volledige query gebruiken gebruiken\n"; // !!! $res = $this->db->query('SELECT id, dossier_id, bestandsnaam, png_status FROM dossier_bescheiden ORDER BY id DESC'); // $res = $this->db->query('SELECT id, dossier_id, bestandsnaam, png_status FROM dossier_bescheiden WHERE dossier_id = 55139 ORDER BY id DESC'); } else { // !!! $res = $this->db->query('SELECT dossier_bescheiden.id, dossier_bescheiden.dossier_id, dossier_bescheiden.bestandsnaam, dossier_bescheiden.png_status, klanten.id AS klant_id FROM `dossier_bescheiden` INNER JOIN `dossiers` ON `dossier_bescheiden`.`dossier_id` = `dossiers`.`id` INNER JOIN `gebruikers` ON `dossiers`.`gebruiker_id` = `gebruikers`.`id` INNER JOIN `klanten` ON `gebruikers`.`klant_id` = `klanten`.`id` WHERE klanten.id <> 165 ORDER BY dossier_bescheiden.id DESC'); //$res = $this->db->query('SELECT dossier_bescheiden.id, dossier_bescheiden.dossier_id, dossier_bescheiden.bestandsnaam, dossier_bescheiden.png_status, klanten.id AS klant_id FROM `dossier_bescheiden` INNER JOIN `dossiers` ON `dossier_bescheiden`.`dossier_id` = `dossiers`.`id` INNER JOIN `gebruikers` ON `dossiers`.`gebruiker_id` = `gebruikers`.`id` INNER JOIN `klanten` ON `gebruikers`.`klant_id` = `klanten`.`id` WHERE dossier_bescheiden.dossier_id = 55139 AND klanten.id <> 165 ORDER BY dossier_bescheiden.id DESC'); } $result = $res->result(); $res->free_result(); foreach ($result as $row) { $filename = DIR_DOSSIER_BESCHEIDEN . "/{$row->dossier_id}/{$row->id}"; if( file_exists($filename) ) { $row->datasize = filesize($filename); $bescheidenlijst[] = $row; } else { echo "Bestand bestaat niet: $filename\n"; } } echo "Verwerken: " . sizeof($bescheidenlijst) . " bescheiden...\n"; foreach ($bescheidenlijst as $i => $dossierbescheiden) { // 05-08-2015 if De Bilt needs to be processed, make sure the script only runs for a minute. if ($process_debilt) { // In light of the cron schedule, as well as the fact that during the night MANY documents can be incoming for clients like De Bilt, etc. // during the time interval from 22:00 - 5:00 we DO always allow complete runs to be made, without the 1 minute cut-off restriction. $cur_hour = intval(date("H")); $allow_complete_run = ( ($cur_hour >= 22) || ($cur_hour < 5) ); echo "De Bilt Proces is van toepassing\n"; if (!$allow_complete_run) { $mins = round(abs(time()-$timestart) / 60); if ($mins > 0) { echo date("Y-m-d H:i:s").": Het De Bilt proces heeft langer dan 1 minuut gedraaid, dus stoppen we er nu mee. File wordt unlockt\n"; // When we reach the end of the run of the entire method, unlock the outer lock file. $outer_filelock->unlock(); // Also unconditionally release the lock for the PDF/A conversion. $pdfa_conversion_filelock->unlock(); exit; } } } echo sprintf( "%05d/%05d", $i+1, sizeof($bescheidenlijst) ) . ' [' . $dossierbescheiden->id . '.jpg] ' . $dossierbescheiden->bestandsnaam . ' (' . number_format( $dossierbescheiden->datasize / 1024, 0, ',', '.' ) . ' Kb) ... '; if (!preg_match( '/\.(pdf|jpe?g|png)$/i', $dossierbescheiden->bestandsnaam )) { echo "GEEN PDF OF JPG OF PNG\n"; continue; } // see if we can obtain a filelock, if not, this process is already running, // in which case we bail $filelock = $this->filelock->create( 'convert-bescheiden-' . $dossierbescheiden->id ); if ($filelock->try_lock() != LOCKFILE_SUCCESS) { echo "LOCKED\n"; $filelock->unlock(); continue; } if ($dossierbescheiden->png_status == 'fout') { echo "FOUT STATUS\n"; $filelock->unlock(); continue; } $this->imageprocessor->slice( null ); $this->imageprocessor->id( $dossierbescheiden->id ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( null ); $this->imageprocessor->page_number( 1 ); if (!$force) { if (sizeof( $available_modes = $this->imageprocessor->available() ) == sizeof( $ip_modes )) { echo "VOLLEDIG GECONVERTEERD\n"; $filelock->unlock(); continue; } } else $available_modes = array(); // convert all modes that are not yet available echo "CONVERTEREN...\n"; $convert_modes = array_diff( $ip_modes, $available_modes ); sort( $convert_modes ); /* so original always goes first! */ foreach ($convert_modes as $mode) { echo "... $mode: "; try { $this->imageprocessor->num_slices( $mode=='original' ? 4 : 1 ); $this->imageprocessor->mode( $mode ); for ($page_number = 1; ; ++$page_number) { $this->imageprocessor->page_number($page_number); if (!$this->imageprocessor->generate()) break; echo "$page_number "; } echo "KLAAR\n"; } catch (Exception $e) { echo "ERROR: " . $e->getMessage() . "\n"; } } // foreach ($convert_modes as $mode) // unlock lock, if we exit/crash before we do this, the filelock system will notice // our PID has become invalid, and will remove the lock, so no need to remove the // lock at all costs $filelock->unlock(); } // foreach ($bescheidenlijst as $i => $dossierbescheiden) // find all deelplan vraag uploads zonder PNG $this->load->model( 'deelplanupload' ); $deelplanlijst = array(); $res = $this->db->query('SELECT id, filename, png_status, datasize FROM deelplan_uploads ORDER BY id DESC'); foreach ($res->result() as $row) { $deelplanlijst[] = $row; } $res->free_result(); $deelplanlijst = $this->deelplanupload->all(); echo "Verwerken: " . sizeof($deelplanlijst) . " deelplan uploads...\n"; foreach ($deelplanlijst as $i => $deelplanupload) { echo sprintf( "%05d/%05d", $i+1, sizeof($deelplanlijst) ) . ' [' . $deelplanupload->id . '.jpg] ' . $deelplanupload->filename . ' (' . number_format( $deelplanupload->datasize / 1024, 0, ',', '.' ) . ' Kb) ... '; // see if we can obtain a filelock, if not, this process is already running, // in which case we bail $filelock = $this->filelock->create( 'convert-vraagupload-' . $deelplanupload->id ); if ($filelock->try_lock() != LOCKFILE_SUCCESS) { echo "LOCKED\n"; $filelock->unlock(); continue; } $this->imageprocessor->slice( null ); $this->imageprocessor->id( $deelplanupload->id ); $this->imageprocessor->type( 'vraagupload' ); $this->imageprocessor->mode( null ); if (!$force) { if (sizeof( $available_modes = $this->imageprocessor->available() ) == sizeof( $ip_modes )) { echo "VOLLEDIG GECONVERTEERD\n"; $filelock->unlock(); continue; } } else $available_modes = array(); // convert all modes that are not yet available echo "CONVERTEREN...\n"; $convert_modes = array_diff( $ip_modes, $available_modes ); sort( $convert_modes ); /* so original always goes first! */ foreach ($convert_modes as $mode) { echo "... $mode: "; try { $this->imageprocessor->num_slices( $mode=='original' ? 4 : 1 ); $this->imageprocessor->mode( $mode ); $this->imageprocessor->generate(); echo "KLAAR\n"; } catch (Exception $e) { echo "ERROR: " . $e->getMessage() . "\n"; } } // foreach ($convert_modes as $mode) // unlock lock, if we exit/crash before we do this, the filelock system will notice // our PID has become invalid, and will remove the lock, so no need to remove the // lock at all costs $filelock->unlock(); } // foreach ($deelplanlijst as $i => $deelplanupload) // When we reach the end of the run of the entire method, unlock the outer lock file. $outer_filelock->unlock(); // Also unconditionally release the lock for the PDF/A conversion. $pdfa_conversion_filelock->unlock(); } // if ($outer_file_lock_success) else { echo "The maximum amount of {$this->max_allowed_convert_bescheiden_instances} instances of the bescheiden conversion is already running or the PDFA conversion is running. Skipping this run.\n"; } echo "\n\n>>> Ending bescheiden conversion at: " . date("Y-m-d H:i:s") . " <<<\n"; //mj 05-08-2015: if there is time left, process De Bilt. $mins = round(abs(time()-$timestart) / 60); echo "Script heeft $mins minuten gedraaid\n"; if ($mins < 2 && !$process_debilt) { echo "Het script heeft maar $mins minuten gedraaid, dus gaan we een gedeelte van De Bilt meenemen.\n"; $this->convert_bescheiden (0,true); } } // public function convert_bescheiden( $force=0 ) public function ssosynchronizer() { $ss = new SSOSynchronizer(); $ss->run(); } public function calc_voortgangen() { // clear output buffers while (ob_get_level()) ob_end_flush(); $this->load->model( 'deelplan' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'matrix' ); $this->load->model( 'gebruiker' ); $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); $deelplannen = $this->deelplan->all(); foreach ($deelplannen as $d => $deelplan) { $gebruiker = $this->gebruiker->get( $deelplan->get_dossier()->gebruiker_id ); $this->login( $gebruiker->klant_id, $gebruiker->id ); $checklistgroepen = $deelplan->get_checklistgroepen(); echo sprintf( "deelplan %04d/%04d\n", $d+1, sizeof($deelplannen) ); foreach ($checklistgroepen as $c => $checklistgroep) { echo sprintf( "... checklistgroep %04d/%04d\n", $c+1, sizeof($checklistgroepen) ); if ($checklistgroep->modus != 'niet-combineerbaar') { $voortgang = round( 100 * $deelplan->get_progress_by_checklistgroep( $checklistgroep->id ) ); $this->deelplanchecklistgroep->update_voortgang( $deelplan->id, $checklistgroep->id, $voortgang ); } else { foreach ($deelplan->get_checklisten() as $k => $checklist) if ($checklist->checklist_groep_id == $checklistgroep->id) { echo "... checklist $k\n"; $voortgang = round( 100 * $deelplan->get_progress_by_checklist( $checklist->id ) ); $this->deelplanchecklist->update_voortgang( $deelplan->id, $checklist->id, $voortgang ); } } } } } public function planning_update() { $obj = new UpdatePlanningTables(); $obj->run(); } public function checkthemas( $fix=false ) { throw new Exception( 'don\'t run, destroys hoofdthema/thema relations!' ); $this->login( 1, 1 ); foreach ($this->klant->all() as $klant) { $ct = new CheckThemas( $klant ); $ct->run( $fix ); } } public function checkutf8( $fix=false ) { foreach ($this->klant->all() as $klant) { $gebruikers = $klant->get_gebruikers( true ); $gebruiker = reset( $gebruikers ); $this->login( $klant->id, $gebruiker->id ); $ct = new CheckUTF8( $klant ); $ct->run( $fix ); } $ct = new CheckUTF8( NULL ); $ct->run( $fix ); } public function verantwoordingstekst_import() { $f = fopen( APPPATH . '/../docs/importer-verantwoordingstekst/Brandweer_Nederland_2012-11-26.csv.csv', 'r' ); if (!$f) throw new Exception( 'Kon CSV bestand niet inlezen.' ); $regel = 0; $queries = array(); $queries[] = 'SET @KLANT_ID = 1;'; $queries[] = 'SET AUTOCOMMIT = 0;'; $queries[] = 'BEGIN;'; $read_now = true; for (; !$read_now || ($row = fgetcsv( $f )); ) { $read_now = true; ++$regel; // skip header if ($regel == 1 || empty($row)) continue; // read ahead $last_row = sizeof($row)-1; while ($next_row = fgetcsv( $f )) if ($next_row && $next_row[0] != 'Bouwbesluit 2012') { $row[$last_row] .= "\n" . implode( ',', $next_row ); } else break; // converteer alles naar UTF-8 foreach ($row as $i => $element) $row[$i] = iconv( 'ISO-8859-1', 'UTF-8', $element ); // handle row $queries[] = 'INSERT INTO verantwoordingen (klant_id, status, grondslag, artikel, tekst) VALUES (@KLANT_ID, \'voldoet_niet\', \'BB12\', \'' . $this->db->escape_str($row[4]) . '\', \'' . $this->db->escape_str($row[6]) . '\');'; $queries[] = 'INSERT INTO verantwoordingen (klant_id, status, grondslag, artikel, tekst) VALUES (@KLANT_ID, \'voldoet_niet\', \'BB2012\', \'' . $this->db->escape_str($row[4]) . '\', \'' . $this->db->escape_str($row[6]) . '\');'; // finish row $read_now = false; if (!$next_row) break; $row = $next_row; } echo "$regel regels\n"; $queries[] = 'COMMIT;'; if (!file_put_contents( 'verantwoordingsteksten.sql', implode( "\n", $queries ) )) throw new Exception( 'Kon CBB.sql niet schrijven' ); } public function update_prio_data() { // init hoofdthemas-per-hoofdthema tabel $this->load->model( 'hoofdthema' ); $res = $this->db->Query( ' SELECT DISTINCT(h.id), h.*, c.hoofdgroep_id FROM bt_themas t JOIN bt_hoofdthemas h ON t.hoofdthema_id = h.id JOIN bt_vragen v ON v.thema_id = t.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen hg ON c.hoofdgroep_id = hg.id JOIN bt_checklisten cl ON hg.checklist_id = cl.id ORDER BY h.nummer, h.naam '); $hoofdthemas_per_hoofdgroep = array(); foreach ($res->result() as $row) { if (!isset( $hoofdthemas_per_hoofdgroep[$row->hoofdgroep_id] )) $hoofdthemas_per_hoofdgroep[$row->hoofdgroep_id] = array(); $hoofdthemas_per_hoofdgroep[$row->hoofdgroep_id][] = $this->hoofdthema->getr( $row ); } $res->free_result(); // run queries $this->db->trans_start(); $res = $this->db->query( 'SELECT * FROM bt_prioriteitstelling_waarden' ); $origrows = $res->result(); $res->free_result(); $this->db->query( 'DELETE FROM bt_prioriteitstelling_waarden' ); foreach ($origrows as $row) { $hoofdthemas = @$hoofdthemas_per_hoofdgroep[$row->hoofdgroep_id]; if (!$hoofdthemas) continue; $query = 'INSERT INTO bt_prioriteitstelling_waarden (prioriteitstelling_id, hoofdgroep_id, hoofdthema_id, waarde) VALUES '; foreach ($hoofdthemas as $i => $hoofdthema) $query .= ($i ? ', ' : '') . sprintf( "(%d, %d, %d, '%s')", $row->prioriteitstelling_id, $row->hoofdgroep_id, $hoofdthema->id, $row->waarde ); $this->db->query( $query ); } $this->db->trans_complete(); } public function vraagupload2bescheidenconverter() { $vu2bc = new VraagUpload2BescheidenConverter(); $vu2bc->run(); } public function fillgrondslagtekstentabel() { $fg = new FillGrondslagTekstenTabel(); $fg->run(); } // Some clients have reported that all of a sudden ALL of the checked "themas" for each deelplan was gone. This script fixes such situations. // Basically what it does is to assign ALL themas of the checklist to each of the deelplannen. The script can be run on the level of EVERYONE of a specific // 'klant' or just of a single user, passing their gebruiker DB ID. public function assign_all_checklist_themas_to_all_deelplannen_for_klant($klantId, $gebruikerId = null) { echo "\n\n>>> Starting 'checklist thema' assignments to all 'deelplannen' run for client with ID {$klantId}: " . date("Y-m-d H:i:s") . " <<<\n"; $debug = false; //$debug = true; $this->load->model( 'gebruiker' ); $this->load->model( 'dossier' ); $this->load->model( 'deelplan' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'deelplanthema' ); $this->load->model( 'checklist' ); $this->load->model( 'klant' ); $klant = $this->klant->get($klantId); echo "\nKlant: " . $klant->naam . "\n"; if (!is_null($gebruikerId)) { $gebruiker = $this->gebruiker->get($gebruikerId); $gebruikers = array($gebruiker); echo "\nBeperkt tot gebruiker: " . $gebruiker->volledige_naam . "\n"; } else { $gebruikers = $this->gebruiker->get_by_klant($klantId); } //d($gebruikers); // Start looping over the gebruikers, drilling down to their dossiers -> deelplannen -> deelplanchecklists, etc. foreach ($gebruikers as $gebruiker) { echo "\nDossiers van gebruiker '" . $gebruiker->volledige_naam . "' ("; $gebruikerDossiers = $this->dossier->get_by_gebruiker($gebruiker->id); //d($gebruikerDossiers); echo sizeof($gebruikerDossiers) . " dossiers)....\n"; foreach ($gebruikerDossiers as $gebruikerDossier) { echo "Processing dossier: '" . $gebruikerDossier->beschrijving . "' ("; $existingDeelplannen = $gebruikerDossier->get_deelplannen(); echo sizeof($existingDeelplannen) . " deelplannen)....\n"; //d($existingDeelplannen); foreach ($existingDeelplannen as $existingDeelplan) { $debug = false; //$debug = true; if ($debug) { echo "Existing deelplan {$existingDeelplan->naam}\n\n"; //d($existingDeelplan); } // Assign all of the available themas of the checklists that are assigned to this deelplan directly to the deelplan too. $existingDeelplan->zet_alle_themas_van_checklisten(); // Now, force-update the content of the deelplan, this copies the proper questions for the checklists, etc. // Note that as we are NOT logged in to BTZ, we need to pass the user ID, as it cannot be determined from the base level! $existingDeelplan->update_content($gebruiker->id); } // foreach ($existingDeelplannen as $existingDeelplan) } // foreach ($gebruikerDossiers as $gebruikerDossier) } // foreach ($gebruikers as $gebruiker) echo "\n\n>>> Ending 'checklist thema' assignments to all 'deelplannen' run for client with ID {$klantId}: " . date("Y-m-d H:i:s") . " <<<\n"; } // public function assign_all_checklist_themas_to_all_deelplannen_for_klant($klantId, $gebruikerId = null) public function zet_hoofd_en_sub_thema_voor_checklistgroep( $checklist_groep_id=0, $hoofdthema_naam=null, $thema_naam=null, $fix=false ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'categorie' ); $this->load->model( 'vraag' ); $this->load->model( 'hoofdthema' ); $this->load->model( 'thema' ); $this->load->helper( 'wizard' ); echo "------ PARAMETERS --------------------------------------------------------------\n"; echo "Checklistgroep id: " . $checklist_groep_id . "\n"; echo "Hoofdthema naam: " . $hoofdthema_naam . "\n"; echo "Thema naam: " . $thema_naam . "\n"; echo "Test run: " . ($fix ? 'nee' : 'ja') . "\n"; if (!($cg = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Checklist ID "' . $checklist_groep_id . '" niet bekend.' ); echo "------ CHECKLIST INFO ----------------------------------------------------------\n"; echo "Id: " . $cg->id . "\n"; echo "Naam: " . $cg->naam . "\n"; echo "Klant: " . $cg->get_klant()->naam . ' (id ' . $cg->klant_id . ')' . "\n"; echo "------ LOGIN INFO --------------------------------------------------------------\n"; if (!($gebruiker = reset( $cg->get_klant()->get_gebruikers( true ) ))) throw new Exception( 'Geen gebruikers gevonden bij klant.' ); $this->login( $gebruiker->klant_id, $gebruiker->id, false ); echo "Ingelogd als: " . $gebruiker->volledige_naam . ' (id ' . $gebruiker->id . ') ' . "\n"; $this->db->trans_start(); try { echo "------ OPHALEN HOOFD EN SUB THEMA's --------------------------------------------\n"; $thema = resolve_thema( 'new', $hoofdthema_naam, $thema_naam ); echo "Hoofdthema: " . $thema->get_hoofdthema()->naam . ' (id ' . $thema->hoofdthema_id . ')' . "\n"; echo "Thema: " . $thema->thema . ' (id ' . $thema->id . ')' . "\n"; echo "------ ZETTEN HOOFD EN SUB THEMA's ---------------------------------------------\n"; $checklisten = $cg->get_checklisten(); echo "Checklisten: " . sizeof($checklisten) . ' gevonden' . "\n"; foreach ($checklisten as $i => $cl) { echo "Checklist: " . sprintf( "%03d/%03d: %s", $i+1, sizeof($checklisten), $cl->naam ) . "\n"; foreach ($cl->get_hoofdgroepen() as $hoofdgroep) { foreach ($hoofdgroep->get_categorieen() as $categorie) { foreach ($categorie->get_vragen() as $vraag) { $vraag->thema_id = $thema->id; $vraag->save( false, null, false ); } } } } echo "------ TRANSACTIE --------------------------------------------------------------\n"; if ($fix) { if (!$this->db->trans_complete()) throw new Exception( 'Fout bij transactie commit.' ); echo "Transactie commit.\n"; } else { $this->db->_trans_status = false; $this->db->trans_complete(); echo "Transactie rollback uitgevoerd.\n"; } } catch (Exception $e) { echo "------ EXCEPTION ---------------------------------------------------------------\n"; $this->db->_trans_status = false; $this->db->trans_complete(); echo "Transactie rollback uitgevoerd.\n"; throw $e; } echo "------ RESULTAAT ---------------------------------------------------------------\n"; echo "Done\n"; } // public function zet_hoofd_en_sub_thema_voor_checklistgroep( $checklist_groep_id=0, $hoofdthema_naam=null, $thema_naam=null, $fix=false ) public function fix_checklist_sortering( $checklist_groep_id=null, $fix=0 ) { if (!$checklist_groep_id) throw new Exception( 'Geef checklist groep id op die gesorteerd moet worden.' ); $this->load->model( 'checklist' ); $checklisten = $this->checklist->search( array( 'checklist_groep_id' => $checklist_groep_id ), null, false, 'AND', 'naam ASC' ); echo sizeof($checklisten) . ' checklisten gevonden.' . "\n"; $this->db->trans_start(); foreach ($checklisten as $i => $checklist) { echo "{$checklist->naam} wordt $i\n"; if ($fix) { if ($checklist->sortering != $i) { $checklist->sortering = $i; $checklist->save(); } } } if (!$this->db->trans_complete()) throw new Exception( 'Database commit fout' ); } public function fill_deelplan_upload_data_table( $store=false ) { $res = $this->db->query( 'SELECT id, filename FROM deelplan_uploads' ); $idrows = $res->result(); $res->free_result(); $this->db->trans_start(); foreach ($idrows as $idrow) { echo "upload {$idrow->id}: {$idrow->filename}...\n"; // haal enkel data blok op $res = $this->db->query( 'SELECT data FROM deelplan_uploads WHERE id = ' . intval($idrow->id) ); if (!$res) throw new Exception( 'Kon upload met id ' . $idrow->id . ' niet laden?' ); $datarows = $res->result(); $res->free_result(); $data = reset($datarows)->data; unset( $datarows ); // !!! TODO: LOB handling // sla op in nieuwe tabel if (!($this->db->query( 'INSERT INTO deelplan_upload_data (data) VALUES (' . $this->db->escape( $data ) . ')' ))) throw new Exception( 'Kon regel niet inserten.' ); $id = $this->db->insert_id(); unset( $data ); // !!! TODO: LOB handling // zet id if (!($this->db->query( 'UPDATE deelplan_uploads SET deelplan_upload_data_id = ' . intval($id) . ' WHERE id = ' . intval($idrow->id) ))) throw new Exception( 'Kon regel niet updaten.' ); } if ($store) { echo "COMMIT!\n"; if (!$this->db->trans_complete()) throw new Exception( 'Database commit fout' ); } else { echo "ROLLBACK\n"; $this->db->_trans_status = false; $this->db->trans_complete(); } } private function _import_csv( $filename, $keycolumn, array $columns, $sep=';', $use_key_column = true ) { // In order to be able to properly handle files that were created under Windows, Mac, Unix, etc., make sure each and every file contains the same // line separator $nl = "\n"; $fileAsString = file_get_contents($filename); if (empty($fileAsString)) { throw new Exception( 'Kon ' . $filename . ' niet openen, of het bestand is leeg.' ); } $fileAsString = str_replace("\r\n", $nl, $fileAsString); $fileAsString = str_replace("\n\r", $nl, $fileAsString); $fileAsString = str_replace("\r", $nl, $fileAsString); $fileAsString = str_replace("\n", $nl, $fileAsString); file_put_contents($filename, $fileAsString); // Now open the file 'for real' and process it. $fd = fopen( $filename, "rb" ); //$fd = fopen( $filename, "r" ); if (!$fd) throw new Exception( 'Kon ' . $filename . ' niet openen.' ); $line = 0; $rows = array(); while ($row = fgetcsv( $fd, 0, $sep )) { ++$line; if ($line == 1) continue; foreach ($row as &$r) $r = iconv( 'CP437', 'UTF-8', $r ); $newrow = array(); foreach ($columns as $column => $name) { $newrow[$name] = $row[$column]; } // If a key column should be used, we store all records using the designated column as (main) associative index. If no key column should be used, // we just store the rows without using a main associative index first, so the result set just becomes a numerically indexed (normal) array. if ($use_key_column) { $rows[ $row[$keycolumn] ] = $newrow; } else { $rows[] = $newrow; } } fclose( $fd ); return $rows; } public function restore_wetteksten3() { $tabel = $this->_import_csv( 'foute-artikelen_22-03-2013.csv', 6, array( 7 => 'artikel' ), ',' ); $queries = array(); foreach ($tabel as $id => $artikel) $queries[] = 'UPDATE bt_grondslag_teksten SET artikel = ' . $this->db->escape( $artikel['artikel'] ) . ', artikel_new = ' . $this->db->escape( $artikel['artikel'] ) . ' WHERE id = ' . $id . ';'; echo implode( "\n", $queries ) . "\n"; } public function cleanup_wetteksten( $fix=0 ) { require_once( APPPATH . '/controllers/cli/wetteksten_cleanup.php' ); $obj = (new WettekstenCleanup()); $obj->run( $fix ); } public function import_wetteksten( $grondslag, $file, $fix=0 ) { require_once( APPPATH . '/controllers/cli/wetteksten_import.php' ); $obj = (new WettekstenImport( $grondslag, $file )); $obj->run( $fix ); } public function pdfannotator_processor() { $this->load->library( 'pdfannotatorlib' ); define( 'PDFANNOTATOR_PROCESSOR_CONVERT', false ); define( 'PDFANNOTATOR_PROCESSOR_LOOP', false ); require_once( PDFANNOTATOR_CODE_PATH . 'base/processor.php' ); } public function quest() { $this->load->library( 'quest' ); $id = $this->quest->query_single_id( 'docs/wet/bb2012', 'art3-16' ); echo "ID=$id\n"; if (false) { var_dump( $this->quest->info( 'docs/wet/bb2012' ) ); } if (false) { $text = trim( preg_replace( '/(\r?\n){3,}/', "\n\n", preg_replace( '/^\s+$/m', '', preg_replace( '/<.*?>/', '', preg_replace( '/<a\s+.*?<\/a>/', '', $this->quest->data( $id ) ) ) ) ) ); echo $text; } } public function update_quest_koppeling( $force=0 ) { $this->load->model( 'grondslag' ); $this->load->model( 'grondslagtekst' ); $gqd = new GrondslagQuestData(); $gqd->node_force_when_unavailable( $force ? true : false ); foreach ($this->grondslagtekst->all( 'grondslag_id, artikel' ) as $grondslagtekst) { $node = $grondslagtekst->get_quest_node( $gqd ); if (!$force && !$node) echo $grondslagtekst->get_grondslag()->grondslag . ' ' . $grondslagtekst->artikel . ': ' . "\n"; else if ($force && $gqd->node_fetched_remotely()) { echo $grondslagtekst->get_grondslag()->grondslag . ' ' . $grondslagtekst->artikel . ': ' . $node . ' [FETCHED]'; if ($gqd->node_fetched_alternative()) echo ' [ALTERNATIVE]'; echo "\n"; } } } public function outlooksynchronizer( $options='' ) { $os = new OutlookSynchronizer(); $os->run( $options ); } public function annotatieschaler( $options='' ) { $as = new AnnotatieSchaler(); $as->run( $options ); } public function cleanup_verlopen_tokens( $sleep=0 ) { $cvt = new CleanupVerlopenTokens(); $cvt->run(); if ($sleep) { echo "Sleeping $sleep seconds and then running again...\n"; sleep( $sleep ); $cvt->run(); } } public function export_checklistgroep( $cg_id=null ) { $ec = new ExportChecklistgroep(); $ec->run( $cg_id ); } public function fix_standaard_themas_in_checklistgroepen() { $this->load->model( 'checklistgroep' ); $this->load->model( 'thema' ); $this->load->model( 'hoofdthema' ); $thema = $hoofdthema = 'Algemeen'; foreach ($this->checklistgroep->all() as $checklistgroep) { // checklistgroep echo 'Checklistgroep ' . $checklistgroep->id . ': ' . $checklistgroep->naam . ', klant ' . $checklistgroep->klant_id . ': '; // hoofdthema echo 'hoofdthema: '; $hoofdthemaobj = reset( $this->hoofdthema->search( array( 'klant_id' => $checklistgroep->klant_id, 'naam' => $hoofdthema ) ) ); if ($hoofdthemaobj) echo '[bestaand] '; else { echo '[nieuw] '; $hoofdthemaobj = $this->hoofdthema->add( $hoofdthema, 0, 'Eigen', $checklistgroep->klant_id ); } echo $hoofdthemaobj->id . ', '; // thema echo 'thema: '; $themaobj = reset( $this->thema->search( array( 'klant_id' => $checklistgroep->klant_id, 'thema' => $thema, 'hoofdthema_id' => $hoofdthemaobj->id ) ) ); if ($themaobj) echo '[bestaand] '; else { echo '[nieuw] '; $themaobj = $this->thema->add( $thema, 0, $hoofdthemaobj->id, $hoofdthemaobj->klant_id ); } echo $themaobj->id . ' '; // save $checklistgroep->standaard_hoofdthema_id = $hoofdthemaobj->id; $checklistgroep->standaard_thema_id = $themaobj->id; if (!$checklistgroep->save(0,0,0)) throw new Exception( 'Fout bij opslaan' ); // done echo "\n"; } } public function opdrachtprocessor() { $os = new OpdrachtProcessor(); $os->run(); } public function load_lease_teksten() { $fn = APPPATH . '../sql-dump/migrations/2.0.0/lease-teksten.csv'; if (!($fd = fopen( $fn, 'rb' ))) die( 'Failed to read ' . $fn . "\n" ); while ($row = fgetcsv( $fd )) { if (empty( $row )) continue; $string = $row[0]; $tekst = $row[1]; $timestamp = $row[2]; $lease_configuratie_id = $row[3]; echo sprintf( "REPLACE INTO teksten (string, tekst, timestamp, lease_configuratie_id) VALUES (%s,%s,%s,%d);\n", $this->db->escape($string), $this->db->escape($tekst), $this->db->escape($timestamp), $lease_configuratie_id ); //!!! note: for Oracle the above doesn't work! If we need this code on Oracle based platforms, we must make an Oracle compatible version of the above; check the // DBEX :: prepare_replace_into method for how to do this! } fclose( $fd ); } public function riepairimporter( $override=0 ) { $ri = new RiepairImporter(); $ri->run( $override ); } public function test_toezichtgegevens( $checklist_groep_id, $deelplan_id, $checklist_id=null ) { $this->load->library( 'curl' ); $curl = $this->curl->create(); $curl->set_incoming_cookies_file( 'cookies' ); $curl->set_outgoing_cookies_file( 'cookies' ); $curl->set_opt( CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); $curl->set_opt( CURLOPT_USERPWD, '<EMAIL>:XXX' ); $curl->set_user_agent( 'Firefox' ); $curl->set_url( $url = 'http://dev.bristoezicht.imotepbv.nl/deelplannen/toezichtgegevens/' . $checklist_groep_id . '/' . $deelplan_id . '/' . $checklist_id ); $res = $curl->execute(); if ($curl->get_http_code() != 200) throw new Exception( 'URL failed: ' . $curl->get_http_code() . ': ' . $url ); dump( json_decode( $res ), 3 ); } public function dumpbescheiden() { $path = APPPATH . '../bescheiden/'; if (!is_dir( $path )) if (!mkdir( $path, 0766, true )) die( "Couldn't create directory: $path\n" ); $this->load->model( 'dossierbescheiden' ); $all_bescheiden = $this->dossierbescheiden->all(); foreach ($all_bescheiden as $i => $bescheiden) { if ($bescheiden->bestandsnaam) { echo sprintf( "%5d/%5d #%06d %s\n", $i+1, sizeof($all_bescheiden), $bescheiden->id, $bescheiden->bestandsnaam ); $bescheiden->laad_inhoud(); if (!file_put_contents( $path . $bescheiden->id . '__' . $bescheiden->bestandsnaam, $bescheiden->bestand )) die( "Failed to write file\n" ); $bescheiden->geef_inhoud_vrij(); } } } public function strip_duplicate_photos( $fix=false ) { // select all USED data rows (yes, we have some unused rows, but not going to do something about that here) $res = $this->db->query('SELECT id, deelplan_id, dp.dossier_id, '. 'FROM deelplan_uploads '. 'INNER JOIN deelplan dp ON dp.id = deelplan_id '. 'GROUP BY deelplan_id ORDER BY deelplan_id'); $ids = $res->result(); $res->free_result(); // going to keep track of SHA1's seen per deelplan // every time we have a duplicate, it can be removed! $sha1s = array(); echo "Found " . sizeof($ids) . " photos to check\n"; foreach ($ids as $i => $row) { echo "... checking " . sprintf("%6d/%6d", $i+1, sizeof($ids) ) . "... [" . $row->deelplan_upload_data_id . "] "; $filename = DIR_DEELPLAN_UPLOAD . '/' . $row->dossier_id . '/' . $row->deelplan_id . '/' .$row->id; if( !file_exists($filename) ) { continue; } $sha1 = sha1(file_get_contents($filename)); echo "[$sha1] "; // see if the "tag" (combo of deelplan id and sha1) is already known, // if so, we can delete the photo $tag = $row->deelplan_id . '|' . $sha1; if (!isset( $sha1s[$tag] )) { $sha1s[$tag] = $row->deelplan_upload_data_id; } else { echo "... DUPLICATE OF " . $sha1s[$tag] . " "; if ($fix) { $this->db->query( 'DELETE FROM deelplan_upload_data WHERE id = ' . $row->deelplan_upload_data_id ); echo "... DELETED"; } } echo "\n"; } } public function strip_duplicate_documenten( $fix=false ) { $this->load->model( 'dossierbescheiden' ); // select all USED data rows (yes, we have some unused rows, but not going to do something about that here) $res = $this->db->query('SELECT id, dossier_id FROM dossier_bescheiden ORDER BY id'); $ids = $res->result(); $res->free_result(); // going to keep track of SHA1's seen per deelplan // every time we have a duplicate, it can be removed! $sha1s = array(); echo "Found " . sizeof($ids) . " bescheiden to check\n"; foreach ($ids as $i => $row) { echo "... checking " . sprintf("%6d/%6d", $i+1, sizeof($ids) ) . "... [" . $row->id . "] "; // get the sha1 $dossierBescheiden = $this->dossierbescheiden->get($row->id); $dossierBescheiden->laad_inhoud(); //$res = $this->db->query('SELECT SHA1(bestand) AS sha1 FROM dossier_bescheiden WHERE id = ' . $row->id ); //$sha1 = $res->row_object()->sha1; //$res->free_result(); $sha1 = sha1($dossierBescheiden->bestand); echo "[$sha1] "; // see if the "tag" (combo of dossier id and sha1) is already known, // if so, we can delete the photo $tag = $row->dossier_id . '|' . $sha1; if (!isset( $sha1s[$tag] )) $sha1s[$tag] = $row->id; else { echo "... DUPLICATE OF " . $sha1s[$tag] . " "; if ($fix) { $this->db->query( 'DELETE FROM dossier_bescheiden WHERE id = ' . $row->id ); echo "... DELETED"; } } echo "\n"; } } public function database_id_cleanup() { $cl = new DatabaseIdCleanup(); $cl->run(); } public function wet_tekst_fetcher() { $wtf = new WetTekstFetcher(); $wtf->run(); } public function update_dossier_geolocaties() { $dgu = new DossierGeolocatieUpdater(); $dgu->run(); } public function dump_annotaties( $deelplan_id=null, $bescheiden_id=null ) { $res = $this->db->query( 'SELECT layer_data, pagetransform_data FROM deelplan_layers WHERE deelplan_id = ' . intval($deelplan_id) . ' AND dossier_bescheiden_id = ' . intval($bescheiden_id) ); if ($res->num_rows()) { $row = $res->row_object(); dump( json_decode( $row->layer_data ) , 10); } else echo "No data for deelplan_id '$deelplan_id' and bescheiden_id '$bescheiden_id'\n"; } public function maak_layer_image( $deelplan_id=null, $bescheiden_id=null, /* optional */ $vraag_id=null ) { $this->load->library( 'pdfannotatorlib' ); $str = $this->pdfannotatorlib->bescheiden_naar_png( $deelplan_id, $bescheiden_id, $vraag_id ); file_put_contents( 'test.png', $str ); } public function generate_random_dossiers( $klant_id=null, $gebruiker_id=null, $num=1000 ) { $this->load->model( 'klant' ); $this->load->model( 'dossier' ); $this->load->model( 'geolocatie' ); if (!($klant = $this->klant->get( $klant_id ))) throw new Exception( 'Invalid klant_id "' . $klant_id . '"' ); if (!$gebruiker_id) { $gebruikers = $klant->get_gebruikers( true ); if (!($gebruiker = reset( $gebruikers ))) throw new Exception( 'Klant doesn\'t have active gebruikers.' ); } else if (!($gebruiker = $this->gebruiker->get( $gebruiker_id ))) throw new Exception( 'Invalid gebruiker_id "' . $gebruiker_id . '"' ); if ($num<=0) throw new Exception( 'Invalid num "' . $num . '"' ); $latitude = 52.2241719; $longitude = 6.8426897; $diff = 0.2; $address_starts = array( 'Vogel', 'Bere', 'Katte', 'Honde', 'Zwarte', 'Witte', 'Gele' ); $address_ends = array( 'laan', 'straat', 'weg', 'allee', 'pad' ); for ($i=0; $i<$num; ++$i) { $adres = $address_starts[ mt_rand(0, sizeof($address_starts)-1 ) ] . $address_ends[ mt_rand(0, sizeof($address_starts)-1 ) ] . ' ' . mt_rand(1,10000); $woonplaats = 'Enschede'; $kenmerk = 'RANDOM-' . sprintf('%09d',mt_rand(1,100000000)); $latDiff = -($diff / 2) + $diff * ((float)mt_rand() / (float)mt_getrandmax()); $longDiff = -($diff / 2) + $diff * ((float)mt_rand() / (float)mt_getrandmax()); $geolocatie = $this->geolocatie->insert( array( 'adres' => $adres . ', ' . $woonplaats . ' [GENERATED]', 'latitude' => $latitude + $latDiff, 'longitude' => $longitude + $longDiff, ) ); $this->dossier->insert( array( 'herkomst' => 'handmatig', 'gebruiker_id' => $gebruiker->id, 'kenmerk' => $kenmerk, 'beschrijving' => 'Random generated dossier', 'aanmaak_datum' => time(), 'locatie_adres' => $adres, 'locatie_postcode' => '', 'locatie_woonplaats' => $woonplaats, 'geo_locatie_id' => $geolocatie->id, 'geo_locatie_opgehaald' => 1, ) ); } } public function annotatie_afbeelding_processor($deelplan_id, $checklist_groep_id, $checklist_id=null, $padding=50) { $this->load->library('annotatieafbeeldingprocessor'); $aap = $this->annotatieafbeeldingprocessor->create($deelplan_id, $checklist_groep_id, $checklist_id, $padding, $log_enabled=false); $aap->run(new TestAnnotatieAfbeeldingProcessorCallback()); } // Helper function to filter files for importing. // Currently this function only filters by file extension. // Note: the '$fileinfo' parameter should be of the type that is returned by reading from the DirectoyIterator, like the following: // $dir = new DirectoryIterator($directory_to_traverse); // foreach ($dir as $fileinfo) private function filter_import_file($fileinfo) { $allowed_extensions = array('pdf', 'docx', 'doc', 'xls', 'xlsx', 'rtf'); return (in_array(strtolower($fileinfo->getExtension()), $allowed_extensions)); } // Raw script to automatically assign ALL dossier documents of a specific client to ALL underlying 'deelplannen'. public function assign_all_bescheiden_to_deelplannen($klantId) { $this->load->model( 'dossier' ); $this->load->model( 'klant' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'deelplanbescheiden' ); $this->load->model( 'gebruiker' ); $klant = $this->klant->get($klantId); if (is_null($klant)) { echo "De klant met ID {$klantId} bestaat niet!\n"; } else { echo "\nDossierbescheiden van klant '" . $klant->naam . "' (ID: {$klantId}) worden toegekend aan de onderliggende deelplannen...\n\n"; // First get all users of the chosen client $gebruikers = $this->gebruiker->get_by_klant($klant->id); if (!$this->dbex->is_prepared( 'set_deelplan_bescheiden' )) $this->dbex->prepare( 'set_deelplan_bescheiden', 'INSERT INTO deelplan_bescheiden (deelplan_id, dossier_bescheiden_id) VALUES (?, ?)' ); // Loop over each one of them, getting their dossiers, and processing those. foreach ($gebruikers as $gebruiker) { echo "Dossiers van gebruiker '" . $gebruiker->volledige_naam . "' worden verwerkt...\n"; // Get the dossiers and process them $gebruikerDossiers = $this->dossier->get_by_gebruiker($gebruiker->id); foreach ($gebruikerDossiers as $gebruikerDossier) { echo "-Dossier met ID: '" . $gebruikerDossier->id . "' en kenmerk: '" . $gebruikerDossier->kenmerk . "': "; // Now get the 'dossierbescheiden' for the dossier $dossierBescheidenen = $this->dossierbescheiden->get_by_dossier($gebruikerDossier->id, true); $dossierBescheidenenIds = array_keys($dossierBescheidenen); echo sizeof($dossierBescheidenen) . " bescheiden "; //d($dossierBescheidenen); $dossierDeelplannen = $gebruikerDossier->get_deelplannen(); echo sizeof($dossierDeelplannen) . " deelplannen "; //d($dossierDeelplannen); echo "\n"; //foreach($dossierDeelplannen AS $dpIdx => $dossierDeelplan) foreach($dossierDeelplannen AS $dossierDeelplan) { echo "Deelplan met ID: '" . $dossierDeelplan->id . "'\n"; // Get the currently assigned documents for this deelplan $currentlyAssignedDeelplanBescheidenen = $this->deelplanbescheiden->get_by_deelplan($dossierDeelplan->id); // Now use the model to assign the proper set of documents to the deelplan. $this->deelplanbescheiden->set_for_deelplan($dossierDeelplan->id, $dossierBescheidenenIds, $currentlyAssignedDeelplanBescheidenen); } } // foreach ($gebruikerDossiers as $gebruikerDossier) } // foreach ($gebruikers as $gebruiker) } } // public function assign_all_bescheiden_to_deelplannen($klantId) // Bunschoten specific dossier import functionality. Uses a CSV file for specifying the dossier data and file locations ('map -> sub_map') // that, in combination with the proper file structure, adds 'dossier_bescheiden' in the proper 'dossier_bescheiden_mappen' too. public function bunschoten_dossiers_import ($start_row = 0, $end_row = 0) { set_time_limit(3600); //ini_set('memory_limit', '512M'); //ini_set('memory_limit', '1024M'); ini_set('memory_limit', '2048M'); $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); // Set the various paths etc. that we will need //$base_import_path = APPPATH . '../sql-dump/import/Bunnik/'; $base_import_path = APPPATH . '../sql-dump/import/Bunschoten/'; $csv_file_name = $base_import_path . 'bunschoten_dossiers_20140714.csv'; $base_files_path = $base_import_path . 'locaties/'; // The import file in question only ever has two people as 'dossier owners'. Make a map for them so they can be mapped to the right BTZ user ID. // Note: as this is a one-shot script, we took the lazy approach of simply looking up those IDs in the DB, instead of matching them by user name or so. // We use lowercase names for the look-up! //$users_mapping = array('<NAME>' => 513, '<NAME>' => 448); $users_mapping = array('<NAME>' => 513, '<NAME>endaal' => 448); // First get the CSV data. We do not really need the second column, but we get it anyway. $columns_in_csv_file = array( 0 => 'dossier_nummer', 1 => 'opmerking_code', 2 => 'locatie_adres', 3 => 'woonplaats', 4 => 'toelichting', 5 => 'datum_besluit', 6 => 'datum_besluit_plus_26_weken', 7 => 'bag_nummer', 8 => 'naam_ambtenaar', 9 => 'map', 10 => 'sub_map' ); // Get the actual CSV data. Note: the first column (i.e. dossier number) is NOT suitable as a key, as there are several locations // where multiple occurrences of the same dossier number appear for different addresses. We therefore MUST use the addresses instead! // Alternative strategy: group by the dossier numbers. This does NOT result in correct location addresses though! $csv_data = $this->_import_csv( $csv_file_name, 0, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 2, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 9, $columns_in_csv_file, ';' ); //d($csv_data); // Now loop over the retrieved data, processing it as required. echo "Importing dossiers" . ((($start_row > 0) && ($end_row > 0)) ? " from row {$start_row} to row{$end_row}\n" : "\n" ); $cnt = 0; $successful_rows = $unsuccessful_rows = 0; foreach ($csv_data as $key => $row) { $cnt++; // Check if the current row needs to be skipped or not. if ( ($start_row > 0) && ($end_row > 0) && (($cnt < $start_row) || ($cnt > $end_row)) ) { continue; } //echo "Row " . ++$cnt . " - key: {$key} - data:"; echo "\n\nRow " . $cnt . " - key: {$key}\n"; //d($row); // Note: there are several occurrences of various dossiernumbers and at times the addresses vary in odd manners in between them. // The most correct location addresses appear to be those mentioned in the 'map' column, so we use those for determining the address too. // Should we create dossiers per location address, rather than per dossier number, we need to change this around, such that the 'locatie_adres' // column is used. That, however, introduces different (worse!) issues, being duplicate dossier numbers and identical files being used for ALL those // duplicates! $locatie_address = $map = trim($row['map']); if (empty($map) && !empty($row['locatie_adres'])) { $locatie_address = trim($row['locatie_adres']); } if (empty($locatie_address)) { $unsuccessful_rows++; echo "Skipped! No valid address specified.\n"; echo "Full data:"; d($row); continue; } // Next, make sure a dossier owner is properly set. If we cannot work out a dossier owner, we bail out too. $dossier_owner_name = trim($row['naam_ambtenaar']); $dossier_owner_name_key = strtolower($dossier_owner_name); $dossier_owner_id = (array_key_exists($dossier_owner_name_key, $users_mapping)) ? $users_mapping["{$dossier_owner_name_key}"] : 0; if (empty($dossier_owner_id)) { $unsuccessful_rows++; echo "Skipped! No valid dossier owner specified.\n"; echo "Full data:"; d($row); continue; } // Extract the rest of the data we need $dossier_number = trim($row['dossier_nummer']); // All data is deemed to be o.k. to create the dossier, so proceed echo "Dossier data o.k.\nNumber: {$dossier_number} Address: {$locatie_address} Owner: {$dossier_owner_name}\n"; // Create the dossier $new_dossier_data = array( 'herkomst' => 'handmatig', 'gebruiker_id' => $dossier_owner_id, 'kenmerk' => $dossier_number, 'beschrijving' => trim($row['toelichting']), 'aanmaak_datum' => time(), 'locatie_adres' => $locatie_address, 'locatie_postcode' => '', 'locatie_woonplaats' => trim($row['woonplaats']), 'bag_identificatie_nummer' => trim($row['bag_nummer']), ); // If an exception occurred when creating the dossier, bail out. try { $new_dossier = $this->dossier->insert($new_dossier_data); } catch (Exception $e) { $unsuccessful_rows++; echo "Dossier could not be created. Reason: " . $e->getMessage() . "\n"; continue; } // In case no exception was thrown, but the dossier object otherwise is null, bail out too. This situation is not likely to occur. if (is_null($new_dossier)) { $unsuccessful_rows++; echo "Dossier could not be created.\n"; continue; } // If we reached this point, at least the dossier was created. Proceed processing the files. $successful_rows++; // Check if a proper file location exists for the dossier, and if so, process the files in it. $sub_map = trim($row['sub_map']); if (!empty($map) && !empty($sub_map)) { // A folder was specified for the files. Get the path to it. //$main_files_path = $base_files_path . $map . '/' . $sub_map . '/'; $main_files_path = $base_files_path . $map . '/' . $sub_map; echo "Trying to add files from directory: {$main_files_path}\n"; // Loop over the directory, processing the contents as required $files_in_main_directory = array(); $files_in_sub_directories = array(); try { // Iterate over the main directory, separating files from subdirectories $dir = new DirectoryIterator($main_files_path); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) if ($fileinfo->isDir()) { // Create an empty array in the 'sub directories' data set, using the directory name as a key. $files_in_sub_directories["{$file_name}"] = array(); // Create a 'dossier bescheiden map' for the subdirectory. We could postpone this so it only gets done for non-empty sub-directories. $dossier_bescheiden_map = $this->dossierbescheidenmap->add($new_dossier, $file_name, null); echo "Creating folder: {$file_name} - ID: " . $dossier_bescheiden_map->id . "\n"; // Iterate over the sub directory. Store only files found at this level, without performing full recursion. try { // Iterate over the sub directory, separating files from subdirectories $sub_dir = new DirectoryIterator($complete_path); foreach ($sub_dir as $sub_dir_fileinfo) { if (!($sub_dir_fileinfo->isDir()) && $this->filter_import_file($sub_dir_fileinfo)) { // Store the file echo "Storing file (sub): " . $sub_dir_fileinfo->getFilename() . " - Status: "; $files_in_sub_directories["{$file_name}"][] = $sub_dir_fileinfo->getFilename(); // PATCH bestand kolom!!! // Create the dossierbescheiden $new_dossier_bescheiden_data = array( 'dossier_id' => $new_dossier->id, 'tekening_stuk_nummer' => $sub_dir_fileinfo->getFilename(), 'omschrijving' => $sub_dir_fileinfo->getFilename(), 'zaaknummer_registratie' => $dossier_number, 'bestandsnaam' => $sub_dir_fileinfo->getFilename(), 'bestand' => file_get_contents($sub_dir_fileinfo->getPathname()), 'dossier_bescheiden_map_id' => $dossier_bescheiden_map->id, ); $new_dossier_bescheiden = $this->dossierbescheiden->insert($new_dossier_bescheiden_data); echo (is_null($new_dossier_bescheiden)) ? " failed.\n" : " success.\n"; } } } catch (Exception $e2) { // Fail silently, no need to show errors on this level //echo "Directory does not exist or cannot be read\n"; } } else { if ($this->filter_import_file($fileinfo)) { // Store the file echo "Storing file (main): " . $fileinfo->getFilename() . " - Status: "; $files_in_main_directory[] = $file_name; // PATCH bestand kolom!!! // Create the dossierbescheiden $new_dossier_bescheiden_data = array( 'dossier_id' => $new_dossier->id, 'tekening_stuk_nummer' => $fileinfo->getFilename(), 'omschrijving' => $fileinfo->getFilename(), 'zaaknummer_registratie' => $dossier_number, 'bestandsnaam' => $fileinfo->getFilename(), 'bestand' => file_get_contents($fileinfo->getPathname()), 'dossier_bescheiden_map_id' => null, ); $new_dossier_bescheiden = $this->dossierbescheiden->insert($new_dossier_bescheiden_data); echo (is_null($new_dossier_bescheiden)) ? " failed.\n" : " success.\n"; } } } } // Now we handle the files that are present in the main directory and those that appear in subdirectories /* echo "Files in main directory:"; d($files_in_main_directory); echo "Files in sub directories:"; d($files_in_sub_directories); * */ } catch (Exception $e) { //echo "Directory does not exist or cannot be read: " . $e->getMessage() . "\n"; echo "Directory does not exist or cannot be read\n"; } } // if (!empty($map)) // DEBUG/TEST only: exit after one iteration, so as to not have to process the entire set of files. if ($successful_rows > 50) { break; } } // foreach ($csv_data as $key => $row) echo "\n\nDone. Dossiers created with success: {$successful_rows}. Dossiers that failed: {$unsuccessful_rows}\n"; } // public function bunschoten_dossiers_import () // De Bilt specific dossier import functionality. Uses a CSV file for specifying the dossier data and unique 'kenmerken' // that, in combination with the proper file structure, adds 'dossier_bescheiden' in the proper 'dossier_bescheiden_mappen' too. public function bilt_dossiers_import ($start_row = 0, $end_row = 0) { set_time_limit(3600); //ini_set('memory_limit', '512M'); //ini_set('memory_limit', '1024M'); ini_set('memory_limit', '2048M'); $this->load->model( 'gebruiker' ); $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); // Set the various paths etc. that we will need //$base_import_path = APPPATH . '../sql-dump/import/Bilt/'; $base_import_path = APPPATH . '../documents/bilt_documenten/'; $csv_file_name = $base_import_path . 'bilt_dossiers.csv'; $base_files_path = $base_import_path . 'documenten/'; // hardcode the klant_id value to that of 'Gemeente De Bilt' (= 165). $klant_id = 165; // The import file in question only ever has two people as 'dossier owners'. Make a map for them so they can be mapped to the right BTZ user ID. // Note: as this is a one-shot script, we took the lazy approach of simply looking up those IDs in the DB, instead of matching them by user name or so. // We use lowercase names for the look-up! //$users_mapping = array('<NAME>' => 513, '<NAME>' => 448); // The import file does not (always) have a (valid) user defined to whom the dossier should be associated. Towards that end, a dummy user was created with the // name set to '<NAME>'. We now get the users of the Gemeente De Bilt for trying to find the correct user to whom the dossier needs to be assigned. // For those dossiers for which no normal user could be determined, we assign the dossier to the 'Nog Niet Toegewezen' user. $gebruikerIds = array(); $gebruikerNames = array(); $gebruikers = $this->gebruiker->get_by_klant($klant_id); // As the Excel sheet contains the full name of the dossier owners, we create a look-up set that uses that as a key. foreach($gebruikers as $gebruiker) { $gebruikerId = $gebruiker->id; $gebruikerName = $gebruiker->volledige_naam; $gebruikerIds["$gebruikerName"] = $gebruikerId; $gebruikerNames["$gebruikerId"] = $gebruikerName; } /* d($gebruikerIds); d($gebruikerNames); * */ //exit; // First get the CSV data. We do not really need the second column, but we get it anyway. $columns_in_csv_file = array( 0 => 'kenmerk', 1 => 'datum_besluit', 2 => 'locatie_aanduiding', 3 => 'toelichting', 4 => 'naam_ambtenaar', 5 => 'datum_start_werk', 6 => 'datum_gereed_gemeld', 7 => 'opdrachtgever', 8 => 'bsn', 9 => 'voorletters', 10 => 'voorvoegsels', 11 => 'geboortenaam', 12 => 'opdrachtgever_straat', 13 => 'opdrachtgever_huis_nummer', 14 => 'opdrachtgever_huis_letters', 15 => 'opdrachtgever_huis_toevoeging', 16 => 'opdrachtgever_postcode', 17 => 'opdrachtgever_woonplaats', 18 => 'email', 19 => 'telefoon', 20 => 'straat', 21 => 'huis_nummer', 22 => 'huis_letters', 23 => 'huis_toevoeging', 24 => 'postcode' ); // Get the actual CSV data. Note: the first column (i.e. dossier number) is NOT suitable as a key, as there are several locations // where multiple occurrences of the same dossier number appear for different addresses. We therefore MUST use the addresses instead! // Alternative strategy: group by the dossier numbers. This does NOT result in correct location addresses though! $csv_data = $this->_import_csv( $csv_file_name, 0, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 2, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 9, $columns_in_csv_file, ';' ); //d($csv_data); //exit; // Now loop over the retrieved data, processing it as required. echo "Importing dossiers" . ((($start_row > 0) && ($end_row > 0)) ? " from row {$start_row} to row {$end_row}\n" : "\n" ); $cnt = 0; $successful_rows = $unsuccessful_rows = 0; foreach ($csv_data as $key => $row) { $cnt++; // Check if the current row needs to be skipped or not. if ( ($start_row > 0) && ($end_row > 0) && (($cnt < $start_row) || ($cnt > $end_row)) ) { continue; } // Further checks to see if the current row needs to be skipped or not. if (empty($key)) { echo "Skipping row that is (deemed to be) empty.\n"; continue; } // Further checks to see if the current row needs to be skipped or not. if (empty($row['kenmerk'])) { echo "Skipping row that does not have a valid 'kenmerk'.\n"; continue; } // Further checks to see if the current row needs to be skipped or not. /* if (empty($row['locatie_aanduiding'])) { echo "Skipping row that does not have a valid 'locatie aanduiding'.\n"; continue; } * */ // If we reached this point we assume to have enough information to create a dossier, so we proceed to extract the data and process it. //echo "Row " . ++$cnt . " - key: {$key} - data:"; echo "\n\nRow " . $cnt . " - key: {$key}\n"; //d($row); //exit; // Extract/map the information as needed so we can compile the compound data that will constitute a dossier record. $naamAmbtenaar = $row['naam_ambtenaar']; $dossierOwnerId = (array_key_exists($naamAmbtenaar, $gebruikerIds)) ? $gebruikerIds["$naamAmbtenaar"] : $gebruikerIds["Nog Niet Toegewezen"]; echo "Listed dossier owner: '{$naamAmbtenaar}'. Mapping to ID: {$dossierOwnerId} ({$gebruikerNames["$dossierOwnerId"]})\n"; // Work out the address to use. // Begin by trying to use the composite 'locatie_aanduiding' column. list($locatieAdres, $locatieWoonplaats) = explode(' te ', $row['locatie_aanduiding']); $locatieAdres = trim($locatieAdres); $locatieWoonplaats = trim($locatieWoonplaats); // If no valid address could be determined from the 'locatie_aanduiding' column, try to construct it from the subparts. if (empty($locatieAdres)) { $locatieAdres = trim($row['straat']); if (!empty($row['huis_nummer'])) { $locatieAdres .= ' ' . trim($row['huis_nummer']); if (!empty($row['huis_letters'])) { $locatieAdres .= trim($row['huis_letters']); } if (!empty($row['huis_toevoeging'])) { $locatieAdres .= ' ' . trim($row['huis_toevoeging']); } } // if (!empty(trim($row['huis_nummer']))) } // If no valid 'woonplaats' could be determined, use that of the person who is listed as the 'applicant'. // TODO: Check if this is really desired or not! if (empty($locatieWoonplaats)) { $locatieWoonplaats = trim($row['opdrachtgever_woonplaats']); } // We require a valid address, so bail out if none could be determined. if (empty($locatieAdres)) { $unsuccessful_rows++; echo "Skipped! No valid address specified.\n"; echo "Full data:"; d($row); continue; } else { echo "Using address: '{$locatieAdres}' in: '{$locatieWoonplaats}'\n"; } // Extract the rest of the data we need $kenmerk = trim($row['kenmerk']); // All data is deemed to be o.k. to create the dossier, so proceed echo "Dossier data o.k.\nNumber: {$kenmerk} Address: {$locatieAdres} Owner: {$naamAmbtenaar}\n"; // Check if a dossier already exists for the combination of the 'kenmerk' and 'klant_id'. $dossier = $this->dossier->get_by_kenmerk( $kenmerk, $klant_id ); // Check if we need to create the dossier or if one exists for it already if (is_null($dossier)) { // Try to create the dossier. $newDossierData = array( 'herkomst' => 'handmatig', 'gebruiker_id' => $dossierOwnerId, 'kenmerk' => $kenmerk, 'beschrijving' => trim($row['toelichting']), 'aanmaak_datum' => time(), 'locatie_adres' => $locatieAdres, 'locatie_postcode' => trim($row['postcode']), 'locatie_woonplaats' => $locatieWoonplaats, //'bag_identificatie_nummer' => '', ); // If an exception occurred when creating the dossier, bail out. try { $dossier = $this->dossier->insert($newDossierData); } catch (Exception $e) { $unsuccessful_rows++; echo "Dossier could not be created. Reason: " . $e->getMessage() . "\n"; continue; } // In case no exception was thrown, but the dossier object otherwise is null, bail out too. This situation is not likely to occur. if (is_null($dossier)) { $unsuccessful_rows++; echo "Dossier could not be created.\n"; continue; } } // if (is_null($dossier)) // If we reached this point, at least the dossier was successfully created or retrieved. Proceed processing the files. $successful_rows++; // At this point we can choose to allow updates to the dossier object (or not). For now this is not done, so as to not accidentally overwrite any and all // potentially manually made changes. // $dossier->... = ...; // $dossier->save(); // Now proceed to process the files. First get an overview of the files that already exist for the currently processed dossier (if any). $dossierBescheidenen = $this->dossierbescheiden->get_by_dossier($dossier->id); //echo "Existing bescheiden:"; //d($dossierBescheidenen); // Check if a proper file location exists for the dossier, and if so, process the files in it. $main_files_path = $base_files_path . $kenmerk . '/'; echo "Trying to add files from directory: {$main_files_path}\n"; // Loop over the directory, processing the contents as required $files_in_main_directory = array(); $files_in_sub_directories = array(); try { // Iterate over the main directory, separating files from subdirectories $dir = new DirectoryIterator($main_files_path); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) if ($fileinfo->isDir()) { // Create an empty array in the 'sub directories' data set, using the directory name as a key. $files_in_sub_directories["{$file_name}"] = array(); // Create a 'dossier bescheiden map' for the subdirectory. We could postpone this so it only gets done for non-empty sub-directories. $dossier_bescheiden_map = $this->dossierbescheidenmap->add($dossier, $file_name, null); echo "Creating folder: {$file_name} - ID: " . $dossier_bescheiden_map->id . "\n"; // Iterate over the sub directory. Store only files found at this level, without performing full recursion. try { // Iterate over the sub directory, separating files from subdirectories $sub_dir = new DirectoryIterator($complete_path); foreach ($sub_dir as $sub_dir_fileinfo) { if (!($sub_dir_fileinfo->isDir()) && $this->filter_import_file($sub_dir_fileinfo)) { // Store the file, if it doesn't exist yet echo "Processing file (sub): " . $sub_dir_fileinfo->getFilename() . " - Status: "; $files_in_sub_directories["{$file_name}"][] = $sub_dir_fileinfo->getFilename(); // First check if the file already exists. $file_exists = false; foreach ($dossierBescheidenen as $dossierBescheiden) { if ( ($sub_dir_fileinfo->getFilename() == $dossierBescheiden->bestandsnaam) && ($dossier_bescheiden_map->id == $dossierBescheiden->dossier_bescheiden_map_id) ) { $file_exists = true; } } // Only create the file if it doesn't exists yet. if (!$file_exists) { // Create the 'bescheiden' $dossierBescheiden = $this->dossierbescheiden->add( $dossier->id ); $dossierBescheiden->bestandsnaam = $sub_dir_fileinfo->getFilename(); $dossierBescheiden->bestand = file_get_contents($sub_dir_fileinfo->getPathname()); $dossierBescheiden->tekening_stuk_nummer = $sub_dir_fileinfo->getFilename(); $dossierBescheiden->auteur = ''; $dossierBescheiden->omschrijving = $sub_dir_fileinfo->getFilename(); $dossierBescheiden->zaaknummer_registratie = $kenmerk; $dossierBescheiden->versienummer = ''; $dossierBescheiden->datum_laatste_wijziging = date('d-m-Y H:i'); $dossierBescheiden->dossier_bescheiden_map_id = $dossier_bescheiden_map->id; if (!$dossierBescheiden->save()) { //throw new Exception( 'Fout bij opslaan van het bescheiden in de database.' ); echo " failed.\n"; } else { echo " success.\n"; } } else { echo " file already exists - skipping.\n"; } } // if (!($sub_dir_fileinfo->isDir()) && $this->filter_import_file($sub_dir_fileinfo)) } // foreach ($sub_dir as $sub_dir_fileinfo) } catch (Exception $e2) { // Fail silently, no need to show errors on this level //echo "Directory does not exist or cannot be read\n"; } } // if ($fileinfo->isDir()) else { if ($this->filter_import_file($fileinfo)) { // Store the file, if it doesn't exist yet echo "Processing file (main): " . $fileinfo->getFilename() . " - Status: "; $files_in_main_directory[] = $file_name; // First check if the file already exists. $file_exists = false; foreach ($dossierBescheidenen as $dossierBescheiden) { if ( ($fileinfo->getFilename() == $dossierBescheiden->bestandsnaam) && (is_null($dossierBescheiden->dossier_bescheiden_map_id)) ) { $file_exists = true; } } // Only create the file if it doesn't exists yet. if (!$file_exists) { // Create the 'bescheiden' $dossierBescheiden = $this->dossierbescheiden->add( $dossier->id ); $dossierBescheiden->bestandsnaam = $fileinfo->getFilename(); $dossierBescheiden->bestand = file_get_contents($fileinfo->getPathname()); $dossierBescheiden->tekening_stuk_nummer = $fileinfo->getFilename(); $dossierBescheiden->auteur = ''; $dossierBescheiden->omschrijving = $fileinfo->getFilename(); $dossierBescheiden->zaaknummer_registratie = $kenmerk; $dossierBescheiden->versienummer = ''; $dossierBescheiden->datum_laatste_wijziging = date('d-m-Y H:i'); if (!$dossierBescheiden->save()) { //throw new Exception( 'Fout bij opslaan van het bescheiden in de database.' ); echo " failed.\n"; } else { echo " success.\n"; } } else { echo " file already exists - skipping.\n"; } } // if ($this->filter_import_file($fileinfo)) } // else of clause: if ($fileinfo->isDir()) } // if (!$fileinfo->isDot()) } // foreach ($dir as $fileinfo) // Now we handle the files that are present in the main directory and those that appear in subdirectories //echo "Files in main directory:"; //d($files_in_main_directory); //echo "Files in sub directories:"; //d($files_in_sub_directories); } catch (Exception $e) { //echo "Directory does not exist or cannot be read: " . $e->getMessage() . "\n"; echo "Directory does not exist or cannot be read\n"; } // DEBUG/TEST only: exit after one iteration, so as to not have to process the entire set of files. /* if ($successful_rows > 50) { break; } * */ } // foreach ($csv_data as $key => $row) echo "\n\nDone. Dossiers created or updated with success: {$successful_rows}. Dossiers that failed: {$unsuccessful_rows}\n"; } // public function bilt_dossiers_import () // De Bilt specific dossier archiver functionality. Uses a CSV file for specifying the dossiers that need to be archived. // Removes files that are associated with the dossier. public function bilt_dossiers_cleanup ($dryrun = true) { set_time_limit(3600); //ini_set('memory_limit', '512M'); //ini_set('memory_limit', '1024M'); ini_set('memory_limit', '2048M'); $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); $this->load->library( 'imageprocessor' ); // Set the various paths etc. that we will need //$base_import_path = APPPATH . '../sql-dump/import/Bilt/'; $base_import_path = APPPATH . '../sql-dump/import/Bilt/'; $csv_file_name = $base_import_path . 'bilt_dossiers_archive.csv'; $base_files_path = $base_import_path . 'documenten/'; // hardcode the klant_id value to that of '<NAME>' (= 165). $klant_id = 165; // First get the CSV data. We do not really need the second column, but we get it anyway. $columns_in_csv_file = array( 0 => 'kenmerk', ); // Get the actual CSV data. Note: the first column (i.e. dossier number) is NOT suitable as a key, as there are several locations // where multiple occurrences of the same dossier number appear for different addresses. We therefore MUST use the addresses instead! // Alternative strategy: group by the dossier numbers. This does NOT result in correct location addresses though! $csv_data = $this->_import_csv( $csv_file_name, 0, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 2, $columns_in_csv_file, ';' ); //$csv_data = $this->_import_csv( $csv_file_name, 9, $columns_in_csv_file, ';' ); //d($csv_data); //exit; // Now loop over the retrieved data, processing it as required. echo "Archiving dossiers... Mode: " . (($dryrun) ? " dry-run\n" : "real run\n" ); $cnt = 0; $successful_rows = $unsuccessful_rows = 0; foreach ($csv_data as $key => $row) { $cnt++; // Further checks to see if the current row needs to be skipped or not. if (empty($key)) { echo "Skipping row that is (deemed to be) empty.\n"; continue; } // If we reached this point we assume to have enough information to create a dossier, so we proceed to extract the data and process it. //echo "Row " . ++$cnt . " - key: {$key} - data:"; echo "\n\nRow " . $cnt . " - key: {$key}\n"; //d($row); //exit; // Extract the rest of the data we need $kenmerk = trim($row['kenmerk']); echo "Trying to get dossier for 'kenmerk': {$kenmerk}\n"; // Check if a dossier already exists for the combination of the 'kenmerk' and 'klant_id'. $dossier = $this->dossier->get_by_kenmerk( $kenmerk, $klant_id ); // Check if we need to create the dossier or if one exists for it already if (is_null($dossier)) { $unsuccessful_rows++; echo "Dossier does not exist or was not found - skipping.\n"; continue; } else { echo "Dossier was found - archiving.\n"; // Now proceed to process the files. First get an overview of the files that already exist for the currently processed dossier (if any). $dossierBescheidenen = $this->dossierbescheiden->get_by_dossier($dossier->id); //d($dossierBescheidenen); echo "Amount of 'bescheiden' to remove: ".sizeof($dossierBescheidenen)."\n"; // Remove the dossier bescheiden (if any) $dossierBescheidenenPath = ''; foreach ($dossierBescheidenen as $dossierBescheiden) { // Start by removing any and all sliced data, thumbnails, etc. for this bescheiden. // Use the imageprocessor library for this for calculating the proper directory. $this->imageprocessor->slice( null ); $this->imageprocessor->id( $dossierBescheiden->id ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( null ); $this->imageprocessor->page_number( 1 ); $convertedBescheidenFilesPath = $this->imageprocessor->get_image_base_path(); // If a path was successfully calculated, empty it. if (!empty($convertedBescheidenFilesPath) && !is_null($convertedBescheidenFilesPath)) { echo "Removing slices and thumbnails for 'bescheiden' with ID: ".$dossierBescheiden->id." from the path: ".$convertedBescheidenFilesPath."\n"; try { $dir = new DirectoryIterator($convertedBescheidenFilesPath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) echo "Removing file: {$file_name} - complete path: {$complete_path}\n"; if (!$dryrun) { echo "Performing actual delete of the file...\n"; unlink($complete_path); } else { echo "Dry-run: Skipping actual removal.\n"; } } } } catch (Exception $e) { echo "Directory does not exist or cannot be read\n"; } } // if (!empty($convertedBescheidenFilesPath) && !is_null($convertedBescheidenFilesPath)) // Proceed to remove the 'bescheiden' themselves (DB + base files). $dossierBescheidenenPath = $dossierBescheiden->get_file_path(); echo "Removing 'bescheiden' with ID: ".$dossierBescheiden->id." and filename: ".$dossierBescheiden->bestandsnaam."\n"; if (!$dryrun) { echo "Performing actual delete of the 'bescheiden'...\n"; $dossierBescheiden->delete(); } else { echo "Dry-run: Skipping actual removal.\n"; } } // foreach ($dossierBescheidenen as $dossierBescheiden) // When the dossierbescheiden have been removed, remove any and all data that is present in the directory where the files were. // Do this by file path (it is enough to do so using 1 dossierbescheiden, we don't have to loop over them). //$dossierBescheiden->get_file_path(); if (!empty($dossierBescheidenenPath)) { // Iterate over the dossier bescheiden directory, deleting files as they are encountered. // Note: This piece of code doesn't traverse encountered subdirectories! See the bilt_dossiers_import method for the logic to // do such traversing if needed. try { $dir = new DirectoryIterator($dossierBescheidenenPath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) echo "Removing file: {$file_name} - complete path: {$complete_path}\n"; if (!$dryrun) { echo "Performing actual delete of the file...\n"; unlink($complete_path); } else { echo "Dry-run: Skipping actual removal.\n"; } } // if (!$fileinfo->isDot()) } // foreach ($dir as $fileinfo) } catch (Exception $e) { echo "Directory does not exist or cannot be read\n"; } } // if (!empty($dossierBescheidenenPath)) // Then archive the dossier itself if (!$dryrun) { $dossier->gearchiveerd = 1; $dossier->save(); } // If we reached this point, at least the dossier was successfully created or retrieved. Proceed processing the files. $successful_rows++; } } // foreach ($csv_data as $key => $row) echo "\n\nDone. Dossiers archived success: {$successful_rows}. Dossiers that could not be archived: {$unsuccessful_rows}\n"; } // public function bilt_dossiers_cleanup ($dryrun = true) // VIIA specific script for automatically creating the proper 'dossier_bescheiden_mappen' structure under all of the VIIA dossiers. // Note that this script can be used for other clients and/or folder structures too with minor modifications. public function generate_dossier_bescheiden_mappen_viia ($klantId) { // Load the models we need $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); // Define the folders that need to be created $folderStructure = array( 'Bureau studie' => array( 'Berekeningen', 'Contactgegevens', 'Tekeningen' ), 'Correspondentie' => array( 'Intern', 'NAM', 'Stakeholders' ), 'Engineering' => array( 'Berekeningen', 'Engineeringsrapportage', 'Kostenraming', 'Tekeningen' ), 'HRBE' => array( 'Plan van aanpak', 'Uitvoeringsrapportage' ), 'Inspectie' => array( 'HSE', 'Inspectieplan', 'Inspectierapport' ), 'Vrijgegeven documenten' => array( ) ); //d($folderStructure); // Get the dossiers for which we need to create the folders $dossiersQuery = "SELECT * FROM dossiers WHERE gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = ?)"; $this->dbex->prepare( 'dossiers_for_folders', $dossiersQuery ); $res = $this->dbex->execute( 'dossiers_for_folders', array( $klantId ) ); // Iterate over the dossiers, creating the folders as needed. foreach ($res->result() as $row) { // Get the dossier as an object $dossier = $this->dossier->get($row->id); //d($row); //d($dossier); // Show the dossier we're processing echo "\n\nProcessing dossier with ID: '{$dossier->id}' - Kenmerk: '{$dossier->kenmerk}' - Beschrijving: '{$dossier->beschrijving}' :\n"; // Get the existing (level 1) folders, if any $existingDossierFolders = $this->dossierbescheidenmap->get_by_dossier($dossier->id); // Iterate over the folders that need to be created. For now, if a level 1 folder already exists, skip it. foreach ($folderStructure as $folderLevel1Name => $foldersLevel2) { // Check if the level 1 folder already exists in the set of existing folders. If so, skip it, if not, continue $folderLevel1Exists = false; $folderLevel1 = null; foreach($existingDossierFolders as $existingDossierFolder) { if ($existingDossierFolder->naam == $folderLevel1Name) { echo "Level 1 folder '{$folderLevel1Name}' already exists - retrieving...\n"; $folderLevel1 = $existingDossierFolder; $folderLevel1Exists = true; } } // Only create the level 1 folder if it doesn't exist yet if (!$folderLevel1Exists) { // Create the level 1 'dossier bescheiden map'. $folderLevel1 = $this->dossierbescheidenmap->add($dossier, $folderLevel1Name, null); echo "Creating level 1 folder: '{$folderLevel1Name}' - ID: " . $folderLevel1->id . "\n"; } // if (!$folderLevel1Exists) // Now process the level 2 folders (if any) for the level 1 folder if (!empty($foldersLevel2) && !is_null($folderLevel1)) { // First get the existing level 2 folders for the current level 1 folder $existingDossierFoldersLevel2 = $this->dossierbescheidenmap->get_by_dossier($dossier->id, $folderLevel1->id); // Now create the level 2 folders if they do not yet exist foreach ($foldersLevel2 as $folderLevel2Name) { // Check if the level 2 folder already exists in the current level 1 folder. If so, skip it, if not, continue $folderLevel2Exists = false; $folderLevel2 = null; foreach($existingDossierFoldersLevel2 as $existingDossierFolderLevel2) { if ($existingDossierFolderLevel2->naam == $folderLevel2Name) { echo "Level 2 folder '{$folderLevel2Name}' already exists - skipping...\n"; $folderLevel2 = $existingDossierFolderLevel2; $folderLevel2Exists = true; } } // Only create the level 2 folder under the current level 1 folder if it doesn't exist there yet if (!$folderLevel2Exists) { $folderLevel2 = $this->dossierbescheidenmap->add($dossier, $folderLevel2Name, $folderLevel1->id); echo "Creating level 2 folder: '{$folderLevel2Name}' - ID: " . $folderLevel2->id . "\n"; } } } // if (!empty($foldersLevel2) && !is_null($folderLevel1)) } // foreach ($folderStructure as $folderLevel1Name => $foldersLevel2) } // foreach ($res->result() as $row) $res->free_result(); } // public function generate_dossier_bescheiden_mappen_viia ($klantId) // VIIA specific script for automatically creating the proper 'deelplannen' structure under all of the VIIA dossiers. // This script also adds a standard document to all of the dossiers. // Note that this script can be used for other clients and/or folder structures too with minor modifications. public function generate_deelplannen_and_documenten_viia ($klantId) { // Load the models we need $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); $this->load->model( 'deelplan' ); $this->load->model( 'deelplanbescheiden' ); // Define the deelplannen that need to be created $deelplannenToAdd = array('Schoolcontact', 'Voorinspectie', 'Bureaustudie', 'Inspectie', 'HRBEs'); // Set the various paths etc. that we will need for adding the standard document(s) $baseImportPath = APPPATH . '../sql-dump/import/VIIA/'; $standardDocumentFilename = 'notitieblad.pdf'; $standardDocumentFileLocation = $baseImportPath . $standardDocumentFilename; $standardDocumentContents = file_get_contents($standardDocumentFileLocation); if (empty($standardDocumentContents) || is_null($standardDocumentContents)) { die("Could not find or open the specified standard document '{$standardDocumentFilename}' at location '{$standardDocumentFileLocation}'\n"); } // Get the dossiers for which we need to create the folders $dossiersQuery = "SELECT * FROM dossiers WHERE gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = ?)"; $this->dbex->prepare( 'dossiers_for_deelplannen_and_documenten', $dossiersQuery ); $res = $this->dbex->execute( 'dossiers_for_deelplannen_and_documenten', array( $klantId ) ); // Iterate over the dossiers, creating the deelplannen and standard documents as needed. foreach ($res->result() as $row) { // Get the dossier as an object $dossier = $this->dossier->get($row->id); //d($row); //d($dossier); // Show the dossier we're processing echo "\n\nProcessing dossier with ID: '{$dossier->id}' - Kenmerk: '{$dossier->kenmerk}' - Beschrijving: '{$dossier->beschrijving}' :\n"; // Get the existing dossier bescheidenen (if any). $existingDossierBescheidenen = $this->dossierbescheiden->get_by_dossier($dossier->id); // Get the existing deelplannen (if any) from before the attempt to add the new ones. $existingDossierDeelplannen = $dossier->get_deelplannen(); //d($existingDossierBescheiden); //d($existingDossierDeelplannen); // Start by adding the deelplannen. foreach ($deelplannenToAdd as $deelplanToAdd) { // Check if a deelplan already exists with that name and if so, use that one $deelplan = null; foreach ($existingDossierDeelplannen as $existingDossierDeelplan) { if ($deelplanToAdd == $existingDossierDeelplan->naam) { $deelplan = $existingDossierDeelplan; } } // If no deelplan exists for the currently processed name, create one now if (is_null($deelplan)) { echo "Deelplan with the name: '{$deelplanToAdd}' does not yet exist. Adding.\n"; $this->deelplan->add($dossier->id, $deelplanToAdd); } else { echo "Deelplan with the name: '{$deelplanToAdd}' already exists. Skipping.\n"; } } // foreach ($deelplannenToAdd as $deelplanToAdd) // After we added the deelplannen, we get the entire set again so we have the complete set of ALL deelplannen for the current dossier. // Note that we could have added deelplannen as needed to the array above too, but this additional call is easier and requires less // administrative checks. $existingDossierDeelplannen = $dossier->get_deelplannen(); // Now add the document as dossierbescheiden, if it doesn't already exist for the current dossier. $dossierBescheiden = null; foreach($existingDossierBescheidenen as $existingDossierBescheiden) { if ($standardDocumentFilename == $existingDossierBescheiden->bestandsnaam) { $dossierBescheiden = $existingDossierBescheiden; } } // If no dossierbescheiden exists for the standard document, create one now if (is_null($dossierBescheiden)) { echo "Dossierbescheiden with the name: '{$standardDocumentFilename}' does not yet exist. Adding.\n"; $dossierBescheiden = $this->dossierbescheiden->add($dossier->id); $dossierBescheiden->tekening_stuk_nummer = 'Notitieblad'; //$dossierBescheiden->auteur = ''; $dossierBescheiden->omschrijving = 'Algemeen (leeg) notitieblad'; //$dossierBescheiden->zaaknummer_registratie = ''; $dossierBescheiden->versienummer = '1'; //$dossierBescheiden->datum_laatste_wijziging = ''; $dossierBescheiden->bestandsnaam = $standardDocumentFilename; $dossierBescheiden->bestand = $standardDocumentContents; $dossierBescheiden->save(); } else { echo "Dossierbescheiden with the name: '{$standardDocumentFilename}' already exists. Skipping.\n"; } // At this point, we should have all of the required deelplannen and we should have the new dossierbescheiden. // Get the IDs of all of the dossier bescheidenen so we can add them to all of the deelplannen. // Get all of the currently existing dossierbescheidenen and add their IDs to the $dossierBescheidenenIds set. $dossierBescheidenenIds = array(); $existingDossierBescheidenen = $this->dossierbescheiden->get_by_dossier($dossier->id); foreach($existingDossierBescheidenen as $existingDossierBescheiden) { $dossierBescheidenenIds[] = $existingDossierBescheiden->id; } // As a last step, add the dossierbescheiden to all of the deelplannen. foreach ($existingDossierDeelplannen as $existingDossierDeelplan) { // Get the currently assigned documents for this deelplan $currentlyAssignedDeelplanBescheidenen = $this->deelplanbescheiden->get_by_deelplan($existingDossierDeelplan->id); // Now use the model to assign the proper set of documents to the deelplan. $this->deelplanbescheiden->set_for_deelplan($existingDossierDeelplan->id, $dossierBescheidenenIds, $currentlyAssignedDeelplanBescheidenen); } } // foreach ($res->result() as $row) $res->free_result(); echo "Done.\n"; } // public function generate_deelplannen_and_documenten_viia ($klantId) // Specific one-shot script that fixes the various references to the 'Zorgrie' checklisten. // A messy CSV file was delivered for these checklists. It could not be automatically processed and the questions were then created manually. // This method processes an adapted (and cleaned up) version of the CSV file that could previously not be imported. It serves as basis for fixing // references to missing 'grondslagen' etc. //public function fix_zorgrie_checklisten ($start_row = 0, $end_row = 0) public function fix_zorgrie_checklisten () { $this->load->model( 'vraag' ); // Hard-code these values for now. These could be made dynamic too (e.g. as parameters). $klant_id = 155; $clg_id = 607; // Set the various paths etc. that we will need //$base_import_path = APPPATH . '../sql-dump/import/Bunnik/'; $base_import_path = APPPATH . '../sql-dump/import/Riepair/'; $csv_file_name = $base_import_path . 'zorgrie_gecorrigeerd_20141014.csv'; // First get the CSV data. For now simply get all columns. $columns_in_csv_file = array( 0 => 'checklist', 1 => 'hoofdgroep', 2 => 'vraag', 3 => 'hoofdthema', 4 => 'thema', 5 => 'grondslag_1', 6 => 'artikel_1', 7 => 'grondslag_2', 8 => 'artikel_2', 9 => 'grondslag_3', 10 => 'artikel_3', 11 => 'grondslag_4', 12 => 'artikel_4', 13 => 'grondslag_5', 14 => 'artikel_5', 15 => 'grondslag_6', 16 => 'artikel_6', 17 => 'grondslag_7', 18 => 'artikel_7', 19 => 'grondslag_8', 20 => 'artikel_8', 21 => 'grondslag_9', 22 => 'artikel_9', 23 => 'grondslag_10', 24 => 'artikel_10', 25 => 'toezichtmoment', 26 => 'fase' ); // Get the actual CSV data. // Note: there is no really suitable "key column" in the used CSV file, so as the last parameter we pass the value 'false' so the result set becomes a // normal numerically indexed array. $csv_data = $this->_import_csv( $csv_file_name, 0, $columns_in_csv_file, ';', false ); echo "\nFixing Zorgrie checklists.\nProcessing " . sizeof($csv_data) . " rows in CSV file....\n"; //d($csv_data); // Now proceed to get the currently existing data for everything under the selected 'checklistgroep'. $existing_data_query = "SELECT t4.id AS cl_id, t4.naam AS cl_naam, t3.naam AS hg_naam, t1.id AS v_id, t1.tekst AS v_tekst, t1.gebruik_grndslgn AS v_gebruik_grndslgn FROM bt_vragen t1 INNER JOIN bt_categorieen t2 ON (t1.categorie_id = t2.id) INNER JOIN bt_hoofdgroepen t3 ON (t2.hoofdgroep_id = t3.id) INNER JOIN bt_checklisten t4 ON (t3.checklist_id = t4.id) INNER JOIN bt_checklist_groepen t5 ON (t4.checklist_groep_id = t5.id) WHERE t5.id = ?"; $this->dbex->prepare( 'existing_data', $existing_data_query ); $res = $this->dbex->execute( 'existing_data', array( $clg_id ) ); // Store the data in a lookup set, indexed by checklistnaam-hoogfdgroepnaam $existing_data = array(); foreach ($res->result() as $row) { $cl_naam = $row->cl_naam; $hg_naam = $row->hg_naam; if (empty($existing_data["$cl_naam"]["$hg_naam"])) { $existing_data["$cl_naam"]["$hg_naam"] = array(); } $existing_data["$cl_naam"]["$hg_naam"][] = $row; } $res->free_result(); // Now loop over the retrieved data, processing it as required. $cnt = 0; $successful_rows = $unsuccessful_rows = 0; $errors = array(); // Initialise sets for holding the grondslagen and thema's $grondslagen = array(); $themas = array(); // Now proceed to get the currently existing themas for the selected client. $existing_themas_query = "SELECT t1.id AS ht_id, t1.naam AS ht_naam, t2.id AS t_id, t2.thema AS t_thema FROM bt_hoofdthemas t1 LEFT JOIN bt_themas t2 ON (t1.id = t2.hoofdthema_id) WHERE t1.klant_id = ? ORDER BY t1.id, t2.thema"; $this->dbex->prepare( 'existing_themas', $existing_themas_query ); $res = $this->dbex->execute( 'existing_themas', array( $klant_id ) ); // Store the data in the themas lookup set, indexed by hoofdthema-themas foreach ($res->result() as $row) { $hoofdthema = $row->ht_naam; $thema = $row->t_thema; if (empty($themas["$hoofdthema"])) { $themas["$hoofdthema"] = array(); } $themas["$hoofdthema"]["$thema"] = $row; } $res->free_result(); //d($themas); //exit; // Prepare the various queries that are used for manipulating the themas. $existing_hoofdthema_query = "SELECT * FROM bt_hoofdthemas WHERE (klant_id = ?) AND (naam = ?)"; $this->dbex->prepare( 'existing_hoofdthema_check', $existing_hoofdthema_query ); $existing_thema_query = "SELECT * FROM bt_themas WHERE (klant_id = ?) AND (thema = ?) AND (hoofdthema_id = ?)"; $this->dbex->prepare( 'existing_thema_check', $existing_thema_query ); $add_hoofdthema_query = "INSERT INTO bt_hoofdthemas (klant_id, naam) VALUES (?, ?)"; $this->dbex->prepare( 'add_hoofdthema', $add_hoofdthema_query ); $add_thema_query = "INSERT INTO bt_themas (klant_id, thema, hoofdthema_id) VALUES (?, ?, ?)"; $this->dbex->prepare( 'add_thema', $add_thema_query ); //foreach ($csv_data as $key => $row) foreach ($csv_data as $row) { $cnt++; // Extract the data we need to look up the currently processed combination of checklistnaam-hoofdgroepnaam-vraagtekst $cl_naam = $row['checklist']; $hg_naam = $row['hoofdgroep']; $vraag = $row['vraag']; // Extract the other data we shall be using here $toezichtmoment = (!empty($row['toezichtmoment'])) ? $row['toezichtmoment'] : 'Algemeen'; $fase = (!empty($row['fase'])) ? $row['fase'] : 'Algemeen'; $hoofdthema = $row['hoofdthema']; $thema = $row['thema']; //echo "\n\nRow " . $cnt . " - key: {$key}\n"; echo "\n\nRow " . $cnt . ": {$cl_naam} - {$hg_naam} - {$vraag}\n"; //d($row); // Get the proper checklist-hoofdgroep combination $cl_hg = (!empty($existing_data["$cl_naam"]["$hg_naam"])) ? $existing_data["$cl_naam"]["$hg_naam"] : array(); // If the checklist-hoofdgroep combination doesn't exist, we can't use the current row for any updates! if (empty($cl_hg)) { $unsuccessful_rows++; $error_msg = "Combination of checklist '{$cl_naam}' and hoofdgroep '{$hg_naam}' does not exist in the dataset!"; if (!in_array($error_msg, $errors)) { $errors[] = $error_msg; } echo $error_msg . "\n"; continue; } // If we reached this point, try to find the question. $existing_vraag_data = null; foreach ($cl_hg as $vraag_row) { //d($vraag_row); exit; if ($vraag_row->v_tekst == $vraag) { $existing_vraag_data = $vraag_row; } } // If the checklist-hoofdgroep-vraag combination doesn't exist, we can't use the current row for any updates! if (is_null($existing_vraag_data)) { $unsuccessful_rows++; $error_msg = "Combination of checklist '{$cl_naam}' and hoofdgroep '{$hg_naam}' and vraag '{$vraag}' does not exist in the dataset!"; if (!in_array($error_msg, $errors)) { $errors[] = $error_msg; } echo $error_msg . "\n"; continue; } // If we reached this point, we have found the existing question and we have the data that was present in the CSV file. We can now proceed to update the record. // Start by getting the 'vraag' as an object. $vraag_object = $this->vraag->get($existing_vraag_data->v_id); // Process the thema (and the hoofdthema). $thema_id = $hoofdthema_id = null; $hoofdthema_themas = array(); if (!empty($hoofdthema) && !empty($thema)) { echo "Processing themas. Hoofdthema: '{$hoofdthema}' - thema: '{$thema}'\n"; if (!array_key_exists($hoofdthema, $themas)) { // Create a new hoofdthema first. echo "Adding hoofdthema: '{$hoofdthema}'\n"; $res2 = $this->dbex->execute( 'add_hoofdthema', array( $klant_id, $hoofdthema ) ); // If the hoofdthema was added successfully, proceed to get the ID of it. if ($res2) { // Query the same value back, to get the DB ID of it, if it exists. $res3 = $this->dbex->execute( 'existing_hoofdthema_check', array( $klant_id, $hoofdthema ) ); foreach ($res3->result() as $res_row) { $hoofdthema_id = $res_row->id; } $res3->free_result(); if (!is_null($hoofdthema_id)) { $themas["$hoofdthema"] = array(); } else { $errors[] = "Hoofdthema '{$hoofdthema}' could not be retrieved"; } } else { $errors[] = "Hoofdthema '{$hoofdthema}' could not be added"; } } // if (!array_key_exists($hoofdthema, $themas)) else { echo "Retrieving existing set for hoofdthema "; $hoofdthema_themas = $themas["$hoofdthema"]; echo sizeof($hoofdthema_themas) . " entries "; //if (!empty($hoofdthema_themas) && !empty($hoofdthema_themas[0])) foreach ($hoofdthema_themas as $cur_thema_naam => $cur_thema_data) { //$hoofdthema_id = $hoofdthema_themas[0]->ht_id; $hoofdthema_id = $cur_thema_data->ht_id; } echo " retrieved hoofdthema ID: {$hoofdthema_id}\n"; } // Now get the current themas for the hoofdthema, or an empty set in case the hoofdthema could neither be retrieved nor created. if (!is_null($hoofdthema_id)) { // Check if we already have the thema, or if we need to create it first. foreach ($hoofdthema_themas as $cur_thema_naam => $hoofdthema_thema) { if ($hoofdthema_thema->t_thema == $thema) { $thema_id = $hoofdthema_thema->t_id; } } // If the thema was not found yet, create it now if (is_null($thema_id)) { // Create a new thema first. echo "Adding thema: '{$thema}'\n"; $res2 = $this->dbex->execute( 'add_thema', array( $klant_id, $thema, $hoofdthema_id ) ); // If the thema was added successfully, proceed to get the ID of it. if ($res2) { // Query the same value back, to get the DB ID of it, if it exists. $res3 = $this->dbex->execute( 'existing_thema_check', array( $klant_id, $thema, $hoofdthema_id ) ); $cur_hoofdthema_thema_record = new stdClass(); foreach ($res3->result() as $res_row) { $thema_id = $res_row->id; $cur_hoofdthema_thema_record->ht_id = $hoofdthema_id; $cur_hoofdthema_thema_record->ht_naam = $hoofdthema; $cur_hoofdthema_thema_record->t_id = $thema_id; $cur_hoofdthema_thema_record->t_thema = $thema; } $res3->free_result(); if (!is_null($thema_id)) { $themas["$hoofdthema"]["$thema"] = $cur_hoofdthema_thema_record; } else { $errors[] = "Thema '{$thema}' could not be retrieved"; } } else { $errors[] = "Thema '{$thema}' could not be added"; } } // if (!array_key_exists($hoofdthema, $themas)) } // if (!is_null($hoofdthema_id)) } // if (!empty($hoofdthema) && !empty($thema)) // Now update the fields that we can update directly on the object. echo "Setting direct data: thema_id: '{$thema_id}' toezicht_moment: '{$toezichtmoment}' fase: {$fase}\n"; $vraag_object->thema_id = $thema_id; $vraag_object->toezicht_moment = $toezichtmoment; $vraag_object->fase = $fase; $vraag_object->save(); // Postpone the actual processing of the grondslagen. First store all of them in a look-up set and later process them. for ($i=1; $i<=10; $i++) { $grondslag_idx_str = "grondslag_{$i}"; $artikel_idx_str = "artikel_{$i}"; if (!empty($row["$grondslag_idx_str"]) && !empty($row["$artikel_idx_str"])) { $cur_grondslag = ucfirst($row["$grondslag_idx_str"]); $cur_artikel = $row["$artikel_idx_str"]; if (!array_key_exists($cur_grondslag, $grondslagen)) { $grondslagen["$cur_grondslag"]["$cur_artikel"] = array(); } //$grondslagen["$cur_grondslag"][] = array('grondslag' => $cur_grondslag, 'artikel' => $row["$artikel_idx_str"], 'vraag_id' => $existing_vraag_data->v_id); $grondslagen["$cur_grondslag"]["$cur_artikel"][] = array('vraag_id' => $existing_vraag_data->v_id, 'clg_id' => $clg_id, 'cl_id' => $existing_vraag_data->cl_id); } } // If we reached this point, at least the dossier was created. Proceed processing the files. $successful_rows++; } // foreach ($csv_data as $row) echo "\n\nDone. Rows processed with success: {$successful_rows}. Rows that failed: {$unsuccessful_rows}\n"; // Now create the grondslagen. First prepare the check queries. $existing_grondslag_query = "SELECT * FROM bt_grondslagen WHERE (klant_id = ?) AND (grondslag = ?)"; $this->dbex->prepare( 'existing_grondslag_check', $existing_grondslag_query ); $existing_grondslagtekst_query = "SELECT * FROM bt_grondslag_teksten WHERE (grondslag_id = ?) AND (artikel = ?)"; $this->dbex->prepare( 'existing_grondslagtekst_check', $existing_grondslagtekst_query ); // Prepare queries for adding grondslagen data too. $add_grondslag_query = "INSERT INTO bt_grondslagen (klant_id, grondslag) VALUES (?, ?)"; $this->dbex->prepare( 'add_grondslag', $add_grondslag_query ); $add_grondslagtekst_query = "INSERT INTO bt_grondslag_teksten (grondslag_id, artikel) VALUES (?, ?)"; $this->dbex->prepare( 'add_grondslagtekst', $add_grondslagtekst_query ); // Queries for properly linking vragen to grondslagteksten $update_vraag_query = "UPDATE bt_vragen SET gebruik_grndslgn = 1 WHERE id = ?"; $this->dbex->prepare( 'update_vraag', $update_vraag_query ); $add_vraag_grondslag_query = "REPLACE INTO bt_vraag_grndslgn (vraag_id, checklist_groep_id, checklist_id, grondslag_tekst_id) VALUES (?, ?, ?, ?)"; $this->dbex->prepare( 'add_vraag_grondslag', $add_vraag_grondslag_query ); // Now process the grondslagen. foreach($grondslagen as $grondslag => $artikelen) { //d($grondslag); //d($artikelen); // Check if the grondslag exists or not. $res2 = $this->dbex->execute( 'existing_grondslag_check', array( $klant_id, $grondslag ) ); // Retrieve the grondslag ID, creating new grondslagen if necessary $grondslag_id = 0; if ($res2->num_rows) { // Existing grondslag. Retrieve directly. echo "Grondslag '{$grondslag}' bestaat reeds...\n"; foreach ($res2->result() as $row) { $grondslag_id = $row->id; } $res2->free_result(); } else { // Grondslag doesn't exist yet. Create it first. echo "Grondslag '{$grondslag}' bestaat nog niet en wordt nu toegevoegd...\n"; $res3 = $this->dbex->execute( 'add_grondslag', array( $klant_id, $grondslag ) ); // Now see if we can retrieve the ID by simply performing the same check query again $res2 = $this->dbex->execute( 'existing_grondslag_check', array( $klant_id, $grondslag ) ); foreach ($res2->result() as $row) { $grondslag_id = $row->id; } $res2->free_result(); } if (empty($grondslag_id)) { $errors[] = "Grondslag '{$grondslag}' kon niet worden aangemaakt"; continue; } // Now proceed to create the artikelen for the grondslag. foreach ($artikelen as $artikel => $vragen) { //d($artikel); //d($vragen); // Check if the grondslagtekst exists or not. $res2 = $this->dbex->execute( 'existing_grondslagtekst_check', array( $grondslag_id, $artikel ) ); // Retrieve the grondslagtekst ID, creating new grondslagteksten if necessary $grondslagtekst_id = 0; if ($res2->num_rows) { // Existing grondslagtekst. Retrieve directly. echo "Grondslagtekst voor artikel '{$artikel}' bestaat reeds...\n"; foreach ($res2->result() as $row) { $grondslagtekst_id = $row->id; } $res2->free_result(); } else { // Grondslag doesn't exist yet. Create it first. echo "Grondslagtekst voor artikel '{$artikel}' bestaat nog niet en wordt nu toegevoegd...\n"; $res3 = $this->dbex->execute( 'add_grondslagtekst', array( $grondslag_id, $artikel ) ); // Now see if we can retrieve the ID by simply performing the same check query again $res2 = $this->dbex->execute( 'existing_grondslagtekst_check', array( $grondslag_id, $artikel ) ); foreach ($res2->result() as $row) { $grondslagtekst_id = $row->id; } $res2->free_result(); } if (empty($grondslagtekst_id)) { $errors[] = "Grondslagtekst voor artikel '{$artikel}' kon niet worden aangemaakt"; continue; } // Now that we have the proper grondslagtekst ID too, we can create the links to the vragen foreach($vragen as $vraag) { // Signal that the vraag has grondslagen echo "Koppeling wordt gelegd voor vraag met ID: '" . $vraag['vraag_id'] . "' en grondslagtekst met ID: '{$grondslagtekst_id}'...\n"; $res3 = $this->dbex->execute( 'update_vraag', array( $vraag['vraag_id'] ) ); $res3 = $this->dbex->execute( 'add_vraag_grondslag', array( $vraag['vraag_id'], $vraag['clg_id'], $vraag['cl_id'], $grondslagtekst_id ) ); } // foreach($vragen as $vraag) } // foreach ($artikelen as $artikel => $vragen) } // foreach($grondslagen as $grondslag => $artikelen) // Output any and all error messages. if (!empty($errors)) { echo "Errors: \n"; foreach ($errors as $error_msg) { echo "{$error_msg}\n"; } } } // public function fix_zorgrie_checklisten () // Specific one-shot script that imports 'grondslagen' for the 'Approve' client. public function import_approve_grondslagen () { //$this->load->model( 'vraag' ); // Hard-code these values for now. These could be made dynamic too (e.g. as parameters). $klant_id = 218; // Set the various paths etc. that we will need //$base_import_path = APPPATH . '../sql-dump/import/Bunnik/'; $base_import_path = APPPATH . '../sql-dump/import/Approve/'; $csv_file_name = $base_import_path . 'approve_grondslagen_20151013.csv'; // First get the CSV data. For now simply get all columns. $columns_in_csv_file = array( 0 => 'grondslag', 1 => 'hoofdstuk', 2 => 'afdeling', 3 => 'paragraaf', 4 => 'artikel', 5 => 'lid', 6 => 'tekst' ); // Get the actual CSV data. // Note: there is no really suitable "key column" in the used CSV file, so as the last parameter we pass the value 'false' so the result set becomes a // normal numerically indexed array. $csv_data = $this->_import_csv( $csv_file_name, 0, $columns_in_csv_file, ';', false ); echo "\nImporting grondslagen.\nProcessing " . sizeof($csv_data) . " rows in CSV file....\n"; // Now loop over the retrieved data, processing it as required. $cnt = 0; $successful_rows = $unsuccessful_rows = 0; $errors = array(); // Initialise sets for holding the grondslagen and thema's $grondslagen = array(); // First build up the grondslagen array //foreach ($csv_data as $key => $row) echo "De data uit het CSV bestand wordt geanalyseerd en voorbereid voor verwerking...\n"; foreach ($csv_data as $row) { $cnt++; $errorFound = false; echo "\nRij " . $cnt . " wordt gecontroleerd. Resultaat: \n"; //d($row); // Extract the data we need $grondslag = $row['grondslag']; if (empty($grondslag) || empty($row['tekst'])) { $errorFound = true; $error_msg = "De 'grondslag' mag niet leeg zijn!"; $errors[] = $error_msg; echo $error_msg . "\n"; } if (empty($row['tekst'])) { $errorFound = true; $error_msg = "De 'tekst' mag niet leeg zijn!"; $errors[] = $error_msg; echo $error_msg . "\n"; } if ( empty($row['hoofdstuk']) && empty($row['afdeling']) && empty($row['paragraaf']) && empty($row['artikel']) && empty($row['lid']) ) { $errorFound = true; $error_msg = "Er dient minimaal één van de volgende kolommen ingevuld te zijn: 'hoofdstuk', 'afdeling', 'paragraaf', 'artikel', 'lid'!"; $errors[] = $error_msg; echo $error_msg . "\n"; } if ($errorFound) { $unsuccessful_rows++; echo "Rij " . $cnt . " kan niet succesvol verwerkt worden en wordt overgeslagen!\n"; //continue; } else { $successful_rows++; echo "Rij " . $cnt . " bevat geen fouten en gaat verwerkt worden...\n"; if (!array_key_exists($grondslag, $grondslagen)) { $grondslagen["$grondslag"] = array(); } $row['tekst'] = str_replace('linebreak', "\n", $row['tekst']); $grondslagen["$grondslag"][] = $row; } } // foreach ($csv_data as $row) echo "\n\nVoorbereiding gereed. Aantal rijen die verwerkt worden: {$successful_rows}. Aantal rijen die overgeslagen worden: {$unsuccessful_rows}\n\n\n"; echo "Verwerking wordt nu gestart...\n\n"; //d($grondslagen); // Now create the grondslagen. First prepare the check queries. $existing_grondslag_query = "SELECT * FROM bt_grondslagen WHERE (klant_id = ?) AND (grondslag = ?)"; $this->dbex->prepare( 'existing_grondslag_check', $existing_grondslag_query ); $existing_grondslagtekst_query = "SELECT * FROM bt_grondslag_teksten WHERE ( (grondslag_id = ?) AND (artikel = ?) AND (display_hoofdstuk = ?) AND (display_afdeling = ?) " . "AND (display_paragraaf = ?) AND (display_artikel = ?) AND (display_lid = ?) )"; $this->dbex->prepare( 'existing_grondslagtekst_check', $existing_grondslagtekst_query ); // Prepare queries for adding grondslagen data too. $add_grondslag_query = "INSERT INTO bt_grondslagen (klant_id, grondslag) VALUES (?, ?)"; $this->dbex->prepare( 'add_grondslag', $add_grondslag_query ); $add_grondslagtekst_query = "INSERT INTO bt_grondslag_teksten (grondslag_id, artikel, display_hoofdstuk, display_afdeling, display_paragraaf, display_artikel, " . "display_lid, tekst) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $this->dbex->prepare( 'add_grondslagtekst', $add_grondslagtekst_query ); $update_grondslagtekst_query = "UPDATE bt_grondslag_teksten SET tekst = ? WHERE id = ?"; $this->dbex->prepare( 'update_grondslagtekst', $update_grondslagtekst_query ); // Now process the grondslagen. $errors = array(); foreach($grondslagen as $grondslag => $artikelen) { $artikelenAmount = sizeof($artikelen); echo "Grondslag '{$grondslag}' wordt nu verwerkt. Aantal artikelen: {$artikelenAmount}...\n\n"; //d($grondslag); //d($artikelen); //continue; // Check if the grondslag exists or not. $res2 = $this->dbex->execute( 'existing_grondslag_check', array( $klant_id, $grondslag ) ); // Retrieve the grondslag ID, creating new grondslagen if necessary $grondslag_id = 0; if ($res2->num_rows) { // Existing grondslag. Retrieve directly. echo "Grondslag '{$grondslag}' bestaat reeds...\n"; foreach ($res2->result() as $row) { $grondslag_id = $row->id; } $res2->free_result(); } else { // Grondslag doesn't exist yet. Create it first. echo "Grondslag '{$grondslag}' bestaat nog niet en wordt nu toegevoegd...\n"; $res3 = $this->dbex->execute( 'add_grondslag', array( $klant_id, $grondslag ) ); // Now see if we can retrieve the ID by simply performing the same check query again $res2 = $this->dbex->execute( 'existing_grondslag_check', array( $klant_id, $grondslag ) ); foreach ($res2->result() as $row) { $grondslag_id = $row->id; } $res2->free_result(); } if (empty($grondslag_id)) { $errors[] = "Grondslag '{$grondslag}' kon niet worden aangemaakt"; continue; } // Now proceed to create the artikelen for the grondslag. $artikelenCnt = 0; foreach ($artikelen as $artikel) { $artikelenCnt++; echo "Artikel {$artikelenCnt}/{$artikelenAmount} wordt nu verwerkt...\n"; // Extract the data that we need $hoofdstukVal = $artikel['hoofdstuk']; $afdelingVal = $artikel['afdeling']; $paragraafVal = $artikel['paragraaf']; $artikelVal = $artikel['artikel']; $lidVal = $artikel['lid']; $tekstVal = $artikel['tekst']; // Check if the grondslagtekst exists or not. $res2 = $this->dbex->execute( 'existing_grondslagtekst_check', array( $grondslag_id, $artikelVal, $hoofdstukVal, $afdelingVal, $paragraafVal, $artikelVal, $lidVal ) ); // Retrieve the grondslagtekst ID, creating new grondslagteksten if necessary $grondslagtekst_id = 0; if ($res2->num_rows) { // Existing grondslagtekst. Retrieve directly. echo "Grondslagtekst voor artikel bestaat reeds en wordt nu bijgewerkt...\n"; foreach ($res2->result() as $row) { $grondslagtekst_id = $row->id; } $res2->free_result(); $res3 = $this->dbex->execute( 'update_grondslagtekst', array( $tekstVal, $grondslagtekst_id ) ); } else { // Grondslag doesn't exist yet. Create it first. echo "Grondslagtekst voor artikel bestaat nog niet en wordt nu toegevoegd...\n"; $res3 = $this->dbex->execute( 'add_grondslagtekst', array( $grondslag_id, $artikelVal, $hoofdstukVal, $afdelingVal, $paragraafVal, $artikelVal, $lidVal, $tekstVal ) ); // Now see if we can retrieve the ID by simply performing the same check query again $res2 = $this->dbex->execute( 'existing_grondslagtekst_check', array( $grondslag_id, $artikelVal, $hoofdstukVal, $afdelingVal, $paragraafVal, $artikelVal, $lidVal ) ); foreach ($res2->result() as $row) { $grondslagtekst_id = $row->id; } $res2->free_result(); } if (empty($grondslagtekst_id)) { $errors[] = "Grondslagtekst voor artikel '{$artikel}' kon niet worden aangemaakt"; continue; } } // foreach ($artikelen as $artikel => $vragen) } // foreach($grondslagen as $grondslag => $artikelen) // echo "\n\nDone. Rows processed with success: {$successful_rows}. Rows that failed: {$unsuccessful_rows}\n"; // Output any and all error messages. if (!empty($errors)) { echo "\n\n\De volgende fouten zijn opgetreden tijdens de verwerking van de grondslagen: \n"; foreach ($errors as $error_msg) { echo "{$error_msg}\n"; } } echo "\n\nImport script gereed.\n"; } // public function import_approve_grondslagen () // Small helper function to recursively remove a directory: USE WITH EXTREME CARE!!!!!!!!! private function removeDirectory($path, $silent = true) { if (!$silent) { echo "Recursively deleting path '{$path}'...\n"; } $files = glob($path . '/*'); foreach ($files as $file) { if (!$silent) { echo "Removing file or directory: '{$file}'...\n"; } is_dir($file) ? $this->removeDirectory($file, $silent) : unlink($file); } if (is_dir($path)) { if (!$silent) { echo "Removing directory: '{$path}'...\n"; } rmdir($path); } else { if (!$silent) { echo "Directory: '{$path}' does not exist. Nothing to do...\n"; } } return; } // !!! Use this function with EXTREME care, for it WILL really be quite destructive by removing everything in the non-dryrun mode !!! // Supported 'mode' values: // -dryrun: only show which data wwould be removed in the non-dryrun modes. // -everything: remove all data entered by the klant and remove the users and klant themselves too. // -preserveusers: does the same as the 'everything' mode, but with the difference that the users and klant are NOT removed. public function remove_all_klant_data ($klantId, $mode = 'dryrun', $dirstyle = 'old') { // Start by making sure that a valid mode is selected. If such is not the case, force it to the dryrun mode. $supported_modes = array('dryrun', 'everything', 'preserveusers'); if (!in_array($mode, $supported_modes)) { $mode = 'dryrun'; } // Load the required models. $this->load->model( 'klant' ); // Get the klant data. $klant = $this->klant->get($klantId); // Check that a valid klant ID value has been passed. If not, bail out. if ( (intval($klantId) <= 0) || is_null($klant) ) { die('Ongeldige klant ID opgegeven! Opgegeven waarde: ' . $klantId . "\n\n"); } // If all input is deemed to be valid, continue. echo "Removing data for klant '{$klant->volledige_naam}' ({$klantId}). Chosen mode: {$mode}....\n\n"; // Get the data that we need to delete. // Start by getting the dossier IDs that need to be removed. $dossierIdsQuery = "SELECT id FROM dossiers WHERE gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = ?)"; $this->dbex->prepare( 'dossier_ids_to_remove', $dossierIdsQuery ); $res = $this->dbex->execute( 'dossier_ids_to_remove', array( $klantId ) ); $dossierIdsToRemove = array(); foreach ($res->result() as $row) { $dossierIdsToRemove[] = $row->id; } //echo "Dossiers to remove (ID values):\n"; //d($dossierIdsToRemove); // Also get the amounts of other data that will be removed. $countChecklistGroepenQuery = "SELECT COUNT(*) AS cnt FROM bt_checklist_groepen WHERE klant_id = ?"; $this->dbex->prepare( 'count_clgs', $countChecklistGroepenQuery ); $countChecklistsQuery = "SELECT COUNT(*) AS cnt FROM bt_checklisten WHERE checklist_groep_id IN (SELECT id FROM bt_checklist_groepen WHERE klant_id = ?)"; $this->dbex->prepare( 'count_cls', $countChecklistsQuery ); $countThemasQuery = "SELECT COUNT(*) AS cnt FROM bt_themas WHERE klant_id = ?"; $this->dbex->prepare( 'count_themas', $countThemasQuery ); $countHoofdThemasQuery = "SELECT COUNT(*) AS cnt FROM bt_hoofdthemas WHERE klant_id = ?"; $this->dbex->prepare( 'count_hoofdthemas', $countHoofdThemasQuery ); $countGebruikersQuery = "SELECT COUNT(*) AS cnt FROM gebruikers WHERE klant_id = ?"; $this->dbex->prepare( 'count_gebruikers', $countGebruikersQuery ); // Output the amounts that will be deleted in the non-dryrun mode echo "Amount of 'dossiers' to remove: " . sizeof($dossierIdsToRemove) . "\n"; $res = $this->dbex->execute( 'count_clgs', array( $klantId ) ); $row = $res->result(); echo "Amount of 'checklistgroepen' to remove: " . $row[0]->cnt . "\n"; $res = $this->dbex->execute( 'count_cls', array( $klantId ) ); $row = $res->result(); echo "Amount of 'checklists' to remove: " . $row[0]->cnt . "\n"; $res = $this->dbex->execute( 'count_themas', array( $klantId ) ); $row = $res->result(); echo "Amount of 'themas' to remove: " . $row[0]->cnt . "\n"; $res = $this->dbex->execute( 'count_hoofdthemas', array( $klantId ) ); $row = $res->result(); echo "Amount of 'hoofdthemas' to remove: " . $row[0]->cnt . "\n"; $res = $this->dbex->execute( 'count_gebruikers', array( $klantId ) ); $row = $res->result(); echo "Amount of 'gebruikers' to remove: " . $row[0]->cnt . "\n"; // Now perform the actual removal actions that need to be performed. if ( ($mode == 'everything') || ($mode == 'preserveusers') ) { // Start by preparing all queries. $removeDossiersQuery = "DELETE FROM dossiers WHERE gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = ?)"; $this->dbex->prepare( 'remove_dossiers', $removeDossiersQuery ); $removeChecklistGroepenQuery = "DELETE FROM bt_checklist_groepen WHERE klant_id = ?"; $this->dbex->prepare( 'remove_clgs', $removeChecklistGroepenQuery ); $removeChecklistsQuery = "DELETE FROM bt_checklisten WHERE checklist_groep_id IN (SELECT id FROM bt_checklist_groepen WHERE klant_id = ?)"; $this->dbex->prepare( 'remove_cls', $removeChecklistsQuery ); $removeThemasQuery = "DELETE FROM bt_themas WHERE klant_id = ?"; $this->dbex->prepare( 'remove_themas', $removeThemasQuery ); $removeHoofdThemasQuery = "DELETE FROM bt_hoofdthemas WHERE klant_id = ?"; $this->dbex->prepare( 'remove_hoofdthemas', $removeHoofdThemasQuery ); $removeGebruikersQuery = "DELETE FROM gebruikers WHERE klant_id = ?"; $this->dbex->prepare( 'remove_gebruikers', $removeGebruikersQuery ); $removeKlantQuery = "DELETE FROM klanten WHERE id = ?"; $this->dbex->prepare( 'remove_klant', $removeKlantQuery ); // Now remove all binary data. For now this is done unconditionally, but later we may want to change this so it depends on the chosen mode. if (1) { // Loop over all dossiers, removing the data as needed... foreach ($dossierIdsToRemove as $dossierIdToRemove) { echo "Cleaning all binary data for the dossier with ID {$dossierIdToRemove}...\n"; // We have to support the old style and new style directories, as the live environment at this moment in time still uses the old style. :( if ($dirstyle == 'old') { $this->removeDirectory(BASEPATH . '../documents/' . $dossierIdToRemove, false); } else if ($dirstyle == 'new') { // Remove all of the dossierbescheiden $this->removeDirectory(DIR_DOSSIER_BESCHEIDEN.'/'.$dossierIdToRemove, false); // Remove all of the dossierrapporten $this->removeDirectory(DIR_DOSSIER_RAPPORT.'/'.$dossierIdToRemove, false); // Remove all of the deelplan upload data $this->removeDirectory(DIR_DEELPLAN_UPLOAD.'/'.$dossierIdToRemove, false); } } } // Once the binary data has been removed (or preserved) delete the various DB data as required. Again, for now do so unconditionally (mostly), // but keep in mind that some more parts may be desired to be made conditionally, so implement hooks for that already. // Note that the order has been chosen such that we deliberately NOT rely on the DB's cascading settings! if (1) { // Remove the dossiers echo "Removing dossiers...\n"; $this->dbex->execute( 'remove_dossiers', array( $klantId ) ); // Remove the checklists echo "Removing checklists...\n"; $this->dbex->execute( 'remove_cls', array( $klantId ) ); // Remove the checklist groups echo "Removing checklist groups...\n"; $this->dbex->execute( 'remove_clgs', array( $klantId ) ); // Remove the themas echo "Removing themas...\n"; $this->dbex->execute( 'remove_themas', array( $klantId ) ); // Remove the hoofdthemas echo "Removing hoofdthemas...\n"; $this->dbex->execute( 'remove_hoofdthemas', array( $klantId ) ); } // The following data will only be removed in 'everything' mode // Note that the order has been chosen such that we deliberately NOT rely on the DB's cascading settings! if ( ($mode == 'everything') ) { // Remove the users echo "Removing users...\n"; $this->dbex->execute( 'remove_gebruikers', array( $klantId ) ); // Remove the klant echo "Removing client...\n"; $this->dbex->execute( 'remove_klant', array( $klantId ) ); } } // if ( ($mode == 'everything') || ($mode == 'preserveusers') ) echo "\n\nDone.\n"; } // public function remove_all_klant_data ($klantId, $mode = 'dryrun', $dirstyle = 'old') // Used for measuring the amount of data that is used by the dossiers of a klant. // Usage: // - Pass a single numeric klant DB ID in the '$klantId' parameter for getting data of only 1 klant. // - Pass the string value 'all' in the '$showKlantId' parameter for getting data of all klanten. // - Pass the string value 'summary' in the '$outputStyle' parameter for showing only the totals (per klant). // - Pass the string value 'verbose' in the '$outputStyle' parameter for showing the data of each dossier and the totals (per klant). // - Pass the string value 'everything' in the '$mode' parameter for including all binary data of each dossier in the calculations. // - Other '$mode' and '$outputStyle' values are TBD. public function get_klant_storage_usage ($showKlantId, $outputStyle = 'summary', $mode = 'everything') { // Use the 'new style' directory structure. $dirstyle = 'new'; // Start by making sure that a valid mode is selected. If such is not the case, force it to the 'everything' mode. $supported_modes = array('everything'); if (!in_array($mode, $supported_modes)) { $mode = 'everything'; } // Then make sure that a valid output style is selected. If such is not the case, force it to the 'summary' mode. $supported_output_styles = array('summary', 'verbose'); if (!in_array($outputStyle, $supported_output_styles)) { $outputStyle = 'summary'; } // Load the required models. $this->load->model( 'klant' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossier' ); $this->load->model( 'deelplanupload' ); // Init image processor $this->load->library( 'imageprocessor' ); // Get the set of klant IDs for which to perform the calculations $klantenIds = array(); if ($showKlantId == 'all') { $klanten = $this->klant->all( array('naam' => 'ASC'), true ); $klantenIds = array_keys($klanten); } else { $klantenIds = array(intval($showKlantId)); } //d($klantenIds); //exit; // Initialise the counters for the grand totals $grandDirDossierBescheidenTotalSize = $grandDirDossierRapportTotalSize = $grandDirDeelplanUploadTotalSize = $grandDirConvertedBescheidenTotalSize = $grandDirConvertedVraagUploadsTotalSize = $grandAmountOfDossiers = $grandEmptyDossiers = $grandNonEmptyDossiers = $grandMinDossierDataSize = $grandMaxDossierDataSize = 0; foreach ($klantenIds as $klantId) { // Get the klant data. $klant = $this->klant->get($klantId); // Check that a valid klant ID value has been passed. If not, bail out. if ( (intval($klantId) <= 0) || is_null($klant) ) { die('Ongeldige klant ID opgegeven! Opgegeven waarde: ' . $klantId . "\n\n"); } // If all input is deemed to be valid, continue. echo "\n\n\nCalculating data usage for klant '{$klant->volledige_naam}' ({$klantId}). Chosen mode: {$mode}....\n"; // Initialise the counters. Note: the counters are in 1024 byte blocks! $blockSize = 1024; $dirDossierBescheidenTotalSize = $dirDossierRapportTotalSize = $dirDeelplanUploadTotalSize = $dirConvertedBescheidenTotalSize = $dirConvertedVraagUploadsTotalSize = $amountOfDossiers = $emptyDossiers = $nonEmptyDossiers = $minDossierDataSize = $maxDossierDataSize = 0; // Start by getting the dossier IDs that need to be used for calculating the storage usage. $dossierIdsQuery = "SELECT id, kenmerk FROM dossiers WHERE gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = ?)"; $this->dbex->prepare( 'dossier_ids_to_count', $dossierIdsQuery ); $res = $this->dbex->execute( 'dossier_ids_to_count', array( $klantId ) ); $dossiersToCheck = array(); foreach ($res->result() as $row) { $idx = $row->id; $dossiersToCheck["$idx"] = $row->kenmerk; } // Output the amounts that will be deleted in the non-dryrun mode $amountOfDossiers = sizeof($dossiersToCheck); $grandAmountOfDossiers += $amountOfDossiers; echo "Amount of 'dossiers': " . $amountOfDossiers . "\n"; // Now perform the actual calculations. if ( ($mode == 'everything') ) { // Now calculate the size of all binary data. For now this is done unconditionally, but later we may want to change this so it depends on the chosen mode. if (1) { // Loop over all dossiers, calculating the data size as needed... foreach ($dossiersToCheck as $dossierIdToCheck => $dossierKenmerk) { if ($outputStyle == 'verbose') { echo "\n\nGrootte wordt berekend van dossier met ID {$dossierIdToCheck} - Kenmerk: '{$dossierKenmerk}'...\n"; } // We have to support the old style and new style directories, as the live environment at this moment in time still uses the old style. :( if ($dirstyle == 'old') { // $this->removeDirectory(BASEPATH . '../documents/' . $dossierIdToCheck, false); } else if ($dirstyle == 'new') { // Instantiate the dossier object $dossier = $this->dossier->get($dossierIdToCheck); // Keep track of the total size of the dossier $dossierDataTotalSize = $dirConvertedBescheidenSize = $dirConvertedVraagUploadsSize = 0; // Calculate the size of all of the dossierbescheiden $dirDossierBescheidenSize = calculate_directory_size(DIR_DOSSIER_BESCHEIDEN.'/'.$dossierIdToCheck); $dossierDataTotalSize += $dirDossierBescheidenSize; $dirDossierBescheidenTotalSize += $dirDossierBescheidenSize; $grandDirDossierBescheidenTotalSize += $dirDossierBescheidenSize; if ($outputStyle == 'verbose') { //echo "Dossier bescheiden (inclusief back-ups): {$dirDossierBescheidenSize} KB...\n"; show_directory_size_formatted($dirDossierBescheidenSize, 'Dossier bescheiden (inclusief back-ups)'); } // Calculate the size of all of the dossierrapporten $dirDossierRapportSize = calculate_directory_size(DIR_DOSSIER_RAPPORT.'/'.$dossierIdToCheck); $dossierDataTotalSize += $dirDossierRapportSize; $dirDossierRapportTotalSize += $dirDossierRapportSize; $grandDirDossierRapportTotalSize += $dirDossierRapportSize; if ($outputStyle == 'verbose') { //echo "Dossier rapporten: {$dirDossierRapportSize} KB...\n"; show_directory_size_formatted($dirDossierRapportSize, 'Dossier rapporten'); } // Calculate the size of all of the deelplan upload data $dirDeelplanUploadSize = calculate_directory_size(DIR_DEELPLAN_UPLOAD.'/'.$dossierIdToCheck); $dossierDataTotalSize += $dirDeelplanUploadSize; $dirDeelplanUploadTotalSize += $dirDeelplanUploadSize; $grandDirDeelplanUploadTotalSize += $dirDeelplanUploadSize; if ($outputStyle == 'verbose') { //echo "Deelplan uploads: {$dirDeelplanUploadSize} KB...\n"; show_directory_size_formatted($dirDeelplanUploadSize, 'Deelplan uploads'); } // Calculate the size of all of the converted dossierbescheiden $dossierBescheiden = $this->dossierbescheiden->get_by_dossier( $dossierIdToCheck, true ); $dirConvertedBescheidenSizeBytes = 0; if (!empty($dossierBescheiden)) { $dossierBescheidenIds = array_keys($dossierBescheiden); foreach($dossierBescheidenIds as $dossierBescheidenId) { $this->imageprocessor->slice( null ); $this->imageprocessor->id( $dossierBescheidenId ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( null ); $imageBasePath = $this->imageprocessor->get_image_base_path(); //d($dossierBescheidenId); try { $dir = new DirectoryIterator($imageBasePath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) if (strpos($file_name, "{$dossierBescheidenId}.") === 0) { //echo "*** {$dossierBescheidenId} : {$file_name} - size: " . filesize($complete_path) . "\n"; $fileSize = filesize($complete_path); $dirConvertedBescheidenSizeBytes += $fileSize; } } } //exit; } catch (Exception $e) { //echo "Directory '{$imageBasePath}' does not exist or cannot be read\n"; } //d($this->imageprocessor->get_image_base_path()); //$dirConvertedBescheidenSize += calculate_directory_size($this->imageprocessor->get_image_base_path()); } } if ($dirConvertedBescheidenSizeBytes > 0) { $dirConvertedBescheidenSize += $dirConvertedBescheidenSizeBytes/1024; $dossierDataTotalSize += $dirConvertedBescheidenSize; if ($outputStyle == 'verbose') { show_directory_size_formatted($dirConvertedBescheidenSize, 'Geconverteerde dossier bescheiden'); } } // show_directory_size_formatted($dirConvertedBescheidenSize, 'Geconverteerde dossier bescheiden'); // Calculate the size of all of the converted deelplanuploads $dirConvertedVraagUploadsSizeBytes = 0; foreach ($dossier->get_deelplannen() as $deelplan) { $deelplanUploads = $this->deelplanupload->find_by_deelplan( $deelplan->id ); //$deelplanConvertedFilesDirectories = array(); if (!empty($deelplanUploads)) { foreach($deelplanUploads as $deelplanUpload) { $this->imageprocessor->slice( null ); $this->imageprocessor->id( $deelplanUpload->id ); $this->imageprocessor->type( 'vraagupload' ); $this->imageprocessor->mode( null ); $imageBasePath = $this->imageprocessor->get_image_base_path(); //if (!in_array($imageBasePath, $deelplanConvertedFilesDirectories)) //{ try { $dir = new DirectoryIterator($imageBasePath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { //d($fileinfo); //var_dump($fileinfo->getFilename()); $file_name = $fileinfo->getFilename(); //$complete_path = $main_files_path . '/' . $fileinfo->getFilename(); $complete_path = $fileinfo->getPathname(); //if (is_dir($complete_path)) if (strpos($file_name, "{$deelplanUpload->id}.") === 0) { //echo "+++ {$deelplanUpload->id} : {$file_name} - size: " . filesize($complete_path) . "\n"; $fileSize = filesize($complete_path); $dirConvertedVraagUploadsSizeBytes += $fileSize; } } } //exit; } catch (Exception $e) { //echo "Directory '{$imageBasePath}' does not exist or cannot be read\n"; } //$deelplanConvertedFilesDirectories[] = $imageBasePath; //$dirConvertedVraagUploadsSize += calculate_directory_size($imageBasePath); //} /* if ($dossier->id == 8835) { d($this->imageprocessor->get_image_base_path()); } * */ //$dirConvertedVraagUploadsSize += calculate_directory_size($this->imageprocessor->get_image_base_path()); } //exit; //show_directory_size_formatted($dirConvertedVraagUploadsSize, 'Geconverteerde deelplan uploads'); //$dossierDataTotalSize += $dirConvertedVraagUploadsSize; } } if ($dirConvertedVraagUploadsSizeBytes > 0) { $dirConvertedVraagUploadsSize += $dirConvertedVraagUploadsSizeBytes/1024; $dossierDataTotalSize += $dirConvertedVraagUploadsSize; if ($outputStyle == 'verbose') { show_directory_size_formatted($dirConvertedVraagUploadsSize, 'Geconverteerde deelplan uploads'); } } // Output some more details that we want to show, and update the min and max dossier size if necessary $dirConvertedBescheidenTotalSize += $dirConvertedBescheidenSize; $grandDirConvertedBescheidenTotalSize += $dirConvertedBescheidenSize; $dirConvertedVraagUploadsTotalSize += $dirConvertedVraagUploadsSize; $grandDirConvertedVraagUploadsTotalSize += $dirConvertedVraagUploadsSize; $grandDossierDataTotalSize += $dossierDataTotalSize; if ($outputStyle == 'verbose') { show_directory_size_formatted($dossierDataTotalSize, 'Totale dossiergrootte'); } $minDossierDataSize = ($dossierDataTotalSize < $minDossierDataSize) ? $dossierDataTotalSize : $minDossierDataSize; $grandMinDossierDataSize = ($dossierDataTotalSize < $grandMinDossierDataSize) ? $dossierDataTotalSize : $grandMinDossierDataSize; $maxDossierDataSize = ($dossierDataTotalSize > $maxDossierDataSize) ? $dossierDataTotalSize : $maxDossierDataSize; $grandMaxDossierDataSize = ($dossierDataTotalSize > $grandMaxDossierDataSize) ? $dossierDataTotalSize : $grandMaxDossierDataSize; if (empty($dossierDataTotalSize)) { $emptyDossiers++; $grandEmptyDossiers++; } else { $nonEmptyDossiers++; $grandNonEmptyDossiers++; } } } // foreach ($dossiersToCheck as $dossierIdToCheck => $dossierKenmerk) } } // if ( ($mode == 'everything') ) // Calculate some totals and averages $totalDataSizeSourceData = $dirDossierBescheidenTotalSize + $dirDossierRapportTotalSize + $dirDeelplanUploadTotalSize; $totalDataSizeConvertedData = $dirConvertedBescheidenTotalSize + $dirConvertedVraagUploadsTotalSize; $totalDataSize = $totalDataSizeSourceData + $totalDataSizeConvertedData; $avgDossierSize = ($amountOfDossiers > 0) ? $totalDataSize/$amountOfDossiers : 0; $avgNonEmptyDossierSize = ($nonEmptyDossiers > 0) ? $totalDataSize/$nonEmptyDossiers : 0; if ($outputStyle == 'verbose') { echo "\n\n"; } echo "Samenvatting:\n"; echo "Aantal dossiers: {$amountOfDossiers}\n"; echo "Aantal lege dossiers: {$emptyDossiers}\n"; echo "Aantal niet-lege dossiers: {$nonEmptyDossiers}\n"; show_directory_size_formatted($avgDossierSize, 'Gemiddelde grootte dossiers'); show_directory_size_formatted($avgNonEmptyDossierSize, 'Gemiddelde grootte niet-lege dossiers'); show_directory_size_formatted($minDossierDataSize, 'Grootte kleinste dossier'); show_directory_size_formatted($maxDossierDataSize, 'Grootte grootste dossier'); show_directory_size_formatted($totalDataSizeSourceData, 'Totale grootte brondata dossiers'); show_directory_size_formatted($totalDataSizeConvertedData, 'Totale grootte conversiedata dossiers'); show_directory_size_formatted($totalDataSize, 'Totale grootte van alle dossiers'); echo "\n\n"; } // foreach ($klantenIds as $klantId) // If we retrieved data for more than 1 klant, we also show the grand totals //if (1) if (sizeof($klantenIds) > 1) { // Calculate some totals and averages $grandTotalDataSizeSourceData = $grandDirDossierBescheidenTotalSize + $grandDirDossierRapportTotalSize + $grandDirDeelplanUploadTotalSize; $grandTotalDataSizeConvertedData = $grandDirConvertedBescheidenTotalSize + $grandDirConvertedVraagUploadsTotalSize; $grandTotalDataSize = $grandTotalDataSizeSourceData + $grandTotalDataSizeConvertedData; $grandAvgDossierSize = ($grandAmountOfDossiers > 0) ? $grandTotalDataSize/$grandAmountOfDossiers : 0; $grandAvgNonEmptyDossierSize = ($grandAmountOfDossiers > 0) ? $grandTotalDataSize/$grandNonEmptyDossiers : 0; // Output the totals echo "TOTALEN OVER ALLE KLANTEN:\n"; echo "Aantal dossiers: {$grandAmountOfDossiers}\n"; echo "Aantal lege dossiers: {$grandEmptyDossiers}\n"; echo "Aantal niet-lege dossiers: {$grandNonEmptyDossiers}\n"; show_directory_size_formatted($grandAvgDossierSize, 'Gemiddelde grootte dossiers'); show_directory_size_formatted($grandAvgNonEmptyDossierSize, 'Gemiddelde grootte niet-lege dossiers'); show_directory_size_formatted($grandMinDossierDataSize, 'Grootte kleinste dossier'); show_directory_size_formatted($grandMaxDossierDataSize, 'Grootte grootste dossier'); show_directory_size_formatted($grandTotalDataSizeSourceData, 'Totale grootte brondata dossiers'); show_directory_size_formatted($grandTotalDataSizeConvertedData, 'Totale grootte conversiedata dossiers'); show_directory_size_formatted($grandTotalDataSize, 'Totale grootte van alle dossiers'); echo "\n\n"; } } // public function get_klant_storage_usage ($klantId, $outputStyle = 'summary', $mode = 'everything') // For MANY records in the 'deelplan_vraag_geschiedenis' table invalid 'status' values are set. This method fix those that can be fixed, by assinging the // 'standard answer' (if available). public function fix_deelplan_vraag_geschiedenis_status () { // Load the required models. $this->load->model( 'vraag' ); //$this->load->model( 'deelplanvraaggeschiedenis' ); echo "Fixing the 'status' values of the 'deelplanvragen geschiedenis'...\n\n"; // Get the data that we need to fix. // Start by getting the records that need to be patched. $dpvgRecordsToPatchQuery = "SELECT * FROM deelplan_vraag_geschiedenis WHERE status NOT LIKE 'w__'"; $this->dbex->prepare( 'dpvg_records_to_patch', $dpvgRecordsToPatchQuery ); $res = $this->dbex->execute( 'dpvg_records_to_patch', array( ) ); // Prepare a patch query; we could also use the model's update method, but that's undoubtedly unnecessarily heavy on resources. $dpvgRecordPatchQuery = "UPDATE deelplan_vraag_geschiedenis SET status = ? WHERE id = ?"; $this->dbex->prepare( 'dpvg_record_patch', $dpvgRecordPatchQuery ); // Iterate over the results, patching them as needed and possible. foreach ($res->result() as $row) { // Get the ID of the question and then get the vraag object, so we can determine the proper standard answer for it. $vraag = $this->vraag->get($row->vraag_id); $standaardAntwoord = $vraag->get_standaard_antwoord(); $status = $oldStatus = $row->status; if (!is_null($standaardAntwoord) && !empty($standaardAntwoord)) { $status = $standaardAntwoord->status; } // Now perform the patching echo "Changing invalid status: '{$oldStatus}' to: '{$status}' for id: {$row->id}\n"; $patchParameters = array($status, $row->id); //d($patchParameters); $this->dbex->execute( 'dpvg_record_patch', $patchParameters ); } } // public function fix_deelplan_vraag_geschiedenis_status () public function send_scheduled_dpv_emails($minutesDelay = 60) { // Make sure that minutesDelay contains a valid value (default to 60 in case the value is invalid). $minutesDelay = (is_numeric($minutesDelay) && ($minutesDelay > 0)) ? $minutesDelay : 60; echo "\n\nDe geschedulede (onverzonden) e-mails die minimaal {$minutesDelay} minuten geleden ingesteld zijn worden opgehaald...\n\n"; // Load the models we need $this->load->model( 'vraag' ); // Retrieve the deelplan_vraag_emails records that need to be sent $query = "SELECT * FROM deelplan_vraag_emails WHERE (datum_sent IS NULL) AND (DATE_SUB(NOW(),INTERVAL {$minutesDelay} MINUTE) > datum_entered)"; //$this->CI->dbex->prepare( 'find', $query ); //$res = $this->CI->dbex->execute( 'find', array() ); $this->dbex->prepare( 'find', $query ); $res = $this->dbex->execute( 'find', array() ); // Loop over each of the deelplan_vraag_emails records and send the emails foreach ($res->result() as $row) { // If we have all the information we need, we proceed to send the email Vraag::sendEmail($row->id); } // foreach ($res->result() as $row) } // public function send_scheduled_dpv_emails($minutesDelay = 60) // test stuff for Foddex, never bother about this in any way! public function foddextest() { $ft = new FoddexTest(); $ft->run(); } // Note: use this method with care! // When calling it, the method expects two parameters, being a fromUser ID and a toUser ID. All data that belongs to the "fromUser" will be assigned to the // "toUser" and at the end of the run, the "fromUser" will be removed. public function merge_user($fromUserId, $toUserId, $dryrun = true) { echo "Merging user with ID {$fromUserId} to user with ID {$toUserId} mode: " . (($dryrun) ? 'dryrun' : 'real' ) . "\n"; // Now retrieve the from and to users. if either of them doesn't exist, throw an error and exit, otherwise proceed. $userQuery = "SELECT t1.id, t1.volledige_naam, t2.id, t2.naam FROM gebruikers t1 INNER JOIN klanten t2 ON (t1.klant_id = t2.id) WHERE t1.id = ?"; $this->dbex->prepare( 'findUser', $userQuery ); // Start with the "from" user $fromUserName = $fromUserKlantName = ''; $fromUserFound = false; $res = $this->dbex->execute( 'findUser', array($fromUserId) ); foreach ($res->result() as $row) { $fromUserName = $row->volledige_naam; $fromUserKlantName = $row->naam; $fromUserFound = true; } if (!$fromUserFound) { die("No 'from' user was found for the user ID {$fromUserId}\n"); } // Then proceed with the "to" user $toUserName = $toUserKlantName = ''; $toUserFound = false; $res = $this->dbex->execute( 'findUser', array($toUserId) ); foreach ($res->result() as $row) { $toUserName = $row->volledige_naam; $toUserKlantName = $row->naam; $toUserFound = true; } if (!$toUserFound) { die("No 'to' user was found for the user ID {$toUserId}\n"); } // If we reached this point in the code, we have found a "from" and a "to" user, and we can proceed to do the patching. echo "Found 'from user': {$fromUserName} (client: $fromUserKlantName) -> found 'to' user: {$toUserName} (client: $toUserKlantName).\n"; // Define the columns per table that need to be patched. $tablesColumnsMap = array( 'back_log' => array('gebruiker_id', 'actie_voor_gebruiker_id'), 'bt_gebruiker_beperkingen' => array('gebruiker_id'), 'deelplan_checklist_groepen' => array('toezicht_gebruiker_id'), 'deelplan_checklisten' => array('toezicht_gebruiker_id'), 'deelplan_opdrachten' => array('opdrachtgever_gebruiker_id'), 'deelplan_uploads' => array('gebruiker_id'), 'deelplan_vraag_emails' => array('gebruiker_id'), 'deelplan_vraag_geschiedenis' => array('gebruiker_id'), 'deelplan_vragen' => array('gebruiker_id'), 'dossier_rapporten' => array('gebruiker_id'), 'dossier_subjecten' => array('gebruiker_id'), 'dossiers' => array('gebruiker_id'), 'gebruiker_checklist_groepen' => array('gebruiker_id'), 'gebruiker_collegas' => array('gebruiker1_id', 'gebruiker2_id'), 'gebruikers_import_mapping' => array('btz_gebruiker_id'), 'logs' => array('gebruiker_id'), 'notificaties' => array('gebruiker_id'), 'notificaties_bekeken' => array('gebruiker_id'), 'rollen' => array('gemaakt_door_gebruiker_id'), 'stats_sessies' => array('gebruiker_id'), 'supervision_moments_cl' => array('supervisor_user_id'), 'supervision_moments_clg' => array('supervisor_user_id'), 'zoek_instellingen' => array('gebruiker_id'), ); // Now loop over the array with tables-columns mappings. Always output the data that will/would be patched, and if we are not // being run in dry run mode also actually perform the patching. foreach ($tablesColumnsMap as $tableName => $columnNames) { foreach ($columnNames as $columnName) { // Process the current table-column combination. echo "\nProcessing table '{$tableName}' - column '{$columnName}' combination.\n"; // Start by getting the amount of records that will/would be patched. $countQuery = "SELECT COUNT(*) AS cnt FROM {$tableName} WHERE {$columnName} = ?"; $this->dbex->prepare( "count{$tableName}{$columnName}", $countQuery ); $res = $this->dbex->execute( "count{$tableName}{$columnName}", array($fromUserId) ); $amountOfRowsToPatch = 0; foreach ($res->result() as $row) { $amountOfRowsToPatch = $row->cnt; echo "Amount of found records for the 'from' user: {$amountOfRowsToPatch}\n"; } // Only perform the patching if we are not being run in dry run mode and if records were found that need to be patched. if ( ($amountOfRowsToPatch > 0) && (!$dryrun)) { echo "Patching table - column combination... Status: "; $patchQuery = "UPDATE {$tableName} SET {$columnName} = ? WHERE {$columnName} = ?"; $this->dbex->prepare( "patch{$tableName}{$columnName}", $patchQuery ); //d($patchQuery); try { $res = $this->dbex->execute( "patch{$tableName}{$columnName}", array($toUserId, $fromUserId) ); echo ($res) ? "success\n" : "failed\n"; } catch (Exception $e) { // An exception here doesn't necessarily have to be a problem. Some tables like 'gebruiker_collegas' and 'zoek_instellingen' // often result in duplicate keys. Therefore we ignore these occurences here. It is left up to the person who uses this method // to determine if further action is required or not. if (substr($e->getMessage(),0,30) == 'Database fout: Duplicate entry') { echo "done (ignoring duplicates)\n"; } else { die("EXCEPTION occurred: " . $e->getMessage() . "\n"); } } } } } // foreach ($tablesColumnsMap as $tableName => $columnNames) // Finally, if we are not being run in dry run mode, we also remove the user record if (!$dryrun) { // Start by getting the amount of records that will/would be patched. echo "\nRemoving 'from' user record... Status: "; $removeUserQuery = "DELETE FROM gebruikers WHERE id = ?"; $this->dbex->prepare( "removeUser", $removeUserQuery ); $res = $this->dbex->execute( "removeUser", array($fromUserId) ); echo ($res) ? "success\n" : "failed\n"; } echo "\nDone.\n"; } // public function merge_user($fromUser, $toUser, $dryrun = true) private function prepareDebug_Btz_Dossiers( $btDossiers ){ $this->load->model( 'dossier' ); $this->load->model( 'deelplan' ); $this->load->model( 'btbtzdossier' ); $this->load->model( 'dossiersubject' ); $bwns = array('BWN-1', 'BWN-2', "BWN-3") // array() ; $qnt_doss = count($bwns); // $i = 0; $i=rand(100,999999); $ret_bt_dossiers = array(); foreach( $btDossiers as $bt_doss ){ if($bt_doss->dossierId != 21877 ) continue; $bt_doss->bouwnummers = implode(',', $bwns ); $bt_doss->status = 'afgerond'; $ret_bt_dossiers[] = $bt_doss; $btz_doss_id = $this->dossier->add( 'DSSD-'.$i, 'Debug Doss-BWN-'.$i, time(), 'Debug Dossier address '.$i, 'PC_'.$i, 'LW_'.$i, '', '', '', '', '','handmatig' // ,567 ,874 // eps21 ); $dlp_id = $this->deelplan->add($btz_doss_id, 'Dbg Deelpln-BWN-'.$i); $bt_btz_data = array( 'bt_dossier_id' => $bt_doss->dossierId, 'bt_dossier_hash' => '0ae3fc1364f3f5e240160266b287cea7e2791260', 'btz_dossier_id' => $btz_doss_id, 'btz_dossier_hash' => '', 'bouwnummers' => $bt_doss->bouwnummers, 'bt_status' => 'bouwfase', 'btz_status' => 'open', 'project_status' => 'toets bouwfase' ); $this->btbtzdossier->insert($bt_btz_data); break; } return $ret_bt_dossiers; } private function get_bt_btz_dossiers(){ $this->load->model( 'btbtzdossier' ); // First get the existing records in the bt_btz_dossiers table that we (may) want to manipulate. // Note: for now at least, we skip the records that have project_status == 'afgesloten'. // As currently all entries are for Woningborg, we don't bother to pass a klant_id value as parameter. $klantId = null; $allNonClosedBtBtzDossiers = $this->btbtzdossier->get_all_non_closed($klantId); // Create a handy look-up table of these dossiers, indexed by their BT dossier ID $btBtzDossiers = array(); foreach($allNonClosedBtBtzDossiers as $nonClosedBtBtzDossier) { $btDossierId = $nonClosedBtBtzDossier->bt_dossier_id; if (!is_null($btDossierId) && !empty($btDossierId) && ($btDossierId > 0)) { $btBtzDossiers["$btDossierId"] = $nonClosedBtBtzDossier; } } return $btBtzDossiers; } // This method is specifically used for getting data for Woningborg from BT. There is some chance that someday other clients // will also use it, but for now this is not anticipated. Should it also need to become used for other clients, the below code needs // to be made more flexible. public function update_woningborg_bt_dossier_data() { echo "Updating Woningborg project data with data from BRIStoets...\n"; // Load the SOAP client helper $this->load->helper( 'soapclient' ); // Load the models we will be using //$this->load->model( 'webserviceaccount' ); $this->load->model( 'klant' ); $this->load->model( 'gebruiker' ); $this->load->model( 'dossier' ); $this->load->model( 'deelplan' ); $this->load->model( 'colectivematrix' ); $this->load->model( 'projectmap' ); $this->load->model( 'deelplanthema' ); $this->load->model( 'checklist' ); $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'deelplanchecklisttoezichtmoment' ); $this->load->model( 'bijwoonmomentenmap' ); //d(array_keys($btBtzDossiers)); //exit; // Then call the BT Soapdossier webservice (RPC method soapGetDossierStatus for retrieving the dossier data we need from BT. $btDataSuccessfullyRetrieved = false; $btDossiers = array(); // Note: for 'chatty' debug connections that generate output, the following settings should be used. $debug = true; $silent = false; // Note: for 'silent' connections that generate no output, the following settings should be used. $debug = false; $silent = true; // Instantiate a wrapped SoapClient helper so we can easily connect to the main soapDossier SOAP service, and use that for implementing the functionality // that should be available through the MVVSuite webservice functionality. $randval = rand(); $remoteBtSoapWsdl = $this->config->item('ws_url_wsdl_bt_soapdossier'); $btMethodName = 'soapGetDossierStatus'; $btMethodParameters = array(); $btMethodParameters['licentieNaam'] = 'WB_woningborg_usr'; $btMethodParameters['licentieWachtwoord'] = 'WB_woningborg_pwd'; $btMethodParameters['dossierId'] = ''; $btMethodParameters['dossierHash'] = ''; //$wrappedSoapClient = getWrappedSoapClientHelper($this->remoteBtSoapWsdl."/{$randval}", $methodName, $debug, $silent); $wrappedSoapClient = getWrappedSoapClientHelper($remoteBtSoapWsdl."&{$randval}", $btMethodName, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $btMethodParameters); //d($wrappedSoapClient); //d($wsResult); if (empty($wsResult)) { $errorMessage = "De BT SoapDossier webservice aanroep heeft geen data geretourneerd!"; if (!$silent) { echo "{$errorMessage}<br /><br />"; } } } // if (empty($wrappedSoapClient->soapErrors)) else { $errorMessage = "Foutmelding(en) bij maken connectie naar BT SoapDossier webservice:<br />\n<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; } } // else of clause: if (empty($wrappedSoapClient->soapErrors)) // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { $errorMessage = "Foutmelding(en) bij RPC aanroep naar BT SoapDossier webservice:<br />\n<br />\n"; foreach ($errorsDuringCall as $curError) { $errorMessage .= $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } if (!$silent) { echo "{$errorMessage}<br /><br />"; d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; } } // if (!empty($errorsDuringCall)) else { // If all went well and the main dossier webservice was called successfully and did its work, we should have received an answer from it. // We then extract the results from that (success or failure of the actual action that the webservice performed) and return that to the caller. if (!empty($wsResult) && isset($wsResult->success) && $wsResult->success) { // The call succeeded so signal that. $btDataSuccessfullyRetrieved = true; // If dossiers were retrieved, extract them and store them in the dataset that we will be using later. if (!empty($wsResult->results->dossierStatussen)) { $btDossiers = $wsResult->results->dossierStatussen; } /* // Extract the results that we need from the main service and pass them back in the result set $resultSet['success'] = $wsResult->success; $resultSet['message'] = $wsResult->message; $resultSet['errorCode'] = $wsResult->errorCode; $resultSet['wsResult'] = $wsResult; * */ //d($wsResult); } // if (!empty($wsResult)) } // else of clause: if (!empty($errorsDuringCall)) $is_force_debug = false; $is_force_debug = true; // ATT: This is DEBUG method!!! $is_force_debug ? $btDossiers = $this->prepareDebug_Btz_Dossiers( $btDossiers ):null; // For the debug purpose. Replace the method to get existing records in the bt_btz_dossiers table that we (may) want to manipulate. // Note: for now at least, we skip the records that have project_status == 'afgesloten'. // As currently all entries are for Woningborg, we don't bother to pass a klant_id value as parameter. $btBtzDossiers = $this->get_bt_btz_dossiers(); // Now process the retrieved dossiers, if any $btzDossiersForDuplication = array(); if ($btDataSuccessfullyRetrieved) { // Now that we know that we have actually retrieved dossiers from BT, we proceed to update our local records if necessary. foreach($btDossiers as $btDossier) { //d($btDossier); // Check if we have a mapping record for the currently processed BT dossier and if so, process it if something has changed. $curBtDossierId = $btDossier->dossierId; if (array_key_exists($curBtDossierId, $btBtzDossiers)) { // Extract the mapping record and update it if necessary $btBtzDossier = $btBtzDossiers["$curBtDossierId"]; // Perform the checks we want to do to determine if we should update the record or not. // First determine the current project status. $currentProjectStatus = $btBtzDossier->project_status; // Now unconditionally set the new BT project status and calculate what the new project status outcome would become. // In order to maintain more control, postpone the 'save' call by passing the value 'false'. This way we can do // additional checks and/or manipulate other fields too before actually saving the record. $btBtzDossier->bt_status = $btDossier->status; // Work out the correct new 'project_status' value only - don't save it yet! $btBtzDossier->determineAndSetProjectStatus(false); // Now check if the new project status is different from the current one and if so, update the DB record too. /* if ( ($btDossier->status != $btBtzDossier->bt_status) || ( !is_null($btDossier->bouwnummers) && ($btDossier->bouwnummers != $btBtzDossier->bouwnummers) ) ) * */ if ($is_force_debug|| //ATT: DEBUG condition ($currentProjectStatus != $btBtzDossier->project_status) || ( !is_null($btDossier->bouwnummers) && ($btDossier->bouwnummers != $btBtzDossier->bouwnummers) ) ) { // Update the BT fields echo "Updating status for project with kenmerk '{$btBtzDossier->kenmerk}' (ID: '{$btBtzDossier->id}'). " . "Current status: '{$currentProjectStatus}' - New status: '{$btBtzDossier->project_status}'\n"; //$btBtzDossier->bt_status = $btDossier->status; $btBtzDossier->bouwnummers = $btDossier->bouwnummers; //$btBtzDossier->bijgewerkt_op = date("Y-m-d H:i:s"); $btBtzDossier->verwerkt = false; // The new 'project_status' was already worked out, now save it (updating the DB record too) //$btBtzDossier->determineAndSetProjectStatus(true); $btBtzDossier->save(); // If the duplication code needs to be applied for a dossier, add the ID of the dossier to the set for it. // !!! Check if this is the EXACTLY correct check, or if further checks/conditions apply too. //if ($btBtzDossier->project_status == 'toezicht open') if ($is_force_debug|| //ATT: DEBUG condition $btBtzDossier->project_status == 'toets bouwfase') { $btzDossierId = $btBtzDossier->btz_dossier_id; $btzDossiersForDuplication["$btzDossierId"] = $btBtzDossier; } } } // if (array_key_exists($btDossier->dossierId, $btBtzDossiers)) } // foreach($btDossiers as $btDossier) } // if ($btDataSuccessfullyRetrieved) // !!! Yukon: Implement the following part (apply the duplication code for all BTZ dossiers of which the ID appears in the // look-up set foreach($btzDossiersForDuplication as $btzDossierIdForDuplication => $btBtzDossier) { // Get the BTZ dossier object $btzDossier = $this->dossier->get($btzDossierIdForDuplication); // !!! TODO (Yukon): apply duplication code (BEGIN)... $bt_project_matrix = $this->colectivematrix->getProjectSpecifiekeMapping( $btBtzDossier->bt_dossier_id, $btBtzDossier->bt_dossier_hash ); $bt_matrix_id = $bt_project_matrix['collective_matrix_id']; $gebruiker = $this->gebruiker->get($btzDossier->gebruiker_id); $klant = $this->klant->get( $gebruiker->klant_id ); $btz_matrixes = $klant->get_mappingen(); foreach($btz_matrixes as $btz_matrix ) { if($btz_matrix->bt_matrix_id == $bt_matrix_id ) { break; } } $checklist_id = $btz_matrix->checklist_id; $checklist = $this->checklist->get($checklist_id); $checklist_groep_id = $checklist->checklist_groep_id; $deelplannen = $btzDossier->get_deelplannen(); foreach( $deelplannen as $deelplan ) { $deelplan = $this->deelplan->get( $deelplan->id ); $deelplan->update_checklisten( array( 'checklistgroep' => array("$checklist_groep_id"=>'on'), // Empty 'checklist' => array("$checklist_id"=>'on'),//Set ids 'toezichthouders' => null, 'matrices' => null, ), TRUE ); $this->projectmap->create_project( $deelplan ); $deelplan->update_content( $btzDossier->gebruiker_id, true ); $project_vragen = $deelplan->get_project_mappen(); $thema_ids = array(); foreach( $project_vragen as $project_vraag ) { $thema_ids[] = $project_vraag->thema_id; } $thema_ids = array_unique( $thema_ids, SORT_NUMERIC ); $themachanges = $this->deelplanthema->set_for_deelplan( $deelplan->id, $thema_ids, array() ); foreach ($deelplan->get_checklistgroepen() as $checklistgroep) { foreach ($checklistgroep->get_checklisten() as $checklist) { if ($checklist->checklist_groep_id == $checklistgroep->id) { $voortgang = round( 100 * $deelplan->get_progress_by_checklist( $checklist->id ) ); $this->deelplanchecklist->update_voortgang( $deelplan->id, $checklist->id, $voortgang ); } } } $dp_checlisten = $deelplan->get_deelplan_checklisten(); foreach ($dp_checlisten as $dp_checklist ) { $dp_chlst_toezichtmomenten = $this->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist($dp_checklist->id); foreach ($dp_chlst_toezichtmomenten as $dp_toezichtmoment ) { $bijwoonmomentenmap = $this->bijwoonmomentenmap->get_by_toezichtmoment( $dp_toezichtmoment->bt_toezichtmoment_id, $btz_matrix->id ); $dp_toezichtmoment->bijwoonmoment = $bijwoonmomentenmap->is_drsm_bw; $dp_toezichtmoment->save(); } } } // At the end, signal that the record has been processed and store it. $btBtzDossier->verwerkt = true; $btBtzDossier->bijgewerkt_op = date("Y-m-d H:i:s"); $btBtzDossier->save(); } // foreach($btzDossierIdsForDuplication as $btzDossierIdForDuplication => $btBtzDossier) } // public function update_woningborg_bt_dossier_data() //---------------------------------------------------------------------------------------------------- private static function get_tag( &$tags ) { $tag = md5(rand()); while(in_array($tag, $tags )){$tag = md5(rand());} $tags[] = $tag; return $tag; } //ATT: Debug method /* public function generate_aa( $dp_chklist_tm_id ) { echo "\n"; $this->load->model( 'deelplanchecklisttoezichtmoment' ); echo "Generatining Woningborg deelplan opdrachten...\DeelplanChecklistToezichtmoment id: $dp_chklist_tm_id\n"; $t_moment = $this->deelplanchecklisttoezichtmoment->get($dp_chklist_tm_id); $t_moment->voornaam_uitvoerende = 'Debug-voornaam-'.$dp_chklist_tm_id; $t_moment->naam = 'Debug-naam-'.$dp_chklist_tm_id; $t_moment->achternaam_uitvoerende = 'Debug-achternaam-'.$dp_chklist_tm_id; $t_moment->email_uitvoerende = 'Debug-email-'.$dp_chklist_tm_id.'@debug.eml'; $t_moment->mobiele_nummer_uitvoerende = '+088-555-55-55'; $t_moment->datum_einde = date('Y-m-d',strtotime('+11 day')); $t_moment->save(false, null, false); echo "deelplan_checklist_id: ".$t_moment->deelplan_checklist_id."\n\n"; $t_moment->generate_deelplan_opdrachten(); } /* */ public function texts_db_migration(){ $teksten = $this->db->query( 'SELECT * FROM teksten WHERE tekst like "%BRIStoezicht%"' ); $lease_config_data=$this->db->query( 'SELECT * FROM lease_configuraties'); $i=0; foreach ($teksten->result() as $teksten_value){ foreach ($lease_config_data->result() as $lease_config_value){ unset($data); unset($new_text); $res=$this->db->query( "SELECT * FROM teksten WHERE string='".$teksten_value->string."' and lease_configuratie_id=".$lease_config_value->id); if($res->num_rows()==0){ $new_text=str_replace(array("BRIStoezicht","Bbristoezicht"), $lease_config_value->pagina_titel, $teksten_value->tekst); $data = array( 'string' => $teksten_value->string, 'tekst' => $new_text, 'timestamp'=>date('Y-m-d H:i:s'), 'lease_configuratie_id' => $lease_config_value->id ); $this->db->insert('teksten', $data); $i++; } } } print $i; } public function set_current_bijwoonmomenten_migration(){ echo "\n Default Bijwoonmomenten are being setted.\n"; $this->load->model( 'btbtzdossier' ); $this->load->model( 'dossier' ); $this->load->model( 'deelplanchecklisttoezichtmoment' ); $this->load->model( 'toezichtmoment' ); $btbtzdossiers = $this->btbtzdossier->all(); foreach($btbtzdossiers as $btbtzdossier ){ $dossier = $this->dossier->get($btbtzdossier->btz_dossier_id); $deelplannen = $dossier->get_deelplannen(); foreach( $deelplannen as $deelplan ) { $project_vragen = $deelplan->get_project_mappen(); $dp_checlisten = $deelplan->get_deelplan_checklisten(); foreach ($dp_checlisten as $dp_checklist ) { $dp_chlst_toezichtmomenten = $this->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist($dp_checklist->id); foreach ($dp_chlst_toezichtmomenten as $dp_toezichtmoment ) { $toezichtmoment = $this->toezichtmoment->get($dp_toezichtmoment->bt_toezichtmoment_id); $hoofdgroepen = $toezichtmoment->get_hoofdgroepen(); if( isset($hoofdgroepen[0]) )// Set bijwoonmoment status. { $dp_toezichtmoment->bijwoonmoment = FALSE; foreach($project_vragen as $project_vraag) { if($project_vraag->hoofdgroep_id == $hoofdgroepen[0]->id) { break; } } $dp_toezichtmoment->bijwoonmoment = $project_vraag->is_bw; $dp_toezichtmoment->save(); } } } } } } public function gereed_uitvoerende_test($opdrachtId) { echo "Test call to update 'status_gereed_uitvoerende' of a deelplan_checklist_toezichtmoment\n"; $this->load->model( 'deelplanopdracht' ); $deelplanOpdracht = $this->deelplanopdracht->get($opdrachtId); if (!is_null($deelplanOpdracht)) { echo "Opdracht met ID {$opdrachtId} gevonden. Verwerking volgt...\n"; echo "Huidige status opdracht: " . $deelplanOpdracht->status . "\n"; // Set status to 'gereed' and save $deelplanOpdracht->status = 'gereed'; $deelplanOpdracht->save(); } else { echo "Opdracht kon niet worden opgehaald. Mogelijk bestaat geen opdracht met ID {$opdrachtId}\n"; } } }// Class end <file_sep><?php $this->load->view('elements/header', array('page_header'=>'toezichtmomenten.hoofdgroepen','map_view'=>true));?> <h1><?=tgg('toezichtmomenten.headers.hoofdgroepen')?></h1> <?php $t_val = (bool)$toezichtmoment_id ? '/'.$toezichtmoment_id : ''; ?> <form id="toezichtmomentForm" action="<?=site_url('/toezichtmomenten/save_toezichtmoment/').'/'.$checklistgroep_id.'/'.$checklist_id.$t_val ?>" method="POST"> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list"> <tr> <td><input type="text" name="codekey" id="codekey" maxlength="5" class="rounded5" placeholder="Codekey" value="<?=$codekey ?>" /></td> <td><input type="text" name="naam" id="naam" size="80" class="rounded5" placeholder="Naam" value="<?=$naam ?>" /></td> </tr> </table> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==sizeof($list)-1) ? 'bottom' : ''; $checked = $entry->toezichtmoment_id ? 'checked' :''; ?> <li class="entry top left right <?=$bottom?>" entry_id="<?=$entry->id ?>"> <img style="margin-left: 3px; padding-top: 10px; vertical-align: bottom;" src="<?=$image_url ?>"> <div class="list-entry" style="margin-top: 3px; vertical-align: bottom;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> <div style="float: right; margin-right: 8px; margin-top: 8px;" title=""> <input type="checkbox" id="hoofdgroep_<?=$entry->id ?>" name="hoofdgroepen[<?=$entry->id ?>]" <?=$checked ?> /> </div> </li> <? endforeach; ?> </ul> </div> <div class="button opslaan"> <a href="javascript:void(0);" style="font-weight: bold; font-size: 120%; "><?=tgng('form.opslaan')?>!</a> </div> </form> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $(document).ready(function(){ var message = "<?=$message ?>" ,mess_type="<?=$mess_type ?>" ; $("#codekey").focus(); if(message != "" ){ showMessageBox({ message: message, type: mess_type, buttons: ['ok'] ,onClose: function( res ) { (mess_type=="error") ? $("#codekey").focus():null; } }); } $(".button.opslaan").click(function(){ if($("#codekey").val().trim() == ""){ showMessageBox({ message: 'Lege codekey niet toegestaan.', type: 'error', buttons: ['ok'] }); $("#codekey").focus(); return false; } if($("#naam").val().trim() == ""){ showMessageBox({ message: 'Lege naam niet toegestaan.', type: 'error', buttons: ['ok'] }); $("#naam").focus(); return false; } $("#toezichtmomentForm").submit(); }); }); </script><file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_log_informatie')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Log informatie', 'expanded' => true, 'width' => '920px', 'height' => 'auto' ) ); ?> <form name="form" method="post"> <table width="100%"> <tr> <td colspan="5"> <h3><?=tg('filter_instellingen')?></h3> </td> </tr> <tr> <th><?=tg('soorten')?>:</th> <td> <input type="button" value="<?=tgng('form.alle')?>" onclick="alle_soorten();" /> <input type="button" value="<?=tgng('form.geen')?>" onclick="geen_soorten();" /> </td> <td colspan="3"> <? foreach ($soorten as $soort): ?> <input type="checkbox" <?=array_search($soort,$selected_soorten)!==FALSE?'checked ':''?>name="soort_<?=$soort?>" />&nbsp;<?=$soort?> <? endforeach; ?> <script language="JavaScript"> function alle_soorten() { x_soorten( true ); } function geen_soorten() { x_soorten( false ); } function x_soorten( val ) { <? foreach ($soorten as $soort): ?> document.form.soort_<?=$soort?>.checked=val; <? endforeach; ?> } </script> </td> </tr> <tr> <th><?=tg('gebruikers')?>:</th> <td> <input type="button" value="<?=tgng('form.alle')?>" onclick="alle_gebruikers();" /> <input type="button" value="<?=tgng('form.geen')?>" onclick="geen_gebruikers();" /> </td> <td colspan="4"> <? foreach ($gebruikers as $gebruiker): ?> <input type="checkbox" <?=array_search($gebruiker->id,$selected_gebruikers)!==FALSE?'checked ':''?>name="gebruiker_<?=$gebruiker->id?>" />&nbsp;<?=$gebruiker->volledige_naam?> <? endforeach; ?> <script language="JavaScript"> function alle_gebruikers() { x_gebruikers( true ); } function geen_gebruikers() { x_gebruikers( false ); } function x_gebruikers( val ) { <? foreach ($gebruikers as $gebruiker): ?> document.form.gebruiker_<?=$gebruiker->id?>.checked=val; <? endforeach; ?> } </script> </td> </tr> <tr> <th><?=tg('vanaf_datum')?>:</th> <td colspan="4"> <input type="text" name="start_datum" value="<?=$start_datum?>" /> </td> </tr> <tr> <th><?=tg('tot_datum')?>:</th> <td colspan="4"> <input type="text" name="eind_datum" value="<?=$eind_datum?>" /> </td> </tr> <tr> <th></th> <td> <input type="submit" value="Zoeken" /> </td> <td colspan="3" style="text-align:right"> <input type="button" value="<?=tgng('form.alles_wissen')?>" onclick="location.href='<?=site_url('/instellingen/log')?>';" /> </td> </tr> <tr> <td colspan="5"> <h3><?=tg('resultaten', $count)?></h3> </td> </tr> <tr> <th style="text-align:left"><?=tg('gebruiker')?></th> <th style="text-align:left"><?=tg('datum')?></th> <th style="text-align:left"><?=tg('soort')?></th> <th style="text-align:left"><?=tg('omschrijving')?></th> <th style="text-align:left"><?=tg('dossier')?></th> </tr> <? if (isset( $data )): ?> <? foreach ($data as $entry): ?> <tr> <td><?=$entry->volledige_naam?></td> <td><?=date('d-m-Y G:i', $entry->datum)?></td> <td><?=htmlentities($entry->soort)?></td> <td> <? if ($entry->extra_info): ?> <img src="<?=site_url('/content/png/info_small')?>" onmouseover="$('#npb_<?=$entry->id?>').toggle();" onmouseout="$('#npb_<?=$entry->id?>').toggle();" /> <? endif; ?> <?=$entry->omschrijving?> <? if ($entry->extra_info): ?> <div id="npb_<?=$entry->id?>" style="display:none;position:relative;"> <div class="npb" style="width:500px; left:-150px;"> <?=$entry->extra_info?> </div> </div> <? endif; ?> </td> <td><?=htmlentities($entry->kenmerk)?></td> </tr> <? endforeach; ?> <? endif; ?> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE `teksten` DROP `taal`; ALTER TABLE `teksten` CHANGE `timestamp` `timestamp` DATETIME NULL DEFAULT NULL ; <file_sep>CREATE TABLE IF NOT EXISTS `deelplan_bouwdelen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `naam` varchar(128) NOT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `deelplan_id_2` (`deelplan_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `deelplan_bouwdelen` ADD CONSTRAINT `deelplan_bouwdelen_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>ALTER TABLE `deelplannen` ADD `foreignid` INT NULL DEFAULT NULL AFTER `id` ; ALTER TABLE `deelplannen` ADD `kenmerk` VARCHAR( 32 ) NULL DEFAULT NULL AFTER `naam` ; <file_sep><?php class BAGKoppelingInstelling extends Model { private $CI; private $waarden = array(); public function __construct() { $this->CI = get_instance(); $res = $this->CI->db->get( 'bag_koppeling_instellingen' ); foreach ($res->result() as $row) $this->waarden[ $row->sleutel ] = $row->waarde; $res->free_result(); } public function get( $sleutel, $default=null ) { if (!isset( $this->waarden[ $sleutel ] )) return $default; return $this->waarden[ $sleutel ]; } public function set( $sleutel, $waarde ) { $sleutel = strval( $sleutel ); $waarde = strval( $waarde ); //$this->CI->dbex->prepare( 'BAGKoppelingInstelling::set', 'REPLACE INTO bag_koppeling_instellingen (sleutel, waarde) VALUES (?, ?)' ); $this->CI->dbex->prepare_replace_into( 'BAGKoppelingInstelling::set', 'REPLACE INTO bag_koppeling_instellingen (sleutel, waarde) VALUES (?, ?)', null, array('sleutel') ); if (!$this->CI->dbex->execute( 'BAGKoppelingInstelling::set', array( $sleutel, $waarde ) )) throw new Exception( 'Fout bij opslaan bag koppeling instelling ' . $sleutel ); $this->waarden[ $sleutel ] = $waarde; } public function keys() { return array_keys( $this->waarden ); } } <file_sep>ALTER TABLE `bt_grondslag_teksten` DROP `artikel_new` ; ALTER TABLE `bt_grondslag_teksten` ADD `display_hoofdstuk` VARCHAR( 32 ) NOT NULL, ADD `display_afdeling` VARCHAR( 32 ) NOT NULL, ADD `display_paragraaf` VARCHAR( 32 ) NOT NULL, ADD `display_artikel` VARCHAR( 32 ) NOT NULL, ADD `display_lid` VARCHAR( 32 ) NOT NULL; <file_sep>ALTER TABLE `kennisid_tijden` ADD `tijdstip` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; <file_sep><? $this->load->view('elements/header', array('page_header'=>'mappingen.mappingenlist','map_view'=>true)); ?> <h1><?=tgg('mappingen.headers.mappingenlist')?></h1> <div class="main"> <table cellspacing="0" cellpadding="0" border="0" class="list"> <tr> <td> <input type="text" id="naam" name="naam" size="80" class="rounded5" placeholder="Naam"> <div class="button snel" style="margin-left: 10px;"> <i class="icon-plus" style="font-size: 12pt;"></i> <span>Snel</span> </div> <?=htag('snel')?> </td> </tr> </table> <?$lcount = count($list);?> <?if($lcount > 0):?> <?$lcount--; ?> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==$lcount) ? 'bottom' : ''; ?> <li class="entry top left right <?=$bottom?>" entry_id="<?=$entry->id ?>"> <div class="list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> <? if(0&& $entry->bt_matrix_id && $entry->checklist_id ): ?> <div class="optiebutton clone_btn" style="margin-top:5px;margin-left:3px;float:right;"><i class="icon-copy" style="font-size:12pt;" title="<?=$titles['btn_clone_title']?>"></i></div> <? endif; ?> </li> <? endforeach; ?> </ul> <?else:?> <div style="padding-top:10px;padding-left:5px;font-weight:bold;"><?=tgg('mappingen.noitems') ?></div> <?endif ?> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = "<?=site_url('/mappingen/checklistenmap/').'/'?>"+$(this).attr("entry_id"); }); //------------------------------------------------------------------------------ $(".clone_btn").click(function(evt){ eventStopPropagation (evt); if( $("#naam").val()=='' ){ showMessageBox({ message: "You must enter DMM name.", type: "error", buttons: ["ok"] }); return; } location.href = "<?=site_url('/mappingen/dmmclonemap/').'/'?>"+$(this).parent("li").attr("entry_id")+"/"+encodeURI($("#naam").val()); }); //------------------------------------------------------------------------------ // handle toevoegen $('div.main input[type=text]').keypress(function(event){ if (event.which == 13) $('div.main div.button.snel').trigger('click'); }); //------------------------------------------------------------------------------ $('div.main div.button.snel').click(function(){ $.ajax({ url: "<?=site_url('mappingen/savetitle')?>", type: 'POST', data: { naam: $("#naam").val() }, dataType: 'json', success: function( data ) { if (data && data.success){ location.href = location.href; // refresh }else { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen:<br/><br/><i>' + data.error + '</i>', type: 'error', buttons: ['ok'] }); } }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); }); //------------------------------------------------------------------------------ }); </script> <file_sep><?php class WizardException extends Exception { var $field; public function __construct( $message, $field=null) { parent::__construct( $message ); $this->field = $field; } public function getField() { return $this->field; } } function resolve_thema( $thema_id, $thema_new, $hoofdthema_new ) { $CI = get_instance(); $thema = NULL; $hoofdthema = NULL; if (!$thema_id) throw new WizardException( 'Geen thema geselecteerd.', 'thema_id' ); else { if ($thema_id != 'new') { $thema = $CI->thema->get( $thema_id ); if (!$thema) throw new WizardException( 'Onbekend thema geselecteerd.', 'thema_id' ); } else { // check hoofdthema naam $hoofdthema_new = trim( $hoofdthema_new ); if (!$hoofdthema_new) throw new WizardException( 'Lege hoofdthemanaam niet toegestaan.', 'hoofdthema_new' ); // check thema naam if (!strlen($thema_new)) throw new WizardException( 'Lege themanaam niet toegestaan.', 'thema_new' ); // resolve hoofdthema $hoofdthema = $CI->hoofdthema->find( $hoofdthema_new ); if (!$hoofdthema) { $hoofdthema = $CI->hoofdthema->add( $hoofdthema_new, 0, 'Eigen' ); if (!$hoofdthema) throw new WizardException( 'Fout bij toevoegen hoofdthema.', 'hoofdthema_new' ); } // resolve thema $thema = $CI->thema->find( $thema_new, null, $hoofdthema->id ); if (!$thema) { $thema = $CI->thema->add( $thema_new, 0, $hoofdthema->id ); if (!$thema) throw new WizardException( 'Fout bij toevoegen thema.', 'thema_new' ); } } } return $thema; } function resolve_hoofdthema( $hoofdthema_naam ) { $CI = get_instance(); if (!isset( $CI->hoofdthema )) $CI->load->model( 'hoofdthema' ); $hoofdthema = $CI->hoofdthema->find( $hoofdthema_naam ); if (!$hoofdthema) { $hoofdthema = $CI->hoofdthema->add( $hoofdthema_naam, 0, 'Eigen' ); if (!$hoofdthema) throw new Exception( 'Fout bij toevoegen hoofdthema.' ); } return $hoofdthema; } function resolve_grondslag( $grondslag_id, $grondslag_new ) { $CI = get_instance(); $grondslag = NULL; if (!$grondslag_id) throw new WizardException( 'Geen grondslag geselecteerd.', 'grondslag_id' ); else { if ($grondslag_id != 'new') { $grondslag = $CI->grondslag->get( $grondslag_id ); if (!$grondslag) throw new WizardException( 'Onbekende grondslag geselecteerd.', 'grondslag_id' ); } else { $grondslag_new = trim( $grondslag_new ); if (!$grondslag_new) throw new WizardException( 'Lege grondslag niet toegestaan.', 'grondslag_new' ); else { $grondslag = $CI->grondslag->find( $grondslag_new ); if (!$grondslag) { $grondslag = $CI->grondslag->add( $grondslag_new ); if (!$grondslag) throw new WizardException( 'Fout bij toevoegen grondslag.', 'grondslag_new' ); } } } } return $grondslag; } function calc_aanwezigheid( $prios ) { $aanwezigheid = 0; foreach ($prios as $prio) $aanwezigheid |= 1 << ($prio-1); return $aanwezigheid; } function get_verander_prioriteiten_values_from_post( &$or, &$clear ) { $or = null; $clear = null; for ($i=1; $i<=5; ++$i) { $bit = pow( 2, $i-1 ); switch ($_POST['prio'.$i]) { case 'null': break; case 'set': if (is_null( $or )) $or = 0; $or |= $bit; break; case 'clear': if (is_null( $clear )) $clear = 0; $clear |= $bit; break; } } } // werkt voor checklist related objecten (checklistgroep, checklist, hoofdgroepm // categorie, vraag) die een "sortering" veld hebben. // // LET OP: als new_parent_value gezet is, gaat dit object er vanuit dat // het een kopie van het opgegeven object moet maken op dezelfde plek (qua sortering) als binnen // het origineel, en dus wordt het veld sortering gewoon gekopieerd. Anders wordt // een sorterings waarde opgezocht waardoor de kopie onderaan komt te staan. // // LET OP: als parent_name wordt weggelaten, wordt de sortering bijgewerkt zonder te kijken // naar een parent. Dit is alleen van toepassing voor checklist groepen. function kopieer_object( BaseResult $object, $parent_name=null, $new_parent_value=null ) { // bepaal parent ID en sortering $CI = get_instance(); $model = $object->get_model(); if ($new_parent_value && $parent_name != 'klant_id') { $sortering = $object->sortering; $naam = null; // niet veranderen! } else { // bepaal stukje SQL wat nodig is om te zoeken "binnen de huidige parent context" if ($parent_name) $parent_query = ' AND ' . $parent_name . ' = ' . $object->{$parent_name}; else $parent_query = ''; // Determine which "null function" should be used $null_func = get_db_null_function(); // !!! Query tentatively made Oracle compatible. To be fully tested... // zoek sortering $res = $CI->db->query( 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS sortering FROM ' . $model->get_table() . ' WHERE 1=1 ' . $parent_query ); if (!$res) throw new Exception( 'Database fout bij het ophalen van de sortering bij het kopieren.' ); $sortering = $res->row_object()->sortering; $res->free_result(); // als het object een naam heeft, voeg dan iets van "kopie 2, kopie 3" etc toe if (isset( $object->naam )) { $i = 1; do { if ($i > 1) $naam = 'Kopie ' . $i . ' van ' . $object->naam; else $naam = 'Kopie van ' . $object->naam; $res = $CI->db->query( 'SELECT COUNT(*) AS count FROM ' . $model->get_table() . ' WHERE naam = ' . $CI->db->escape($naam) . ' ' . $parent_query ); if (!$res) throw new Exceptoin( 'Database fout bij het ophalen van de juiste nieuwe naam bij het kopieren.' ); $found = $res->row_object()->count > 0; $res->free_result(); ++$i; } while ($found); } else $naam = null; } // kopieer waarden naar array $object_waarden = $object->get_array_copy(); // (hoofd)thema stuff aanpassen wanneer nodig if (array_key_exists( 'thema_id', $object_waarden ) || array_key_exists( 'standaard_thema_id', $object_waarden )) // "categorie" zit er nog tussen, die heeft dit niet!! { $onze_klant_id = $CI->gebruiker->get_logged_in_gebruiker()->klant_id; $prefix = array_key_exists( 'standaard_thema_id', $object_waarden ) ? 'standaard_' : ''; if (!is_null( $object_waarden[$prefix . 'thema_id'] )) { if (!isset( $CI->thema )) $CI->load->model( 'thema' ); $thema = $CI->thema->get( $object_waarden[$prefix . 'thema_id'] ); if ($thema->klant_id != $onze_klant_id) { $hoofdthema = $thema->get_hoofdthema(); $new_thema = resolve_thema( 'new', $thema->thema, $hoofdthema->naam ); $object_waarden[$prefix . 'thema_id'] = $new_thema->id; } } } // bouw query $query = 'INSERT INTO ' . $model->get_table() . ' ('; // SQL $query_values = ''; // SQL $values = array(); // values $c = 0; foreach ($object_waarden as $k => $v) { if ($k == 'id') continue; $query .= ($c?',':'') . $k; $query_values .= ($c?',':''); ++$c; if ($k == $parent_name && $new_parent_value) $v = $new_parent_value; else if ($k == 'sortering' && $sortering) $v = $sortering; else if ($k == 'naam' && $naam) $v = $naam; $query_values .= '?'; $values[] = $v; } $query .= ') VALUES (' . $query_values . ')'; if (!($CI->dbex->prepare( 'kopieer', $query ))) throw new Exception( 'Database statement prepare fout bij kopieren: ' . $CI->db->_error_message() ); if (!($CI->dbex->execute( 'kopieer', $values ))) throw new Exception( 'Database statement execute fout bij kopieren.' ); if (!($obj = $model->get( $CI->db->insert_id() ))) throw new Exception( 'Database fout: kon nieuw aangemaakt object niet vinden na toevoegen.' ); // kopieer achtergrond informatie if ($object instanceof ChecklistGroepResult) $achtergrondtabellen = array( 'bt_checklist_groep_ndchtspntn' => array( '*' => 'checklist_groep_id', 'checklist_groep_id' => $obj->id, 'aandachtspunt' => null ), 'bt_checklist_groep_grndslgn' => array( '*' => 'checklist_groep_id', 'checklist_groep_id' => $obj->id, 'grondslag_tekst_id' => null ), 'bt_checklist_groep_rchtlnn' => array( '*' => 'checklist_groep_id', 'checklist_groep_id' => $obj->id, 'richtlijn_id' => null ), 'bt_checklist_groep_opdrachten' => array( '*' => 'checklist_groep_id', 'checklist_groep_id' => $obj->id, 'opdracht' => null ), 'bt_checklist_groep_verantwtkstn' => array( '*' => 'checklist_groep_id', 'checklist_groep_id' => $obj->id, 'verantwoordingstekst' => null, 'status' => null ), ); else if ($object instanceof ChecklistResult) $achtergrondtabellen = array( 'bt_checklist_ndchtspntn' => array( '*' => 'checklist_id', 'checklist_groep_id' => $obj->checklist_groep_id, 'checklist_id' => $obj->id, 'aandachtspunt' => null ), 'bt_checklist_grndslgn' => array( '*' => 'checklist_id', 'checklist_groep_id' => $obj->checklist_groep_id, 'checklist_id' => $obj->id, 'grondslag_tekst_id' => null ), 'bt_checklist_rchtlnn' => array( '*' => 'checklist_id', 'checklist_groep_id' => $obj->checklist_groep_id, 'checklist_id' => $obj->id, 'richtlijn_id' => null ), 'bt_checklist_opdrachten' => array( '*' => 'checklist_id', 'checklist_groep_id' => $obj->checklist_groep_id, 'checklist_id' => $obj->id, 'opdracht' => null ), 'bt_checklist_verantwtkstn' => array( '*' => 'checklist_id', 'checklist_groep_id' => $obj->checklist_groep_id, 'checklist_id' => $obj->id, 'verantwoordingstekst' => null, 'status' => null ), ); else if ($object instanceof HoofdgroepResult) { $checklist = $obj->get_checklist(); $achtergrondtabellen = array( 'bt_hoofdgroep_ndchtspntn' => array( '*' => 'hoofdgroep_id', 'checklist_groep_id' => $checklist->checklist_groep_id, 'hoofdgroep_id' => $obj->id, 'aandachtspunt' => null ), 'bt_hoofdgroep_grndslgn' => array( '*' => 'hoofdgroep_id', 'checklist_groep_id' => $checklist->checklist_groep_id, 'hoofdgroep_id' => $obj->id, 'grondslag_tekst_id' => null ), 'bt_hoofdgroep_rchtlnn' => array( '*' => 'hoofdgroep_id', 'checklist_groep_id' => $checklist->checklist_groep_id, 'hoofdgroep_id' => $obj->id, 'richtlijn_id' => null ), 'bt_hoofdgroep_opdrachten' => array( '*' => 'hoofdgroep_id', 'checklist_groep_id' => $checklist->checklist_groep_id, 'hoofdgroep_id' => $obj->id, 'opdracht' => null ), 'bt_hoofdgroep_verantwtkstn' => array( '*' => 'hoofdgroep_id', 'checklist_groep_id' => $checklist->checklist_groep_id, 'hoofdgroep_id' => $obj->id, 'verantwoordingstekst' => null, 'status' => null ), ); } else if ($object instanceof CategorieResult) $achtergrondtabellen = array(); else if ($object instanceof VraagResult) { $checklist = $obj->get_categorie()->get_hoofdgroep()->get_checklist(); $achtergrondtabellen = array( 'bt_vraag_ndchtspntn' => array( '*' => 'vraag_id','checklist_groep_id' => $checklist->checklist_groep_id, 'checklist_id' => $checklist->id, 'vraag_id' => $obj->id, 'aandachtspunt' => null ), 'bt_vraag_grndslgn' => array( '*' => 'vraag_id','checklist_groep_id' => $checklist->checklist_groep_id, 'checklist_id' => $checklist->id, 'vraag_id' => $obj->id, 'grondslag_tekst_id' => null ), 'bt_vraag_rchtlnn' => array( '*' => 'vraag_id','checklist_groep_id' => $checklist->checklist_groep_id, 'checklist_id' => $checklist->id, 'vraag_id' => $obj->id, 'richtlijn_id' => null ), 'bt_vraag_opdrachten' => array( '*' => 'vraag_id','checklist_groep_id' => $checklist->checklist_groep_id, 'checklist_id' => $checklist->id, 'vraag_id' => $obj->id, 'opdracht' => null ), 'bt_vraag_verantwtkstn' => array( '*' => 'vraag_id','checklist_groep_id' => $checklist->checklist_groep_id, 'checklist_id' => $checklist->id, 'vraag_id' => $obj->id, 'verantwoordingstekst' => null, 'status' => null ), ); } else throw new Exception( 'kopieer_object: geen checklistgroep, checklist, hoofdgroep of vraag: ' . get_class($object) ); foreach ($achtergrondtabellen as $tabel => $velden) { if (!isset( $velden['*'] )) throw new Exception( 'Achtergrondtabellen kopieer informatie bevat geen zoekveld (*).' ); $zoekveld = $velden['*']; unset( $velden['*'] ); $query = 'INSERT INTO ' . $tabel . ' (' . implode(',', array_keys( $velden ) ) . ') SELECT '; $c = 0; foreach ($velden as $veld => $waarde) { $query .= ($c++?',':''); if (is_null( $waarde )) $query .= $veld; else $query .= $CI->db->escape( $waarde ); } $query .= ' FROM ' . $tabel . ' WHERE ' . $zoekveld . ' = ' . $object->id; if (!$CI->db->query( $query )) throw new Exception( 'Fout bij kopieren achtergrondinformatie: ' . $query ); } return $obj; } // geeft een getal terug dat afwijkingen van de defaults/standaarden aangeeft: // 0 - geen afwijkingen (of is een checklistgroep) // 1 - heeft zelf afwijkingen // 2 - onderliggende objecten wijken af (alleen mogelijke return waarde als $recursief=true) function wizard_object_heeft_afwijkingen( BaseResult $object, $recursief=true ) { // dit is de top laag, een checklistgroep kan nooit afwijken van de defaults, omdat hij // de defaults "is"! if ($object instanceof ChecklistGroepResult) return 0; $velden = array( 'actief', 'vraag_type', 'aanwezigheid', 'thema_id', 'toezicht_moment', 'fase', 'wo_tekst_00', 'wo_is_leeg_00', 'wo_kleur_00', 'wo_in_gebruik_00', 'wo_tekst_01', 'wo_is_leeg_01', 'wo_kleur_01', 'wo_in_gebruik_01', 'wo_tekst_02', 'wo_is_leeg_02', 'wo_kleur_02', 'wo_in_gebruik_02', 'wo_tekst_03', 'wo_is_leeg_03', 'wo_kleur_03', 'wo_in_gebruik_03', 'wo_tekst_04', 'wo_is_leeg_04', 'wo_kleur_04', 'wo_in_gebruik_04', 'wo_tekst_10', 'wo_is_leeg_10', 'wo_kleur_10', 'wo_in_gebruik_10', 'wo_tekst_11', 'wo_is_leeg_11', 'wo_kleur_11', 'wo_in_gebruik_11', 'wo_tekst_12', 'wo_is_leeg_12', 'wo_kleur_12', 'wo_in_gebruik_12', 'wo_tekst_13', 'wo_is_leeg_13', 'wo_kleur_13', 'wo_in_gebruik_13', 'wo_tekst_20', 'wo_is_leeg_20', 'wo_kleur_20', 'wo_in_gebruik_20', 'wo_tekst_21', 'wo_is_leeg_21', 'wo_kleur_21', 'wo_in_gebruik_21', 'wo_tekst_22', 'wo_is_leeg_22', 'wo_kleur_22', 'wo_in_gebruik_22', 'wo_tekst_23', 'wo_is_leeg_23', 'wo_kleur_23', 'wo_in_gebruik_23', 'wo_standaard', 'wo_steekproef', 'wo_steekproef_tekst', 'gebruik_grndslgn', 'gebruik_rchtlnn', 'gebruik_ndchtspntn', 'gebruik_opdrachten', 'gebruik_verantwtkstn', ); foreach ($velden as $veld) if ((property_exists( $object, $veld ) && !is_null( $object->$veld )) || (property_exists( $object, 'standaard_' . $veld ) && !is_null( $object->{'standaard_' . $veld} ))) return 1; if ($recursief) foreach ($object->get_wizard_onderliggenden() as $child) if (wizard_object_heeft_afwijkingen( $child, $recursief )) return 2; return 0; } /* zoekt recursief, wanneer een vraag b.v. geen grondslagen heeft, wordt het hoofdgroep getest, etc. */ function wizard_get_grondslagen( BaseResult $object ) { return wizard_get_achtergrond_informatie( $object, 'grondslagen', 'grondslagtekst', 'grondslag_tekst_id' ); } function wizard_get_richtlijnen( BaseResult $object ) { return wizard_get_achtergrond_informatie( $object, 'richtlijnen', 'richtlijn', 'richtlijn_id' ); } function wizard_get_aandachtspunten( BaseResult $object ) { return wizard_get_achtergrond_informatie( $object, 'aandachtspunten', null, 'aandachtspunt' ); } function wizard_get_opdrachten( BaseResult $object ) { return wizard_get_achtergrond_informatie( $object, 'opdrachten', null, 'opdracht' ); } function wizard_get_automatic_verantwoordingsteksten( BaseResult $object ){ $CI = get_instance(); $query = "SELECT * FROM bt_vraag_verantwtkstn_automatic WHERE bt_vraag_verantwtkstn_automatic.vraag_id =".$object->id; $res = $CI->db->query( $query ); if (!$res) throw new Exception( 'Fout bij database query: ' . $query ); $result = $res->result(); $automatic_verantwoordingsteksten=array(); if($result){ foreach ($result as $result_value){ $button_naam=array(); $res_config = $CI->db->query( "select * from verantwoordingstekst_config where vraag_verantwtkstn_id=".$result_value->id); $result_config = $res_config->result(); foreach ($result_config as $value_result_config){ $button_naam[]=$object->get_wizard_veld_recursief(str_replace("w", "wo_tekst_", $value_result_config->name)); } $automatic_verantwoordingsteksten[]=array("id"=>$result_value->id,"verantwoordingsteksten"=>$result_value->verantwoordingstekst, "button_naam"=>$button_naam, "vraag_id"=>$object->id, "automatish_generate"=>$result_value->automatish_generate); } $res->free_result(); $res_config->free_result(); return $automatic_verantwoordingsteksten; } } function wizard_get_verantwoordingsteksten( BaseResult $object ) { return wizard_get_achtergrond_informatie( $object, 'verantwoordingsteksten', null, array('verantwoordingstekst', 'status') ); } function wizard_get_achtergrond_informatie( BaseResult $object, $type, $model, $veld ) { // !!! Get the short type name, this is needed for the tables that were renamed on behalf of Oracle compatibility (identifiers <= 30 characters) $type_short = $type; if ($type == 'aandachtspunten') $type_short = 'ndchtspntn'; else if ($type == 'grondslagen') $type_short = 'grndslgn'; else if ($type == 'richtlijnen') $type_short = 'rchtlnn'; else if ($type == 'verantwoordingsteksten') { //$type_short = ($object instanceof ChecklistGroepResult) ? 'veranttkstn' : 'verantwtkstn'; $type_short = 'verantwtkstn'; } $testveld = $object instanceof VraagResult ? 'gebruik_' . $type_short : 'standaard_gebruik_' . $type_short; if (!@$object->$testveld && ($parent = $object->get_wizard_parent())) return wizard_get_achtergrond_informatie( $parent, $type, $model, $veld ); if ($object instanceof ChecklistGroepResult) { $tabel = 'bt_checklist_groep_' . $type_short; $zoekveld = 'checklist_groep_id'; } else if ($object instanceof ChecklistResult) { $tabel = 'bt_checklist_' . $type_short; $zoekveld = 'checklist_id'; } else if ($object instanceof HoofdgroepResult) { $tabel = 'bt_hoofdgroep_' . $type_short; $zoekveld = 'hoofdgroep_id'; } else if ($object instanceof VraagResult) { $tabel = 'bt_vraag_' . $type_short; $zoekveld = 'vraag_id'; } else throw new Exception( 'wizard_get_achtergrond_informatie: niet ondersteund object type: ' . get_class( $object ) ); $CI = get_instance(); $query = 'SELECT ' . (is_array($veld) ? implode(', ', $veld) : $veld) . ' FROM ' . $tabel . ' WHERE ' . $zoekveld . ' = ' . intval($object->id); if ($model) { $CI->load->model( $model ); return $CI->$model->search( array(), 'id IN (' . $query . ')' ); } else { $res = $CI->db->query( $query ); if (!$res) throw new Exception( 'Fout bij database query: ' . $query ); $result = $res->result(); $res->free_result(); return $result; } } function wizard_cleanup_table_name( $type ) { if ($type == 'opdrachten') return $type; if ($type == 'verantwoordingsteksten') return 'verantwtkstn'; return preg_replace( '/(ij)|[aeoiu]/', '', $type ); } /* delete NIET recursief, alleen de achtergrondinfo bij het opgegeven object wordt verwijderd, als deze ze niet heeft gebeurt er dus niks */ function wizard_verwijder_grondslagen( BaseResult $object ) { return wizard_verwijder_achtergrond_informatie( $object, 'grondslagen' ); } function wizard_verwijder_richtlijnen( BaseResult $object ) { return wizard_verwijder_achtergrond_informatie( $object, 'richtlijnen' ); } function wizard_verwijder_aandachtspunten( BaseResult $object ) { return wizard_verwijder_achtergrond_informatie( $object, 'aandachtspunten' ); } function wizard_verwijder_opdrachten( BaseResult $object ) { return wizard_verwijder_achtergrond_informatie( $object, 'opdrachten' ); } function wizard_verwijder_verantwoordingsteksten( BaseResult $object ) { return wizard_verwijder_achtergrond_informatie( $object, 'verantwoordingsteksten' ); } function wizard_verwijder_achtergrond_informatie( BaseResult $object, $type ) { $type = wizard_cleanup_table_name( $type ); //if ($object instanceof ChecklistGroepResult) { $tabel = 'bt_checklist_groep_' . (($type == 'verantwtkstn') ? 'veranttkstn' : $type); $zoekveld = 'checklist_groep_id'; } if ($object instanceof ChecklistGroepResult) { $tabel = 'bt_checklist_groep_' . $type; $zoekveld = 'checklist_groep_id'; } else if ($object instanceof ChecklistResult) { $tabel = 'bt_checklist_' . $type; $zoekveld = 'checklist_id'; } else if ($object instanceof HoofdgroepResult) { $tabel = 'bt_hoofdgroep_' . $type; $zoekveld = 'hoofdgroep_id'; } else if ($object instanceof VraagResult) { $tabel = 'bt_vraag_' . $type; $zoekveld = 'vraag_id'; } else throw new Exception( 'wizard_verwijder_achtergrond_informatie: niet ondersteund object type: ' . verwijder_class( $object ) ); if (!(get_instance()->db->query( $query = 'DELETE FROM ' . $tabel . ' WHERE ' . $zoekveld . ' = ' . intval($object->id) ))) throw new Exception( 'Fout bij verwijderen van achtergrond informatie: ' . $query ); } /* voegt NIET recursief toe, er wordt achtergrondinfo bij alleen het opgegeven object opgeslagen */ function wizard_zet_grondslagen( BaseResult $object, array $rows, $checklist_groep_id, $checklist_id ) { return wizard_zet_achtergrond_informatie( $object, 'grondslagen', $rows, 'grondslag_tekst_id', $checklist_groep_id, $checklist_id ); } function wizard_zet_richtlijnen( BaseResult $object, array $rows, $checklist_groep_id, $checklist_id ) { return wizard_zet_achtergrond_informatie( $object, 'richtlijnen', $rows, 'richtlijn_id', $checklist_groep_id, $checklist_id ); } function wizard_zet_aandachtspunten( BaseResult $object, array $rows, $checklist_groep_id, $checklist_id ) { return wizard_zet_achtergrond_informatie( $object, 'aandachtspunten', $rows, 'aandachtspunt', $checklist_groep_id, $checklist_id ); } function wizard_zet_opdrachten( BaseResult $object, array $rows, $checklist_groep_id, $checklist_id ) { return wizard_zet_achtergrond_informatie( $object, 'opdrachten', $rows, 'opdracht', $checklist_groep_id, $checklist_id ); } function wizard_zet_verantwoordingsteksten( BaseResult $object, array $rows, $checklist_groep_id, $checklist_id ) { return wizard_zet_achtergrond_informatie( $object, 'verantwoordingsteksten', $rows, array('verantwoordingstekst', 'status'), $checklist_groep_id, $checklist_id ); } function wizard_zet_achtergrond_informatie( BaseResult $object, $type, array $rows, $veld, $checklist_groep_id, $checklist_id ) { $type = wizard_cleanup_table_name( $type ); //if ($object instanceof ChecklistGroepResult) { $tabel = 'bt_checklist_groep_' . (($type == 'verantwtkstn') ? 'veranttkstn' : $type); $koppelveld = 'checklist_groep_id'; } if ($object instanceof ChecklistGroepResult) { $tabel = 'bt_checklist_groep_' . $type; $koppelveld = 'checklist_groep_id'; } else if ($object instanceof ChecklistResult) { $tabel = 'bt_checklist_' . $type; $koppelveld = 'checklist_id'; } else if ($object instanceof HoofdgroepResult) { $tabel = 'bt_hoofdgroep_' . $type; $koppelveld = 'hoofdgroep_id'; } else if ($object instanceof VraagResult) { $tabel = 'bt_vraag_' . $type; $koppelveld = 'vraag_id'; } else throw new Exception( 'wizard_zet_achtergrond_informatie: niet ondersteund object type: ' . zet_class( $object ) ); $CI = get_instance(); if (!is_array($veld)) { foreach ($rows as $value) { $values = array( 'checklist_groep_id' => $checklist_groep_id, $veld => $value, $koppelveld => $object->id, // let op: bij checklistgroepen is dit checklist_groep_id! ); if (!is_null( $checklist_id )) $values['checklist_id'] = $checklist_id; $query = 'INSERT INTO ' . $tabel . ' (' . implode( ',', array_keys($values) ) . ') VALUES ('; $c = 0; foreach ($values as $v) $query .= ($c++?',':'') . $CI->db->escape( $v ); $query .= ')'; if (!$CI->db->query( $query )) throw new Exception( 'Fout bij toevoegen van achtergrond informatie: ' . $query ); } } else { $firstkey = reset($veld); for ($i=0; $i<sizeof($rows[$firstkey]); ++$i) { $values = array( 'checklist_groep_id' => $checklist_groep_id, $koppelveld => $object->id, // let op: bij checklistgroepen is dit checklist_groep_id! ); foreach ($veld as $vkey) $values[$vkey] = $rows[$vkey][$i]; if (!is_null( $checklist_id )) $values['checklist_id'] = $checklist_id; $query = 'INSERT INTO ' . $tabel . ' (' . implode( ',', array_keys($values) ) . ') VALUES ('; $c = 0; foreach ($values as $v) $query .= ($c++?',':'') . $CI->db->escape( $v ); $query .= ')'; if (!$CI->db->query( $query )) throw new Exception( 'Fout bij toevoegen van achtergrond informatie: ' . $query ); } } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'intro')); ?> <? if ( ($leaseconfiguratie && $leaseconfiguratie->toon_gebruikersforum_knop=='ja')): ?> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td> <? $this->load->view( 'elements/laf-blocks/generic-green-button', array( 'text' => tgn('gebruikersforum'), 'blank' => true, 'url' => 'http://community.bris.nl/forum/forumdisplay.php?1157-BRIStoezicht', 'width' => '150px' ) ) ?> </td> <td style="padding-left: 20px;"> <?=tg('cookie-waarschuwing')?> </td> </tr> </table> <br/> <? endif; ?> <table border="0" cellspacing="10" cellpadding="0" style="width:100%"> <tr> <td valign="top" width="50%"> <? $this->load->view( 'elements/laf-blocks/generic-bar', array( 'header' => tg('nieuwsberichten') ) ); ?> <? foreach ($nieuws as $i => $n): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => htmlentities( $n->titel, ENT_COMPAT, 'UTF-8' ) . '<span style="float:right"><i>' . tg( 'geplaatst_op', date('d-m-Y',$n->datum) ) . '</i></span>', 'onclick' => '', 'expanded' => !$i, 'group_tag' => 'nieuws', 'width' => '100%', 'height' => '300px' ) ); ?> <?=nl2br( $n->tekst )?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> <? if (true): ?> <br/> <? $this->load->view( 'elements/laf-blocks/generic-bar', array( 'header' => tg('app.toegang') ) ); ?> <div style="height:20px; border: 1px solid #ABABAB; padding: 20px; cursor: pointer;" onclick="location.href='<?=site_url('/root/apptoegang')?>';"> <?=tg('app.toegang.header')?> <? $app_toegang = $this->gebruiker->get_logged_in_gebruiker()->app_toegang; $class = $app_toegang ? 'ja' : 'nee'; $text = tg('app.toegang.button.' . $class); ?> <div style="float:right; position: relative; top: -5px;" class="apptoegang <?=$class?> rounded5"><?=$text?></div> </div> <? endif; ?> </td> <td valign="top"> <? $this->load->view( 'elements/laf-blocks/generic-bar', array( 'header' => tg('dashboard') ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('notificaties'), 'group_tag' => 'dashboard', 'onclick' => '', 'expanded' => true, 'width' => '100%', 'height' => '300px' ) ); ?> <? if (!$notificaties):?> <?=tg('geen-notificaties-lease')?> <? else: ?> <? $col_widths = array( 'melding' => 250, 'datum' => 70, 'opties' => 30, ); $col_description = array( 'melding' => tg('melding'), 'datum' => tg('datum'), 'opties' => '&nbsp;', ); $rows = array(); foreach ($notificaties as $i => $notificatie) { $row = (object)array(); $row->onclick = 'void(0);'; if ($notificatie->klikbaar && $notificatie->deelplan_id && $notificatie->is_opdracht==0) $url = site_url('/dossiers/bekijken/' . $notificatie->get_deelplan()->dossier_id . '/' . $notificatie->deelplan_id); else if ($notificatie->klikbaar && $notificatie->dossier_id) $url = site_url('/dossiers/bekijken/' . $notificatie->dossier_id); else if ($notificatie->klikbaar && $notificatie->is_opdracht==1) $url = site_url('/deelplannen/opdrachtenoverzicht/' . $notificatie->deelplan_id.'/-/vraag/'.$notificatie->vraag_id); else $url = ""; $row->data = array(); if ($url) $row->data['melding'] = '<span onclick="location.href=\'' . $url . '\';">' . htmlentities( $notificatie->bericht, ENT_COMPAT, 'UTF-8' ) . '</span>'; else $row->data['melding'] = htmlentities( $notificatie->bericht, ENT_COMPAT, 'UTF-8' ); $row->data['datum'] = date( 'd-m-Y', strtotime( $notificatie->datum ) ); $row->data['opties'] = '<i class="icon-trash" style="font-size:15pt; margin-left: 10px;" notificatie_id="' . $notificatie->id . '"></i> '; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'header' => '', 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, 'new_button_js' => null, 'url' => '/intro/index', 'scale_field' => 'melding', 'do_paging' => false, 'disable_search' => true, ) ); ?> <? endif; ?> <br/> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <div style="height:auto; border: 1px solid #ABABAB; margin-top: 10px; padding: 50px 10px 20px 10px"> <?=tgg('BRIStoezicht')?> <?=tg('release_version_value')?><br/> <?=tg('releasedatum')?>: <?=tg('release_date_value')?><br/> <br/> <?=tga('versieinformatie', site_url('/versie'))?> </div> </td> </tr> </table> <script type="text/javascript"> $('i[notificatie_id]').click(function(){ $(this).closest('table').closest('tr').fadeOut( 200 ); $.ajax({ url: '<?=site_url('/intro/notificatie_bekeken')?>/' + $(this).attr( 'notificatie_id' ), type: 'POST' }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php class Over extends Controller { function Over() { parent::Controller(); } function ons() { $this->load->view('over/ons'); } function disclaimer() { $this->load->view('over/disclaimer'); } } <file_sep>BRISToezicht.Toets.Planning = { select: null, initialize: function() { this.select = $('[name=hercontrole_datum_select]'); if (!BRISToezicht.Toets.readonlyMode) { this.select.change( function(){ if (this.value == 'nieuw') { afspraakPopup( '', '', '', function( nieuweDatum, nieuweStartTijd, nieuweEindTijd ) { BRISToezicht.Toets.Planning.onSelectDatum( nieuweDatum + '|' + nieuweStartTijd + '|' + nieuweEindTijd ); }); } else BRISToezicht.Toets.Planning.onSelectDatum( this.value ); }); } }, enable: function() { this.select.removeAttr( 'disabled' ); }, disable: function() { this.select.attr( 'disabled', 'disabled' ); }, selectDatum: function( datum ) { if (!datum) datum = 'geen'; for (var i=0; i<this.select[0].options.length - 1; ++i) { if (this.select[0].options[i].value == datum) { this.select[0].options[i].selected = true; return; } } // shouldn't really happen, but just to be sure, add it... this.onSelectDatum( datum ); }, onSelectDatum: function( datum ) { // 'geen' betekent lege datum if (datum == 'geen') datum = ''; // sla datum op var vraagData = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraagData) return; vraagData.inputs.hercontrole_datum.value = datum; BRISToezicht.Toets.Vraag.markDirty( true ); // zie of er al een option is voor deze datum // let op: dit hoeft niet per se nodig te zijn, maar we kunnen hier komen // via de select, of via de input ;-) if (datum) { for (var i=1; i<this.select[0].options.length - 1; ++i) if (this.select[0].options[i].value == datum) { this.select[0].options[i].selected = true; return; } this.addOption( datum, i ).selected = true; } else { this.select[0].options[0].selected = true; } }, addOption: function( value, at_index ) { // split datum in 3 delen: datum, starttijd en eindtijd var parts = value.split( '|' ); var datum = parts[0]; var start_tijd = parts[1]; var eind_tijd = parts[2]; var html = datum + (start_tijd ? ' van ' + start_tijd + ' tot ' + eind_tijd : ''); // maak DOM element var option = document.createElement( 'option' ); option.value = value; option.innerHTML = html; // voeg toe aan select this.select.find( 'option:nth-child('+at_index+')' ).after( option ); return option; } }; <file_sep><?php class CI_ChecklistExport { public function create( $checklistgroep_id, $file_encoding='ISO-8859-1' ) { return new ChecklistExport( $checklistgroep_id, $file_encoding ); } } class ChecklistExport { private $CI; private $data_for_csv_file; private $file_name = ''; private $counts = array(); private $checklistgroep_id = 0; private $checklist_id = 0; private $file_encoding; private $speciale_tekens_teksten = array(); private $queries = array(); public function __construct( $checklistgroep_id, $file_encoding ) { $this->CI = get_instance(); //$this->csvfile = $csvfile; $this->checklistgroep_id = intval( $checklistgroep_id ); $this->file_encoding = $file_encoding; } public function run() { $checklistGroepId = $this->checklistgroep_id; $checklistId = $this->checklist_id; //echo "Exporting checklistgroep with ID: {$checklistGroepId}\n"; if ($checklistId > 0) { //echo "Limiting to checklist with ID: {$checklistId}\n"; } // Prepare the main query that gets all of the data, with exception of the 'grondslagen' and 'artikelen'. $query_params = array($checklistGroepId); $query = "SELECT bg.naam AS checklist_groep_naam, bl.naam AS checklist_naam, bh.naam AS hoofdgroep_naam, bv.tekst AS vraag_tekst, COALESCE(bv.aanwezigheid, 0) AS prio, bht.naam AS hoofdthema, bt.thema AS thema, br.filename AS richtlijn, bva.aandachtspunt AS aandachtspunt, bv.toezicht_moment, bv.fase, bv.id AS vraag_id FROM bt_vragen bv INNER JOIN bt_categorieen bc ON (bv.categorie_id = bc.id) INNER JOIN bt_hoofdgroepen bh ON (bc.hoofdgroep_id = bh.id) INNER JOIN bt_checklisten bl ON (bh.checklist_id = bl.id) INNER JOIN bt_checklist_groepen bg ON (bl.checklist_groep_id = bg.id) LEFT JOIN bt_themas bt ON (bv.thema_id = bt.id) LEFT JOIN bt_hoofdthemas bht ON (bt.hoofdthema_id = bht.id) LEFT JOIN bt_vraag_rchtlnn bvr ON ((bv.gebruik_rchtlnn = 1) AND (bvr.vraag_id = bv.id)) LEFT JOIN bt_richtlijnen br ON (bvr.richtlijn_id = br.id) LEFT JOIN bt_vraag_ndchtspntn bva ON ((bv.gebruik_ndchtspntn = 1) AND (bva.vraag_id = bv.id)) WHERE bl.checklist_groep_id = ?"; if ($checklistId > 0) { $query .= " AND bl.id = ?"; $query_params[] = $checklistId; } $this->CI->dbex->prepare( 'find', $query ); $res = $this->CI->dbex->execute( 'find', $query_params ); // Prepare the helper query that gets the 'grondslagen' and 'artikelen'. This will be executed from within the loop that processes the results of the main query. $grondslagenQuery = "SELECT bg.grondslag, bgt.artikel FROM bt_vraag_grndslgn bvg INNER JOIN bt_grondslag_teksten bgt ON (bvg.grondslag_tekst_id = bgt.id) INNER JOIN bt_grondslagen bg ON (bgt.grondslag_id = bg.id) WHERE bvg.vraag_id = ?"; $this->CI->dbex->prepare( 'find_grondslagen', $grondslagenQuery ); $dataToExport = array(); foreach ($res->result() as $row) { // First initialise the row data set $dataRowToExport = array(); $dataRowToExport['Checklistgroep'] = ''; $dataRowToExport['Checklist'] = ''; $dataRowToExport['Hoofdgroep'] = ''; $dataRowToExport['Categorie'] = '?'; $dataRowToExport['Vraag'] = ''; $dataRowToExport['Prio S'] = ''; $dataRowToExport['Prio 1'] = ''; $dataRowToExport['Prio 2'] = ''; $dataRowToExport['Prio 3'] = ''; $dataRowToExport['Prio 4'] = ''; $dataRowToExport['Hoofdthema'] = ''; $dataRowToExport['Thema'] = ''; $dataRowToExport['Richtlijn'] = ''; $dataRowToExport['Aandachtspunt'] = ''; for ($i = 1 ; $i <= 10 ; $i++) { $dataRowToExport["Grondslag {$i}"] = ''; $dataRowToExport["Artikel {$i}"] = ''; } $dataRowToExport['Toezichtmoment'] = ''; $dataRowToExport['Fase'] = ''; // Then proceed to process and store the results. Start with the straightforward columns that require no manipulation. $dataRowToExport['Checklistgroep'] = strval($row->checklist_groep_naam); $dataRowToExport['Checklist'] = strval($row->checklist_naam); $dataRowToExport['Hoofdgroep'] = strval($row->hoofdgroep_naam); $dataRowToExport['Vraag'] = strval($row->vraag_tekst); $dataRowToExport['Hoofdthema'] = strval($row->hoofdthema); $dataRowToExport['Thema'] = strval($row->thema); $dataRowToExport['Richtlijn'] = strval($row->richtlijn); $dataRowToExport['Aandachtspunt'] = strval($row->aandachtspunt); $dataRowToExport['Toezichtmoment'] = strval($row->toezicht_moment); $dataRowToExport['Fase'] = strval($row->fase); // Properly determine which 'prioriteiten' should be set and store them $prio = $row->prio; $prio_s = $prio_1 = $prio_2 = $prio_3 = $prio_4 = 0; //$prio_s = $prio_1 = $prio_2 = $prio_3 = $prio_4 = $prio; if ($prio > 0) { $prio_s = (($prio & 0x01) > 0); $prio_1 = (($prio & 0x02) > 0); $prio_2 = (($prio & 0x04) > 0); $prio_3 = (($prio & 0x08) > 0); $prio_4 = (($prio & 0x10) > 0); } /* $dataRowToExport['Prio S'] = intval($prio_s); $dataRowToExport['Prio 1'] = intval($prio_1); $dataRowToExport['Prio 2'] = intval($prio_2); $dataRowToExport['Prio 3'] = intval($prio_3); $dataRowToExport['Prio 4'] = intval($prio_4); * */ $dataRowToExport['Prio S'] = ($prio_s) ? 'S' : ''; $dataRowToExport['Prio 1'] = ($prio_1) ? '1' : ''; $dataRowToExport['Prio 2'] = ($prio_2) ? '2' : ''; $dataRowToExport['Prio 3'] = ($prio_3) ? '3' : ''; $dataRowToExport['Prio 4'] = ($prio_4) ? '4' : ''; // The 'Grondslagen' and 'Artikelen' require a helper query, as they have a variable amount of occurences. unset($resGrondslagen); $resGrondslagen = $this->CI->dbex->execute( 'find_grondslagen', array($row->vraag_id) ); $i = 0; foreach ($resGrondslagen->result() as $rowGrondslagen) { $i++; // Careful here! // Some questions have more than 10 grondslagen defined, but the import file only allows 10, so limit it! if ($i <= 10) { $dataRowToExport["Grondslag {$i}"] = strval($rowGrondslagen->grondslag); $dataRowToExport["Artikel {$i}"] = strval($rowGrondslagen->artikel); } } // Finally add the properly constructed row data to the set of complete data. $dataToExport[] = $dataRowToExport; } // Now that we have properly constructed the entire data set write it out to a CSV file. //d($dataToExport); if (!empty($dataToExport)) { // Brute-force create (or truncate) a file. //$filename = "checklistgroep_{$checklistGroepId}_export.csv"; $filename = "files/checklist_export/checklistgroep_{$checklistGroepId}_export.csv"; $this->file_name = $filename; echo "Creating CSV file {$filename}\n"; $fp = fopen($filename, 'w'); // Specify a CSV delimiter $delimiter = "\t"; $enclosed_by = '"'; // Write a row with headers for the export. Simply use the array keys of the first row for this. fputcsv($fp, array_keys($dataToExport[0]), $delimiter); // Now add the data of the retrieved rows. foreach ($dataToExport as $dataRowToExport) { //$values_to_write = array_values($dataRowToExport); fputcsv($fp, array_values($dataRowToExport), $delimiter, $enclosed_by); } // Close the file fclose($fp); } //d($dataToExport); //exit; $this->data_for_csv_file = $dataToExport; //echo "Done.\n"; } public function get_data_for_csv_file() { return $this->data_for_csv_file; } public function get_file_name() { return $this->file_name; } } <file_sep><? require_once 'base.php'; class VerantwoordingResult extends BaseResult { function VerantwoordingResult( &$arr ) { parent::BaseResult( 'verantwoording', $arr ); } } class Verantwoording extends BaseModel { function Verantwoording() { parent::BaseModel( 'VerantwoordingResult', 'verantwoordingen', true ); } public function check_access( BaseResult $object ) { if ($object && is_null( $object->klant_id )) return; return parent::check_access( $object ); } function add( $klant_id, $tekst, $checklist_groep_id=NULL, $checklist_id=NULL, $status=NULL ) { /* if (!$this->dbex->is_prepared( 'Verantwoording::add' )) $this->dbex->prepare( 'Verantwoording::add', 'INSERT INTO verantwoordingen (klant_id, tekst, checklist_groep_id, checklist_id, status) VALUES (?, ?, ?, ?, ?)' ); $args = array( 'klant_id' => $klant_id, 'tekst' => $tekst, 'checklist_groep_id' => $checklist_groep_id, 'checklist_id' => $checklist_id, 'status' => $status, ); $this->dbex->execute( 'Verantwoording::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'klant_id' => $klant_id, 'tekst' => $tekst, 'checklist_groep_id' => $checklist_groep_id, 'checklist_id' => $checklist_id, 'status' => $status, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'iciis' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } private function _get_search_subquery( $alias, $search, array &$args ) { if (!$search) { return '1=1'; } //return 1; for ($i=0; $i<6; ++$i) $args[] = '%' . $search . '%'; //$str = '(0'; $str = '(0=1'; $str .= ' OR '.$alias.'.tekst LIKE ?'; $str .= ' OR '.$alias.'.status LIKE ?'; $str .= ' OR '.$alias.'.grondslag LIKE ?'; $str .= ' OR '.$alias.'.artikel LIKE ?'; $str .= ' OR '.$alias.'.checklist_id IN (SELECT id FROM bt_checklisten WHERE naam LIKE ?)'; // klant_id is filtered out later $str .= ' OR '.$alias.'.checklist_groep_id IN (SELECT id FROM bt_checklist_groepen WHERE naam LIKE ?)'; // klant_id is filtered out later $str .= ')'; return $str; } private function _process_result( $res ) { $result = array(); foreach ($res->result() as $row) { $obj = $this->getr( $row ); $result[] = $obj; } return $result; } public function get_for_klant( $klant_id, $search=null ) { $stmt_name = 'verantwoording::get_for_klant'; $args = is_null($klant_id) ? array() : array( $klant_id ); if (!$this->dbex->prepare( $stmt_name, $query = ' SELECT v.* FROM verantwoordingen v LEFT JOIN bt_checklist_groepen cg ON v.checklist_groep_id = cg.id LEFT JOIN bt_checklisten c ON v.checklist_id = c.id WHERE ' . (is_null($klant_id) ? 'v.klant_id IS NULL' : 'v.klant_id = ?') . ' AND ' . $this->_get_search_subquery( 'v', $search, $args ) . ' ORDER BY cg.sortering, c.sortering, v.status ' )) throw new Exception( 'Fout bij preparen statement' ); if (!($res = $this->dbex->execute( $stmt_name, $args ))) throw new Exception( 'Fout bij executen statement' ); $result = $this->_process_result( $res ); $res->free_result(); return $result; } public function get_for_checklist_groep( $checklist_groep_id ) { $stmt_name = 'verantwoording::get_for_klant'; if (!$this->dbex->prepare( $stmt_name, ' SELECT v.* FROM verantwoordingen v LEFT JOIN bt_checklist_groepen cg ON v.checklist_groep_id = cg.id LEFT JOIN bt_checklisten c ON v.checklist_id = c.id WHERE (v.klant_id = ? OR v.klant_id IS NULL) AND (v.checklist_groep_id IS NULL OR v.checklist_groep_id = ?) ORDER BY cg.sortering, c.sortering, v.status ' )) throw new Exception( 'Fout bij preparen statement' ); $klant_id = get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id; $args = array( $klant_id, $checklist_groep_id ); if (!($res = $this->dbex->execute( $stmt_name, $args ))) throw new Exception( 'Fout bij executen statement' ); $result = $this->_process_result( $res ); $res->free_result(); return $result; } public function automatic_verantwoordingstekst_save(){ $data = array( 'checklist_groep_id' =>$_POST['checklistgroep'], 'checklist_id' => $_POST['checklist'], 'vraag_id' => $_POST['vraag_id'], 'verantwoordingstekst' =>$_POST['text'], 'automatic' =>1, 'automatish_generate' =>isset($_POST['automatish']) ? 1 : 0, ); if (!$_POST['vraag_verantwtkstn_id']) { $this->db->insert('bt_vraag_verantwtkstn_automatic', $data); $vraag_verantwtkstn_id=$this->db->insert_id(); if(isset($_POST['button_name'])){ foreach ($_POST['button_name'] as $value){ $button_config = array( 'vraag_id' =>$_POST['vraag_id'], 'vraag_verantwtkstn_id' => $vraag_verantwtkstn_id, 'name' => $value, ); $this->db->insert('verantwoordingstekst_config', $button_config); } } } elseif ($_POST['vraag_verantwtkstn_id']){ $this->db->where('id', $_POST['vraag_verantwtkstn_id']); $this->db->update('bt_vraag_verantwtkstn_automatic', $data); $this->db->delete('verantwoordingstekst_config', array('vraag_verantwtkstn_id' => $_POST['vraag_verantwtkstn_id'])); if(isset($_POST['button_name'])){ foreach ($_POST['button_name'] as $value){ $button_config = array( 'vraag_id' =>$_POST['vraag_id'], 'vraag_verantwtkstn_id' => $_POST['vraag_verantwtkstn_id'], 'name' => $value, ); $this->db->insert('verantwoordingstekst_config', $button_config); } } } } public function find_automatic_verantwtkstn($vraag_id){ $query = "SELECT * FROM bt_vraag_verantwtkstn_automatic WHERE vraag_id =".$vraag_id." and automatish_generate=1"; $res = $this->db->query( $query ); if (!$res) throw new Exception( 'Fout bij database query: ' . $query ); $result = $res->result(); if($result){ return true; } else { return false; } } public function get_verantwoording_by_id($vraag_verantwtkstn_id){ $query = "SELECT * FROM bt_vraag_verantwtkstn_automatic WHERE bt_vraag_verantwtkstn_automatic.id =".$vraag_verantwtkstn_id; $res = $this->db->query( $query ); if (!$res) throw new Exception( 'Fout bij database query: ' . $query ); $result = $res->result(); $automatic_verantwoordingsteksten=array(); foreach ($result as $result_value){ $button_naam=array(); $res_config = $this->db->query( "select * from verantwoordingstekst_config where vraag_verantwtkstn_id=".$result_value->id); if (!$res_config) throw new Exception( 'Fout bij database query: ' . $query ); $result_config = $res_config->result(); foreach ($result_config as $value_result_config){ $button_naam[]=$value_result_config->name; } $automatic_verantwoordingsteksten[]=array("id"=>$result_value->id,"verantwoordingsteksten"=>$result_value->verantwoordingstekst, "button_naam"=>$button_naam, "vraag_id"=>$vraag_verantwtkstn_id, "automatish_generate"=>$result_value->automatish_generate); } $res->free_result(); $res_config->free_result(); return $automatic_verantwoordingsteksten; } public function automatic_verantwoordingstekst_delete($vraag_verantwtkstn_id=null){ if($vraag_verantwtkstn_id){ $this->db->delete('verantwoordingstekst_config', array('vraag_verantwtkstn_id' => $vraag_verantwtkstn_id)); $this->db->delete('bt_vraag_verantwtkstn_automatic', array('id' => $vraag_verantwtkstn_id)); } } } <file_sep><!-- mode1 bar --> <table border="0" cellspacing="0" cellpadding="0" class="mode1bar"><tr><td class="left"></td><td class="mid"> <table border="0" cellspacing="0" cellpadding="0"><tr><td> <?=$header?> </td></tr></table> </td><td class="right"></td></tr></table> <file_sep> ALTER TABLE deelplannen ADD COLUMN geintegreerd SET('nee','ja') NOT NULL DEFAULT 'nee';<file_sep>CREATE TABLE IF NOT EXISTS `notificaties_bekeken` ( `gebruiker_id` int(11) NOT NULL, `notificatie_id` int(11) NOT NULL, PRIMARY KEY (`gebruiker_id`,`notificatie_id`), KEY `notificatie_id` (`notificatie_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notificaties_bekeken` ADD CONSTRAINT `notificaties_bekeken_ibfk_2` FOREIGN KEY (`notificatie_id`) REFERENCES `notificaties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `notificaties_bekeken_ibfk_1` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><? if ($json_output) { $result = array(); foreach ($verantwoordingen as $verantwoording) { foreach ($verantwoording as $k => $v) if (is_null($v)) unset($verantwoording->$k); $data = (array)$verantwoording; $data['verantwoordingstekst'] = html_entity_decode($data['verantwoordingstekst']); $data['status'] = isset($data['status']) ? preg_replace( '/_/', ' ', $data['status']) : ''; $result[] = $data; } echo json_encode($result); } else { ?> (function(){ BRISToezicht.Toets.data.verantwoordingen = [ <? $c=0; foreach ($verantwoordingen as $verantwoording): ?> <?=$c++?',':''?>{ status: '<?=$verantwoording->status?>', checklist_groep_id: <?=$verantwoording->checklist_groep_id ? $verantwoording->checklist_groep_id : 'null'?>, checklist_id: <?=$verantwoording->checklist_id ? $verantwoording->checklist_id : 'null'?>, hoofdgroep_id: <?=$verantwoording->hoofdgroep_id ? $verantwoording->hoofdgroep_id : 'null'?>, vraag_id: <?=$verantwoording->vraag_id ? $verantwoording->vraag_id : 'null'?>, verantwoordingstekst: '<?=jsstr( $verantwoording->verantwoordingstekst )?>', button_naam:'<?=$verantwoording->button_name?>', type:'<?=$verantwoording->type?>', automatish_generate:'<?=$verantwoording->automatish_generate?>', } <? endforeach; ?> ]; })(); <? } <file_sep><? require_once 'base.php'; define( 'VRAAG_FLAGS_STEEKPROEF_VERWERKT', 0x01 ); define( 'VRAAG_FLAGS_GROEPSANTWOORD', 0x02 ); class DeelplanResult extends BaseResult { function DeelplanResult( &$arr ) { parent::BaseResult( 'deelplan', $arr ); } function add_create_notificatie() { // voeg notificatie toe $dossier = $this->get_dossier(); if (!($gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker())) $gebruiker = $dossier->get_gebruiker(); $this->_CI->notificatie->add_deelplan_notificatie( $this->id, 'Deelplan "' . $this->naam . '" binnen dossier "' . $dossier->kenmerk . '" aangemaakt door ' . $gebruiker->volledige_naam ); } function get_eerste_revisie_datum() { if (!isset( $this->_eerste_revisie_datum )) { $res = $this->_CI->db->query( ' SELECT MIN(last_updated_at) AS mindate FROM deelplan_vragen WHERE deelplan_id = ' . $this->id . ' AND (status IS NOT NULL OR toelichting IS NOT NULL) AND vraag_id NOT IN ( SELECT id FROM bt_vragen WHERE automatische_toel_moment = \'bij aanmaken\' ) ' ); $date1 = $res->row_object()->mindate; $res->free_result(); $res = $this->_CI->db->query( ' SELECT MIN(datum) AS mindate FROM deelplan_vraag_geschiedenis WHERE deelplan_id = ' . $this->id . ' AND vraag_id NOT IN ( SELECT id FROM bt_vragen WHERE automatische_toel_moment = \'bij aanmaken\' ) ' ); $date2 = $res->row_object()->mindate; $res->free_result(); if (!$date1) $mindate = $date2; else if (!$date2) $mindate = $date1; else $mindate = min( $date1, $date2 ); $this->_eerste_revisie_datum = $mindate ? date( 'Y-m-d', strtotime( $mindate ) ) : ''; } return $this->_eerste_revisie_datum; } function get_laatste_revisie_datum() { if (!isset( $this->_laatste_revisie_datum )) { $res = $this->_CI->db->query( ' SELECT MAX(maxdate) AS revisiedatum FROM (SELECT last_updated_at AS maxdate FROM deelplan_vragen WHERE deelplan_id = ' . $this->id . ' AND (status IS NOT NULL OR toelichting IS NOT NULL) AND vraag_id NOT IN (SELECT id FROM bt_vragen WHERE automatische_toel_moment = \'bij aanmaken\') UNION ALL SELECT datum AS maxdate FROM deelplan_vraag_geschiedenis WHERE deelplan_id = ' . $this->id . ' AND vraag_id NOT IN (SELECT id FROM bt_vragen WHERE automatische_toel_moment = \'bij aanmaken\')) AS maxdatetable; ' ); $maxdate = $res->row_object()->revisiedatum; $res->free_result(); if ($maxdate) { $this->_laatste_revisie_datum = date( 'Y-m-d', strtotime( $maxdate ) ); } else { $this->_laatste_revisie_datum = null; } } return $this->_laatste_revisie_datum; } // This method iterates over all of the "themas" that are specified for the combination of all checklists that have been assigned to the deelplan. function zet_alle_themas_van_checklisten($limit_to_actively_used_themas = false) { $debug = false; //$debug = true; $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'deelplanchecklist' ); $this->_CI->load->model( 'deelplanthema' ); // Define the data query. This is what is used for getting ALL of the themas assignments for a specific checklist. There is no easy completely correct 'group by' clause, so we // simply process the results in the code. Note that 'in_use_thema_ids' gives the exact set of actually used themas, but the deelplan/bewerken view gives the union of the // first 4 individual values (which often are more themas than the more precise one), so by default we use those values instead. $themas_query = 'SELECT t1.thema_id AS vr_thema_id, t3.standaard_thema_id AS hg_thema_id, t4.standaard_thema_id AS cl_thema_id, t5.standaard_thema_id AS clg_thema_id, COALESCE(t1.thema_id, t3.standaard_thema_id, t4.standaard_thema_id, t5.standaard_thema_id) AS in_use_thema_id FROM bt_vragen t1 INNER JOIN bt_categorieen t2 ON (t1.categorie_id = t2.id) INNER JOIN bt_hoofdgroepen t3 ON (t2.hoofdgroep_id = t3.id) INNER JOIN bt_checklisten t4 ON (t3.checklist_id = t4.id) INNER JOIN bt_checklist_groepen t5 ON (t4.checklist_groep_id = t5.id) WHERE t4.id = ?'; if (!$this->_CI->dbex->is_prepared( 'deelplan::zet_alle_themas_van_checklisten' )) { $this->_CI->dbex->prepare( 'deelplan::zet_alle_themas_van_checklisten', $themas_query ); } // Initialise the thema_ids sets $all_available_thema_ids = array(); $in_use_thema_ids = array(); // Then proceed to assign the corresponding "thema's". $curDeelplanChecklists = $this->_CI->deelplanchecklist->get_by_deelplan( $this->id ); if ($debug) { echo "Aantal deelplan checklists: " . sizeof($curDeelplanChecklists) . "\n\n"; //d($curDeelplanChecklists); } if (!is_null($curDeelplanChecklists) && !empty($curDeelplanChecklists)) { // Initialise the sets that contain the currently assigned deelplanthema's as well as the thema IDs of the thema's that // are associated with the checklists. //$curDeelplanThemas = array(); $curDeelplanThemas = $this->_CI->deelplanthema->get_by_deelplan( $this->id ); if ($debug) { //echo "Deelplan themas:"; //d($curDeelplanThemas); echo "\nExisting thema IDs:"; d(array_keys($curDeelplanThemas)); } // echo '+++ 2 +++<br />'; $checklistThemaIds = array(); // d($curDeelplanChecklists); exit; // Loop over each deelplanchecklist and extract the thema's foreach($curDeelplanChecklists as $curDeelplanChecklist) { if ($debug) { echo "Deelplan checklist:"; d($curDeelplanChecklist); } // d($curDeelplanChecklist); exit; // As we normally don't have a filled in checklist at this point, we cannot use the following call: // $this->_CI->thema->get_by_checklist($checklistData->checklistId, true)); // Instead, we simply assign all possible themas to the deelplan, which requires 'drilling down' to the 'questions level'. $curChecklist = $this->_CI->checklist->get($curDeelplanChecklist->checklist_id); if ($debug) { echo "Checklist: {$curChecklist->naam}\n\n"; //d($curChecklist); } // d($curChecklist); exit; if (!is_null($curChecklist) && !empty($curChecklist)) { // Get the available and in-use themas for the current checklist $res = $this->_CI->dbex->execute( 'deelplan::zet_alle_themas_van_checklisten', array( $curChecklist->id ) ); foreach ($res->result() as $row) { // Add all non-null values to the arrays of thema IDs. We'll make them unique right before setting them for the deelplan. if (!is_null($row->vr_thema_id)) $all_available_thema_ids[] = $row->vr_thema_id; if (!is_null($row->hg_thema_id)) $all_available_thema_ids[] = $row->hg_thema_id; if (!is_null($row->cl_thema_id)) $all_available_thema_ids[] = $row->cl_thema_id; if (!is_null($row->clg_thema_id)) $all_available_thema_ids[] = $row->clg_thema_id; if (!is_null($row->in_use_thema_id)) $in_use_thema_ids[] = $row->in_use_thema_id; } $res->free_result(); } // if (!is_null($curChecklist) && !empty($curChecklist)) } // foreach($curDeelplanChecklists as $curDeelplanChecklist) // Once all currently assigned thema's have been determined, as well as those that are associatied with the checklists, we assign the // current set. $all_available_thema_ids = array_unique($all_available_thema_ids); $in_use_thema_ids = array_unique($in_use_thema_ids); $thema_ids_to_assign = ($limit_to_actively_used_themas) ? $in_use_thema_ids : $all_available_thema_ids; if ($debug) { echo "<br />\n+++ All available thema's +++"; echo "<br />\nCurrently assigned thema IDs:"; d(array_keys($curDeelplanThemas)); echo "<br />\nAll available thema IDs:"; d($all_available_thema_ids); echo "<br />\nIn use thema IDs:"; d($in_use_thema_ids); echo "<br />\nAssigning thema IDs:"; d($thema_ids_to_assign); } // Finally, set the right values for the deelplan. $this->_CI->deelplanthema->set_for_deelplan( $this->id, $thema_ids_to_assign, $curDeelplanThemas ); } // if (!is_null($curDeelplanChecklists) && !empty($curDeelplanChecklists)) } // function zet_alle_themas_van_checklisten($limit_to_actively_used_themas = false) function werk_automatische_antwoorden_bij( $moment ) { // Determine which "null function" should be used $null_func = get_db_null_function(); $this->_CI->load->model( 'vraag' ); $vragen = $this->_CI->deelplan->get_alle_vragen( $this->id, false ); foreach ($vragen as $vraag) { if ($vraag->automatische_toel_moment == $moment) { $toelichting = $vraag->expand_automatische_toel_template( $this->id ); switch ($vraag->automatische_toel_methode) { case 'aanvullen': // !!! Query tentatively/partially made Oracle compatible. To be fully tested... // !!! TODO FIX CONCAT and FIX LIMIT for Oracle $this->_CI->db->query( $q = 'UPDATE deelplan_vragen SET toelichting = CONCAT( '.$null_func.'(toelichting, \'\'), \'\\n\', ' . $this->_CI->db->escape( $toelichting) . ' ) WHERE deelplan_id = ' . intval( $this->id ) . ' AND vraag_id = ' . $vraag_id . ' LIMIT 1' ); break; case 'overschrijven': if ($vraag->toelichting != $toelichting) { $vraag->toelichting = $toelichting; $this->_CI->db->query( $q = 'UPDATE deelplan_vragen SET toelichting = ' . $this->_CI->db->escape( $toelichting) . ' WHERE deelplan_id = ' . intval( $this->id ) . ' AND vraag_id = ' . $vraag->id . ' LIMIT 1' ); } break; default: error_log( 'vraag_data->automatische_toel_methode: ongeldige waarde:' ); break; } } } } function alle_automatische_antwoord_gezet_voor_moment( $moment ) { $this->_CI->load->model( 'vraag' ); $vragen = $this->_CI->deelplan->get_alle_vragen( $this->id, false ); foreach ($vragen as $vraag) { if ($vraag->automatische_toel_moment == $moment) { if (!strlen( $vraag->toelichting )) return false; } } return true; } function meld_af() { // Werk automatische antwoorden bij $this->werk_automatische_antwoorden_bij( 'bij afmelden' ); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // Zet deelplan als afgemeld // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_CI->db->query( 'UPDATE deelplannen SET afgemeld = 1, afgemeld_op = '.$now_func.' WHERE id = ' . intval( $this->id ) ); // Voeg notificatie toe $dossier = $this->get_dossier(); $this->_CI->notificatie->add_deelplan_notificatie( $this->id, 'Deelplan "' . $this->naam . '" binnen dossier "' . $dossier->kenmerk . '" afgemeld' ); // For Woningborg, closing a deelplan results in a project status transition. // Instead of checking if the current client is Woningborg, etc. we simply check if the current dossier has a BtBtzDossier // and if so, take the logic from there. Currently, they are ONLY allowed to do this if the current project status is 'toets afgerond'! $this->_CI->load->model('btbtzdossier'); $btBtzDossier = $this->_CI->btbtzdossier->get_one_by_btz_dossier_id( $this->dossier_id ); if (!is_null($btBtzDossier) && ($btBtzDossier->project_status == 'toets afgerond')) { $btBtzDossier->btz_status = 'afgerond'; // Work out the correct new 'project_status' value and save it! $btBtzDossier->determineAndSetProjectStatus(true); } // Klaar! return true; } /* geeft associative array terug met checklist_id -> mag_verwijderen_status (true/false) */ function mag_checklisten_verwijderen() { if (!($res = $this->_CI->db->query( ' SELECT COUNT(*) AS count, h.checklist_id FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id WHERE dv.deelplan_id = ' . intval( $this->id ) . ' AND status IS NOT NULL GROUP BY h.checklist_id ' ))) throw new Exception( 'Fout bij ophalen van checklist-verwijder informatie.' ); $result = array(); foreach ($res->result() as $row) $result[$row->checklist_id] = ($row->count == 0); $res->free_result(); return $result; } function get_standaard_toezichthouder_gebruiker_id() { if (!($dossier = $this->get_dossier())) return NULL; if (!($gebruiker = $dossier->get_gebruiker())) return NULL; return ($gebruiker && $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_VERANTWOORDELIJKE_ZIJN, $gebruiker->id ) != RECHT_MODUS_GEEN) ? $gebruiker->id : NULL; } // Returns either 'none' or 'write' function get_toezichthouder_toekennen_access_to_deelplan() { $toewijsrecht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_TOEWIJZEN_TOEZICHTHOUDERS ); if ($toewijsrecht == RECHT_MODUS_GEEN) return 'none'; // afgemeld dossier? readonly! if ($this->afgemeld) return 'none'; if ($toewijsrecht == RECHT_MODUS_ALLE) return 'write'; if ($this->get_dossier()->gebruiker_id == $this->_CI->login->get_user_id()) return 'write'; return 'none'; } // Returns either 'none', 'readonly' or 'write' function get_access_to_deelplan() { $logged_in_user_id = $this->_CI->login->get_user_id(); $deelplan_lees_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DEELPLAN_LEZEN ); $deelplan_schrijf_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DEELPLAN_SCHRIJVEN ); $dossier = $this->get_dossier(); // bekijk wat het toegangsrecht tot het dossier is $dossier_recht = $this->get_dossier()->get_access_to_dossier(); if ($dossier_recht == 'none') return 'none'; // heeft de gebruiker geen recht om dossiers te lezen? if ($deelplan_lees_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen deelplans te lezen? dan geen toegang // als dit deelplan niet van de ingelogde gebruiker is if ($deelplan_lees_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $dossier->gebruiker_id) return 'none'; // afgemeld dossier? readonly! if ($this->afgemeld) return 'readonly'; // heeft de gebruiker geen recht om dossiers te schrijven? dan op dit moment, alleen lezen if ($deelplan_schrijf_recht == RECHT_MODUS_GEEN) return 'readonly'; // heeft de gebruiker recht om z'n eigen dossier te schrijven? dan readonly toegang // als dit deelplan niet van de ingelogde gebruiker is if ($deelplan_schrijf_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $dossier->gebruiker_id) return 'readonly'; // heeft de gebruiker geen schrijf recht tot dit deelplan? dan readonly if ($dossier_recht == 'readonly') return 'readonly'; // toegang! return 'write'; } // Returns either 'none', 'readonly' or 'write' function get_scope_access_to_deelplan( DeelplanChecklistGroepObject $scope ) { $logged_in_user_id = $this->_CI->login->get_user_id(); $scope_lees_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_SCOPE_LEZEN ); $scope_schrijf_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_SCOPE_SCHRIJVEN ); $dossier = $this->get_dossier(); // bekijk wat het toegangsrecht tot het dossier is $dossier_recht = $this->get_dossier()->get_access_to_dossier(); if ($logged_in_user_id == $dossier->gebruiker_id) return $dossier_recht; if ($dossier_recht == 'none') return 'none'; // heeft de gebruiker geen recht om dossiers te lezen? if ($scope_lees_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen scopes te lezen? dan geen toegang // als dit deelplan niet van de ingelogde gebruiker is if ($scope_lees_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $scope->toezicht_gebruiker_id) return 'none'; // afgemeld dossier? readonly! if ($this->afgemeld) return 'readonly'; // heeft de gebruiker geen recht om dossiers te schrijven? dan op dit moment, alleen lezen if ($scope_schrijf_recht == RECHT_MODUS_GEEN) return 'readonly'; // heeft de gebruiker recht om z'n eigen dossier te schrijven? dan readonly toegang // als dit deelplan niet van de ingelogde gebruiker is if ($scope_schrijf_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $scope->toezicht_gebruiker_id) return 'readonly'; // heeft de gebruiker geen schrijf recht tot dit deelplan? dan readonly if ($dossier_recht == 'readonly') return 'readonly'; // toegang! return 'write'; } // Returns either 'none', 'readonly' or 'write' function get_toezicht_access_to_deelplan( ChecklistGroepResult $checklistgroep, ChecklistResult $checklist=null, $bouwnummer='' ) { $logged_in_user_id = $this->_CI->login->get_user_id(); // bekijk wat het dossier toegangsrecht is $scope_recht = $this->get_dossier()->get_access_to_dossier(); // geen toegang tot dossier? dan ook niet tot deelplan if ($scope_recht == 'none') return 'none'; // afgemeld dossier? readonly! if ($this->afgemeld) return 'readonly'; // gebruik bestaande functie voor de rest if ($checklist) return $this->_get_access_to_checklist( $checklist ); else return $this->_get_access_to_checklistgroep( $checklistgroep ); } // Returns either 'readonly' or 'write', to indicate if the current logged in user // has readonly or write access to the checklist data for the given checklistgroep within // the current deelplan // NOTE: if the deelplan is not owned by the logged in user or one of its colleagues, then // this object could never load (see check_access), so there's no reason to check for that // situation! private function _get_access_to_checklistgroep( ChecklistGroepResult $checklistgroep ) { $this->_CI->load->model( 'deelplanchecklistgroep' ); // init data $deelplan_id = $this->id; $checklist_groep_id = $checklistgroep->id; $logged_in_user_id = $this->_CI->login->get_user_id(); $tzh = $this->_CI->deelplanchecklistgroep->get_by_deelplan( $deelplan_id ); $toezichthouder_user_id = isset( $tzh[ $checklist_groep_id ] ) ? $tzh[ $checklist_groep_id ]->toezicht_gebruiker_id : null; $toezicht_lees_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN ); $toezicht_schrijf_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $dossier = $this->get_dossier(); // heeft de gebruiker geen recht om dossiers te lezen? if ($toezicht_lees_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen toezicht te lezen? dan geen toegang // als dit deelplan niet van de ingelogde gebruiker is of de gebruiker niet als toezichthouder gezet is if ($toezicht_lees_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $toezichthouder_user_id && $logged_in_user_id != $dossier->gebruiker_id) return 'none'; // heeft de gebruiker geen recht om dossiers te schrijven? dan op dit moment, alleen lezen if ($toezicht_schrijf_recht == RECHT_MODUS_GEEN) return 'readonly'; // heeft de gebruiker alleen recht om z'n eigen toezicht te schrijven? dan readonly toegang // als dit deelplan niet van de ingelogde gebruiker is of de gebruiker niet als toezichthouder gezet is if ($toezicht_schrijf_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $toezichthouder_user_id && $logged_in_user_id != $dossier->gebruiker_id) return 'readonly'; // toegang! return 'write'; } // Returns either 'readonly' or 'write', to indicate if the current logged in user // has readonly or write access to the checklist data for the given checklist within // the current deelplan // NOTE: if the deelplan is not owned by the logged in user or one of its colleagues, then // this object could never load (see check_access), so there's no reason to check for that // situation! private function _get_access_to_checklist( ChecklistResult $checklist, $bouwnummer='' ) { $this->_CI->load->model( 'deelplanchecklist' ); // init data $deelplan_id = $this->id; $checklist_id = $checklist->id; $logged_in_user_id = $this->_CI->login->get_user_id(); $dp_checklist = $this->get_deelplanchecklist($checklist_id,$bouwnummer); // $toezichthouder_user_id = isset( $dp_checklisten[ $checklist_id ] ) ? $dp_checklisten[ $checklist_id ]->toezicht_gebruiker_id : null; $toezichthouder_user_id = $dp_checklist->toezicht_gebruiker_id; $toezicht_lees_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN ); $toezicht_schrijf_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN ); $dossier = $this->get_dossier(); // heeft de gebruiker geen recht om dossiers te lezen? if ($toezicht_lees_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen toezicht te lezen? dan geen toegang // als dit deelplan niet van de ingelogde gebruiker is of de gebruiker niet als toezichthouder gezet is if ($toezicht_lees_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $toezichthouder_user_id && $logged_in_user_id != $dossier->gebruiker_id) return 'none'; // heeft de gebruiker geen recht om dossiers te schrijven? dan op dit moment, alleen lezen if ($toezicht_schrijf_recht == RECHT_MODUS_GEEN) return 'readonly'; // heeft de gebruiker alleen recht om z'n eigen toezicht te schrijven? dan readonly toegang // als dit deelplan niet van de ingelogde gebruiker is of de gebruiker niet als toezichthouder gezet is if ($toezicht_schrijf_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $toezichthouder_user_id && $logged_in_user_id != $dossier->gebruiker_id) return 'readonly'; // toegang! return 'write'; } //------------------------------------------------------------------------- // getters //------------------------------------------------------------------------- function get_dossier() { $this->_CI->load->model( 'dossier' ); return $this->_CI->dossier->get( $this->dossier_id ); } function get_checklisten( $force_new=false ) { if (!isset($this->_checklisten) || $force_new) $this->_checklisten = $this->_CI->deelplan->get_checklisten( $this->id ); return $this->_checklisten; } function get_checklistgroepen() { $klant = $this->_CI->klant->get_logged_in_klant(); $is_bouwnummer = $klant->heeft_toezichtmomenten_licentie == 'ja' && $this->geintegreerd=='nee'; if (!isset($this->_checklistgroepen)){ $this->_checklistgroepen = $this->_CI->deelplan->get_checklistgroepen( $this->id ); foreach($this->_checklistgroepen as &$checklistgroep ) $checklistgroep->modus = $is_bouwnummer ? 'niet-combineerbaar' : $checklistgroep->modus; } return $this->_checklistgroepen; } function get_checklistgroepen_assoc() { $this->get_checklistgroepen(); $arr = array(); foreach ($this->_checklistgroepen as $checklistgroep) $arr[$checklistgroep->id] = $checklistgroep; return $arr; } function get_checklisten_assoc() { $this->get_checklisten(); $arr = array(); foreach ($this->_checklisten as $checklist) $arr[$checklist->checklist_id] = $checklist->checklist_id; return $arr; } public function get_deelplanchecklist($checklist_id, $bouwnummer='' ){ $this->_CI->load->model( 'deelplanchecklist' ); if (!is_null($bouwnummer) && !empty($bouwnummer) && $bouwnummer != '') { $deelplanchecklist = $this->_CI->deelplanchecklist->search( array( 'deelplan_id' => $this->id, 'checklist_id'=> $checklist_id, 'bouwnummer'=>$bouwnummer) ); } elseif(!is_null($checklist_id) && !empty($checklist_id)) { $deelplanchecklist = $this->_CI->deelplanchecklist->search( array( 'deelplan_id' => $this->id, 'checklist_id'=> $checklist_id) ); } if(!isset($deelplanchecklist[0])) { $data = array('id'=>null, 'deelplan_id'=>null, 'checklist_id'=>null, 'bouwnummer'=>'', 'toezicht_gebruiker_id'=>null); $deelplanchecklist = array(new DeelplanChecklistResult($data)); } return $deelplanchecklist[0]; } function get_checklist_vragen( $checklist_id, &$verboden_hoofdgroepen=null, $bouwnummer=null ) { return $this->_CI->deelplan->get_checklist_vragen( $this->id, $checklist_id, $bouwnummer ); } function get_checklistgroep_vragen( $checklistgroep_id ) { return $this->_CI->deelplan->get_checklistgroep_vragen( $this->id, $checklistgroep_id ); } /** Geeft array met nummers terug van checklists waar dit deelplan vragen voor heeft, * dus waardes in de range 2-8. */ function get_checklists() { return $this->_CI->deelplan->get_checklists( $this->id ); } /** Geeft array met vraag id's als keys, array's met grondslag data terug. */ function get_grondslagen( $checklist_groep_id ) { return $this->_CI->deelplan->get_grondslagen( $this->id, $checklist_groep_id ); } /** Geeft array met distinct grondslag namen terug. */ function get_distinct_grondslagen( $checklist_groep_id ) { return $this->_CI->deelplan->get_distinct_grondslagen( $this->id, $checklist_groep_id ); } /** Geeft array met vraag id's als keys, array's met richtlijn data terug. */ function get_richtlijnen( $checklist_groep_id ) { return $this->_CI->deelplan->get_richtlijnen( $this->id, $checklist_groep_id ); } /** Geeft array met subjecten terug die aan dit deelplan zijn gekoppeld. */ function get_subjecten() { return $this->_CI->deelplan->get_subjecten( $this->id ); } /** Geeft array met alle bescheiden die gekoppeld zijn aan dit deelplan. */ function get_bescheiden( $assoc=true, $limit_to_pdfa_only = false ) { $this->_CI->load->model( 'dossierbescheiden' ); // Define the base query. This is what is used for getting ALL of the bescheiden. Further filtering can be applied to this for limiting the files that are // retrieved. $base_query = 'SELECT b.id, b.dossier_id, b.tekening_stuk_nummer, b.auteur, b.omschrijving, b.zaaknummer_registratie, b.versienummer, b.datum_laatste_wijziging, b.bestandsnaam, b.png_status, b.laatste_bestands_wijziging_op, b.dossier_bescheiden_map_id FROM deelplan_bescheiden lb JOIN dossier_bescheiden b ON lb.dossier_bescheiden_id = b.id WHERE lb.deelplan_id = ?'; // The app uses a restircted set of files, limited to the PDF/A copies only. The below "if" switched between delivering that data and delivering the full data. if ($limit_to_pdfa_only) { // Limit the results strictly to those files for which a PDF/A copy exists. This is used for the BTZ app! $limited_query = $base_query .= ' AND (has_pdfa_copy = 1)'; if (!$this->_CI->dbex->is_prepared( 'deelplan::get_bescheiden_pdfa_only' )) $this->_CI->dbex->prepare( 'deelplan::get_bescheiden_pdfa_only', $limited_query ); $res = $this->_CI->dbex->execute( 'deelplan::get_bescheiden_pdfa_only', array( $this->id ) ); } else { if (!$this->_CI->dbex->is_prepared( 'deelplan::get_bescheiden' )) $this->_CI->dbex->prepare( 'deelplan::get_bescheiden', $base_query ); $res = $this->_CI->dbex->execute( 'deelplan::get_bescheiden', array( $this->id ) ); } $result = array(); foreach ($res->result() as $row) if ($assoc) $result[$row->id] = $this->_CI->dossierbescheiden->getr( $row ); else $result[] = $this->_CI->dossierbescheiden->getr( $row ); $res->free_result(); return $result; } /** Geeft array met datums terug, gesorteerd op datum. */ function get_toezichtmomenten_by_checklist( $checklist_id ) { $stmt_name = 'get_toezichtmomenten_by_checklist'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT * FROM ( SELECT '.get_db_date_field_from_timestamp_for_literal_comparison('d.last_updated_at').' AS datum, d.gebruiker_id FROM deelplan_vragen d JOIN bt_vragen v ON d.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id WHERE d.deelplan_id = ? AND h.checklist_id = ? AND d.status IS NOT NULL GROUP BY '.get_db_date_field_from_timestamp_for_literal_comparison('d.last_updated_at').', d.gebruiker_id UNION SELECT '.get_db_date_field_from_timestamp_for_literal_comparison('d.datum').' AS datum, d.gebruiker_id FROM deelplan_vraag_geschiedenis d JOIN bt_vragen v ON d.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id WHERE d.deelplan_id = ? AND h.checklist_id = ? AND d.status IS NOT NULL GROUP BY '.get_db_date_field_from_timestamp_for_literal_comparison('d.datum').', d.gebruiker_id ) a GROUP BY datum, gebruiker_id ORDER BY datum '); $res = $this->_CI->dbex->execute( $stmt_name, array( $this->id, $checklist_id, $this->id, $checklist_id ) ); $result = array(); foreach ($res->result() as $row) { if (!isset( $result[$row->datum] )) $result[$row->datum] = array(); if (!in_array( $row->gebruiker_id, $result[$row->datum] )) $result[$row->datum][] = $row->gebruiker_id; } $res->free_result(); return $result; } public function get_deelplan_checklisten($checklist_id = null) { $this->_CI->load->model( 'deelplanchecklist' ); $query_parameters = array( $this->id ); $additional_where_clause = ''; if (!is_null($checklist_id)) { $additional_where_clause = ' AND checklist_id = ? '; $query_parameters[] = $checklist_id; } $deelplan_checklisten_query = "SELECT * FROM deelplan_checklisten WHERE deelplan_id = ? {$additional_where_clause} ORDER BY id"; $this->_CI->dbex->prepare( 'get_deelplan_checklisten', $deelplan_checklisten_query ); return $this->_CI->deelplanchecklist->convert_results( $this->_CI->dbex->execute( 'get_deelplan_checklisten', $query_parameters ) ); } /** Geeft progress terug, in 0-1 waarde. */ function get_progress_by_checklistgroep( $checklist_groep_id ) { $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'deelplanthema' ); $this->_CI->load->model( 'hoofdthema' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->library( 'prioriteitstelling' ); $cg = $this->_CI->checklistgroep->get( $checklist_groep_id ); if (!$cg) return 0; $vragen = $this->get_checklistgroep_vragen( $checklist_groep_id ); // maak lijst van onderwerpen if ($cg->modus == 'niet-combineerbaar') $classname = 'OnderwerpenSplitterNietCombineerbareChecklistgroep'; else if ($cg->modus == 'combineerbaar') $classname = 'OnderwerpenSplitterCombineerbareChecklistgroep'; else $classname = 'OnderwerpenSplitterCombineerbaarOpChecklistChecklistgroep'; return $this->_calc_progress( $vragen, $classname ); } /** Geeft progress terug, in 0-1 waarde. */ function get_progress_by_checklist( $checklist_id, $bouwnummer=null ) { $this->_CI->load->model( 'checklist' ); $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'deelplanthema' ); $this->_CI->load->model( 'hoofdthema' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->library( 'prioriteitstelling' ); $cl = $this->_CI->checklist->get( $checklist_id ); if (!$cl) return 0; $vragen = $this->get_checklist_vragen( $checklist_id, $dummy, $bouwnummer ); return $this->_calc_progress( $vragen, 'OnderwerpenSplitterNietCombineerbareChecklistgroep', $bouwnummer ); } private function prepareSupervisionMoments( $dbMoments ){ $moments = array(); $date = ''; foreach( $dbMoments as $row ){ if( $date != $row-> date){ $date = $row-> date; $users = array(); } $users[] = $row->user_id; unset($row->user_id); $row->users = $users; $moments[$row->date] = $row; } return $moments; } function get_supervision_moments_cl( $force_new=FALSE ) { if (!isset($this->_supervision_moments_cl) || $force_new) $this->_supervision_moments_cl = $this->_CI->deelplan->get_supervision_moments_cl( $this->id ); $moments = $this->prepareSupervisionMoments( $this->_supervision_moments_cl ); return $moments; } function get_supervision_moments_clg( $force_new=FALSE ) { if ( !isset($this->_supervision_moments_clg) || $force_new) $this->_supervision_moments_clg = $this->_CI->deelplan->get_supervision_moments_clg( $this->id ); $moments = $this->prepareSupervisionMoments( $this->_supervision_moments_clg ); return $moments; } function _calc_progress( $vragen, $splitterclass, $bouwnummer='' ) { $vragen = $this->_CI->deelplan->filter_vragen( $this->id, $vragen, $prioriteiten ); $deelplan_onderwerpen = new $splitterclass( $this, $vragen, $prioriteiten ); $deelplan_onderwerpen->run(); $onderwerp_data = $deelplan_onderwerpen->result(); $done = $total = 0; foreach ($onderwerp_data->onderwerpen as $onderwerp_id => $checklist_data){ foreach ($checklist_data['vragen'] as $vraag) { $total++; switch ($vraag->vraag_type) { case 'invulvraag': if (strlen($vraag->status)) $done++; break; case 'meerkeuzevraag': // als er een status (antwoord) gezet is, dan deze gebruiken if ($vraag->status) $status = $vraag->status; // anders de standaard waarde pakken voor dit veld else $status = $vraag->get_wizard_veld_recursief( 'wo_standaard' ); // controleer status waarde if (!$status) // geen default, mag eigenlijk niet, maar niet op crashen! continue; if (!preg_match( '/^w(\d{2})s?/', $status, $matches )) throw new Exception( 'Fout bij bepalen voortgang, status ' . $status . ' niet geldig.' ); // vervolgens van de gevonden $status bepalen of deze moet worden meegeteld // of niet $is_leeg = $vraag->get_wizard_veld_recursief( 'wo_is_leeg_' . $matches[1] ); if ($is_leeg == '0') $done++; break; default: throw new Exception( 'Onbekend vraag type: ' . $vraag->type ); } } } return $total ? ($done / $total) : 0; } /** Geeft array met subjecten terug die aan dit deelplan zijn gekoppeld, en ingesteld door de HUIDIGE TOEZICHTHOUDER, voor vragen behorend aan de opgegeven CHECKLISTGROEP. */ function get_hercontrole_data_voor_checklistgroep( $checklist_groep_id, $gebruiker_id, $alleen_in_toekomst=true ) { if (!$gebruiker_id) { $gebruiker = $this->get_toezichthouder( $checklist_groep_id ); if (!$gebruiker) return array(); $gebruiker_id = $gebruiker->id; } return $this->_CI->deelplan->get_hercontrole_data( $this->id, $checklist_groep_id, $gebruiker_id, $alleen_in_toekomst, null /* checklist id */ ); } /** Geeft array met subjecten terug die aan dit deelplan zijn gekoppeld voor vragen gekoppeld aan de opgegeven CHECKLIST. */ function get_hercontrole_data_voor_checklist( $checklist_id, $alleen_in_toekomst=true ) { return $this->_CI->deelplan->get_hercontrole_data( $this->id, null /* checklistgroep id */, null /* gebruiker id */, $alleen_in_toekomst, $checklist_id ); } function get_toezichthouder( $checklist_groep_id ) { $CI = get_instance(); $CI->load->model( 'deelplanchecklistgroep' ); foreach ($CI->deelplanchecklistgroep->get_by_deelplan( $this->id ) as $deelplanchecklistgroep) if ($deelplanchecklistgroep->checklist_groep_id == $checklist_groep_id) return $CI->gebruiker->get( $deelplanchecklistgroep->toezicht_gebruiker_id ); return null; } function get_toezichthouder_checklist( $checklist_id, $bouwnummer='' ) { $CI = get_instance(); $CI->load->model( 'deelplanchecklist' ); foreach ($CI->deelplanchecklist->get_by_deelplan( $this->id ) as $deelplanchecklist){ if ($deelplanchecklist->checklist_id == $checklist_id && $deelplanchecklist->bouwnummer==$bouwnummer){ return $CI->gebruiker->get( $deelplanchecklist->toezicht_gebruiker_id ); } } return null; } function get_sjabloon() { if (!$this->sjabloon_id) return null; $CI = get_instance(); $CI->load->model( 'sjabloon' ); return $CI->sjabloon->get( $this->sjabloon_id ); } /** Retourneert 3 soorten plannings data: wanneer het wordt aangeroepen zonder parameters * retourneert deze functie de eerst volgende datum waarop iets gepland is voor het deelplan * in z'n geheel, dus over alle scopes. * Wanneer een scope wordt meegegeven, dus wanneer een checklistgroep id plus eventueel * een checklist id wordt meegegeven, wordt de eerstvolgende datum voor DIE scope teruggeven, * of NULL wanneer de scope niet bestaat in dit deelplan, of er nog niks gepland is. */ public function get_plannings_datum( $checklist_groep_id=null, $checklist_id=null ) { // geen scope? if (!$checklist_groep_id && !$checklist_id) { $res = $this->_CI->db->query( $q = 'SELECT gepland_datum AS datum1, NULL AS datum2 FROM deelplan_planning WHERE deelplan_id = ' . intval($this->id) ); } else { // checklistgroep scope? checklistgroep moet altijd gezet zijn (zo niet dan wordt NULL // teruggeven doordat onderstande query dan nooit iets zal teruggeven) if (!$checklist_id) { // !!! Fix the 'if' for Oracle $res = $this->_CI->db->query( $q = ' SELECT dcp.eerste_hercontrole_datum AS datum1, dc.initiele_datum AS datum2 FROM deelplan_checklistgroep_plnng dcp RIGHT JOIN deelplan_checklist_groepen dc ON dcp.deelplan_id = dc.deelplan_id AND dcp.checklist_groep_id = ' . intval($checklist_groep_id) . ' WHERE dc.deelplan_id = ' . intval($this->id) . ' AND dc.checklist_groep_id = ' . intval($checklist_groep_id) . ' ' ); } // checklist scope! else { // !!! Fix the 'if' for Oracle $res = $this->_CI->db->query( $q = ' SELECT dcp.eerste_hercontrole_datum AS datum1, dc.initiele_datum AS datum2 FROM deelplan_checklist_planning dcp RIGHT JOIN deelplan_checklisten dc ON dcp.deelplan_id = dc.deelplan_id AND dcp.checklist_id = ' . intval($checklist_id) . ' WHERE dc.deelplan_id = ' . intval($this->id) . ' AND dc.checklist_id = ' . intval($checklist_id) . ' ' ); } } // haal resultaat op en return if (!$res->num_rows()) { $datum = NULL; } else { $row = $res->row_object(); $now = date( 'Y-m-d' ); $datum1 = $row->datum1 ? date( 'Y-m-d', strtotime( $row->datum1 ) ) : NULL; if ($datum1 < $now) $datum1 = NULL; $datum2 = $row->datum2 ? date( 'Y-m-d', strtotime( $row->datum2 ) ) : NULL; if ($datum2 < $now) $datum2 = NULL; if (!$datum1) $datum = $datum2; else if (!$datum2) $datum = $datum1; else $datum = $datum1 < $datum2 ? $datum1 : $datum2; } $res->free_result(); return $datum ? date( 'd-m-Y', strtotime( $datum ) ) : NULL; } //------------------------------------------------------------------------- // updaters //------------------------------------------------------------------------- /** Updates categorieen applicable for this deelplan based on its settings. */ // NOTE (OJG - 2014-07-17): this method is a.o. used from the soapdossier SOAP webservice, which is run without being logged in. For this reason, the optional // parameter $override_logged_in_user_id was added and passed along to the deelplan->add_vragen method. // Do NOT remove this, or the webservice WILL break!!! public function update_content($override_logged_in_user_id = null, $is_cli=false ) { $this->_CI->db->trans_start(); // vind antwoorden voor huidige vragen $old_vragen = $this->_CI->deelplan->get_alle_vragen( $this->id ); // verwijder huidige vragen $this->_CI->deelplan->delete_vragen( $this->id ); // vind vragen die nu bij deelplan horen $vragen = $is_cli ? $this->get_project_mappen_vragen() : $this->_CI->deelplan->find_gelinkte_vragen( $this->id ); // voeg vragen toe, en (her)gebruik huidige antwoorden $this->_CI->deelplan->add_vragen( $this->id, $vragen, $old_vragen, $override_logged_in_user_id ); $this->_CI->db->trans_complete(); } private function get_project_mappen_vragen(){ $this->_CI->load->model( 'projectmap' ); $this->_CI->load->model( 'btbtzdossier' ); $this->_CI->load->model( 'dossier' ); $btbtzdossier = $this->_CI->btbtzdossier->get_one_by_btz_dossier_id( $this->dossier_id ); $bouwnummers = $btbtzdossier->get_bouwnummers(); $vragen = $this->_CI->projectmap->get_by_deelplan( $this ); $ret_vragen = array(); foreach( $vragen as $vraag ) { if( $vraag->is_active ) { foreach( $bouwnummers as $bouwnummer ) { $ret_vraag = array( 'id' => $vraag->vraag_id, 'bouwnummer' => $bouwnummer, 'automatische_toel_moment' => $vraag->automatische_toel_moment ); $ret_vragen[] = (object)$ret_vraag; } } } return $ret_vragen; } /** Updates smartgroepen */ public function update_checklisten( $arr, $is_cli=FALSE ) { $new_checklisten = array(); $new_checklistgroepen = array(); if($is_cli){ $this->_CI->load->model( 'checklistgroep' ); $this->_CI->load->model( 'deelplanchecklistgroep' ); foreach( $arr['checklist'] as $id => $vll ) $new_checklisten[] = $id; foreach( $arr['checklistgroep'] as $id => $vll ) $new_checklistgroepen[] = $id; $change_detected = true; }else{ $checklistgroepen = $this->_CI->checklistgroep->get_for_huidige_klant(); $change_detected = false; // get the checklisten currently attached to this deelplan $current_checklisten = $this->get_checklisten_assoc(); // get the new checklisten attached to this deelplan foreach( $checklistgroepen as $checklistgroep ) { if (isset( $arr['checklistgroep'][$checklistgroep->id] ) && $arr['checklistgroep'][$checklistgroep->id]=='on') { $new_checklistgroepen[] = $checklistgroep->id; foreach ($checklistgroep->get_checklisten() as $checklist) { if (isset( $arr['checklist'][$checklist->id] ) && $arr['checklist'][$checklist->id]=='on') { $new_checklisten[] = $checklist->id; } } } } // see if there are changes if (sizeof( $current_checklisten ) == sizeof( $new_checklisten )) { foreach ($new_checklisten as $checklist_id) if (!isset( $current_checklisten[$checklist_id] )) { $change_detected = true; break; } } else $change_detected = true; } // always update matrix/toezichthouder $this->_CI->deelplanchecklistgroep->remove_except( $this->id, $new_checklistgroepen ); if (!is_null( $arr['toezichthouders'] ) && !is_null( $arr['matrices'] )) { foreach ($new_checklistgroepen as $checklistgroep_id) { $this->_CI->deelplanchecklistgroep->replace( $this->id, $checklistgroep_id, $arr['toezichthouders'][$checklistgroep_id], $arr['matrices'][$checklistgroep_id] ); } } else { foreach ($new_checklistgroepen as $checklistgroep_id) { $this->_CI->deelplanchecklistgroep->add( $this->id, $checklistgroep_id ); } } // setup if ($change_detected) { $this->_CI->load->model( 'deelplanchecklist' ); $this->_CI->db->trans_start(); $this->_CI->deelplanchecklist->remove_except( $this->id, $new_checklisten ); $klant = $this->_CI->klant->get_logged_in_klant(); $bouwnummers = array(''); if ($klant->heeft_toezichtmomenten_licentie == 'ja' || $is_cli ) { $this->_CI->load->model( 'btbtzdossier' ); $this->_CI->load->model( 'toezichtmoment' ); $this->_CI->load->model( 'deelplanchecklisttoezichtmoment' ); $bt_btz_dossier = $this->_CI->btbtzdossier->get_one_by_btz_dossier_id( $this->dossier_id ); $bouwnummers = $bt_btz_dossier != NULL ? $bt_btz_dossier->get_bouwnummers() : $bouwnummers; } $dp_chkl_tmoment_ids = array(); // Get the currently existing checklist associations, as we need them for checking if we should add a new association // or not. $existingDeelplanChecklists = $this->_CI->deelplanchecklist->get_by_deelplan( $this->id ); foreach ($new_checklisten as $checklist_id) { foreach($bouwnummers as $bouwnummer ) { // !!! OJG 2016-04-03: The addition of bouwnummers has introduced a weird bug for existing deelplanchecklist // entries (possibly only those that do not have bouwnummers): the bug was that when adding a checklist, the // existing entry was preserved (correct), but always a new entry was made too for essentially the same // deelplancheklist. For this reason, we have to do some extra checks to determine if we really should // create a new entry or not. // Note also that the DB default is NULL, whereas the above code sets an empty string in case bouwnummers // are not used! Take care to check for this situation! //$this->_CI->deelplanchecklist->add( $this->id, $checklist_id, $bouwnummer ); $addNewDeelplanChecklist = true; foreach ($existingDeelplanChecklists as $existingDeelplanChecklist) { if ($existingDeelplanChecklist->checklist_id == $checklist_id) { // An entry already exists for this checklist! Check if we should allow a further one to be added // or not! if ( (is_null($existingDeelplanChecklist->bouwnummer) || empty($existingDeelplanChecklist->bouwnummer)) && empty($bouwnummer) ) { //echo "Skip checklist {$checklist_id}<br />"; $addNewDeelplanChecklist = false; } } } // Only if the checklist passes all checks, do we create a new one for it. if ($addNewDeelplanChecklist) { //echo "Add checklist {$checklist_id}<br />"; $this->_CI->deelplanchecklist->add( $this->id, $checklist_id, $bouwnummer ); } if($klant->heeft_toezichtmomenten_licentie == 'ja' || $is_cli ) { $dlplan_chklist_id = $this->_CI->db->insert_id(); $toezichtmomenten = $this->_CI->toezichtmoment->get_by_checklist($checklist_id); foreach( $toezichtmomenten as $toezichtmoment ){ $data = array( 'deelplan_checklist_id' => $dlplan_chklist_id, 'bt_toezichtmoment_id' => $toezichtmoment->id ); $dp_chkl_tmoment = $this->_CI->deelplanchecklisttoezichtmoment->insert( $data ); $dp_chkl_tmoment_ids[] = $dp_chkl_tmoment->id; } } } } // finalize if (!$this->_CI->db->trans_complete()) throw new Exception( 'Fout bij opslaan van checklisten.' ); } return $change_detected; } /** MAIN TOEZICHT DATA FUNCTIE */ function get_toezicht_data( $checklistgroep, $checklist, $geef_ook_overige_data, $bouwnummer='' ){ // init $CI = get_instance(); $CI->load->model( 'deelplansubjectvraag' ); $CI->load->model( 'grondslagtekst' ); $CI->load->model('deelplanhoofgroepen'); $CI->load->library( 'quest' ); $checklistgroep_id = $checklistgroep->id; $checklist_id = $checklist ? $checklist->id : NULL; $dossier = $this->get_dossier(); $klant = $dossier->get_gebruiker()->get_klant(); // get ALL possible vragen for the selected checklistgroepen $woborg_vragen = $vragen = (!$checklist_id) ? $this->get_checklistgroep_vragen( $checklistgroep_id ) : $this->get_checklist_vragen( $checklist_id, $dummy, $bouwnummer ); // filter the ones that are not visible based on thema's and matrices $prioriteiten = $onafgeronde_checklisten = null; // set by reference $vragen = $CI->deelplan->filter_vragen( $this->id, $vragen, $prioriteiten, $onafgeronde_checklisten ); $vragen = $klant->heeft_toezichtmomenten_licentie == 'nee' ? $vragen : $woborg_vragen; // maak lijst van onderwerpen if ($checklistgroep->modus == 'niet-combineerbaar' && $this->geintegreerd == 'nee' ) $classname = 'OnderwerpenSplitterNietCombineerbareChecklistgroep'; else if ($checklistgroep->modus == 'combineerbaar') $classname = 'OnderwerpenSplitterCombineerbareChecklistgroep'; else $classname = 'OnderwerpenSplitterCombineerbaarOpChecklistChecklistgroep'; $deelplan_onderwerpen = new $classname( $this, $vragen, $prioriteiten ); $deelplan_onderwerpen->run(); $onderwerp_data = $deelplan_onderwerpen->result(); // // PART 1 DONE: moeten we overige data niet ophalen? dan nu kappen // if (!$geef_ook_overige_data) { return array( 'vragen' => $vragen, 'deelplan_onderwerpen' => $deelplan_onderwerpen, 'onderwerp_data' => $onderwerp_data, ); } // haal alle unieke vraag IDs op $vraag_ids = array(); foreach ($vragen as $vraag){ $vraag_ids[] = $vraag->id; } // haal alle hercontrole data op (per deelplan/checklistgroep) voor deze toezichthouder $toezichthouder_cg = $this->get_toezichthouder( $checklistgroep_id ); $toezichthouder_cl = $checklist_id ? $this->get_toezichthouder_checklist( $checklist_id ) : null; $hercontrole_data = array(); if ($toezichthouder_cg || $toezichthouder_cl) { foreach ($dossier->get_deelplannen() as $d) { if ($toezichthouder_cg) { foreach ($d->get_checklistgroepen() as $cg) { if ($dpt = $d->get_toezichthouder( $cg->id )) { if ($dpt->id == $toezichthouder_cg->id) { $hcd = $d->get_hercontrole_data_voor_checklistgroep( $cg->id, $dpt->id ); if (!empty( $hcd )) { $d_tag = $d->id . ':' . $d->naam; $cg_tag = $cg->id . ':' . $cg->naam; if (!isset( $hercontrole_data[$d_tag] )) $hercontrole_data[$d_tag] = array(); $hercontrole_data[$d_tag][$cg_tag] = $hcd; } } } } unset( $cg ); } if ($toezichthouder_cl) { foreach ($d->get_checklisten() as $cl) { if ($dpt = $d->get_toezichthouder_checklist( $cl->id )) { if ($dpt->id == $toezichthouder_cl->id) { $hcd = $d->get_hercontrole_data_voor_checklist( $cl->id, $dpt->id ); if (!empty( $hcd )) { $d_tag = $d->id . ':' . $d->naam; $cl_tag = $cl->id . ':' . $cl->naam; if (!isset( $hercontrole_data[$d_tag] )) $hercontrole_data[$d_tag] = array(); $hercontrole_data[$d_tag][$cl_tag] = $hcd; } } } } unset( $cl ); } } } $hercontrole_lijst = array(); foreach ($hercontrole_data as $deelplan => $checklistgroepen) foreach ($checklistgroepen as $cg => $datums) foreach ($datums as $datum) { $parts = explode( '|', $datum ); $parts[0] = date( 'd-m-Y', strtotime( $parts[0] ) ); $hercontrole_lijst[$datum] = array( 'value' => implode( '|', $parts ), 'html' => $parts[0] . ($parts[1] ? ' van ' . $parts[1] . ' tot ' . $parts[2] : '') . ' (' . preg_replace( '/^\d+\:(.*)$/', '$1', $deelplan) . ', ' . preg_replace( '/^\d+\:(.*)$/', '$1', $cg) . ')', ); } ksort( $hercontrole_lijst ); $hercontrole_lijst = array_values( $hercontrole_lijst ); $aandachtspunten = $this->get_aandachtspunten( $checklistgroep_id, $checklist_id ); // unset bescheiden bestandsdata $bescheiden = array(); foreach ($this->get_bescheiden() as $b) if ($b->bestandsnaam) $bescheiden[] = $b; // laad richtlijnen $richtlijnen = array(); foreach ($CI->deelplan->laad_richtlijnen( $checklistgroep_id, $checklist_id, $this->id ) as $rl) $richtlijnen[] = new RichtlijnEntry( $rl->richtlijn_id, $rl->filename, $rl->url, $rl->url_beschrijving, $rl->checklist_groep_id, $rl->checklist_id, $rl->hoofdgroep_id, $rl->vraag_id ); // laad grondslagen $grondslag_tekst_ids = array(); $grondslagen = array(); foreach ($CI->deelplan->laad_grondslagen( $checklistgroep_id, $checklist_id, $this->id ) as $gs) { $grondslagen[] = new GrondslagEntry( $gs->grondslag_tekst_id, $gs->grondslag, $gs->display_hoofdstuk, $gs->display_afdeling, $gs->display_paragraaf, $gs->display_artikel, $gs->display_lid, $gs->artikel, $gs->checklist_groep_id, $gs->checklist_id, $gs->hoofdgroep_id, $gs->vraag_id ); $grondslag_tekst_ids[ $gs->grondslag_tekst_id ] = true; } // laad (standaard) opdrachten (waar een gebruiker uit kan kiezen bij het maken van echte opdrachten) $opdrachten = array(); foreach ($CI->deelplan->laad_opdrachten( $checklistgroep_id, $checklist_id, $this->id ) as $op) { $opdrachten[] = new OpdrachtEntry( $op->opdracht, $op->checklist_groep_id, $op->checklist_id, $op->hoofdgroep_id, $op->vraag_id ); } $deelplanchecklist = $this->get_deelplanchecklist($checklist_id, $bouwnummer ); // laad reeds ingeplande opdrachten $geplande_opdrachten = $CI->deelplanopdracht->get_by_deelplan_checklistgroep_checklist( $this->id, $checklistgroep_id, $checklist_id ); foreach($geplande_opdrachten as $ind=>$geplande_opdracht ) { if($geplande_opdracht->deelplan_checklist_id != $deelplanchecklist->id) { unset($geplande_opdrachten[$ind]); } } $geplande_opdrachten = array_values($geplande_opdrachten); // It is necessary for JS. // fetch checklist groep info $checklistgroep_info = array( 'id' => intval( $checklistgroep->id ), 'naam' => $checklistgroep->naam ,'checklisten' => array() ); if( ($checklistgroep->modus == 'niet-combineerbaar' || $checklistgroep->modus == 'combineerbaar') && $this->geintegreerd == 'nee' ){ foreach ($onderwerp_data->onderwerpen as $onderwerp => $vragen){ foreach ($vragen['vragen'] as $vraag) { if (isset( $checklistgroep_info['checklisten'][ $vraag->checklist_id ] )) continue; $checklistgroep_info['checklisten'][ $vraag->checklist_id ] = array( 'id' => intval( $vraag->checklist_id ), 'naam' => $CI->checklist->get( $vraag->checklist_id )->naam, ); } } $checklistgroep_info['checklisten'] = array_values( $checklistgroep_info['checklisten'] ); }else{ foreach ($onderwerp_data->onderwerpen as $onderwerp_id => $ochecklist ){ unset($ochecklist['vragen']); $checklistgroep_info['checklisten'][] = $ochecklist; } } if($onderwerp_data->onderwerpen){ $hoofgroepen_ids=array_keys($onderwerp_data->onderwerpen); } if(isset($hoofgroepen_ids)){ foreach ($hoofgroepen_ids as $hoofgroepen_id){ $res=$CI->deelplanhoofgroepen->get_toelichting_for_hoofgroep($this->id,$hoofgroepen_id); if($res){ $hoofgroepen_toelihting[$hoofgroepen_id]=$res; $hoofgroepen_toelihting_last[$hoofgroepen_id]=end($res); } } } // $ra_handler = $checklistgroep->get_risicoanalyse_handler(); $themas = $CI->thema->get_for_huidige_klant( true );// All klant themas // // PART 2 DONE: volledige data structuur terug geven // return array( 'hoofgroepen_toelichting' => isset($hoofgroepen_toelihting) ? $hoofgroepen_toelihting : "", 'last_hoofgroepen_toelichting' => isset($hoofgroepen_toelihting_last) ? $hoofgroepen_toelihting_last:"", 'aandachtspunten' => $aandachtspunten, 'grondslagen' => $grondslagen, 'richtlijnen' => $richtlijnen, 'opdrachten' => $opdrachten, 'geplande_opdrachten' => $geplande_opdrachten, 'grondslag_tekst_ids' => array_keys( $grondslag_tekst_ids ), 'bescheiden' => $bescheiden, 'bescheiden_structuur' => $this->get_bescheiden_en_mappen_structuur()->Ingangen, // only used by app, but makes changes in this data automatically invalidate the scope! (SHA1 changes) 'vraagbescheiden' => $CI->deelplanvraagbescheiden->get_by_deelplan( $this->id ), 'deelplanvraaggeschiedenis' => $CI->deelplanvraaggeschiedenis->get_by_deelplan( $this->id, $bouwnummer ), 'deelplanuploads' => $CI->deelplanupload->find_by_deelplan( $this->id, $bouwnummer, true ), // 'deelplanuploads' => [], 'themas' => $themas, 'onafgeronde_checklisten' => $onafgeronde_checklisten, 'vraag_subjecten' => $CI->deelplansubjectvraag->get_by_deelplan( $this->id ), 'subjecten' => $this->get_subjecten(), 'checklistgroep' => $checklistgroep_info, 'selected_vraag' => $onderwerp_data->selected_vraag, 'onderwerpen' => $onderwerp_data->onderwerpen, // onderwerp id -> array met onderwerp naam en diens vragen 'hoofdgroep_prioriteiten' => $onderwerp_data->hoofdgroep_prioriteiten, // hoofdgroep id -> prioriteit ('laag', 'zeer_laag', 'hoog', etc.) 'hoofdgroep_prioriteiten_origineel' => $onderwerp_data->hoofdgroep_prioriteiten_origineel, // als hoofdgroep_prioriteiten, maar dan de waarde uit de matrix, zonder evt. verhoging 'vraag_ids' => $vraag_ids, 'hercontrole_data' => $hercontrole_data, 'hercontrole_lijst' => $hercontrole_lijst, 'bescheiden_layers' => $CI->deelplanlayer->get_by_deelplan( $this->id ), 'risicoanalyse' => array( 'risico_shortnames' => $ra_handler->get_risico_shortnames(), ), ); } function get_aandachtspunten( $checklistgroep_id, $checklist_id=null ) { // laad elke vorm van aandachtspunten // we hebben er een hele hoop: // VANUIT DE CHECKLIST(GROEP) // - aandachtspunten op checklistgroep niveau // - aandachtspunten op checklist niveau // - aandachtspunten op hoofdgroep niveau // - aandachtspunten op vraag niveau // VANUIT HET DEELPLAN // - globale aandachtspunten (gelden voor hele deelplan) // - niet-globale aandachtspunten (gelden per vraag) // we brouwen daar 1 grote mega array van, en dan laten we de browser // het verder uitzoeken whehehe >:-) $CI = get_instance(); $CI->load->model( 'deelplanaandachtspunt' ); $CI->load->model( 'deelplanvraagaandachtspunt' ); $CI->load->model( 'deelplanopdracht' ); $aandachtspunten = array(); // uiteindelijke array van aandachtspunten $deelplan_aandachtspunten = $CI->deelplanaandachtspunt->get_by_deelplan_id( $this->id, true ); // tijdelijke helper array // globale deelplan aandachtspunten foreach ($deelplan_aandachtspunten as $ap) if ($ap->globaal == 'ja') $aandachtspunten[] = new AandachtspuntEntry( $ap->toetser . ' op ' . $ap->datum . "\n" . $ap->tekst, $ap->grondslag, null, null, null, null, 'altijd' ); // niet-globale deelplan aandachtspunten (instellen per vraag) foreach ($CI->deelplanvraagaandachtspunt->get_by_deelplan_id( $this->id ) as $dap) { $ap = $deelplan_aandachtspunten[ $dap->deelplan_aandachtspunt_id ]; $aandachtspunten[] = new AandachtspuntEntry( $ap->toetser . ' op ' . $ap->datum . "\n" . $ap->tekst, $ap->grondslag, null, null, null, $dap->vraag_id, 'altijd' ); } // alle checklist-related aandachtspunten (instellen zoals aandachtspunt zelf aangeeft) foreach ($CI->deelplan->laad_aandachtspunten( $checklistgroep_id, $checklist_id, $this->id ) as $ap) $aandachtspunten[] = new AandachtspuntEntry( $ap->aandachtspunt, 'Aandachtspunt', $ap->checklist_groep_id, $ap->checklist_id, $ap->hoofdgroep_id, $ap->vraag_id, 'voorwaardelijk' ); return $aandachtspunten; } // !!! Note (OJG - 21-3-2016): the below method is a.o. used in the reporting functionality. In at least that section it is undesirable // if no data is returned when the deelplan has the 'afgemeld' field set to 1. As other locations probably do expect this behaviour, // an extra optional parameter was added in to force-retrieve the data if the value is set to 1 too. //function get_scopes( $voor_gebruiker_id=null ){ function get_scopes( $voor_gebruiker_id=null, $retrieve_scopes_despite_afgemeld = false ){ $klant = $this->_CI->klant->get_logged_in_klant(); $scopes = array(); if (!$this->afgemeld || $retrieve_scopes_despite_afgemeld) { foreach ($this->get_checklistgroepen() as $checklistgroep) { if ($checklistgroep->modus != 'niet-combineerbaar' || $this->geintegreerd == 'ja' ) { if ($voor_gebruiker_id) { $toezichthouder = $this->get_toezichthouder( $checklistgroep->id ); if (!$toezichthouder || $toezichthouder->id != $voor_gebruiker_id) continue; } $scopes[] = array( 'checklist_groep_id' => $checklistgroep->id, 'url' => '/deelplannen/checklistgroep/' . $checklistgroep->id . '/' . $this->id, 'naam' => $checklistgroep->naam, ); } else { foreach ($this->get_checklisten() as $checklist) { if ($checklist->checklist_groep_id == $checklistgroep->id) { if ($voor_gebruiker_id) { $toezichthouder = $this->get_toezichthouder_checklist( $checklist->id ); if (!$toezichthouder || $toezichthouder->id != $voor_gebruiker_id) continue; } $scope_naam = $checklistgroep->naam . ' - ' . $checklist->naam; $scope_naam = ($klant->heeft_toezichtmomenten_licentie == 'ja') ? $scope_naam.' - '.$checklist->bouwnummer : $scope_naam; $scopes[] = array( 'checklist_groep_id' => $checklistgroep->id, 'checklist_id' => $checklist->id, 'url' => '/deelplannen/checklistgroep/' . $checklistgroep->id . '/' . $this->id . '/' . $checklist->id, 'naam' => $scope_naam, 'bouwnummer' => $checklist->bouwnummer, ); } } } } } return $scopes; } function get_mogelijke_waardeoordelen() { return $this->_CI->deelplan->get_mogelijke_waardeoordelen( $this->id ); } function get_bescheiden_en_mappen_structuur($limit_to_pdfa_only = false) { // haal bescheiden op $bescheiden = $this->get_bescheiden(true, $limit_to_pdfa_only); // we hebben nu een kale array van bescheiden, maar we willen de mappen die erbij horen ook // hebben, we moeten dus een soort minimale mappenstructuur maken waarin de bescheiden binnen // dit deelplan zich bevinden! $structuur = (object)array( 'Ingangen' => array() ); foreach ($bescheiden as $b) { // per bescheiden, maak een lijst van alle mappen (dus b.v. "Tekeningen" -> "Bouwtekening" -> "Staal") // loop daarna de mappen af, en bouw deze weer op in $structuur, waarbij we rekening houden // met reeds aangebrachte mappen voor eerdere bescheiden $mappen = array(); $map = $b->get_dossier_bescheiden_map(); while ($map) { $mappen[] = $map; $map = $map->get_parent(); } // verwerk mappen in $structuur $cur_structuur = $structuur; while (!empty( $mappen )) { $mapnaam = array_pop( $mappen )->naam; // pak telkens de laatste, dat is de eerstvolgende in de top-down structuur van mappen $mapentry = null; foreach ($cur_structuur->Ingangen as $entry) if ($entry->Naam == $mapnaam && $entry->Type == 'map') { $mapentry = $entry; break; } if (!$mapentry) { $mapentry = (object)array( 'Naam' => $mapnaam, 'Type' => 'map', 'Ingangen' => array(), ); $cur_structuur->Ingangen[] = $mapentry; } $cur_structuur = $mapentry; } // voeg nu als laatste het bescheiden toe aan de diepste "directory/map" in de structuur // voeg nu als laatste het bescheiden toe aan de diepste "directory/map" in de structuur try { $grootte = $b->imageprocessor_get_original_dimensions(); } catch (Exception $e) { $grootte = array( 'w' => 0, 'h' => 0, ); } $cur_structuur->Ingangen[] = (object)array( 'Naam' => $b->omschrijving, 'Bestandsnaam' => $b->bestandsnaam, 'Type' => 'bescheiden', 'DownloadUrl' => $b->get_download_url(), 'ImageUrl' => $b->imageprocessor_get_original_url(), 'ThumbnailUrl' => $b->imageprocessor_get_thumbnail_url(), 'BescheidenId' => $b->id, 'Grootte' => $grootte, // dimensions of locally converted PNG, required to scale coordinates on iPad ); } return $structuur; } public function get_bouwdelen() { if (!isset( $this->_CI->deelplanbouwdeel )) $this->_CI->load->model( 'deelplanbouwdeel' ); return $this->_CI->deelplanbouwdeel->get_by_deelplan_id( $this->id ); } private function setProjectVragenStatus( $project_vragen ) { $CI = get_instance(); $CI->load->model( 'btbtzdossier' ); $CI->load->model( 'colectivematrix' ); $CI->load->model( 'dossier' ); $CI->load->model( 'gebruiker' ); $CI->load->model( 'klant' ); $CI->load->model( 'bijwoonmomentenmap' ); $CI->load->model( 'deelplanchecklisttoezichtmoment' ); $bt_btz_dosser = $CI->btbtzdossier->get_one_by_btz_dossier_id( $this->dossier_id ); $bt_project_matrix = $CI->colectivematrix->getProjectSpecifiekeMapping( $bt_btz_dosser->bt_dossier_id, $bt_btz_dosser->bt_dossier_hash ); $dossier = $CI->dossier->get( $this->dossier_id ); $gebruiker = $CI->gebruiker->get($dossier->gebruiker_id); $klant = $CI->klant->get($gebruiker->klant_id); $btz_matrixes = $klant->get_mappingen(); foreach( $btz_matrixes as $btz_matrix ) if($btz_matrix->bt_matrix_id == $bt_project_matrix['collective_matrix_id']) break; $CI->load->model( 'artikelvraagmap' ); $default_vragen_map = $CI->artikelvraagmap->get_matrixmapping_vragen( $btz_matrix->id, $bt_project_matrix['risk_profiel_id'] ); $vragen_status = array(); foreach( $default_vragen_map as $default_vraag_map ) { $vragen_status[$default_vraag_map->vraag_id] = $default_vraag_map->is_active; } $checklisten = $this->get_checklisten(); $any_deelplanchecklist = $this->get_deelplanchecklist($checklisten[0]->id); foreach( $project_vragen as &$project_vraag) { if( isset($vragen_status[$project_vraag->vraag_id]) && $project_vraag->is_active && $vragen_status[$project_vraag->vraag_id] ) { $project_vraag->status = 'S'; } elseif( (isset($vragen_status[$project_vraag->vraag_id]) && $project_vraag->is_active && !$vragen_status[$project_vraag->vraag_id]) || (!isset($vragen_status[$project_vraag->vraag_id]) && $project_vraag->is_active ) ) { $project_vraag->status = 'P'; } else { $project_vraag->status = '&#8212;'; } $project_vraag->bw = ''; $project_vraag->bw_color = '#000000'; if( (bool)$project_vraag->toezichtmoment_id ) { $bijwoonmomentenmap = $CI->bijwoonmomentenmap->get_by_toezichtmoment( $project_vraag->toezichtmoment_id, $btz_matrix->id ); $any_deelplanchecklist_toezichtmoment = $CI->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist( $any_deelplanchecklist->id, $project_vraag->toezichtmoment_id ); $any_deelplanchecklist_toezichtmoment = $any_deelplanchecklist_toezichtmoment[0]; $project_vraag->bw = $any_deelplanchecklist_toezichtmoment->bijwoonmoment ? 'J' : 'N'; $project_vraag->bw_color = ( $any_deelplanchecklist_toezichtmoment->bijwoonmoment != $bijwoonmomentenmap->is_drsm_bw ) ? '#FF0000' : '#000000'; } } return $project_vragen; } public function get_project_mappen(){ $CI = get_instance(); $CI->load->model( 'projectmap' ); if (!is_array($project_vragen = $CI->projectmap->get_by_deelplan( $this ))) throw new Exception( 'Ongeldig Project specifieke mapping ID'); $project_vragen = $this->setProjectVragenStatus($project_vragen); return $project_vragen; } } class Deelplan extends BaseModel { public function get_supervision_moments_cl( $deelplan_id ){ $sql = 'SELECT `scl`.`id` AS `id` '. ",DATE_FORMAT(`supervision_start`,'%Y-%m-%d') AS `date` ". ",CONCAT(`progress_end`,'%') AS `progress` ". ',`supervisor_user_id` AS `user_id` '. ',`checklist_id` '. ',`bouwnummer` '. ',`checklist_groep_id` '. 'FROM `supervision_moments_cl` `scl` '. 'LEFT JOIN `bt_checklisten` `btc` ON `btc`.`id`=`scl`.`checklist_id` '. 'WHERE `scl`.`deelplan_id`=? '. 'ORDER BY `supervision_start`,`progress_end` '. ''; $this->dbex->prepare( 'deelplan::get_supervision_moments_cl', $sql ); $args = func_get_args(); $res = $this->dbex->execute( 'deelplan::get_supervision_moments_cl', $args ); $result = array(); foreach ($res->result() as $row) $result[] = (object)$row; $res->free_result(); return $result; } ///--------------------------- public function get_supervision_moments_clg( $deelplan_id ){ $sql = 'SELECT `scl`.`id` AS `id` '. ",DATE_FORMAT(`supervision_start`,'%Y-%m-%d') AS `date` ". ",CONCAT(`progress_end`,'%') AS `progress` ". ',`supervisor_user_id` AS `user_id` '. ',`scl`.`checklist_group_id` AS `checklist_group_id`'. 'FROM `supervision_moments_clg` `scl`'. 'WHERE `scl`.`deelplan_id`=? '. 'ORDER BY `supervision_start`,`progress_end` '. ''; $this->dbex->prepare( 'deelplan::get_supervision_moments_clg', $sql ); $args = func_get_args(); $res = $this->dbex->execute( 'deelplan::get_supervision_moments_clg', $args ); $result = array(); foreach ($res->result() as $row) $result[] = (object)$row; $res->free_result(); return $result; } function Deelplan() { parent::BaseModel( 'DeelplanResult', 'deelplannen' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } function add( $dossier_id, $naam, $sortering=null ) { // Determine which "null function" should be used $null_func = get_db_null_function(); // auto-fetch sortering if (is_null( $sortering )) { // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'deelplan_add_get_sortering', 'SELECT '.$null_func.'(MAX(sortering),0) + 1 AS sortering FROM deelplannen WHERE dossier_id = ?' ); $res = $this->dbex->execute( 'deelplan_add_get_sortering', array( $dossier_id ) ); if ($res) { $regels = $res->result(); $sortering = reset( $regels )->sortering; $res->free_result(); } } // Use the base model's 'insert' method. $data = array( 'dossier_id' => $dossier_id, 'naam' => $naam, 'sortering' => $sortering, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result->id; // foddex says: return id, not the object, the old code does that as well!!! } function get_checklistgroepen( $deelplan_id ) { $CI = get_instance(); $CI->load->model( 'checklistgroep' ); // The below query is now "Oracle-safe" // Note: the query works as expected, the only thing 'missing' is the cl.sortering part in the ORDER BY clause. /* $query = ' SELECT cg.* FROM deelplan_checklisten rc JOIN bt_checklisten cl ON rc.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE rc.deelplan_id = ? GROUP BY cg.id ORDER BY cg.sortering, cl.sortering'; */ $query = ' SELECT cg.* FROM bt_checklist_groepen cg WHERE cg.id IN ( SELECT cg.id FROM deelplan_checklisten rc JOIN bt_checklisten cl ON rc.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE rc.deelplan_id = ? ) ORDER BY cg.sortering'; if (!$this->dbex->is_prepared( 'deelplan::get_checklistgroepen' )) { $this->dbex->prepare( 'deelplan::get_checklistgroepen', $query ); } $args = func_get_args(); $res = $this->dbex->execute( 'deelplan::get_checklistgroepen', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $CI->checklistgroep->getr( $row ); $res->free_result(); return $result; } function get_checklisten( $deelplan_id ) { $klant = $this->_CI->klant->get_logged_in_klant(); $this->_CI->load->model( 'colectivematrix' ); if (!$this->dbex->is_prepared( 'deelplan::get_checklisten' )) $this->dbex->prepare( 'deelplan::get_checklisten', ' SELECT dcl.*, cl.*, de.dossier_id FROM deelplannen de JOIN deelplan_checklisten dcl ON de.id = dcl.deelplan_id JOIN bt_checklisten cl ON cl.id = dcl.checklist_id WHERE de.id = ?' ); $args = func_get_args(); $res = $this->dbex->execute( 'deelplan::get_checklisten', $args ); $result = array(); foreach ($res->result() as $row){ $row = (object)$row; $result[] = $row; } $res->free_result(); return $result; } // uitsluitend te gebruiken door DeelplanResult::update_content function get_alle_vragen( $deelplan_id, $status_non_null=true ) { $this->_CI->load->model('vraag'); if (!$this->dbex->is_prepared( 'deelplan::get_alle_vragen' )) $this->dbex->prepare( 'deelplan::get_alle_vragen', ' SELECT l.*, rl.status, rl.toelichting, rl.last_updated_at, rl.seconden, rl.flags, rl.hercontrole_datum, rl.hercontrole_start_tijd, rl.hercontrole_eind_tijd, rl.gebruiker_id, rl.bouwnummer FROM deelplannen r JOIN deelplan_vragen rl ON r.id = rl.deelplan_id JOIN bt_vragen l ON rl.vraag_id = l.id WHERE r.id = ? AND ' . ($status_non_null ? 'rl.status IS NOT NULL' : '1=1') . ' ' ); $args = array( $deelplan_id ); $res = $this->dbex->execute( 'deelplan::get_alle_vragen', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $this->_CI->vraag->getr( (array)$row, false ); $res->free_result(); return $result; } private function _get_default_field_sql( $field, $final_field=null, $include_alias = true ) { // Determine which "null function" should be used //$null_func = get_db_null_function(); // The below query is now "Oracle-safe" //return // $null_func.'(v.' . $field . ','.$null_func.'(h.standaard_' . $field . ','.$null_func.'(cl.standaard_' . $field . ',cg.standaard_' . $field . ')))' . // ($final_field ? ' AS ' . $final_field : ''); $partial_statement = 'COALESCE(v.' . $field . ', h.standaard_' . $field . ', cl.standaard_' . $field . ',cg.standaard_' . $field . ')'; if ($include_alias && !is_null($final_field) && !empty($final_field)) { $partial_statement .= ' AS ' . $final_field; } return $partial_statement; } private function _get_waardeoordeel_default_field_sql( $field, $final_field, $include_alias = true ) { $s = $this->_get_default_field_sql( $field, null ); // The below query is now "Oracle-safe" // Oracle requires all sorts of tricks to be able to simulate the MySQL IF construction (trust me, I've cracked away at this for more than a day). // To cut a very long story short, in the end, it turned out one even needed to work with the SUBSTR function, as the LENGTH function returns null for empty strings. // DO NOT REFACTOR UNLESS YOU'RE VERY CERTAIN OF WHAT YOU ARE DOING!!! if (get_db_type() == 'oracle') { $partial_statement = "( CASE LENGTH(SUBSTR({$s},0,1)) WHEN 1 THEN {$s} ELSE NULL END )"; } else { $partial_statement = 'IF(LENGTH(' . $s . ')=0,NULL,' . $s. ')'; } if ($include_alias && !is_null($final_field) && !empty($final_field)) { $partial_statement .= ' AS ' . $final_field; } return $partial_statement; } // The query in this method is now 100% Oracle compatible; this was the most difficult one to crack, so far... private function _get_vragen( $deelplan_id, $select_field, $select_value, $bouwnummer='' ) { if (get_db_type() == 'oracle') { $gebruik_fields = " (CASE WHEN v.gebruik_opdrachten IS NOT NULL THEN 'v' WHEN h.standaard_gebruik_opdrachten IS NOT NULL THEN 'h' WHEN cl.standaard_gebruik_opdrachten IS NOT NULL THEN 'cl' ELSE 'cg' END) as gebruik_opdrachten, (CASE WHEN v.gebruik_verantwtkstn IS NOT NULL THEN 'v' WHEN h.standaard_gebruik_verantwtkstn IS NOT NULL THEN 'h' WHEN cl.standaard_gebruik_verantwtkstn IS NOT NULL THEN 'cl' ELSE 'cg' END) as gebruik_verantwtkstn, (CASE WHEN v.gebruik_grndslgn IS NOT NULL THEN 'v' WHEN h.standaard_gebruik_grndslgn IS NOT NULL THEN 'h' WHEN cl.standaard_gebruik_grndslgn IS NOT NULL THEN 'cl' ELSE 'cg' END) as gebruik_grndslgn, (CASE WHEN v.gebruik_rchtlnn IS NOT NULL THEN 'v' WHEN h.standaard_gebruik_rchtlnn IS NOT NULL THEN 'h' WHEN cl.standaard_gebruik_rchtlnn IS NOT NULL THEN 'cl' ELSE 'cg' END) as gebruik_rchtlnn, (CASE WHEN v.gebruik_ndchtspntn IS NOT NULL THEN 'v' WHEN h.standaard_gebruik_ndchtspntn IS NOT NULL THEN 'h' WHEN cl.standaard_gebruik_ndchtspntn IS NOT NULL THEN 'cl' ELSE 'cg' END) as gebruik_ndchtspntn, "; } else { $gebruik_fields = ' IF(v.gebruik_opdrachten IS NOT NULL,\'v\',IF(h.standaard_gebruik_opdrachten IS NOT NULL,\'h\',IF(cl.standaard_gebruik_opdrachten IS NOT NULL,\'cl\',\'cg\'))) AS gebruik_opdrachten, IF(v.gebruik_verantwtkstn IS NOT NULL,\'v\',IF(h.standaard_gebruik_verantwtkstn IS NOT NULL,\'h\',IF(cl.standaard_gebruik_verantwtkstn IS NOT NULL,\'cl\',\'cg\'))) AS gebruik_verantwtkstn, IF(v.gebruik_grndslgn IS NOT NULL,\'v\',IF(h.standaard_gebruik_grndslgn IS NOT NULL,\'h\',IF(cl.standaard_gebruik_grndslgn IS NOT NULL,\'cl\',\'cg\'))) AS gebruik_grndslgn, IF(v.gebruik_rchtlnn IS NOT NULL,\'v\',IF(h.standaard_gebruik_rchtlnn IS NOT NULL,\'h\',IF(cl.standaard_gebruik_rchtlnn IS NOT NULL,\'cl\',\'cg\'))) AS gebruik_rchtlnn, IF(v.gebruik_ndchtspntn IS NOT NULL,\'v\',IF(h.standaard_gebruik_ndchtspntn IS NOT NULL,\'h\',IF(cl.standaard_gebruik_ndchtspntn IS NOT NULL,\'cl\',\'cg\'))) AS gebruik_ndchtspntn,'; } $stmt_name = 'deelplan::_get_vragen::' . $select_field; // !!! Note (OJG - 21-3-2016): as the query below now takes a variable amount of parameters due to the conditional addition of // bouwnummers, we can no longer rely on the 'is_prepared' check to be correct! Therefore, for now it is commented out and the // query is ALWAYS prepared. Not very good practice! A more efficient way would be to prepare two statements, one with // bouwnummers and one without, and then to call the right one at the right time. //if (!$this->dbex->is_prepared( $stmt_name )) if (1) $this->dbex->prepare( $stmt_name, $q = ' SELECT h.checklist_id AS checklist_id, h.id AS hoofdgroep_id, h.naam AS hoofdgroep_naam, c.id AS categorie_id, c.naam, v.id, v.tekst, v.sortering, v.advies_prioriteit, v.automatische_toel_methode, v.automatische_toel_moment, v.automatische_toel_template, v.email_config, ' . $this->_get_default_field_sql( 'thema_id', 'thema_id' ) . ', ' . $this->_get_default_field_sql( 'vraag_type', 'vraag_type' ) . ', ' . $this->_get_default_field_sql( 'aanwezigheid', 'aanwezigheid' ) . ', ' . $this->_get_default_field_sql( 'toezicht_moment', 'toezicht_moment' ) . ', ' . $this->_get_default_field_sql( 'fase', 'fase' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_00', 'wg00' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_01', 'wg01' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_02', 'wg02' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_03', 'wg03' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_04', 'wg04' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_10', 'wg10' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_11', 'wg11' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_12', 'wg12' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_13', 'wg13' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_20', 'wg20' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_21', 'wg21' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_22', 'wg22' ) . ', ' . $this->_get_default_field_sql( 'wo_in_gebruik_23', 'wg23' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_00', 'wt00' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_01', 'wt01' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_02', 'wt02' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_03', 'wt03' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_04', 'wt04' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_10', 'wt10' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_11', 'wt11' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_12', 'wt12' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_13', 'wt13' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_20', 'wt20' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_21', 'wt21' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_22', 'wt22' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_23', 'wt23' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_00', 'wl00' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_01', 'wl01' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_02', 'wl02' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_03', 'wl03' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_04', 'wl04' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_10', 'wl10' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_11', 'wl11' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_12', 'wl12' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_13', 'wl13' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_20', 'wl20' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_21', 'wl21' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_22', 'wl22' ) . ', ' . $this->_get_default_field_sql( 'wo_is_leeg_23', 'wl23' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_00', 'wk00' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_01', 'wk01' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_02', 'wk02' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_03', 'wk03' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_04', 'wk04' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_10', 'wk10' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_11', 'wk11' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_12', 'wk12' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_13', 'wk13' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_20', 'wk20' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_21', 'wk21' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_22', 'wk22' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_23', 'wk23' ) . ', ' . $this->_get_default_field_sql( 'wo_standaard', 'wstandaard' ) . ', ' . $this->_get_default_field_sql( 'wo_steekproef', 'wsteekproef' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_steekproef_tekst', 'wsteekproeftekst' ) . ', ' . $gebruik_fields . ' t.thema, t.hoofdthema_id, ht.naam AS hoofdthema, rv.status, rv.toelichting, rv.last_updated_at, rv.seconden, rv.flags, rv.hercontrole_datum, rv.hercontrole_start_tijd, rv.hercontrole_eind_tijd, rv.gebruiker_id, rv.bouwnummer, rv.id AS `dlpln_vrg_id`, rv.huidige_toelichting_id AS `huidige_toelichting_id`, r.id AS deelplan_id FROM deelplannen r, deelplan_vragen rv, bt_checklist_groepen cg, bt_checklisten cl, bt_hoofdgroepen h, bt_categorieen c, bt_vragen v, bt_themas t, bt_hoofdthemas ht WHERE r.id = ? AND r.id = rv.deelplan_id AND rv.vraag_id = v.id AND v.categorie_id = c.id AND c.hoofdgroep_id = h.id AND h.checklist_id = cl.id AND cl.checklist_groep_id = cg.id AND '. $select_field . ' = ? AND '. '(' . $this->_get_default_field_sql('thema_id') . ' IS NULL OR ' . $this->_get_default_field_sql('thema_id') . ' = t.id) AND t.hoofdthema_id = ht.id '. ($bouwnummer == '' ? '' : 'AND rv.bouwnummer = ? '). 'ORDER BY h.checklist_id, h.sortering, c.sortering, v.sortering' ); $args = $bouwnummer != '' ? array( $deelplan_id, $select_value,$bouwnummer ) : array( $deelplan_id , $select_value ); $res = $this->dbex->execute( $stmt_name, $args ); $result = array(); foreach ($res->result_array() as $row) { $rrow = $this->_CI->vraag->getr( $row, false ); $result[] = $rrow; } $res->free_result(); return $result; } function get_checklistgroep_vragen( $deelplan_id, $checklist_groep_id ) { return $this->_get_vragen( $deelplan_id, 'cg.id', $checklist_groep_id ); } function get_checklist_vragen( $deelplan_id, $checklist_id, $bouwnummer='' ) { return $this->_get_vragen( $deelplan_id, 'cl.id', $checklist_id, $bouwnummer ); } function delete_checklisten( $deelplan_id ) { if (!$this->dbex->is_prepared( 'deelplan::delete_checklisten' )) $this->dbex->prepare( 'deelplan::delete_checklisten', 'DELETE FROM deelplan_checklisten WHERE deelplan_id = ?' ); $args = func_get_args(); $this->dbex->execute( 'deelplan::delete_checklisten', $args ); } function delete_vragen( $deelplan_id ) { if (!$this->dbex->is_prepared( 'deelplan::delete_vragen' )) $this->dbex->prepare( 'deelplan::delete_vragen', 'DELETE FROM deelplan_vragen WHERE deelplan_id = ?' ); $args = func_get_args(); $this->dbex->execute( 'deelplan::delete_vragen', $args ); } function add_checklistgroep( $deelplan_id, $checklist_groep_id, $bg_go, $bg_vg ) { if (!$this->dbex->is_prepared( 'deelplan::add_checklistgroepen' )) $this->dbex->prepare( 'deelplan::add_checklistgroepen', 'INSERT INTO deelplan_checklistgroepen (deelplan_id, checklist_groep_id, bezgraad_gebruiksoppervlakte, bezgraad_verblijfsgebied) VALUES (?, ?, ?, ?)' ); $args = func_get_args(); $this->dbex->execute( 'deelplan::add_checklistgroepen', $args ); } function add_checklist( $deelplan_id, $checklist_groep_id, $checklist_id ) { if (!$this->dbex->is_prepared( 'deelplan::add_checklisten' )) $this->dbex->prepare( 'deelplan::add_checklisten', 'INSERT INTO deelplan_checklisten (deelplan_id, checklist_groep_id, checklist_id) VALUES (?, ?, ?)' ); $args = func_get_args(); $this->dbex->execute( 'deelplan::add_checklisten', $args ); } function update_checklistgroep( $deelplan_id, $checklist_groep_id, $bg_go, $bg_vg ) { if (!$this->dbex->is_prepared( 'deelplan::update_checklistgroep' )) $this->dbex->prepare( 'deelplan::update_checklistgroep', 'UPDATE deelplan_checklistgroepen SET bezgraad_verblijfsgebied = ?, bezgraad_gebruiksoppervlakte = ? WHERE checklist_groep_id = ? AND deelplan_id = ?' ); $args = array_reverse( func_get_args() ); $this->dbex->execute( 'deelplan::update_checklistgroep', $args ); } private function _sorted_vragen_array( $str ) { if (is_null($str)) return null; $arr = explode( ',', $str ); sort( $arr ); $s = implode( ',', $arr ); return $s; } // NOTE (OJG - 2014-07-17): this method is a.o. used from the soapdossier SOAP webservice, which is run without being logged in. For this reason, the optional // parameter $override_logged_in_user_id was added. // Do NOT remove this, or the webservice WILL break!!! function add_vragen( $id, array $vragen, $oldVragen, $override_logged_in_user_id = null ) { if (!is_array($vragen) || sizeof($vragen)==0) return; $CI = get_instance(); $CI->load->model( 'vraag' ); // Oracle uses a different syntax for multiple row inserts than MySQL does, so accomodate for that. if (get_db_type() == 'oracle') { $query = 'INSERT ALL'; } else { $toelichting_id = time(); $query = 'INSERT INTO deelplan_vragen (deelplan_id, vraag_id, status, toelichting, last_updated_at, seconden, flags, hercontrole_datum, gebruiker_id,bouwnummer,huidige_toelichting_id) VALUES '; $query .= str_repeat( "(?,?,?,?,?,?,?,?,?,?,'$toelichting_id'),", sizeof($vragen) ); $query = substr($query, 0, strlen($query)-1 ); } $data = array(); $steekproef_vragen = array(); foreach ($vragen as $vraag_data) { $vraag_id = $vraag_data->id; $data[] = $id; $data[] = $vraag_id; $isset_old_vraag = FALSE; foreach($oldVragen as $old_vraag ) if( $isset_old_vraag = ($old_vraag->id == $vraag_id && $old_vraag->bouwnummer == $vraag_data->bouwnummer) ) break; if( $isset_old_vraag ) { // vraag was al eerder gekoppeld, neem nu dus data over van bestaande status/antwoord data $data[] = $old_vraag->status; $data[] = $old_vraag->toelichting; $data[] = $old_vraag->last_updated_at; $data[] = $old_vraag->seconden; $data[] = $old_vraag->flags; $data[] = $old_vraag->hercontrole_datum; $data[] = $old_vraag->gebruiker_id; $data[] = $old_vraag->bouwnummer; // Use the Oracle-specific version for the last_updated_at column, without manipulating the existing value if (get_db_type() == 'oracle') { // !!! TODO: Check the correctness of the way the last_updated_at field is filled and set using a direct value. // Will this go right or do we then always lose the time information?!? // Possibly we need to force the value of $cur_status[ $vraag_id ]->last_updated_at to a know format, and use that with the TO_DATE function. $query .= ' INTO deelplan_vragen (deelplan_id, vraag_id, status, toelichting, last_updated_at, seconden, flags, hercontrole_datum, gebruiker_id,bouwnummer) VALUES (?,?,?,?,?,?,?,?,?,?)'; } } else { // vraag is nieuw binnen dit deelplan! dus nieuw gekoppelde checklist! $vraag = $CI->vraag->get( $vraag_id ); $standaard = $vraag->get_standaard_antwoord(); if ($standaard->is_leeg) $data[] = null; // standaard waarde telt niet mee, dus ook niks zetten else $data[] = $standaard->status; if ($vraag_data->automatische_toel_moment=='bij aanmaken') { if (!($vraag_obj = $CI->vraag->get( $vraag_id ))) throw new Exception( 'Ongeldig vraag ID ' . $vraag_id ); $data[] = $vraag_obj->expand_automatische_toel_template( $id ); } else $data[] = null; // Use the Oracle-specific version for the last_updated_at column, without manipulating the existing value if (get_db_type() == 'oracle') { // Add the SYSDATE value as a direct value, do NOT add anything to the 'data' array for this column! $query .= ' INTO deelplan_vragen (deelplan_id, vraag_id, status, toelichting, last_updated_at, seconden, flags, hercontrole_datum, gebruiker_id,bouwnummer) VALUES (?,?,?,?,SYSDATE,?,?,?,?,?)'; } else { // MySQL, add a null value for the last_updated_at column $data[] = null; } $data[] = 0; $data[] = 0; $data[] = null; // NOTE (OJG - 2014-07-17): this method is a.o. used from the soapdossier SOAP webservice, which is run without being logged in. For this reason, the optional // parameter $override_logged_in_user_id was added and should be used down below for properly setting a user ID. // Do NOT remove this, or the webservice WILL break (it will then result in a foreign key DB error, as the login->get_user_id() call would return -1)!!! $data[] = (!is_null($override_logged_in_user_id)) ? $override_logged_in_user_id : $this->login->get_user_id(); $data[] = $vraag_data->bouwnummer; } } // Oracle uses a different syntax for multiple row inserts than MySQL does, so accomodate for that. if (get_db_type() == 'oracle') { $query .= ' SELECT * FROM dual'; } $this->dbex->prepare( 'deelplan::add_deelplan_vragen', $query ) or die('prepare error'); $this->dbex->execute( 'deelplan::add_deelplan_vragen', $data ) or die('execute error'); } function find_gelinkte_vragen( $id ) { if (!$this->dbex->is_prepared( 'deelplan::find_gelinkte_vragen' )) $this->dbex->prepare( 'deelplan::find_gelinkte_vragen', 'SELECT v.id, v.automatische_toel_moment, v.automatische_toel_template, v.automatische_toel_methode, rc.bouwnummer,v.tekst AS `naam`'. // ',cl.id AS checklist_id '. 'FROM deelplan_checklisten rc JOIN bt_checklisten cl ON rc.checklist_id = cl.id JOIN bt_hoofdgroepen h ON cl.id = h.checklist_id JOIN bt_categorieen c ON h.id = c.hoofdgroep_id JOIN bt_vragen v ON c.id = v.categorie_id WHERE rc.deelplan_id = ? ' ); $args = func_get_args(); $res = $this->dbex->execute( 'deelplan::find_gelinkte_vragen', $args ); $result = array(); foreach ($res->result() as $row) // $result[$row->id] = $row; $result[] = $row; $res->free_result(); return $result; } function update_status( $id, $vraag_id, $status, $toelichting_tekst, $seconden, $hercontrole_datum, $flags, $new_toelichting_id, $bouwnummer='') { // This block is used to update toelichting for multiplay users. $this->_CI->load->model('deelplanvraaggeschiedenis'); $geschieden = $this->deelplanvraaggeschiedenis->search( array( 'deelplan_id' => $id, 'vraag_id' => $vraag_id, 'toelichting_id' => $new_toelichting_id, 'bouwnummer' => $bouwnummer, ) ); if( count($geschieden) > 0 ){ $geschieden = $geschieden[0]; $geschieden->toelichting = $toelichting_tekst; $geschieden->status = $status; $geschieden->save(); return; } $parts = @explode( '|', $hercontrole_datum ); $datum = @$parts[0]; $start_tijd = @$parts[1]; $eind_tijd = @$parts[2]; $args = array( $status, $toelichting_tekst, $seconden, $this->login->get_user_id(), $datum ? date('Y-m-d', strtotime( $datum ) ) : null, $start_tijd ? $start_tijd : null, $eind_tijd ? $eind_tijd : null, $flags, $new_toelichting_id, $id, $vraag_id ); if( $bouwnummer != '' ){ $bw_clause = 'AND bouwnummer = ? '; $args[] = $bouwnummer; }else{ $bw_clause = ''; } // The below query is now "Oracle-safe" if (!$this->dbex->is_prepared( 'deelplan::update_status' )) $this->dbex->prepare( 'deelplan::update_status', 'UPDATE deelplan_vragen SET '. 'status = ?, '. 'toelichting = ?, '. 'seconden = ?, '. 'gebruiker_id = ?, '. 'hercontrole_datum = '.get_db_prepared_parameter_for_date().', '. 'last_updated_at = '.get_db_now_function().' , '. 'hercontrole_start_tijd = ?, '. 'hercontrole_eind_tijd = ?, '. 'flags = ?, '. 'huidige_toelichting_id=? '. 'WHERE deelplan_id = ? AND vraag_id = ? '.$bw_clause ); $this->dbex->execute( 'deelplan::update_status', $args ); } function get_checklists( $id ) { $query = ' SELECT DISTINCT(checklist_id) AS checklist_id FROM deelplan_checklisten WHERE deelplan_id = ? '; if (!$this->dbex->is_prepared( 'deelplan::deelplan_get_checklists' )) $this->dbex->prepare( 'deelplan::deelplan_get_checklists', $query ); $res = $this->dbex->execute( 'deelplan::deelplan_get_checklists', array( $id ) ); $result = array(); foreach ($res->result() as $row) $result[] = $row->checklist_id; $res->free_result(); return $result; } function get_grondslagen( $id, $checklist_groep_id ) { $query = ' SELECT bl.id AS vraag_id, g.grondslag, gt.artikel, gt.tekst, lg.id AS vraaggrondslag_id, lg.grondslag_tekst_id FROM deelplan_vragen rl JOIN bt_vragen bl ON rl.vraag_id = bl.id JOIN bt_vraag_grndslgn lg ON bl.id = lg.vraag_id JOIN bt_grondslag_teksten gt ON lg.grondslag_tekst_id = gt.id JOIN bt_grondslagen g ON gt.grondslag_id = g.id JOIN bt_categorieen c ON bl.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id WHERE 1=1 AND rl.deelplan_id = ? AND cl.checklist_groep_id = ? '; $this->dbex->prepare( 'deelplan_get_grondslagen', $query ); $res = $this->dbex->execute( 'deelplan_get_grondslagen', array( $id, $checklist_groep_id ) ); $result = array(); foreach ($res->result() as $row) { if (!isset( $result[$row->vraag_id] )) $result[$row->vraag_id] = array(); $result[$row->vraag_id][] = $row; } $res->free_result(); return $result; } function get_distinct_grondslagen( $id, $checklist_groep_id ) { $result = array(); foreach ($this->get_grondslagen( $id, $checklist_groep_id ) as $vraag_grondslagen) foreach ($vraag_grondslagen as $grondslag) $result[ $grondslag->grondslag ] = $grondslag->grondslag; return array_values( $result ); } function get_richtlijnen( $id, $checklist_groep_id ) { $query = ' SELECT bl.id AS vraag_id, r.filename, r.id AS richtlijn_id FROM deelplan_vragen rl JOIN bt_vragen bl ON rl.vraag_id = bl.id JOIN bt_vraag_rchtlnn lr ON bl.id = lr.vraag_id JOIN bt_richtlijnen r ON lr.richtlijn_id = r.id JOIN bt_categorieen c ON bl.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id WHERE 1=1 AND rl.deelplan_id = ? AND cl.checklist_groep_id = ? '; $this->dbex->prepare( 'deelplan_get_richtlijnen', $query ); $res = $this->dbex->execute( 'deelplan_get_richtlijnen', array( $id, $checklist_groep_id ) ); $result = array(); foreach ($res->result() as $row) { if (!isset( $result[$row->vraag_id] )) $result[$row->vraag_id] = array(); $result[$row->vraag_id][] = $row; } $res->free_result(); return $result; } function get_subjecten( $id ) { $CI = get_instance(); $CI->load->model( 'dossiersubject' ); $result = array(); foreach ($CI->dossiersubject->search( array( 'deelplannen.id' => $id ), null, false, 'AND', '', 'JOIN deelplannen ON deelplannen.dossier_id = T1.dossier_id' ) as $deelplansubject) { $result[] = $CI->dossiersubject->get( $deelplansubject->id ); } return $result; } function filter_vragen( $deelplan_id, array $vragen, &$prioriteiten=null, &$onafgeronde_checklisten=null ) { $CI = get_instance(); $CI->load->model( 'deelplanthema' ); $CI->load->model( 'deelplanchecklistgroep' ); $CI->load->model( 'steekproef' ); $CI->load->model( 'matrix' ); $CI->load->library( 'prioriteitstelling' ); // // filter by themas // $alleen_themas = $CI->deelplanthema->get_by_deelplan( $deelplan_id ); // first, filter all vragen by thema id foreach ($vragen as $index => $vraag) { if (!is_null( $vraag->thema_id ) && !isset( $alleen_themas[ $vraag->thema_id ] )) { unset( $vragen[$index] ); } } // // then, filter the ones that $cur_hoofdgroep_id = NULL; $num_vragen = 0; $vragen_aandachtspunt = array(); foreach ($vragen as $index => $vraag) { if ($vraag->hoofdgroep_id != $cur_hoofdgroep_id) { // cleanup all previously seen vragen if they were ONLY aandachtspunten if ($num_vragen == sizeof($vragen_aandachtspunt)) { foreach ($vragen_aandachtspunt as $i) unset( $vragen[$i] ); } // reset $cur_hoofdgroep_id = $vraag->hoofdgroep_id; $num_vragen = 0; $vragen_aandachtspunt = array(); } $num_vragen++; } // do for last if ($num_vragen == sizeof($vragen_aandachtspunt)) { foreach ($vragen_aandachtspunt as $i) unset( $vragen[$i] ); } $vragen = array_values( $vragen ); // // laadt toezichthouders + matrix info // $toezichthouders = $CI->deelplanchecklistgroep->get_by_deelplan( $deelplan_id ); // // process vragen info, remove vragen that are not required or visible // $prioriteiten = array(); $prio_to_value = array( 'nvt'=>-1, 'zeer_laag'=>1, 'laag'=>2, 'gemiddeld'=>3, 'hoog'=>4, 'zeer_hoog'=>5 ); $gevulde_hoofdgroepen = array(); $grondslagen = array(); $richtlijnen = array(); $checklisten = array(); $onafgeronde_checklisten = false; foreach ($vragen as $i => $vraag) { $checklist = $vraag->checklist_id; if (!isset( $checklisten[$checklist] )) { $checklisten[$checklist] = $CI->checklist->get( $checklist ); } if (!isset( $prioriteiten[$checklist] )) { $checklist_groep_id = $checklisten[$checklist]->checklist_groep_id; if (!isset( $toezichthouders[$checklist_groep_id] ) || !$toezichthouders[$checklist_groep_id]->matrix_id) { $toezichthouders[$checklist_groep_id]->matrix_id = $CI->matrix->geef_standaard_matrix_voor_checklist_groep( $CI->checklistgroep->get( $checklist_groep_id ) )->id; } $prioriteiten[$checklist] = $CI->prioriteitstelling->lookup_or_create( $toezichthouders[$checklist_groep_id]->matrix_id, $checklist ); } $prioriteit = $prioriteiten[$checklist]; $vraag->prio = $prioriteit->get_waarde( $vraag->hoofdgroep_id, $vraag->hoofdthema_id ); if (!$vraag->prio) $vraag->prio = 'zeer_hoog'; $vraag->priomode = $prio_to_value[$vraag->prio]; if (!$vraag->toon_adhv_priomode( $vraag->priomode )) { if (!$checklisten[$checklist]->is_afgerond()) $onafgeronde_checklisten = true; unset( $vragen[$i] ); continue; } if ($vraag->is_toetsbaar()) $gevulde_hoofdgroepen[$vraag->hoofdgroep_id] = true; } unset( $checklist ); foreach ($vragen as $i => $vraag) { if (!isset( $gevulde_hoofdgroepen[$vraag->hoofdgroep_id] )) unset( $vragen[$i] ); } // // see if we need to process "steekproeven" here // $inited = false; $klant = null; foreach ($vragen as $vraag) { if ($vraag->prio == 'zeer_laag' && !($vraag->flags & VRAAG_FLAGS_STEEKPROEF_VERWERKT)) { if (!$klant) $klant = $CI->klant->get_logged_in_klant(); $aantal = $CI->steekproef->increase( $vraag->id ); $vraag->flags |= VRAAG_FLAGS_STEEKPROEF_VERWERKT; if ( ($aantal % $klant->steekproef_interval) != 0 ) // 1 op de X moet status NULL blijven, zodat toezichthouder moet antwoorden, anders standaard zetten op "steekproef" waarde $vraag->status = $vraag->get_wizard_veld_recursief( 'wo_steekproef' ); if (!$inited) { $stmt_name = 'deelplan-vraag-update-flags'; $CI->dbex->prepare( $stmt_name, 'UPDATE deelplan_vragen SET flags = ?, status = ? WHERE deelplan_id = ? AND vraag_id = ?' ); $inited = true; } if (!$CI->dbex->execute( $stmt_name, array( $vraag->flags, $vraag->status, $vraag->deelplan_id, $vraag->id ) )) throw new Exception( 'Fout bij opslaan steekproef data.' ); } } $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); if($klant->vragen_alleen_voor_betrokkenen_tonen==1 && (($this->gebruiker->get_logged_in_gebruiker()->rol_id!=9) && $this->gebruiker->get_logged_in_gebruiker()->rol_id!=3 && $this->gebruiker->get_logged_in_gebruiker()->rol_id!=1)){ $CI->load->model("deelplansubjectvraag"); $login_gebruiker_id = $this->gebruiker->get_logged_in_gebruiker()->id; foreach ($vragen as $i => $vraag){ $vraag_access=false; $data=$CI->deelplansubjectvraag->get_gebruker_sbj_id_by_deelplan_and_vraag($deelplan_id, $vraag->id); foreach ($data as $subject_value){ if ($subject_value->gebruiker_id==$login_gebruiker_id || !$subject_value->gebruiker_id){ $vraag_access=true; } } if(!$data) $vraag_access=true; else if($vraag_access===false){ unset($vragen[$i]); } } } return $vragen; } // (OJG: 2014-07-30): added an optional parameter 'full data' so as to be able to obtain all data that the webservice version needs. function get_hercontrole_data( $deelplan_id, $checklist_groep_id, $gebruiker_id, $alleen_in_toekomst=true, $checklist_id=null, $get_full_data = false ) { $CI = get_instance(); // Determine which "null function" should be used $null_func = get_db_null_function(); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // The below query is now "Oracle-safe". Note that the Oracle implementation requires the concatenated string in the 'GROUP BY' clause! $concatenated_field = get_db_concat_string(array('dv.hercontrole_datum', "'|'", "COALESCE(dv.hercontrole_start_tijd,'')", "'|'", "COALESCE(dv.hercontrole_eind_tijd,'')")); if ($get_full_data) { $select_fields = "dv.vraag_id, dv.hercontrole_datum, COALESCE(dv.hercontrole_start_tijd,'') AS hercontrole_start_tijd, COALESCE(dv.hercontrole_eind_tijd,'') AS hercontrole_eind_tijd, dv.gebruiker_id, dcl.voortgang_percentage"; //$select_fields = "dv.vraag_id, dv.hercontrole_datum, COALESCE(dv.hercontrole_start_tijd,'') AS hercontrole_start_tijd, // COALESCE(dv.hercontrole_eind_tijd,'') AS hercontrole_eind_tijd, dv.gebruiker_id, 25 AS voortgang_percentage"; $additional_joins = " JOIN deelplan_checklisten dcl ON ((h.checklist_id = dcl.checklist_id) AND (dv.deelplan_id = dcl.deelplan_id) ) "; $stmt_name = 'deelplan::get_hercontrole_data_full'; } else { $select_fields = $concatenated_field . ' AS hercontrole_datum'; $additional_joins = ''; $stmt_name = 'deelplan::get_hercontrole_data_simple'; } if (!$CI->dbex->prepare( $stmt_name, $q= ' SELECT '.$select_fields.' FROM deelplan_vragen dv JOIN bt_vragen v ON dv.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id '. $additional_joins . 'WHERE dv.deelplan_id = ? ' . ($checklist_groep_id ? 'AND cl.checklist_groep_id = ' . intval($checklist_groep_id) : '') . ' ' . ($checklist_id ? 'AND cl.id = ' . intval($checklist_id) : '' ) . ' ' . ($gebruiker_id ? 'AND dv.gebruiker_id = ' . intval($gebruiker_id) : '' ) . ' AND dv.hercontrole_datum IS NOT NULL AND ('.($alleen_in_toekomst ? '0=1' : '1=1').' OR dv.hercontrole_datum >= '.$now_func.') GROUP BY '.$concatenated_field.', dv.hercontrole_datum ORDER BY dv.hercontrole_datum ' )) throw new Exception( 'Fout bij ophalen van hercontrole data in deelplan (1).' ); if (!($res = $CI->dbex->execute( $stmt_name, array( $deelplan_id ) ))) throw new Exception( 'Fout bij ophalen van hercontrole data in deelplan (2).' ); $result = array(); foreach ($res->result() as $row) { // In 'simple' mode we only extract the concatenated strings, but in 'full' mode, we also extract the additionally retreived fields. if ($get_full_data) { $composite_result = array(); $composite_result['vraag_id'] = $row->vraag_id; $composite_result['hercontrole_datum'] = $row->hercontrole_datum; $composite_result['hercontrole_start_tijd'] = $row->hercontrole_start_tijd; $composite_result['hercontrole_eind_tijd'] = $row->hercontrole_eind_tijd; $composite_result['gebruiker_id'] = $row->gebruiker_id; $composite_result['voortgang_percentage'] = $row->voortgang_percentage; $result[] = $composite_result; } else { $result[] = $row->hercontrole_datum; } } $res->free_result(); return $result; } public function laad_aandachtspunten( $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { return $this->_laad_achtergrond_informatie( 'aandachtspunten', 'aandachtspunt', '', $checklist_groep_id, $checklist_id, $deelplan_id ); } public function laad_richtlijnen( $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { return $this->_laad_achtergrond_informatie( 'richtlijnen', 'r.id AS richtlijn_id, r.filename, r.url, r.url_beschrijving', 'JOIN bt_richtlijnen r ON r.id = %s.richtlijn_id', $checklist_groep_id, $checklist_id, $deelplan_id ); } public function laad_grondslagen( $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { return $this->_laad_achtergrond_informatie( 'grondslagen', 'g.grondslag, gt.display_hoofdstuk, gt.display_afdeling, gt.display_paragraaf, gt.display_artikel, gt.display_lid, gt.artikel, gt.id AS grondslag_tekst_id', 'JOIN bt_grondslag_teksten gt ON gt.id = %s.grondslag_tekst_id JOIN bt_grondslagen g ON gt.grondslag_id = g.id', $checklist_groep_id, $checklist_id, $deelplan_id ); } public function laad_opdrachten( $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { return $this->_laad_achtergrond_informatie( 'opdrachten', 'opdracht', '', $checklist_groep_id, $checklist_id, $deelplan_id ); } public function laad_verantwoordingsteksten( $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { return $this->_laad_achtergrond_informatie( 'verantwoordingsteksten', 'verantwoordingstekst, %s.status', '', $checklist_groep_id, $checklist_id, $deelplan_id ); } public function _laad_achtergrond_informatie( $type, $veld, $join, $checklist_groep_id, $checklist_id=null, $deelplan_id=null ) { $type_short_hand_mapping = array( 'aandachtspunten' => 'ndchtspntn', 'grondslagen' => 'grndslgn', 'richtlijnen' => 'rchtlnn', 'verantwoordingsteksten' => 'verantwtkstn', ); $cg_type = (array_key_exists($type, $type_short_hand_mapping)) ? $type_short_hand_mapping[$type] : $type; $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $is_automatic_accountability_text= $klant->automatic_accountability_text==1; $automatic_accountability_text_subquery='UNION ALL SELECT NULL, NULL, NULL, v.id, vva.verantwoordingstekst, NULL, vva.automatic, avc.name, vva.automatish_generate FROM bt_vragen v JOIN bt_vraag_verantwtkstn_automatic vva ON v.id = vva.vraag_id LEFT JOIN verantwoordingstekst_config AS avc ON vva.id=avc.vraag_verantwtkstn_id WHERE vva.checklist_groep_id = ' . intval($checklist_groep_id) . ' ' . ($checklist_id ? 'AND vva.checklist_id = ' . intval($checklist_id) : '') . ' ' . ($deelplan_id ? 'AND v.id IN (SELECT vraag_id FROM deelplan_vragen WHERE deelplan_id = ' . intval($deelplan_id) . ')' : ''); // The below query is now "Oracle-safe" $q = ' SELECT cg.id AS checklist_groep_id, NULL AS checklist_id, NULL AS hoofdgroep_id, NULL AS vraag_id, ' . str_replace('%s', 'cga', $veld) . ' , NULL AS type, NULL as button_name, NULL AS automatish_generate FROM bt_checklist_groepen cg JOIN bt_checklist_groep_' . $cg_type . ' cga ON cg.id = cga.checklist_groep_id ' . sprintf($join, 'cga') . ' WHERE cg.id = ' . intval($checklist_groep_id) . ' UNION ALL SELECT NULL, cl.id, NULL, NULL, ' . str_replace('%s', 'cla', $veld) . ', NULL, NULL, NULL FROM bt_checklisten cl JOIN bt_checklist_' . $cg_type . ' cla ON cl.id = cla.checklist_id ' . sprintf($join, 'cla') . ' WHERE cla.checklist_groep_id = ' . intval($checklist_groep_id) . ' ' . ($checklist_id ? 'AND cl.id = ' . intval($checklist_id) : '') . ' UNION ALL SELECT NULL, NULL, h.id, NULL, ' . str_replace('%s', 'ha', $veld) . ', NULL, NULL, NULL FROM bt_hoofdgroepen h JOIN bt_hoofdgroep_' . $cg_type . ' ha ON h.id = ha.hoofdgroep_id ' . sprintf($join, 'ha') . ' WHERE ha.checklist_groep_id = ' . intval($checklist_groep_id) . ' ' . ($checklist_id ? 'AND h.checklist_id = ' . intval($checklist_id) : '') . ' '.($is_automatic_accountability_text && $cg_type=="verantwtkstn" ? $automatic_accountability_text_subquery :"").' UNION ALL SELECT NULL, NULL, NULL, v.id, ' . str_replace('%s', 'va', $veld) . ', NULL, NULL, NULL FROM bt_vragen v JOIN bt_vraag_' . $cg_type . ' va ON v.id = va.vraag_id ' . sprintf($join, 'va' ) .' WHERE va.checklist_groep_id = ' . intval($checklist_groep_id) . ' ' . ($checklist_id ? 'AND va.checklist_id = ' . intval($checklist_id) : '') . ' ' . ($deelplan_id ? 'AND v.id IN (SELECT vraag_id FROM deelplan_vragen WHERE deelplan_id = ' . intval($deelplan_id) . ')' : '') ; // Note: the query itself featured a semicolon! This is not allowed in Oracle. Does MySQL perhaps require this ?!? // ' . ($deelplan_id ? 'AND v.id IN (SELECT vraag_id FROM deelplan_vragen WHERE deelplan_id = ' . intval($deelplan_id) . ')' : '') . ' // ; $CI = get_instance(); $res = $CI->db->query( $q ); if (!$res) throw new Exception( 'Fout bij ophalen ' . $type . ': ' . $q ); $result = $res->result(); $res->free_result(); return $result; } // !!! The query in this method is now 100% Oracle compatible; this was the most difficult one to crack, so far... function get_mogelijke_waardeoordelen( $deelplan_id ) { $mw = new MogelijkeWaardeoordelen(); if (get_db_type() == 'oracle') { // Very "handily", Oracle FIRST evaluates the GROUP BY part, before the SELECT fields, and hence doesn't 'know' the aliases that are generated in the SELECT // part. This results in a necessary (clumsy and costly!) repetition of the EXACT select logic for the respective fields/aliases in the GROUP BY clause. // Really nasty. It makes for potentially VERY long GROUP BY clauses, as the below query handsomely demonstrates. :( $group_by_fields = $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_00', 'wt00', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_01', 'wt01', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_02', 'wt02', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_03', 'wt03', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_04', 'wt04', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_10', 'wt10', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_11', 'wt11', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_12', 'wt12', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_13', 'wt13', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_20', 'wt20', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_21', 'wt21', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_22', 'wt22', false ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_23', 'wt23', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_00', 'wk00', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_01', 'wk01', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_02', 'wk02', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_03', 'wk03', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_04', 'wk04', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_10', 'wk10', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_11', 'wk11', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_12', 'wk12', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_13', 'wk13', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_20', 'wk20', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_21', 'wk21', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_22', 'wk22', false ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_23', 'wk23', false ) . ', ' . $this->_get_default_field_sql( 'vraag_type', 'vraag_type_c', false ); } else { // What a relief! MySQL at least is smart enough to simply allow the SELECT aliases! :) $group_by_fields = 'wt00, wt01, wt02, wt03, wt04, wt10, wt11, wt12, wt13, wt20, wt21, wt22, wt23, wk00, wk01, wk02, wk03, wk04, wk10, wk11, wk12, wk13, wk20, wk21, wk22, wk23, vraag_type_c'; } // Now construct the mpther of all queries... $res = $this->_CI->db->query($q = ' SELECT ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_00', 'wt00' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_01', 'wt01' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_02', 'wt02' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_03', 'wt03' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_04', 'wt04' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_10', 'wt10' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_11', 'wt11' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_12', 'wt12' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_13', 'wt13' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_20', 'wt20' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_21', 'wt21' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_22', 'wt22' ) . ', ' . $this->_get_waardeoordeel_default_field_sql( 'wo_tekst_23', 'wt23' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_00', 'wk00' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_01', 'wk01' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_02', 'wk02' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_03', 'wk03' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_04', 'wk04' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_10', 'wk10' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_11', 'wk11' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_12', 'wk12' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_13', 'wk13' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_20', 'wk20' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_21', 'wk21' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_22', 'wk22' ) . ', ' . $this->_get_default_field_sql( 'wo_kleur_23', 'wk23' ) . ', ' . $this->_get_default_field_sql( 'vraag_type', 'vraag_type_c' ) . ' FROM bt_vragen v JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id JOIN deelplan_vragen dv ON dv.vraag_id = v.id WHERE dv.deelplan_id = ' . intval($deelplan_id) . ' GROUP BY ' . $group_by_fields ); // -- only get each unique combination once // NOTE: Previously the 'vraag_type' alias caused some clashes with the (bt_vragen) 'vraag_type' column, causing to sometimes miss // 'coalesced' question types that traversed upwards and should have been able to work out a proper question type by their checklist // or checklistgroup settings!!!! For this reason, the 'vraag_type' alias has been renamed to 'vraag_type_c'! //echo $q; if (!$res) throw new Exception( 'Fout bij bepalen mogelijke waardeoordelen: ' . $q ); foreach ($res->result() as $row) { if ($row->vraag_type_c == 'invulvraag') $mw->zet_heeft_invulvraag(); else { for ($x=0; $x<3; ++$x) { for ($y=0; $y<5; ++$y) { if (isset( $row->{'wt'.$x.$y} )) { $waardeoordeel = $row->{'wt'.$x.$y}; $kleur = $row->{'wk'.$x.$y}; $mw->add_waardeoordeel( $kleur, $waardeoordeel ); } } } } } return $mw; } } class AandachtspuntEntry { public function __construct( $aandachtspunt, $titel, $cg_id, $cl_id, $h_id, $v_id, $soort ) { if ($cg_id) $this->checklist_groep_id = $cg_id; if ($cl_id) $this->checklist_id = $cl_id; if ($h_id) $this->hoofdgroep_id = $h_id; if ($v_id) $this->vraag_id = $v_id; $this->aandachtspunt = $aandachtspunt; $this->titel = $titel; $this->soort = $soort; if (!in_array( $this->soort, array( 'altijd', 'voorwaardelijk' ))) throw new Exception( 'Ongeldig aandachtspuntsoort: ' . $this->soort ); } } class RichtlijnEntry { public $checklist_groep_id; public $checklist_id; public $hoofdgroep_id; public $vraag_id; public $richtlijn_id, $filename, $url, $url_beschrijving; public function __construct( $richtlijn_id, $filename, $url, $url_beschrijving, $cg_id, $cl_id, $h_id, $v_id ) { if ($cg_id) $this->checklist_groep_id = $cg_id; if ($cl_id) $this->checklist_id = $cl_id; if ($h_id) $this->hoofdgroep_id = $h_id; if ($v_id) $this->vraag_id = $v_id; $this->richtlijn_id = $richtlijn_id; $this->filename = $filename; $this->url = $url; $this->url_beschrijving = $url_beschrijving; } } class GrondslagEntry { public function __construct( $grondslag_tekst_id, $grondslag, $display_hoofdstuk, $display_afdeling, $display_paragraaf, $display_artikel, $display_lid, $artikel, $cg_id, $cl_id, $h_id, $v_id ) { if ($cg_id) $this->checklist_groep_id = $cg_id; if ($cl_id) $this->checklist_id = $cl_id; if ($h_id) $this->hoofdgroep_id = $h_id; if ($v_id) $this->vraag_id = $v_id; $this->grondslag_tekst_id = $grondslag_tekst_id; $this->grondslag = $grondslag; $this->display_hoofdstuk = $display_hoofdstuk; $this->display_afdeling = $display_afdeling; $this->display_paragraaf = $display_paragraaf; $this->display_artikel = $display_artikel; $this->display_lid = $display_lid; $this->artikel = $artikel; } } class OpdrachtEntry { public function __construct( $opdracht, $cg_id, $cl_id, $h_id, $v_id ) { if ($cg_id) $this->checklist_groep_id = $cg_id; if ($cl_id) $this->checklist_id = $cl_id; if ($h_id) $this->hoofdgroep_id = $h_id; if ($v_id) $this->vraag_id = $v_id; $this->opdracht = $opdracht; } } class MogelijkeWaardeoordelen { private $_heeft_invulvraag = false; private $_kleuren = array(); public function add_waardeoordeel( $kleur, $waardeoordeel ) { if (!isset( $this->_kleuren[$kleur] )) $this->_kleuren[$kleur] = array(); if (!in_array( $waardeoordeel, $this->_kleuren[$kleur] )) $this->_kleuren[$kleur][] = $waardeoordeel; } public function get_waardeoordelen() { return $this->_kleuren; } public function zet_heeft_invulvraag( $v=true ) { $this->_heeft_invulvraag = $v; } public function get_heeft_invulvraag() { return $this->_heeft_invulvraag; } } abstract class OnderwerpenSplitter { // data to fill protected $onderwerpen = array(); protected $selected_vraag = null; protected $hoofdgroep_prioriteiten = array(); protected $hoofdgroep_prioriteiten_origineel = array(); // data to do it with protected $deelplan; // DeelplanResult object protected $vragen; // array of VraagResult++ objects protected $prioriteiten; // checklist -> prioriteitstelling array protected $CI; // misc protected $has_run = false; public function __construct( DeelplanResult $deelplan, array $vragen, array $prioriteiten ) { // $this->load->model('gebruiker'); $this->deelplan = $deelplan; $this->vragen = $vragen; $this->prioriteiten = $prioriteiten; $this->CI = get_instance(); } abstract public function get_gelijke_vragen( $vraag_id ); public final function run() { $this->_run(); $this->has_run = true; } abstract protected function _run(); public function has_run() { return $this->has_run; } public function result() { return (object)array( 'onderwerpen' => $this->onderwerpen, 'selected_vraag' => $this->selected_vraag, 'hoofdgroep_prioriteiten' => $this->hoofdgroep_prioriteiten, 'hoofdgroep_prioriteiten_origineel' => $this->hoofdgroep_prioriteiten_origineel, 'prioriteiten' => $this->prioriteiten, ); } protected function _set_selected_vraag( $vraag ) { if (!$this->selected_vraag && !$vraag->status && $vraag->is_toetsbaar()) { $this->selected_vraag = $vraag; return true; } return false; } protected function _set_hoofdgroep_prio( $vraag ) { if (!isset( $this->hoofdgroep_prioriteiten[$vraag->hoofdgroep_id] )) { // zet daadwerkelijk te gebruiken prioriteit if(isset($this->prioriteiten[$vraag->checklist_id])) $prio = $this->prioriteiten[$vraag->checklist_id]->get_waarde( $vraag->hoofdgroep_id, $vraag->hoofdthema_id, $this->deelplan->id ); else $prio = 'zeer_hoog'; if (!$prio) $prio = 'zeer_hoog'; $this->hoofdgroep_prioriteiten[$vraag->hoofdgroep_id] = $prio; // zet originele prioriteit vanuit matrix/prioriteitstelling if(isset($this->prioriteiten[$vraag->checklist_id])) $prio = $this->prioriteiten[$vraag->checklist_id]->get_waarde( $vraag->hoofdgroep_id, $vraag->hoofdthema_id /* originele waarde uit prioriteitstelling, zonder overrides */ ); else $prio = 'zeer_hoog'; if (!$prio) $prio = 'zeer_hoog'; $this->hoofdgroep_prioriteiten_origineel[$vraag->hoofdgroep_id] = $prio; } } } class OnderwerpenSplitterNietCombineerbareChecklistgroep extends OnderwerpenSplitter { protected function _run() { $this->CI->load->model( 'hoofdgroep' ); foreach ($this->vragen as $vraag) { $vraag->tekst = trim($vraag->tekst); if (!isset( $this->onderwerpen[$vraag->hoofdgroep_id] )) { $hoofdgroep = $this->CI->hoofdgroep->get( $vraag->hoofdgroep_id ); $this->onderwerpen[$vraag->hoofdgroep_id] = array( 'naam' => $vraag->hoofdgroep_naam, 'vragen' => array(), 'order' => $hoofdgroep->sortering); $this->_set_hoofdgroep_prio( $vraag ); } $this->_set_selected_vraag( $vraag ); $this->onderwerpen[$vraag->hoofdgroep_id]['vragen'][] = $vraag; } } public function get_gelijke_vragen( $vraag_id ) { return array( $vraag_id ); } } class OnderwerpenSplitterCombineerbaarOpChecklistChecklistgroep extends OnderwerpenSplitter { protected function _run(){ $klant = $this->CI->klant->get_logged_in_klant(); foreach ($this->vragen as $vraag){ $vraag->tekst = trim($vraag->tekst); $onderwerp_id = $vraag->checklist_id.'_'.$vraag->bouwnummer; if (!isset( $this->onderwerpen[$onderwerp_id] )){ $checklist = $this->CI->checklist->get( $vraag->checklist_id ); $checklistgroep = $checklist->get_checklistgroep(); $this->onderwerpen[$onderwerp_id] = array( 'naam' => $checklistgroep->naam . ' - ' . $checklist->naam . ' - ' .$vraag->bouwnummer, 'vragen' => array(), ); } $this->_set_hoofdgroep_prio( $vraag ); $this->_set_selected_vraag( $vraag ); $this->onderwerpen[$onderwerp_id]['vragen'][] = $vraag; } } public function get_gelijke_vragen( $vraag_id ) { return array( $vraag_id ); } } class OnderwerpenSplitterCombineerbareChecklistgroep extends OnderwerpenSplitter { private $split_data; // in _run is md5(vraag->tekst) de key, voor de get_gelijke_vragen wordt dit de vraag_id voor snellere lookup! private $split_data_geconverteerd = false; // is bovengenoemd proces al uitgevoerd? protected function _run() { // bepaal hoe vaak elke vraag voorkomt $this->split_data = array(); foreach ($this->vragen as $vraag) { $md5 = md5( $vraag->tekst ); if (!isset( $this->split_data[ $md5 ] )) $this->split_data[ $md5 ] = array(); $this->split_data[ $md5 ][] = $vraag; $this->_set_hoofdgroep_prio( $vraag ); } // maak onderwerpen aan op basis van het aantal voorkomingen van een vraag foreach ($this->split_data as $vragen) { $vraag = reset( $vragen ); $vraag->tekst = trim($vraag->tekst); if (sizeof( $vragen ) == 1) { // vraag komt maar 1x voor, gooi onder de groep voor z'n checklist $onderwerp_key = 'checklist' . $vraag->checklist_id; $onderwerp_naam = $this->CI->checklist->get( $vraag->checklist_id )->naam; $onderwerp_style = 'font-weight: bold; color: #0000dd'; } else { // vraag komt meer dan eens voor, gooi onder z'n hoofdthema $thema = $vraag->thema_id ? $this->CI->thema->get( $vraag->thema_id ) : null; $hoofdthema = ($thema && $thema->hoofdthema_id) ? $this->CI->hoofdthema->get( $thema->hoofdthema_id ) : null; if ($hoofdthema) { $onderwerp_key = 'hoofdthema' . $hoofdthema->id; $onderwerp_naam = $hoofdthema->naam; } else { $onderwerp_key = 'hoofdthemaALGEMEEN'; $onderwerp_naam = 'Algemeen'; } $onderwerp_style = ''; } if (!isset( $this->onderwerpen[ $onderwerp_key ] )) $this->onderwerpen[ $onderwerp_key ] = array( 'naam' => $onderwerp_naam, 'vragen' => array(), 'style' => $onderwerp_style, ); $this->onderwerpen[ $onderwerp_key ]['vragen'][] = $vraag; } // sorteer $CI = $this->CI; uksort( $this->onderwerpen, function( $a, $b ) use ($CI) { if ($a[0] != $b[0]) return ord( $a[0] ) - ord( $b[0] ); $aid = preg_replace( '/\D/', '', $a ); $bid = preg_replace( '/\D/', '', $b ); $aname = $aid ? ($a[0]=='c' ? $CI->checklist->get( $aid )->naam : $CI->hoofdthema->get( $aid )->naam) : 'Algemeen'; $bname = $bid ? ($a[0]=='c' ? $CI->checklist->get( $bid )->naam : $CI->hoofdthema->get( $bid )->naam) : 'Algemeen'; return strcmp( $aname, $bname ); }); // vindt nu de eerste niet beantwoordde vraag foreach ($this->onderwerpen as $onderwerp_data) foreach ($onderwerp_data['vragen'] as $vraag) if ($this->_set_selected_vraag( $vraag )) break(2); // convert "special keys" into normal indexed array // NOTE: index of 0 is not allowed, so add a bogus value and unset it, making the // array index start from 1 in stead of 0 ;-) $this->onderwerpen = array_values( array_merge( array(-1), $this->onderwerpen ) ); unset( $this->onderwerpen[0] ); } public function get_gelijke_vragen( $vraag_id ) { if (!$this->split_data_geconverteerd) { $this->_converteer_split_data(); $this->split_data_geconverteerd = true; } if (!isset( $this->split_data[$vraag_id] )) throw new Exception( 'Onverwachte vraag id: vraag ID zit niet in split data!' ); return array_map( function( $vraag ) { return $vraag->id; }, $this->split_data[$vraag_id] ); } private function _converteer_split_data() { foreach ($this->split_data as $md5 => $vragen) { $vraag = reset( $vragen ); unset( $this->split_data[$md5] ); $this->split_data[ $vraag->id ] = $vragen; } } } <file_sep>BRISToezicht.Toets.ButtonConfig = { lastConfigSet: null, // laatste button config die we gezet hebben buttonDom: [ // tactisch geformeerde array van arrays van de button dom elementen (td's) [null, null, null, null, null], [null, null, null, null, null], // 1,4 en 2,4 bestaan nooit, maar dat geeft niet [null, null, null, null, null] ], table: null, // jquery collection van de table waar alles in plaats vindt currentUtilityContainer: null, // jquery collection van de dom node waarin momenteel de 3 utility DIVS zich bevinden initialize: function() { this.table = $('.nlaf_TabContent table.waardeoordeel' ); var thiz = this; this.forEachPosition(function(x,y){ var dom = thiz.table.find('.w' + x + y); if (dom.size()) thiz.buttonDom[x][y] = dom; }, true); this.currentUtilityContainer = $('#nlaf_WaardeOordeelUtilsContainer'); }, forEachPosition: function( callback, force ) { for (var x=0; x<3; ++x) { for (var y=0; y<5; ++y) { if (force || this.buttonDom[x][y]) callback( x, y, this.buttonDom[x][y] ); } } }, buttonConfigUpdateRequired: function( bc ) { return !this.lastConfigSet || (this.lastConfigSet.tag != bc.tag); }, zetButtonConfig: function( bc ) { // update required, or is the current one equal to the new one? if (!this.buttonConfigUpdateRequired( bc )) { return; } // set new config as last config this.lastConfigSet = bc; // verberg lege-rij-helpers this.table.find( '.lege-rij-helper' ).hide(); // handle either meerkeuze or invul vragen switch (bc.type) { case 'meerkeuzevraag': // hide invul vraag TD this.table.find( '.invulvraag' ).hide(); // show basic TD's for meerkeuze this.table.find( '[id^=nlaf_Status]' ).hide(); // update waardeoordeel utils visually (foto button, documenten button, verantwoording tekst, geschiedenis buttons.) var maxHeight = 0; this.forEachPosition(function(x, y){ if (!x) return; if (bc.gebruik[x][y] && maxHeight <= y) maxHeight = y + 1; }); this.table.find( '.utilscontainer1' ).attr( 'colspan', '2' ); // see code for invulvraag this.updateWaardeoordeelUtils( 5 ); // set button teksten en kleuren in GUI // LET OP: ivm steekproef teksten KAN het zo zijn dat de tekst // van EEN van deze buttons weer gewijzigd wordt, zie de // functie BRISToezicht.Toets.Vraag.updateSteekproefButton $( ".hidden_td" ).remove(); this.forEachPosition(function(x, y, dom){ dom.removeClass( 'groen geel rood' ); dom.removeClass( 'leeg' ); if (bc.tekst[x][y]) { dom.text( bc.tekst[x][y] ); dom.addClass( bc.kleur[x][y]=='oranje' ? 'geel' : bc.kleur[x][y] ); dom.show(); } else { dom.hide(); dom.after( "<td class='hidden_td'></td>" ); $(".hidden_td").css("background","none"); $(".hidden_td").css("cursor","inherit"); } if (bc.is_leeg[x][y]) dom.addClass( 'leeg' ); }); // wanneer de hele 2e kolom leeg is, maar er wel iets in de 1e kolom zit, toon dan 1 lege kolom helper // zodat de middelste knoppen niet 2x zo groot worden (tabel wordt uitgevuld naar rechts.) // zelfde als hele 1e kolom leeg is, en kolom 2 niet var kolomLeeg = [true, true, true]; var rijLeeg = [true, true, true]; this.forEachPosition(function(x, y){ if (bc.tekst[x][y]) { kolomLeeg[x] = false; rijLeeg[y] = false; } }); /*if (kolomLeeg[2]) $("#nlaf_Status-w10").css("width", "33.33%"); else if(kolomLeeg[1]) $("#nlaf_Status-w20").css("width", "33.33%");*/ //debugger; // if (!kolomLeeg[1] && kolomLeeg[2]) // this.table.find( '.lege-kolom-helper.kolom2' ).show(); // else if (kolomLeeg[1] && !kolomLeeg[2]) //// else if (kolomLeeg[1]) // this.table.find( '.lege-kolom-helper.kolom1' ).show(); // if (kolomLeeg[0]) // this.table.find( '.lege-kolom-helper.kolom0' ).show(); break; case 'invulvraag': // show invul vraag TD this.table.find( '.invulvraag' ).show(); // hide all TD's for meerkeuze this.table.find( '[id^=nlaf_Status], .utilscontainer0, .utilscontainer2, .utilscontainer3, .utilscontainer4' ).hide(); this.table.find( '.utilscontainer1' ).attr( 'colspan', '1' ); // toon waardeoordeel utils this.updateWaardeoordeelUtils( 1 ); break; } }, updateWaardeoordeelUtils: function( start_row ) { // verberg de TD's van alle buttons die we niet meer willen for (var x=1; i<3; ++x) for (var y=start_row; y<4; ++y) this.buttonDom[x][y].hide(); // toon de juiste utility container helper TD for (var i=0; i<6; ++i) { var specialRow = this.table.find( '.utilscontainer' + i); if (i == start_row) { specialRow.show(); // verplaats nu de DIVS naar de nieuwe row, tenzij ze daar // al zijn natuurlijk ;-) if (specialRow[0] != this.currentUtilityContainer[0]) { this.currentUtilityContainer.children().appendTo( specialRow ); this.currentUtilityContainer = specialRow; } } else specialRow.hide(); } // update de hoogte van de verantwoordingstekst div var height; switch (start_row) { case 0: height = 65+4*52; break; case 1: height = 65+3*52; break; case 2: height = 65+2*52; break; case 3: height = 65+1*52; break; case 4: height = 65; break; } $( '#nlaf_VerantwoordingsTekst' ).css( 'height', 150 + 'px' ); $( '#nlaf_VerantwoordingsTekst div.tekst' ).css( 'height', (height-25) + 'px' ); }, /** Converteert een status waarde (b.v. "w30" of "w10s") naar een positie in x/y coordinaten * zoals die te gebruiken is in veel data arrays. * * @param status Status waarde, b.v. "w30", "w21", of "w11s" * @param voor_tekst_of_omschrijving Mag worden weggelaten, maar als deze true is, dan * wordt een steekproef waarde (eindigend op 's') geconverteerd * naar coordinaat 3,0. * @return Object met 2 members: x en y. */ statusNaarPositie: function( status, voor_tekst_of_omschrijving ) { if (typeof(status) != 'string') throw ('BRISToezicht.Toets.ButtonConfig.convertStatusNaarPositie: input geen string, maar: ' + status); if (status.length != 3 && status.length != 4) throw ('BRISToezicht.Toets.ButtonConfig.convertStatusNaarPositie: input heeft onverwachtte lengte, verwachtte 3 of 4, maar is: ' + status); if (status[0] != 'w') throw ('BRISToezicht.Toets.ButtonConfig.convertStatusNaarPositie: input begint niet met een w, maar: ' + status); var result = { x: parseInt( status[1] ), y: parseInt( status[2] ) }; if (voor_tekst_of_omschrijving && status[3] == 's') { result.x = 3; result.y = 0; } return result; } }; <file_sep><?php class OpdrachtProcessor { private $CI; private $_opdrachten = array(); public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'pdfannotatorlib' ); $this->CI->load->library( 'imageprocessor' ); $this->CI->load->library( 'simplemail' ); $this->CI->load->model( 'dossierbescheiden' ); $this->CI->load->model( 'deelplanlayer' ); $this->CI->load->model( 'deelplanopdracht' ); } static public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } public function run() { $this->log( 'initializing' ); $this->_genereer_opdrachten(); $this->_laad_opdrachten(); $this->_verwerk_opdrachten(); } // This method currently should only have impact for Woningborg: it generates opdrachten based on toezichtmomenten. private function _genereer_opdrachten() { echo "Opdrachten worden gegenereerd voor toezichtmomenten...\n"; $this->CI->load->model( 'deelplanchecklisttoezichtmoment' ); $toezichtMomentenForGenerateOpdrachten = $this->CI->deelplanchecklisttoezichtmoment->get_for_generate_deelplan_opdrachten(); echo "Aantal gevonden toezichtmomenten waarvoor opdrachten worden gegenereerd: " . sizeof($toezichtMomentenForGenerateOpdrachten) . "\n"; foreach ($toezichtMomentenForGenerateOpdrachten as $toezichtMomentForGenerateOpdrachten) { echo "Opdrachten worden gegenereerd voor toezichtmoment met ID: " . $toezichtMomentForGenerateOpdrachten->id . "...\n"; try { $toezichtMomentForGenerateOpdrachten->generate_deelplan_opdrachten(); $toezichtMomentForGenerateOpdrachten->opdrachten_gegenereerd = true; $toezichtMomentForGenerateOpdrachten->save(); } catch (Exception $e) { echo "Opdrachten konden niet gegenereerd worden. Reden: " . $e->getMessage() . "\n"; } } } private function _laad_opdrachten() { $this->_opdrachten = $this->CI->deelplanopdracht->search( array( 'email_verzonden' => 0 ) ); //$this->_opdrachten = $this->CI->deelplanopdracht->all(); $this->log( sizeof($this->_opdrachten) . ' gevonden om te verwerken' ); } private function _verwerk_opdrachten() { $allopdrachten = array(); foreach ($this->_opdrachten as $i => $opdracht) { // if it is an assignment to an external user, with customer Woningborg, only include if the date is t-1 $klant = $this->CI->gebruiker->get( $opdracht->opdrachtgever_gebruiker_id)->get_klant()->to_string(); $subject = $opdracht->get_dossier_subject(); if (!$opdracht->datum_begin || strtotime($opdracht->gereed_datum) < strtotime($opdracht->datum_begin)) { $opdracht_date = $opdracht->gereed_datum; } else { $opdracht_date = $opdracht->datum_begin; } $is_foto_opdracht = $opdracht->dossier_bescheiden_id ? true : false; $this->log( 'Verwerken van ' . ($is_foto_opdracht ? 'FOTO ' : '') . 'opdracht ' . $opdracht->id . ', ' . ($i+1) . '/' . sizeof($this->_opdrachten) ); try { // is dit een opdracht met bescheiden? if ($is_foto_opdracht) { $this->_maak_afbeeldingen( $opdracht ); } $klant_naam = $this->CI->gebruiker->get( $opdracht->opdrachtgever_gebruiker_id)->get_klant()->to_string(); $subject = $opdracht->get_dossier_subject(); // Group opdrachten by: // Klant name (to allow sending multiple opdrachten from one customer in one email) // Emailaddress (to find the user in the external users table) // Opdrachtgever id (to get the lease configuration later on if (!isset($subject->gebruiker_id)) { $opdrachtgever_id = $opdracht->opdrachtgever_gebruiker_id; } else { $opdrachtgever_id = null; } // Add the subject e-mailaddress, opdrachtgever id and customer to the array if not already present if (isset($subject->email)) { if (!in_array($klant_naam, $allopdrachten[$subject->email][$opdrachtgever_id])) { $allopdrachten[$subject->email][$opdrachtgever_id][$klant_naam]->subject = $subject; } // next assign the opdracht and lease url if applicable $allopdrachten[$subject->email][$opdrachtgever_id][$klant_naam]->opdrachten[] = $opdracht; } else { $this->log( 'Subject '.$subject->naam.' (id '.$subject->id.')heeft geen email adres (meer)'); } } catch (Exception $e) { // log message $this->log( 'EXCEPTION: ' . $e->getMessage() ); } } foreach ($allopdrachten as $subject_mail=>$opdrachtgever_klantopdrachten) { foreach ($opdrachtgever_klantopdrachten as $opdrachtgever_id=>$klant_opdrachten) { $new_user = false; $user_exists = false; $is_external_user = false; foreach ($klant_opdrachten as $klant_naam=>$subject_opdrachten) { $subject = $subject_opdrachten->subject; // If this is an external user (no gebruiker_id), check if the user already exists if (!isset($subject->gebruiker_id)) { $is_external_user = true; $url_query = 'SELECT id FROM `externe_gebruikers` '. 'WHERE `email` = "'.$subject->email.'";'; $res = $this->CI->db->query($url_query); if ($res->num_rows > 0) { $user_exists = true; } } else { $user_exists = true; } // Check if the user is external and does not already exist. If so, create the external user. if ( !isset($subject->gebruiker_id) && $subject->email && $user_exists == false) { //generate random password. When moving to PHP 7 or higher, use random_bytes instead //used the bin2hex to allow using it in url's (urlencode/decode messed it up) $random_password = bin2hex(openssl_random_pseudo_bytes(14)); //create salted hash for the password. When moving to PHP 5.5 or higher, the require_once can be removed because of the builtin password_hash function require_once(BASEPATH.'libraries/Password.php'); $pwd_hash= password_hash($random_password, PASSWORD_DEFAULT); //create the record if it does not exist already $url_query = 'INSERT IGNORE INTO `externe_gebruikers` '. 'SET `naam` = "'. $subject->naam .'", `email` = "'.$subject->email.'", `token` = "'.$pwd_<PASSWORD>.'";'; $res = $this->CI->db->query($url_query); // TODO: insert check for users that could not be created (perhaps already there or no email address) $new_user = $is_external_user = true; } try { $this->CI->db->_trans_status = true; $this->CI->db->trans_start(); // verzend email if ($new_user) { $this->_verzend_email($subject_opdrachten->subject, $klant_naam, $opdrachtgever_id, $subject_opdrachten->opdrachten, $is_external_user, $random_password); } else { $this->_verzend_email($subject_opdrachten->subject, $klant_naam, $opdrachtgever_id, $subject_opdrachten->opdrachten, $is_external_user); } // update opdrachten foreach ($subject_opdrachten->opdrachten as $opdracht) { $opdracht->email_verzonden = 1; if (!$opdracht->save( 0, 0, 0 )) throw new Exception( 'Fout bij opdracht opslaan in database.' ); // poog te committen if (!$this->CI->db->trans_complete()) throw new Exception( 'Fout bij committen van database transactie.' ); } } catch (Exception $e) { // rollback $this->CI->db->_trans_status = false; $this->CI->db->trans_complete(); // log message $this->log( 'EXCEPTION: ' . $e->getMessage() ); } } } } } private function _maak_afbeeldingen( DeelplanOpdrachtResult $opdracht ) { // initialiseer data $vraag = $opdracht->get_vraag(); $bescheiden = $opdracht->get_dossier_bescheiden(); $photoId = $opdracht->annotatie_tag; // initialiseer PDF annotator met 1 bestand (LET OP: zet $this->guid) $this->_initialiseer_pdfannotator( $bescheiden ); // laad layer informatie (LET OP: zet $this->layer) $page_number = null; if (!$this->_laad_layer( $opdracht, $bescheiden, $page_number )) return; try { // process image (LET OP: zet $this->png) $this->_bake_layer_to_image( $page_number ); // build opdracht images $this->_bake_opdracht_images( $opdracht ); } catch (Exception $e) { // cleanup PDF processor $this->_cleanup_pdfannotator(); // re-throw throw $e; } // cleanup PDF processor, do this OUTSIDE previous try/catch loop to prevent potential looping! $this->_cleanup_pdfannotator(); } private function _laad_layer( DeelplanOpdrachtResult $opdracht, DossierBescheidenResult $bescheiden, &$page_number ) { // zoek de layer informatie uit de database bij de opgegeven opdract en bescheiden // let op: get_layer_for_deelplan_bescheiden() geeft een DeelplanLayer resultaat terug, // maar dit vertegenwoordigt dus het geheel aan layers voor dat deelplan en bescheiden, vandaar // de naam "$layers" en niet "$layer" $layers = $this->CI->deelplanlayer->get_layer_for_deelplan_bescheiden( $opdracht->deelplan_id, $bescheiden->id ); if (!$layers) { $this->log( 'WARNING: geen layers in database voor deelplan ' . $opdracht->deelplan_id . ' en bescheiden ' . $bescheiden->id ); return false; } // kijk of we die json-encoded data kunnen decoderen $this->pagetransform = $layers->pagetransform_data; if (!($this->layer = $layers->geef_layer_voor_vraag( $opdracht->vraag_id ))) { $this->log( 'WARNING: geen layer voor deelplan ' . $opdracht->deelplan_id . ', bescheiden ' . $bescheiden->id . ' en vraag ' . $opdracht->vraag_id ); return false; } // zoek uit welke pagina we nodig hebben $page_number = null; foreach ($this->layer->pages as $pagenr => $data) { foreach ($data as $element) { if ($element->type == 'photoassignment') { if ($element->photoid == $opdracht->annotatie_tag) { $page_number = $pagenr; break; } } } } if (is_null($page_number)) { $this->log('WARNING: kan foto opdracht met id ' . $opdracht->annotatie_tag . ' niet vinden, dus ook de pagina niet'); return false; } $this->log('INFO: pagina nummer is ' . $page_number); // stop layer informatie in de PDF annotator $oldMethod = @$_SERVER['REQUEST_METHOD']; $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = array(); $_POST['layers'] = json_encode( array( $this->layer ) ); ob_start(); require( PDFANNOTATOR_CODE_PATH . 'annotations.php' ); $resultaat = ob_get_clean(); $_SERVER['REQUEST_METHOD'] = $oldMethod; if ($resultaat != '1') { $this->log( 'WARNING: PDF annotator fout bij inladen annotaties: ' . $resultaat ); return false; } // klaar! return true; } private function _bake_layer_to_image( $page_number ) { // selecteer het juiste bescheiden $_POST['guid'] = $this->guid; $_POST['pagetransform'] = $this->pagetransform; $_POST['dimensions'] = null; $_POST['do_headers'] = false; $_POST['page_number'] = $page_number; ob_start(); require( PDFANNOTATOR_CODE_PATH . 'download.php' ); $png = ob_get_clean(); // see if PNG is valid! $testim = @ imagecreatefromstring( $png ); if (!is_resource( $testim )) { if (preg_match( '/<div class="error">(.*?)<\/div>/smi', $png, $matches )) $errorHack = $matches[1]; else $errorHack = ''; throw new Exception( 'Fout opgetreden bij verwerken van annotaties: ' . $errorHack ); } imagedestroy( $testim ); $this->png = $png; } private function _initialiseer_pdfannotator( DossierBescheidenResult $bescheiden ) { $new_filename = preg_replace( '/(\.(pdf|png|jpg))*$/i', '', $bescheiden->bestandsnaam ) . '.jpg'; $document = (object)array( 'filename' => $new_filename, 'pages' => array(), 'external_data' => array( 'document_id' => $bescheiden->id, ), ); $this->CI->imageprocessor->slice( null ); $this->CI->imageprocessor->id( $bescheiden->id ); $this->CI->imageprocessor->type( 'bescheiden' ); $this->CI->imageprocessor->mode( 'original' ); $num_pages = $this->CI->imageprocessor->get_number_of_pages(); for ($i = 1; $i <= $num_pages; ++$i) { $this->CI->imageprocessor->page_number( $i ); if (!$this->CI->imageprocessor->available()) throw new Exception('Pagina (' . $i . ') niet beschikbaar'); $document->pages[] = (object)array( 'local' => $this->CI->imageprocessor->get_image_filename(), 'overview_local'=> $this->CI->imageprocessor->get_image_filename( 'overview' ), 'filename' => $new_filename, ); } // setup POST data and load PDF annotator code $_POST = array(); $_POST['quality'] = 'high'; $_POST['documents'] = json_encode( array( $document ) ); $_POST['no_exit'] = true; require( PDFANNOTATOR_CODE_PATH . 'upload-url-set.php' ); // haal GUID op, die hebben we zo direct nodig if (!load_current_guids() || sizeof($guids = load_current_guids()->get_document_guids()) == 0) throw new Exception( 'Geen guids gevonden na importeren van document.' ); $this->guid = $guids[0]; } private function _cleanup_pdfannotator() { $_POST = array(); $_POST['no_redirect'] = true; require( PDFANNOTATOR_CODE_PATH . 'delete.php' ); } private function _bake_opdracht_images( DeelplanOpdrachtResult $opdracht ) { // de overzichts afbeelding is vrij simpel, pak de PNG zoals die al gemaakt is // van de layers en knip em op in 5MB secties (dit ivm de iPhone die net als de // iPad weigert om JPG's/PNG's van meer dan 5MB aan pixels te tonen) $fotonum = 0; $im = imagecreatefromstring( $this->png ); $w = imagesx( $im ); // image size $h = imagesy( $im ); $x = 0; // start of next crop position $y = 0; $maxsize = 5 * 1024 * 1024; try { while ($w * ($h-$y) > $maxsize) { // too many slices? should never happen really! if ($fotonum == 10) break; // copy part of the image $slicew = $w; $sliceh = floor( $maxsize / $slicew ); $sliceim = imagecreatetruecolor( $slicew, $sliceh ); imagecopy( $sliceim, $im, 0, 0, $x, $y, $slicew, $sliceh ); $this->log( "... slicing $fotonum: pos=$x,$y size=$slicew,$sliceh" ); // output ob_start(); imagepng( $sliceim ); $opdracht->{'overzicht_afbeelding_' . $fotonum} = ob_get_clean(); // destroy image imagedestroy( $sliceim ); /* file_put_contents( $opdracht->id . '-overzicht- ' . $fotonum . '.png', $opdracht->{'overzicht_afbeelding_' . $fotonum} ); */ // next part! $y += $sliceh; $fotonum++; } // take bottom part if ($y > 0) { $slicew = $w; $sliceh = min( $h - $y, floor( $maxsize / $slicew ) ); $sliceim = imagecreatetruecolor( $slicew, $sliceh ); imagecopy( $sliceim, $im, 0, 0, $x, $y, $slicew, $sliceh ); $this->log( "... slicing $fotonum: pos=$x,$y size=$slicew,$sliceh" ); ob_start(); imagepng( $sliceim ); } // take entire image (in case of just a single "slice") else { ob_start(); imagepng( $im ); } $opdracht->{'overzicht_afbeelding_' . $fotonum} = ob_get_clean(); /* file_put_contents( $opdracht->id . '-overzicht- ' . $fotonum . '.png', $opdracht->{'overzicht_afbeelding_' . $fotonum} ); */ if ($y > 0) imagedestroy( $sliceim ); // destroy source image imagedestroy( $im ); } catch (Exception $e) { @imagedestroy( $im ); throw $e; } // voor de snapshot afbeelding moeten we wat meer moeite doen, we moeten uitrekenen // waar op de tekening deze zich bevindt! dit doen we op basis van layer data $x = $y = null; foreach ($this->layer->pages as $pagenr => $data) { foreach ($data as $element) { if ($element->type == 'photoassignment') { if ($element->photoid == $opdracht->annotatie_tag) { $x = $element->x + ($element->imagesizew / 2); $y = $element->y + ($element->imagesizeh / 2); } } } } if (is_null( $x )) { $this->log( 'WARNING: annotatie-tag/photo-id ' . $opdracht->annotatie_tag . ' niet gevonden in layers' ); return; } $pt = @json_decode( $this->pagetransform ); if (!is_object( $pt )) { $this->log( 'WARNING: fout bij decoderen van pagetransform' ); return; } $x *= $pt->zoomLevel; $y *= $pt->zoomLevel; $this->log( '... heb ' . $opdracht->annotatie_tag . ' gevonden op ' . $x . ',' . $y . ' met zoomlevel ' . $pt->zoomLevel ); // bak nu de snapshot afbeelding try { // laad originele afbeelding en bepaal formaat if (!($oim = imagecreatefromstring( $this->png ))) throw new Exception( 'Kon aangemaakt PNG bestand niet inlezen' ); $ow = imagesx( $oim ); $oh = imagesy( $oim ); // bepaal x/y crop in originele afbeelding, en bepaal formaat snapshot $ssw = min( $ow, 512 ); $ssh = min( $oh, 512 ); $ssx = max( 0, $x - $ssw/2 ); $ssy = max( 0, $y - $ssh/2 ); // maak snapshot if (!($ssim = imagecreatetruecolor( $ssw, $ssh ))) throw new Exception( 'Kon geen nieuwe snapshot image aanmaken' ); imagecopy( $ssim, $oim, 0, 0, $ssx, $ssy, $ssw, $ssh ); ob_start(); if (!imagepng( $ssim )) throw new Exception( 'Fout bij aanmaken van PNG voor snapshot' ); $png = ob_get_clean(); if (!$png || !strlen($png)) throw new Exception( 'Geen uitvoer gevonden bij aanmaken van snapshot PNG' ); // zet in opdracht $opdracht->snapshot_afbeelding = $png; } catch (Exception $e) { @imagedestroy( $oim ); throw $e; } /* file_put_contents( $opdracht->id . '-snapshot.png', $opdracht->snapshot_afbeelding ); */ } private function _verzend_email($subject, $klant_naam, $opdrachtgever_id, $opdrachten, $is_external_user = false, $token=null ) { /* $this->log( '... skipping verzend email functie' ); return; */ // Set defaults $sender = '<EMAIL>'; $recipient = $subject->naam; $x_mailer = null; $company_name = 'BRIStoezicht'; $content_type = 'text/html'; $mail_head = '<!DOCTYPE html> <html> <head> <title>Nieuwe opdracht</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { background-color: #A5A5A5; font-family: Arial, Helvetica, sans-serif; } .container { width: 100%; background-color: #FFF; border: 1px solid #000; overflow:hidden; } table, tr, td { border: none; background-color: #FFF; } td { padding: 5px; margin: 0px; } a, a:hover,a:active, a:visited { text-decoration: none; } p { font-style: italic; } .url, .url a, .url a:hover, .url a:active, .url a:visited { color: #41719C; } .right { text-align: right; } .button { background-color: #5B9BD5; border: 1px solid #41719C; margin: 10px; border-radius: 7px; color: #FFF; float: right; display: inline-block; } </style> </head>'; $opdrachten_table = "<table>"; // Check if email address exists if(!$subject->email) { throw new Exception( 'Subject heeft geen email adres (meer): #' . $subject->id . ': ' . $subject->naam ); } // Check if a lease url needs to be applied if ( isset($subject->gebruiker_id) ) { $lease_gebruiker_id = $subject->gebruiker_id; } elseif (!is_null($opdrachtgever_id)) { $lease_gebruiker_id = $opdrachtgever_id; } else { throw new Exception( 'Geen geldig gebruiker id of opdrachtgever id gevonden voor subject'. $subject->id ); } $url_query = 'SELECT l_c.url, email_sender, pagina_titel '. 'FROM lease_configuraties l_c '. 'WHERE EXISTS ('. 'SELECT k.lease_configuratie_id FROM gebruikers g '. 'INNER JOIN klanten k ON k.id = g.klant_id '. 'WHERE l_c.id = k.lease_configuratie_id AND g.id = ' . $lease_gebruiker_id . ')'; $res = $this->CI->db->query($url_query); $result = $res->row(); $res->free_result(); // Get the user status and set login message if applicable if ($is_external_user === true) { $base_url = '/extern/index/'; if ($token) { $base_url .= "/token=$token&email=".$subject->email."/"; $wwstatus = "Bij uw eerste aanmelding zult u worden verzocht een nieuw wachtwoord aan te maken"; } else { $wwstatus = "U kunt inloggen met het eerder door u opgegeven wachtwoord. Mocht u deze zijn vergeten, kunt u uw wachtwoord tijdens het aanmelden laten resetten"; } $login_tekst = ' <tr><td>Inloggegevens:</td></tr> <tr><td> <table> <tr><td>Email:</td><td><font style="display: none;">@</font>'.$subject->email.'</td></tr> <tr><td>Wachtwoord:</td><td>'.$wwstatus.'</td></tr> </table> </td></tr>'; } else { $base_url = '/telefoon/index/'; $login_tekst = ''; } if( !empty($result) && strlen(trim($result->url)) > 0) // Check for lease customers done a few lines back { $sender = $result->email_sender; $x_mailer = ucfirst(preg_replace('~.+@(\w+)\.\w+$~', '$1', $sender)) . '/' . BRIS_TOEZICHT_VERSION; $company_name = $result->pagina_titel; $interface_url = preg_replace( '#^/#', '',strval($result->url.$base_url)); } else { $interface_url = site_url($base_url); } // Start generating the opdrachten table if ($is_external_user) { $opdrachten_table = "<table><tr><td>Adres</td><td>Kenmerk</td><td>Omschrijving</td><td>Link</td></tr>"; foreach ($opdrachten as $opdracht) { $deelplan = $opdracht->get_deelplan(); $dossier = $deelplan->get_dossier(); $link = $interface_url.'/opdracht='. $opdracht->id; $opdrachten_table .= "<tr><td>".$dossier->get_locatie( false )."</td>". "<td>".$dossier->kenmerk."</td>". "<td>".$opdracht->opdracht_omschrijving."</td>". "<td><a class='button' href='$link'>Bewerk</a></td> </tr>"; } } else { $opdrachten_table = "<table><tr><td>Adres</td><td>Kenmerk</td><td>Link</td></tr>"; foreach (array_unique($opdrachten) as $opdracht) { $deelplan = $opdracht->get_deelplan(); $dossier = $deelplan->get_dossier(); $link = $interface_url.'/deelplan='. $deelplan->dossier_id . ',' . $deelplan->id; $opdrachten_table .= "<tr><td>".$dossier->get_locatie( false )."</td>". "<td>".$dossier->kenmerk."</td>". "<td><a class='button' href='$link'>Naar opdracht(en)</a></td> </tr>"; } } $opdrachten_table .= "</table>"; if (count($opdrachten)>1) { $opdrachten_tekst = 'opdrachten'; } else { $opdrachten_tekst = 'opdracht'; } $opdrachten_aantal = count($opdrachten); $mail_body = " <body> <table class='container'><tr><td><b>$klant_naam heeft $opdrachten_aantal nieuwe $opdrachten_tekst voor u klaar staan.</b></td></tr></table> <br /> <table class='container'> <tr><td>Beste $recipient,</td></tr> <tr><td>$klant_naam heeft voor u de onderstaande $opdrachten_tekst klaargezet.</td></tr> <tr><td>U kunt de opdracht vinden en uitvoeren door op de desbetreffende link te klikken.</td></tr> <tr><td>$opdrachten_table</td></tr> $login_tekst </table> <p class='url'>Werken de knoppen niet? Ga dan naar <a href='$interface_url'>$interface_url</a></p> <p>Deze email is automatisch verzonden.</p> </body> </html>"; $onderwerp = ucfirst("$opdrachten_tekst $klant_naam"); if( !$this->CI->simplemail->send( $onderwerp, "$mail_head$mail_body", array($subject->email), $cc = array(), $bcc = array(), $content_type, $extra_headers = array(), $sender, $x_mailer ) ) { throw new Exception( 'The email cannot be send: ' . $subject->email ); } $this->log( '... e-mail verzonden aan ' . $subject->email ); } }<file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account accepteren')); ?> <form method="post" name="form"> <table> <tr> <td id="form_header">Gebruikersnaam*:</td> </tr> <tr> <td id="form_value"><input name="gebruikersnaam" value="<?=$gebruikersnaam?>" type="text" size="40" maxlength="32"/><br/><i>Let op, deze naam moet uniek zijn!</i></td> </tr> <tr> <td id="form_header">Wachtwoord*:</td> </tr> <tr> <td id="form_value"><input name="wachtwoord" value="" type="text" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_header">Volledige naam*:</td> </tr> <tr> <td id="form_value"><input name="volledige_naam" value="<?=$volledige_naam?>" type="text" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_header">Email:</td> </tr> <tr> <td id="form_value"><input name="email" value="<?=$email?>" type="text" size="40" maxlength="32"/></td> </tr> <tr> <td id="form_header">Rol*:</td> </tr> <tr> <td id="form_value"> <select name="rol_id"> <option value="" disabled <?=$rol_id?'':'selected'?>>-- selecteer een rol --</option> <? foreach ($rollen as $rol): ?> <option <?=$rol->id == $rol_id ? 'selected' : ''?> value="<?=$rol->id?>"><?=htmlentities( $rol->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form_button"><input type="submit" value="Toevoegen"/></td> </tr> </table> </form> <? $this->load->view('elements/footer'); ?><file_sep>ALTER TABLE `bt_checklisten` ADD `standaard_gebruik_opdrachten` TINYINT NULL DEFAULT NULL; ALTER TABLE `bt_hoofdgroepen` ADD `standaard_gebruik_opdrachten` TINYINT NULL DEFAULT NULL; ALTER TABLE `bt_vragen` ADD `gebruik_opdrachten` TINYINT NULL DEFAULT NULL; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('checklistwizard.opdrachten', 'Opdrachten', '2013-09-09 14:36:24', 0); <file_sep>// JavaScript Debug function. Wrapper around console.log. This function is safe for older browsers too, and it can easily be disabled in one go. var allowConsoleOutput = true; //allowConsoleOutput = false; function jd (consoleValueToShow) { allowConsoleOutput && window.console && console.log(consoleValueToShow); } <file_sep><div class="scrolldiv hidden" id="TelefoonPaginaOpdrachten"> <div class="header"> <div class="regular_button terug" style="float:left; position: relative; top: -6px;"><?=tg('terug')?></div> <span><?=tg('opdrachten.header')?></span> </div> <div class="content"> <? foreach ($dossiers as $dossierdata): $dossier = $dossierdata['dossier']; $deelplannen = $dossierdata['deelplannen']; ?> <? foreach ($deelplannen as $deelplandata): $deelplan = $deelplandata['deelplan']; $hoofdgroepen = $deelplandata['hoofdgroepen']; ?> <div> <? $j=0; foreach ($hoofdgroepen as $hoofdgroepdata): $hoofdgroep = $hoofdgroepdata['hoofdgroep']; $opdrachten = $hoofdgroepdata['opdrachten']; ?> <ul class="list" style="margin-bottom: 0px;"> <li class="clickable dark bold top" deelplan_id="<?=$deelplan->id?>" hoofdgroep_id="<?=$hoofdgroep->id?>"><?=htmlentities( $hoofdgroep->naam, ENT_COMPAT, 'UTF-8' )?></li> </ul> <ul class="list <?=$j?'hidden':''?> deelplan-list" style="margin-top: 2px; margin-bottom: 2px;" > <? $i=0; foreach ($opdrachten as $i => $opdracht): ?> <? if (sizeof($opdrachten) > 1) $class = !$i ? 'first' : ($i == sizeof($opdrachten)-1 ? 'last' : ''); else $class = 'first last'; ?> <li class="arrow-right <?=$class?> clickable" deelplan_id="<?=$deelplan->id?>" opdracht_id="<?=$opdracht->id?>"> <img class="opdracht-gereed hidden" src="<?=site_url('/files/images/offline-klaar-wel.png')?>" style="float:right; position: relative; top: -3px; margin-right: 6px; "> <img class="opdracht-niet-gereed" src="<?=site_url('/files/images/offline-klaar-nog-niet.png')?>" style="float:right; position: relative; top: -3px; margin-right: 6px; "> <div style="overflow:hidden; white-space: nowrap; display: inline-block; width: 85%;"> <?=htmlentities( $opdracht->get_vraag()->tekst, ENT_COMPAT, 'UTF-8' )?> </div> </li> <? ++$i; endforeach; ?> </ul> <? ++$j; endforeach; ?> </div> <? endforeach; ?> <? endforeach; ?> </div> </div> <script type="text/javascript"> $(document).ready(function(){ var base = $('#TelefoonPaginaOpdrachten'); base.find('.terug').click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_DEELPLANNEN ); }); base.find('ul.list li[hoofdgroep_id]').click(function(){ var list = $(this).parent().next(); if (list.is(':visible')) return; curVisList = list.siblings( '.deelplan-list:visible' ); curVisList.slideUp(); list.slideDown(); }); base.find('ul.list li[opdracht_id]').click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_TOEZICHT, $(this).attr('opdracht_id') ); }); }); </script> <file_sep>-- maak aanvraag datum veld aan in deelplannen, en zet em vanuit dossier data ALTER TABLE `deelplannen` ADD `aanvraag_datum` DATE NULL DEFAULT NULL ; UPDATE deelplannen SET aanvraag_datum = (SELECT IF(aanvraag_datum='1970-01-01',NULL,aanvraag_datum) FROM dossiers WHERE dossiers.id = deelplannen.dossier_id); -- verwijder uit dossiers ALTER TABLE `dossiers` DROP `aanvraag_datum`; <file_sep><? require_once 'base.php'; class ChecklistKlantResult extends BaseResult { function ChecklistKlantResult( &$arr ) { parent::BaseResult( 'checklistgroepklant', $arr ); } } class ChecklistKlant extends BaseModel { function ChecklistKlant() { parent::BaseModel( 'ChecklistKlantResult', 'bt_checklist_klanten', true ); } public function check_access( BaseResult $object ) { return; } public function all() { $res = get_instance()->db->query( 'SELECT * FROM ' . $this->get_table() ); $result = array(); foreach ($res->result() as $row) { $row = (array)$row; $result[] = new ChecklistKlantResult( $row ); } $res->free_result(); return $result; } public function replace_for_checklist( $checklistid, array $klant_ids ) { $stmt1 = 'ChecklistKlant::replace_for_checklistgroep::1'; if (!$this->dbex->prepare( $stmt1, 'DELETE FROM ' . $this->get_table() . ' WHERE checklist_id = ?' )) throw new Exception( 'Fout bij opslaan checklist / klant relaties (1).' ); $stmt2 = 'ChecklistKlant::replace_for_checklistgroep::2'; if (!$this->dbex->prepare( $stmt2, 'INSERT INTO ' . $this->get_table() . ' (checklist_id, klant_id) VALUES (?, ?)' )) throw new Exception( 'Fout bij opslaan checklist / klant relaties (2).' ); if (!$this->dbex->execute( $stmt1, array( $checklistid ) )) throw new Exception( 'Fout bij opslaan checklist / klant relaties (3).' ); foreach ($klant_ids as $klant_id) if (!$this->dbex->execute( $stmt2, array( $checklistid, $klant_id ) )) throw new Exception( 'Fout bij opslaan checklist / klant relaties (4).' ); } } <file_sep><? global $class; if (!strcasecmp( $class, 'webservice' )) throw new Exception( 'PHP error: ' . $message ); ?> <div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"> <h4>A PHP Error was encountered</h4> <p>Severity: <?php echo $severity; ?></p> <p>Message: <?php echo $message; ?></p> <p>Filename: <?php echo $filepath; ?></p> <p>Line Number: <?php echo $line; ?></p> <p><?php if (function_exists( 'dpb' )) dpb(); ?></p> </div><file_sep>-- Register the MVV-suite webservice in the DB and create a webuser for it REPLACE INTO webservice_applicaties SET id = 6, naam = 'MVV-Suite', actief = 1; REPLACE INTO webservice_accounts SET webservice_applicatie_id = 6, omschrijving = 'Den Haag MVV-Suite', gebruikersnaam = 'DH_mvv-suite_usr', wachtwoord = SHA1('DH_mvv-suite_pwd'), actief = 1, alle_klanten = 1, alle_components = 1; -- Create a dummy user for associating new dossiers that are not assigned to. INSERT INTO gebruikers SET klant_id = 131, gebruikersnaam = 'n<PASSWORD>', wachtwoord = SHA1('%^^%$^%^%^^%'), volledige_naam = '<NAME>', status = 'geblokkeerd'; -- ALTER TABLE webservice_applicatie_dssrs ADD COLUMN dossier_hash VARCHAR(40) DEFAULT NULL; <file_sep><?php class QuestException extends Exception {}; class QuestPermissionException extends QuestException {}; class CI_Quest { private $CI; private $_quest; public function __construct() { $this->CI = get_instance(); // hacky, but staying as close to original example as I can include( dirname(__FILE__) . '/kmx/quest.php' ); $this->_quest = $quest; } private function _rmBOM($string) { if(substr($string, 0,3) == pack("CCC",0xef,0xbb,0xbf)) { $string=substr($string, 3); } return $string; } private function _execute( $url, $expect_json=true, $use_magma_token=true ) { if (!isset( $this->CI->kennisid )) throw new QuestPermissionException( 'Toegang geweigerd tot URL: "' . $url . '"' ); global $__RequestTimer; $url = 'http://quest.bris.nl/' . $url; $http_headers = array( 'Accept: application/json', ); if ($use_magma_token) { $token = $this->_quest->getMagmaToken(); $http_headers[] = 'MagmaToken: ' . $token; } else { $token = $this->CI->kennisid->get_session_token_bw(); $http_headers[] = 'MagmaLicenseToken: ' . $token; } $c = curl_init( $url ); curl_setopt( $c, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $c, CURLOPT_HEADER, false ); curl_setopt( $c, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $c, CURLOPT_HTTPHEADER, $http_headers ); curl_setopt( $c, CURLOPT_TIMEOUT, 60 ); if ($__RequestTimer) $__RequestTimer->sub( 'quest request' ); $data = curl_exec( $c ); if ($__RequestTimer) $__RequestTimer->subfinish(); $code = curl_getinfo( $c, CURLINFO_HTTP_CODE ); curl_close( $c ); $data = $this->_rmBOM( $data ); switch ($code) { case 401: throw new QuestPermissionException( 'Toegang geweigerd tot URL: "' . $url . '"' ); case 200: if ($expect_json) return json_decode( $data ); else return $data; default: throw new Exception( 'HTTP fout ' . $code . ' op URL: "' . $url . '"' ); } } public function data( $id ) { /* Do not use application MagmaToken when request comes from a user on the BTZ website, * but use the user's MagmaLicenseToken; * However, since we do not use KennisID logins when in the app, do use the MagmaToken when * this is an app request */ $useMagmaToken = (HTTP_USER_AUTHENTICATION || (defined('FORCE_QUEST_USE_MAGMA_TOKEN') && FORCE_QUEST_USE_MAGMA_TOKEN)) ? true : false; return $this->_execute( 'Api/Document/Data/' . $id . '?linkmanager=false&compose=all&transform=bbonline-sduwenr' , false /* /Data does not support json */ , $useMagmaToken ); } public function info( $id ) { return $this->_execute( 'Api/Document/Version/' . $id ); } public function toclevel( $document_id, $id=null ) { return $this->_execute( 'Api/Document/TocLevel/' . $id . '?questId=' . rawurlencode($document_id) ); } public function collectionlevel( $collection_id, $id=null ) { return $this->_execute( 'Api/Collection/Level/' . $collection_id . '?parentId=' . rawurlencode($id) ); } public function query_id( $document_id, $id_end ) { $res = $this->_execute( 'Api/Document/QueryId/' . $document_id . '?query=' . $id_end ); if (!is_array( $res )) throw new Exception( 'Verwachtte array als resultaat bij QueryId' ); $ids = array(); foreach ($res as $entry) $ids[] = $entry->QuestId; return $ids; } public function query_single_id( $document_id, $id_end ) { $ids = $this->query_id( $document_id, $id_end ); if (empty( $ids )) return null; return $ids[0]; } } <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('nav.mappingen.dmmclonemap', '$1 - cloning', NOW(), 0); REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('mappingen.button.clone', 'Do cloning', NOW(), 0); <file_sep>UPDATE `deelplan_vragen` SET status = NULL WHERE status = ''; <file_sep>ALTER TABLE `gebruikers` ADD `email` VARCHAR( 128 ) NULL DEFAULT NULL ; CREATE TABLE IF NOT EXISTS `outlook_sync_data` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `uid` varchar(64) NOT NULL, `date` date NOT NULL, `vraagids` text NOT NULL, `sequence` int(11) NOT NULL, `recipient_email` VARCHAR( 128 ) NOT NULL, `recipient_name` VARCHAR( 128 ) NOT NULL, `created_at` DATETIME NOT NULL, `last_updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `deelplan_id_2` (`deelplan_id`,`date`), KEY `deelplan_id` (`deelplan_id`) ) ENGINE=InnoDB; ALTER TABLE `outlook_sync_data` ADD CONSTRAINT `outlook_sync_data_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep>SET @lc_name = 'Approve'; SET @lc_key = 'approve'; SET @lc_color = '2daae1'; SET @lc_username = 'approve'; SET @lc_password = '<PASSWORD>!'; SET @lc_rol_id = (SELECT id FROM rollen WHERE naam = '[BL] Beheerder'); INSERT INTO `lease_configuraties` ( `id` ,`naam` ,`login_label` ,`pagina_titel` ,`achtergrondkleur` ,`voorgrondkleur` ,`eigen_nieuws_berichten` ,`automatisch_collega_zijn` ,`toon_gebruikersforum_knop` , `login_systeem` ,`gebruik_matrixbeheer` ,`gebruik_management_rapportage` ,`gebruik_instellingen` ,`gebruik_rollenbeheer` ,`gebruik_dossier_rapportage` , `gebruik_deelplan_email` ,`speciaal_veld_gebruiken` ,`speciaal_veld_waarden` ,`url` ,`email_sender`) VALUES (NULL , @lc_key, CONCAT('Inloggen op ', @lc_name), @lc_name, @lc_color, 'ffffff', 'ja', 'nee', 'nee', 'normaal', 'ja', 'ja', 'ja', 'ja', 'ja', 'nee', '0', '', '', ''); SET @lc_id = LAST_INSERT_ID(); INSERT INTO `klanten` ( `id` ,`kennis_id_unique_id` ,`heeft_word_export_licentie` ,`heeft_bel_import_licentie` ,`heeft_fine_kinney_licentie` ,`status` ,`naam` , `lease_administratie_ips` , `lease_configuratie_id` ,`logo` ,`logo_klein` ,`kleur` ,`volledige_naam` ,`contactpersoon_email` ,`contactpersoon_naam` ,`contactpersoon_telefoon` , `steekproef_interval` , `outlook_synchronisatie` ,`standaard_netwerk_modus`) VALUES (NULL, NULL , 'nee', 'nee', 'nee', 'geaccepteerd', @lc_name, NULL , @lc_id, NULL , NULL , @lc_color, @lc_name, '', '', '', '10', '0', 'wifi'); SET @lc_klant_id = LAST_INSERT_ID(); INSERT INTO `gebruikers` ( `id` , `kennis_id_unique_id` , `klant_id` , `rol_id` , `speciale_functie` , `gebruikersnaam` , `wachtwoord` , `volledige_naam` , `status` , `intern` , `prijs` , `laatste_request` , `email` , `outlook_synchronisatie` , `factuur_flags` , `app_toegang` , `app_toegang_laatste_tijdstip` ) VALUES (NULL , NULL , @lc_klant_id, @lc_rol_id, 'geen', @lc_username, SHA1( @lc_password ) , @lc_name, 'actief', 'ja', '', NULL , NULL , '1', '', '0', NULL);<file_sep><?php class AnnotatieSchaler { private $CI; private $_dry_run; private $_ids; private $_layers; private $_current; private $_old; public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'pdfannotatorlib' ); $this->CI->load->library( 'imageprocessor' ); $this->CI->load->model( 'dossierbescheiden' ); $this->CI->load->model( 'deelplanlayer' ); } static public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } public function run( $options='' ) { // initialize $option_parts = explode( ',', $options ); $this->_dry_run = !in_array( 'real', $option_parts ); $this->log( 'Starting with options: "' . $options . '"' ); if ($this->_dry_run) $this->log( 'NOTE: dry run, not storing changes' ); // get all ids and layers $this->load_ids_and_layers(); // read all current sizes $this->load_current(); // get old sizes $this->load_old(); // start conversion $this->convert(); } public function load_ids_and_layers() { $this->_ids = array(); $res = $this->CI->db->query( 'SELECT * FROM deelplan_layers WHERE laatst_bijgewerkt_op < \'2013-07-15 08:00:00\' ORDER BY dossier_bescheiden_id' ); $this->_ids = array(); $this->_layers = array(); foreach ($res->result() as $row) { $layers = Layers::import( json_decode( $row->layer_data ) ); $has_actual_data = false; foreach ($layers->get_layers() as $layer) if (sizeof( $layer->get_annotations()->get_annotations_for_page( 1 ))) $has_actual_data = true; if ($has_actual_data) { if (!in_array( $row->dossier_bescheiden_id, $this->_ids )) $this->_ids[] = $row->dossier_bescheiden_id; $this->_layers[] = (object)array( 'id' => $row->dossier_bescheiden_id, 'deelplan_id' => $row->deelplan_id, 'layers' => $layers, 'pagetransform' => json_decode( $row->pagetransform_data ) ); } } $res->free_result(); $this->log( 'Loaded ' . sizeof($this->_ids) . ' bescheiden ids' ); $this->log( 'Loaded ' . sizeof($this->_layers) . ' layers' ); } public function load_current() { $this->_current = new DocumentTable(); $this->CI->imageprocessor->mode( 'original' ); $this->CI->imageprocessor->type( 'bescheiden' ); foreach ($this->_ids as $id) { // get binary contents of image $this->CI->imageprocessor->slice( null ); $this->CI->imageprocessor->id( $id ); try { $filename = $this->CI->imageprocessor->get_image_filename(); // get size $res = @getimagesize( $filename ); if ($res === false) throw new Exception( 'Failed to get image size of ' . $filename ); list( $w, $h ) = $res; // set $this->_current->set( $id, $w, $h ); $this->log( 'Loaded current image size for ' . $id . ': ' . $w . 'x' . $h . ' (' . (round( ($w*$h) / (1024*1024), 1 ) ) . 'MB)' ); } catch (Exception $e) { $bescheiden = $this->CI->dossierbescheiden->get( $id ); if (!$bescheiden) throw new Exception( 'Failed to load bescheiden ' . $id . ' for error processing: ' . $e->getMessage() ); if (preg_match( '/\.(jpe?g|png|pdf)$/i', $bescheiden->bestandsnaam )) $this->log( 'Failed to obtain image data for id ' . $id . ': ' . $e->getMessage() ); } } } public function load_old() { $this->_old = new DocumentTable(); // // NOTE: the code below is not very optimal, just copy/pasted code from old image processor, changed // it where it absolutely had to, and used it, to be sure the results are the same as they // used to be with the old image processor // foreach ($this->_ids as $id) { $bescheiden = $this->CI->dossierbescheiden->get( $id ); $bescheiden->laad_inhoud(); $contents = $bescheiden->bestand; $bescheiden->geef_inhoud_vrij(); // PDF conversie if (preg_match( '/\.pdf$/i', $bescheiden->bestandsnaam )) { try { $rand = mt_rand(); $tmpdir = '/tmp/convert-pdf-to-jpeg-' . $rand . '/'; if (!is_dir( $tmpdir ) && !mkdir( $tmpdir, 0766, true )) throw new Exception( 'ImageProcessor: failed to create temp dir: ' . $tmpdir ); $tmpfile = $tmpdir . 'file.pdf'; $tmppage = $tmpdir . 'page'; $dpi = 95; // write temp PDF if (!file_put_contents( $tmpfile, $contents )) throw new Exception( 'ImageProcessor: failed to write temp file: ' . $tmpfile ); // execute pdftoppm $format_options = '-r 95 -png -aa yes'; $command = 'pdftoppm ' . $format_options . ' ' . escapeshellarg($tmpfile) . ' ' . escapeshellarg($tmppage); exec( $command, $lines, $exit_code ); if ($exit_code) throw new Exception( 'ImageProcesor: failed to execute: ' . $command ); // extract page information $pagenum = 1; $pages = array(); while (true) { $filenames = array(); for ($i=1; $i<10; ++$i) $filenames[] = $tmppage . '-' . sprintf( '%0' . $i . 'd', $pagenum ) . '.png'; $real_filename = null; foreach ($filenames as $filename ) if (file_exists( $filename )) { $real_filename = $filename; $pages[$pagenum] = new ImageProcessorPage( $pagenum, $this->_pageformat, $filename ); ++$pagenum; break; } if (!$real_filename) break; } // get info on all images $bakedw = $bakedh = 0; $images = array(); $totalbytes = 0; foreach ($pages as $i => $page) { // create image $images[$i] = imagecreatefrompng( $page->get_filename() ); if (!$images[$i]) throw new Exception( 'ImageProcessor: failed to read page file ' . $page->get_filename() . ' (1)' ); $w = imagesx( $images[$i] ); $h = imagesy( $images[$i] ); $totalbytes += $w * $h * 4; // update width and height of result image $bakedw = max( $bakedw, $w ); $bakedh += $h; // destroy image right away, yes this is inefficient in terms of performance, // but it is efficient in terms of memory usage! imagedestroy( $images[$i] ); // don't create images that are insanely big... if ($bakedh > 20000) { $pages = array_slice( $pages, 0, $i + 1 ); break; } } // cleanup exec( 'rm -rf ' . escapeshellarg( $tmpdir ) ); // set $this->log( 'Loaded old image size for ' . $id . ': ' . $bakedw . 'x' . $bakedh . ' (' . (round( ($bakedw*$bakedh) / (1024*1024), 1 ) ) . 'MB)' ); $this->_old->set( $id, $bakedw, $bakedh ); } catch (Exception $e) { // upon processing error, always cleanup directory //error_log("[DEBUG] exception occurred, removing temp directory $tmpdir"); exec( 'rm -rf ' . escapeshellarg( $tmpdir ) ); $this->log( 'Failed to convert PDF for id ' . $id . ': ' . $e->getMessage() ); } } else if (preg_match( '/\.(png|jpe?g)$/i', $bescheiden->bestandsnaam )) { try { $im = new Imagick(); $im->readImageBlob( $contents ); $w = $im->getImageWidth(); $h = $im->getImageHeight(); $im->destroy(); // set $this->log( 'Loaded old image size for ' . $id . ': ' . $w . 'x' . $h . ' (' . (round( ($w*$h) / (1024*1024), 1 ) ) . 'MB)' ); $this->_old->set( $id, $w, $h ); } catch (Exception $e) { $this->log( 'Failed to read image data for id ' . $id . ': ' . $e->getMessage() ); } } else { $this->log( 'Not processing unknown type: ' . $bescheiden->bestandsnaam ); } } } public function convert() { foreach ($this->_layers as $layerdata) { // check if loading went succesfull if (!$this->_old->has( $layerdata->id )) { $this->log( 'No old image size for ' . $layerdata->id ); continue; } else if (!$this->_current->has( $layerdata->id )) { $this->log( 'No current image size for ' . $layerdata->id ); continue; } // scale! foreach ($layerdata->layers->get_layers() as $layer) $this->convert_layer( $this->_old->get( $layerdata->id ), $this->_current->get( $layerdata->id ), $layer, $layerdata->pagetransform ); // update DB! if (!$this->_dry_run) { $this->log( 'Updating database record' ); $this->CI->deelplanlayer->replace( $layerdata->deelplan_id, $layerdata->id, json_encode( $layerdata->layers->export() ), json_encode( $layerdata->pagetransform ) ); } } } public function convert_layer( array $oldsize, array $currentsize, Layer $layer, stdClass $pagetransform ) { if ($pagetransform->rotation == 90 || $pagetransform->rotation == 270) { $swap = $oldsize[0]; $oldsize[0] = $oldsize[1]; $oldsize[1] = $swap; $swap = $currentsize[0]; $currentsize[0] = $currentsize[1]; $currentsize[1] = $swap; } foreach ($layer->get_annotations()->get_annotations_for_page( 1 ) as $ann) { // use highest value to get most precise scale factor if ($oldsize[0] > $oldsize[1]) $factor = $currentsize[0] / $oldsize[0]; // use width else $factor = $currentsize[0] / $oldsize[0]; // use height $this->log( 'Convert layer from ' . $oldsize[0] . 'x' . $oldsize[1] . ' to ' . $currentsize[0] . 'x' . $currentsize[1] . ', factor ' . round( $factor, 3 ) . ', rotation ' . $pagetransform->rotation . 'deg' ); $ann->scale( $factor ); } } } class DocumentTable { private $_documents = array(); public function set( $document_id, $w, $h ) { $this->_documents[$document_id] = array( $w, $h ); } public function get( $document_id ) // returns array with [0]=$w, [1]=$h { if (!isset( $this->_documents[$document_id] )) throw new Exception( 'DocumentTable: invalid id ' . $document_id ); return $this->_documents[$document_id]; } public function has( $id ) { return isset( $this->_documents[$id] ); } } <file_sep> ALTER TABLE deelplan_checklisten DROP FOREIGN KEY deelplan_checklisten_ibfk_4, DROP FOREIGN KEY deelplan_checklisten_ibfk_5; ALTER TABLE deelplan_checklisten ADD COLUMN id INT NOT NULL AUTO_INCREMENT FIRST, CHANGE COLUMN deelplan_id deelplan_id INT(11) DEFAULT NULL AFTER id, CHANGE COLUMN checklist_id checklist_id INT(11) DEFAULT NULL AFTER deelplan_id, ADD COLUMN bouwnummer_id INT(11) DEFAULT NULL AFTER checklist_id, DROP PRIMARY KEY, ADD PRIMARY KEY (id); ALTER TABLE deelplan_checklisten ADD UNIQUE INDEX UK_deelplan_checklisten_dcb (deelplan_id, checklist_id, bouwnummer_id); ALTER TABLE deelplan_checklisten ADD CONSTRAINT deelplan_checklisten_ibfk_4 FOREIGN KEY (checklist_id) REFERENCES bt_checklisten(id) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE deelplan_checklisten ADD CONSTRAINT deelplan_checklisten_ibfk_5 FOREIGN KEY (deelplan_id) REFERENCES deelplannen(id) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE supervision_moments_cl ADD COLUMN bouwnummer_id INT(11) DEFAULT NULL AFTER checklist_id; ALTER TABLE deelplan_vragen ADD COLUMN bouwnummer_id INT(11) DEFAULT NULL AFTER vraag_id; ALTER TABLE deelplan_vragen DROP INDEX UK__deelplan_vragen__d_id__v_id, ADD UNIQUE INDEX UK__deelplan_vragen__d_id__v_id (deelplan_id, vraag_id, bouwnummer_id); ALTER TABLE deelplan_uploads ADD COLUMN bouwnummer_id INT(11) DEFAULT NULL AFTER vraag_id; ALTER TABLE deelplan_vraag_geschiedenis ADD COLUMN bouwnummer_id INT(11) DEFAULT NULL AFTER vraag_id; <file_sep>-- WOBORG-133 / Revision (overhaul) management serverside. ALTER TABLE deelplan_vragen ADD COLUMN huidige_toelichting_id int DEFAULT 1000; ALTER TABLE deelplan_vraag_geschiedenis ADD COLUMN toelichting_id int DEFAULT 2000; <file_sep> ALTER TABLE project_mappen DROP FOREIGN KEY FK_project_mappingen_artikel_vraag_mappen, CHANGE COLUMN vraag_map_id vraag_id int(11) NOT NULL; ALTER TABLE project_mappen ADD CONSTRAINT FK_project_mappen_bt_vragen_id FOREIGN KEY (vraag_id) REFERENCES bt_vragen (id) ON DELETE RESTRICT ON UPDATE RESTRICT;<file_sep>PDFAnnotator.GUI.Menu.Colors = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( menu, config ) { this._super( menu ); this.choices = config.choices; this.lineselector = config.lineselector; this.fillselector = config.fillselector; this.selectors = this.lineselector.add( this.fillselector ); this.selectedClass = config.selectedClass; var thiz = this; this.lineselector.click(function(){ thiz.fillselector.removeClass( thiz.selectedClass ); thiz.lineselector.addClass( thiz.selectedClass ); }); this.fillselector.click(function(){ thiz.lineselector.removeClass( thiz.selectedClass ); thiz.fillselector.addClass( thiz.selectedClass ); }); this.choices.click(function(){ thiz.selectors.filter('.' + thiz.selectedClass).css( 'background-color', $(this).css( 'background-color' ) ); }); }, getFillColor: function() { return this.fillselector.css( 'background-color' ); }, getLineColor: function() { return this.lineselector.css( 'background-color' ); } }); <file_sep><? require_once 'base.php'; class LogResult extends BaseResult { function LogResult( &$arr ) { parent::BaseResult( 'log', $arr ); } } class Log extends BaseModel { function Log() { parent::BaseModel( 'LogResult', 'logs', true ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'gebruiker', 'gebruiker_id' ); } public function add( $deelplan, $soort, $omschrijving, $extra_info=null ) { $gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker(); if ($gebruiker===null) // we don't care about non-logged-in-events return; if (!$this->_CI->dbex->is_prepared( 'add_log' )) $this->_CI->dbex->prepare( 'add_log', ' INSERT INTO logs(deelplan_id, gebruiker_id, datum, soort, omschrijving, extra_info) VALUES (?, ?, ?, ?, ?, ?)' ); $args = array( $deelplan ? $deelplan->id : null, $gebruiker ? $gebruiker->id : null, time(), $soort, $omschrijving, $extra_info, ); $this->_CI->dbex->execute( 'add_log', $args ); } public function get_soorten() { if (!$this->_CI->dbex->is_prepared( 'get_log_soorten' )) $this->_CI->dbex->prepare( 'get_log_soorten', ' SELECT DISTINCT(soort) FROM logs l JOIN gebruikers g ON (l.gebruiker_id = g.id) WHERE g.klant_id = ? ' ); $args = array( $this->session->userdata( 'kid' ) ); $res = $this->dbex->execute( 'get_log_soorten', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $row->soort; return $result; } public function search_log( $soorten, $gebruikers, $start_datum, $eind_datum ) { // no filter? then find nothing! if (sizeof($soorten)==0 || sizeof($gebruikers)==0) return array(); // setup one-time-query $query = ' SELECT l.*, g.volledige_naam, d.kenmerk FROM logs l JOIN gebruikers g ON (l.gebruiker_id = g.id) LEFT JOIN deelplannen de ON (l.deelplan_id = de.id) LEFT JOIN dossiers d ON (de.dossier_id = d.id) WHERE l.datum >= ? AND l.datum < ? AND (%s) AND (%s) ORDER BY l.datum DESC '; // !!! Oracle doesn't support the 'LIMIT' part, so do not use it for Oracle DBs // Note: a work-around is not straightforward; solve this later (and only if strictly necessary!) if (get_db_type() != 'oracle') { $query .= ' LIMIT 0,250'; } $soorten_query = ''; $gebruikers_query = ''; foreach ($soorten as $soort) $soorten_query .= ($soorten_query?' OR ':'') . 'l.soort = ?'; foreach ($gebruikers as $gebruiker) $gebruikers_query .= ($gebruikers_query?' OR ':''). 'l.gebruiker_id = ?'; $query = sprintf( $query, $soorten_query, $gebruikers_query ); $this->_CI->dbex->prepare( 'log_search', $query ); $args = array_merge( array(strtotime($start_datum),strtotime($eind_datum)), $soorten, $gebruikers ); $res = $this->dbex->execute( 'log_search', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $this->_CI->dbex->unprepare( 'log_search' ); return $result; } } <file_sep>BRISToezicht.Toets.Opdracht = { tabel: null, toonAlleOpdrachten: false, contentIsAlleOpdrachten: false, initialize: function() { }, ymdToDMY: function( datum ) { if (datum.match( /(\d{4})-(\d{2})-(\d{2})/ )) return RegExp.$3 + '-' + RegExp.$2 + '-' + RegExp.$1; return datum; }, openPopup: function( vraag_id, existing_opdracht ) { //var bbttt = BRISToezicht.Toets.data; //debugger; if (!vraag_id) { var vraag = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraag) { return; } vraag_id = vraag.vraag_id; } modalPopup({ width: 500, height: 450, html: '<h3>Opdrachtformulier</h3>' + '<table>' + '<tr>' + '<td><b>Opdracht aan:</b></td>' + '<td style="text-align:right"><select name="dossier_subject_id" style="width: 250px"></select></td>' + '</tr>' + '<tr>' + '<td colspan="2"><b>Opdrachtomschrijving:</b></td>' + '</tr>' + '<tr>' + '<td colspan="2"><textarea style="width: 440px; height: 100px;" name="opdracht_omschrijving"></textarea></td>' + '</tr>' + '<tr>' + '<td colspan="2"><input type="button" value="Standaardopdrachten" class="standaardopdrachten" /></td>' + '</tr>' + '<tr>' + '<td colspan="2" style="display:none"></td>' + '</tr>' + '<tr>' + '<td><b>Datum gereed:</b></td>' + '<td style="text-align:right"><input type="text" name="gereed_datum" size="10" readonly /></td>' + '</tr>' + (existing_opdracht ? '<tr>' + '<td><b>Foto locatie:</b></td>' + '<td align="right">' + (existing_opdracht.annotatie_tag ? existing_opdracht.annotatie_tag : 'n.v.t.') + '</td>' + '</tr>' : '<tr>' + '<td colspan="2"><b>Foto locaties:</b></td>' + '</tr>' + '<tr>' + '<td colspan="2"><div style="max-height: 130px; overflow-y: auto;" class="foto_locaties"></div></td>' + '</tr>') + '<tr>' + '<td colspan="2"><input type="button" value="Inplannen" class="inplannen" style="float: right"/></td>' + '</tr>' + '</table>' , onOpen: function() { var popup = getPopup(); // setup betrokkenen var dossier_subject_id = popup.find( '[name=dossier_subject_id]' ); $('#filterBetrokkene option').each(function(){ if (this.value) { var option = $($(this).outerHTML()); var email_bekend = parseInt( $(this).attr('email_bekend') ) ? true : false; if (!email_bekend) { option .attr( 'disabled', 'disabled' ).append( ' <i>(geen email adres bekend)</i>' ) .attr( 'value', '' ); } dossier_subject_id.append( option ); } }); // setup gereed datum var gereed_datum = popup.find( '[name=gereed_datum]' ); gereed_datum .datepicker({ dateFormat: "dd-mm-yy" }) .val( BRISToezicht.Tools.getDateDMY( new Date( new Date().valueOf() + (14*86400 /* +2 weeks */)*1000 ) ) ); // vind foto lokaties; let op, we werken hier door BTZ's eigen layer data heen, en // slaan de PDF annotator over! var foto_locaties = popup.find( '.foto_locaties' ); for (var bescheiden_id in BRISToezicht.Toets.data.layerdata) { var bescheiden = BRISToezicht.Toets.data.bescheiden[bescheiden_id]; var layers = BRISToezicht.Toets.data.layerdata[bescheiden_id].layers; for (var i in layers) { if (layers[i].metadata && layers[i].metadata.referenceId == vraag_id) { var layerPages = layers[i].pages; for (var p in layerPages) { var page = layerPages[p]; for (var j in page) { var layer = page[j]; if (layer.type == "photoassignment") { var photoId = layer.photoid; foto_locaties.append( $('<div>') .append( $('<input>').attr('type','checkbox').attr('photoId', photoId).attr('bescheiden_id',bescheiden_id) ) .append( ' ' ) .append( $('<b>').text( photoId ) ) .append( ' in ') .append( $('<i>').text( bescheiden.tekening_stuk_nummer.length ? bescheiden.tekening_stuk_nummer : bescheiden.bestandsnaam ) ) ); } } } } } } // if we have an existing opdracht, set its values now if (existing_opdracht) { // set gereed datum if (existing_opdracht.gereed_datum.match( /(\d{4})-(\d{2})-(\d{2})/ )) gereed_datum.val( RegExp.$3 + '-' + RegExp.$2 + '-' + RegExp.$1 ); else gereed_datum.val( existing_opdracht.gereed_datum ); // set betrokkene dossier_subject_id.val( existing_opdracht.dossier_subject_id ); // set opdracht omschrijving popup.find('[name=opdracht_omschrijving]').val( existing_opdracht.opdracht_omschrijving ); } // setup standaard opdrachten var standaardOpdrachten = BRISToezicht.Toets.Vraag.filterOpdrachten( BRISToezicht.Toets.data.vragen[vraag_id] ); var stBtn = popup.find( '.standaardopdrachten' ); var stTd = stBtn.closest('tr').next().children(); stBtn .val( stBtn.val() + ' (' + standaardOpdrachten.length + ')' ) .click( function() { stTd.toggle(); }); if (standaardOpdrachten.length) { for (var i=0; i<standaardOpdrachten.length; ++i) { var opdracht = standaardOpdrachten[i]; stTd.append( $('<div>') .text( opdracht.opdracht ) .css('cursor', 'pointer') .css('padding', '5px 10px') .css('background-color', '#f0f0f0') .css('border', '1px solid #777') .css('margin-bottom', '3px') .click(function(){ popup.find('[name=opdracht_omschrijving]').val( $(this).text() ); stTd.toggle(); }) ); } } else { stBtn.attr( 'disabled', 'disabled' ); } // setup inplannen button popup.find( 'input[type=button].inplannen' ).click(function(){ var dsid = dossier_subject_id.val(); if (!dsid || !dsid.length) { alert( 'Geen betrokkene geselecteerd.' ); return; } var opdracht_omschrijving = popup.find( 'textarea' ).val(); if (!opdracht_omschrijving || !opdracht_omschrijving.length) { alert( 'Geen opdracht omschrijving ingevuld.' ); return; } var datum = gereed_datum.val(); var fotoIds = []; foto_locaties.find( 'input[type=checkbox]:checked' ).each(function(){ fotoIds.push({ photoId: $(this).attr('photoId'), bescheiden_id: $(this).attr('bescheiden_id') }); }); if (!existing_opdracht) BRISToezicht.Toets.Opdracht.inplannen( vraag_id, // openPopup() parameter dsid, // lokale var opdracht_omschrijving, // lokale var datum, // lokale var fotoIds ); else BRISToezicht.Toets.Opdracht.bijwerken( existing_opdracht, dsid, // lokale var opdracht_omschrijving, // lokale var datum // lokale var ); closePopup(); }); } }); }, bijwerken: function( opdracht, dsid, opdracht_omschrijving, gereed_datum ) { // update interne administratie opdracht.dossier_subject_id = dsid; opdracht.opdracht_omschrijving = opdracht_omschrijving; opdracht.gereed_datum = gereed_datum; // voeg store-once data toe om dit commando server-side uit te voeren var data = { _command: 'opdrachtbewerken', vraag_id: opdracht.vraag_id, dossier_subject_id: dsid, opdracht_omschrijving: opdracht_omschrijving, gereed_datum: gereed_datum, tag: opdracht.tag }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); // update visually this.updateLijstInTab(); }, inplannen: function( vraag_id, dsid, opdracht_omschrijving, gereed_datum, foto_ids ) { var vraag = BRISToezicht.Toets.data.vragen[vraag_id]; if (!vraag) return; //var bbttt = BRISToezicht.Toets.data; //debugger; // maak opdrachten aan in onze interne administratie // ofwel 1 opdracht (als er geen foto locaties geselecteerd zijn) // ofwel maak een opdracht per geselecteerde foto locatie if (!foto_ids.length) { var tag = Math.random() + '-' + (new Date().toString()) + ' ' + (new Date().getUTCMilliseconds()); var opdracht = { status: 'nieuw', annotatie_tag: null, deelplan_id: BRISToezicht.Toets.data.deelplan_id, dossier_subject_id: dsid, email_verzonden: 0, gereed_datum: gereed_datum, id: 0, opdracht_omschrijving: opdracht_omschrijving, vraag_id: vraag_id, tag: tag, deelplanchecklist_id: BRISToezicht.Toets.data.deelplanchecklist_id }; vraag.geplande_opdrachten.push(opdracht); BRISToezicht.Toets.data.geplande_opdrachten.push(opdracht); // voeg store-once data toe om dit commando server-side uit te voeren var data = { _command: 'opdrachtinplannen', vraag_id: vraag_id, dossier_subject_id: dsid, opdracht_omschrijving: opdracht_omschrijving, gereed_datum: gereed_datum, foto_ids: foto_ids, tag: tag, deelplanchecklist_id: BRISToezicht.Toets.data.deelplanchecklist_id }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); } else { for (var i=0; i<foto_ids.length; ++i) { var tag = Math.random() + '-' + (new Date().toString()) + ' ' + (new Date().getUTCMilliseconds()) + '-' + foto_ids[i].photoId; var opdracht = { status: 'nieuw', annotatie_tag: foto_ids[i].photoId, deelplan_id: BRISToezicht.Toets.data.deelplan_id, dossier_subject_id: dsid, email_verzonden: 0, gereed_datum: gereed_datum, id: 0, opdracht_omschrijving: opdracht_omschrijving, vraag_id: vraag_id, tag: tag, deelplanchecklist_id: BRISToezicht.Toets.data.deelplanchecklist_id }; vraag.geplande_opdrachten.push(opdracht); BRISToezicht.Toets.data.geplande_opdrachten.push(opdracht); // voeg store-once data toe om dit commando server-side uit te voeren // doe dit PER FOTO zodat we een aparte tag kunnen hebben per opdracht var data = { _command: 'opdrachtinplannen', vraag_id: vraag_id, dossier_subject_id: dsid, opdracht_omschrijving: opdracht_omschrijving, gereed_datum: gereed_datum, foto_ids: [foto_ids[i]], tag: tag, deelplanchecklist_id: BRISToezicht.Toets.data.deelplanchecklist_id }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); } } // update visually this.updateLijstInTab(); }, updateLijstInTab: function() { // update label var noticaties = $('#nlaf_TotaalAantalOpdrachten' ); var vraag = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (vraag && vraag.geplande_opdrachten.length) noticaties.show().text( vraag.geplande_opdrachten.length ); else noticaties.hide(); // performance: check of update van content verder wel nodig is if (this.toonAlleOpdrachten && this.contentIsAlleOpdrachten) return; this.contentIsAlleOpdrachten = this.toonAlleOpdrachten; // voor performance: zet 1x de opdrachten tabel reference, hergebruik daarna if (!this.tabel) this.tabel = $('table.opdrachten-tabel.rows'); // leeg de lijst van opdrachten this.tabel.find( 'tr:not(.header)' ).remove(); // bekijk wel opdrachten lijst we gaan tonen, ofwel ALLE opdrachten, ofwel die van // de huidige vraag var opdrachten; if (this.toonAlleOpdrachten) { opdrachten = BRISToezicht.Toets.data.geplande_opdrachten; } else { // kijk welke vraag er geselecteerd is. is er geen vraag geselecteerd dan // verder niks doen (het geval wanneer er een onderwerp geselecteerd is!) if (!vraag) { noticaties.hide(); return; } opdrachten = vraag.geplande_opdrachten; } // voeg tr toe per opdracht for (var i=0; i<opdrachten.length; ++i) { var opdracht = opdrachten[i]; var subject = BRISToezicht.Toets.data.subjecten[opdracht.dossier_subject_id]; if (subject) { var subject_naam = subject.naam; } else { var subject_naam = ''; } var have_opties = opdracht.status == 'nieuw'; $('<tr>') .attr('tag', opdracht.tag) .append( $('<td style="width:300px">').text(opdracht.opdracht_omschrijving) ) .append( $('<td style="width:130px">').text(opdracht.annotatie_tag ? opdracht.annotatie_tag : 'n.v.t.' ) ) .append( $('<td style="width:130px">').text(subject_naam) ) .append( $('<td style="width:70px">').text(this.ymdToDMY( opdracht.gereed_datum ) ) ) .append( $('<td style="width:70px">').text(opdracht.status == 'nieuw' ? 'nee' : 'ja') ) .append( optiesTD = $('<td style="width:50px">') ) .appendTo( this.tabel ); if (have_opties) { optiesTD .append( $('<i class="icon-pencil" style="cursor:pointer; font-size: 12pt; margin-right: 15px;"></i>') .data('opdracht', opdracht ) .click(function(){ BRISToezicht.Toets.Opdracht.editOpdracht( this ); }) ) .append( $('<i class="icon-trash" style="cursor:pointer; font-size: 12pt"></i>') .data('opdracht', opdracht ) .click(function(){ BRISToezicht.Toets.Opdracht.deleteOpdracht( this ); }) ); } } }, editOpdracht: function( i ) { var vraag = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraag) { return; } var opdracht = $(i).data('opdracht'); BRISToezicht.Toets.Opdracht.openPopup( vraag.vraag_id, opdracht ); }, deleteOpdracht: function( i ) { var vraag = BRISToezicht.Toets.Vraag.getHuidigeVraagData(); if (!vraag) { return; } var opdracht = $(i).data('opdracht'); showMessageBox({ message: 'Deze opdracht werkelijk verwijderen?', width: 500, onClose: function( res ) { if (res == 'ok') { // delete opdracht in interne administratie for (var i=0; i<vraag.geplande_opdrachten.length; ++i) { if (vraag.geplande_opdrachten[i].tag == opdracht.tag) { vraag.geplande_opdrachten.splice( i, 1 ); break; } } // voeg store-once data toe om dit commando server-side uit te voeren var data = { _command: 'opdrachtverwijderen', vraag_id: opdracht.vraag_id, tag: opdracht.tag }; BRISToezicht.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); // update visually BRISToezicht.Toets.Opdracht.updateLijstInTab(); } } }); }, toonAlles: function() { this.toonAlleOpdrachten = true; this.updateLijstInTab(); }, toonRelevant: function() { this.toonAlleOpdrachten = false; this.updateLijstInTab(); } } <file_sep>PDFAnnotator.Handle.MeasureDelete = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0.16, 1, baseurl + 'images/nlaf/edit-handle-measure-delete.png', 32, 32, 'click', this.execute, null, 1 /*inside*/, -1 /*outside*/ ); }, execute: function() { /* this.editable is eigenlijk de measure tool helper window! */ /* this.editable.owner is de measure tool! */ var measureTool = this.editable.owner; if (measureTool.calibrated()) if (confirm( 'Calibratie werkelijk overnieuw uitvoeren?' )) measureTool.reset(); } }); <file_sep><?php class Root extends Controller { function Root() { if (preg_match( '#/online_check#', $_SERVER['REQUEST_URI'] )) $this->online_check(); // super fast online check if (preg_match( '#/fetch_integration#', $_SERVER['REQUEST_URI'] )) define( 'SKIP_TOKEN_VALIDATION', true ); parent::Controller(); $this->navigation->set_active_tab( 'dossierbeheer' ); } function index() { // if not logged in, redirect go user login if (!$this->login->logged_in()) { redirect( '/gebruikers/inloggen' ); } else { $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); $this->load->library( 'deviceinfo' ); if ($this->deviceinfo->is_tablet_type()) // telefoons redirect( '/tablet' ); else if ($this->deviceinfo->is_phone_type()) // tablets redirect( '/telefoon' ); else{ // PC's (overig) if($klant->dossiers_als_startpagina_openen==1){ redirect( '/dossiers' ); } else redirect( '/intro' ); } } } function online_check() { header( 'Content-Type: text/plain' ); echo "BTZ Online"; exit; } function session_check() { header( 'Content-Type: text/plain' ); if ($this->login->logged_in()) echo( 'BTZ Logged in' ); else echo( 'BTZ Logged out' ); } function versie() { $this->navigation->push( 'nav.versieinformatie', '/versie' ); $elements = preg_split( '/^(v[\d+\.]+[a-z]?)$/m', file_get_contents( APPPATH . '/../docs/versiebeheer.txt' ), 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $versies = array(); for ($i=0; $i<sizeof($elements); $i += 2) { $info = preg_split( '/^(Releasedatum.*?)$/m', trim($elements[$i + 1]), 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $versies[] = array( 'versie' => $elements[$i], 'datum' => preg_replace( '/Releasedatum:\s+/', '', $info[0] ), 'tekst' => trim( $info[1] ), ); } $this->load->view( 'root/versie', array( 'versies' => $versies, ) ); } function apptoegang( $zetmodus=null, $wachtwoordfout=null ) { $this->navigation->push( 'nav.apptoegang', '/root/apptoegang' ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); switch ($zetmodus) { case 'inschakelen': $gebruiker->app_toegang = 1; $gebruiker->save(); redirect( '/root/apptoegang' ); break; case 'uitschakelen': $gebruiker->app_toegang = 0; $gebruiker->save(); redirect( '/root/apptoegang' ); break; } if (isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST') { if (strlen($_POST['password']) || strlen($_POST['password'])) { if (strlen($_POST['password']) < 6) redirect( '/root/apptoegang/-/1' ); else if ($_POST['password'] != $_POST['password']) redirect( '/root/apptoegang/-/2' ); else { $num_letters = 0; $num_cijfers = 0; $num_hoofdletters = 0; $num_kleineletters = 0; $num_specialetekens = 0; for ($i=0; $i<strlen($_POST['password']); ++$i) { $c = $_POST['password'][$i]; if ($c >= '0' && $c<='9') ++$num_cijfers; else if ($c >= 'a' && $c<='z') { ++$num_kleineletters; ++$num_letters; } else if ($c >= 'A' && $c<='Z') { ++$num_hoofdletters; ++$num_letters; } else ++$num_specialetekens; } if (!$num_letters || !$num_cijfers || !$num_kleineletters || !$num_hoofdletters || !$num_specialetekens) redirect( '/root/apptoegang/-/3' ); // sla wachtwoord op $gebruiker->wachtwoord = sha1($_POST['password']); if (!$gebruiker->save( 0, 0, 0 )) redirect( '/root/apptoegang/-/4' ); // ga naar hoofdpagina redirect(); } } redirect(); } $errors = null; if (!is_null( $wachtwoordfout )) { switch ($wachtwoordfout) { case 1: $errors[] = 'error.wachtwoord.minstens.6,karakters'; break; case 2: $errors[] = 'error.wachtwoord.niet.gelijk'; break; case 3: $errors[] = 'error.wachtwoord.voldoet.niet'; break; case 4: $errors[] = 'error.wachtwoord.database.fout'; break; } } $this->load->view( 'root/apptoegang', array( 'errors' => $errors, 'app_toegang' => $gebruiker->app_toegang, 'heeft_wachtwoord' => strlen( $gebruiker->wachtwoord ) > 0, 'laatste_tijdstip' => $gebruiker->app_toegang_laatste_tijdstip, 'email' => $gebruiker->email, ) ); } } <file_sep>-- pdf annotator is recht 26 -- modus 2 = alle INSERT INTO rol_rechten (rol_id, recht, modus) SELECT id, 26, 2 FROM rollen WHERE naam NOT LIKE '[BL]%' OR naam = '[BL] Beheerder'; -- phone interface is recht 27 -- modus 2 = alle INSERT INTO rol_rechten (rol_id, recht, modus) SELECT id, 27, 2 FROM rollen WHERE naam NOT LIKE '[BL]%' OR naam = '[BL] Beheerder'; <file_sep><?php class PDFAnnotator extends Controller { public function __construct() { global $method; if ($method == 'line') define( 'SKIP_SESSION', true ); parent::__construct(); $this->load->library( 'pdfannotatorlib' ); if (!$this->pdfannotatorlib->allow()) throw new Exception( 'Geen toegang tot PDF annotator.' ); } public function index( $jump_to_page=null ) { require_once( PDFANNOTATOR_CODE_PATH . 'index.php' ); } public function pageimage( $pagenum=null, $timestamp=null, $version=null, $guid=null ) { $_GET['i'] = $pagenum; if (!is_null( $guid )) $_GET['guid'] = rawurldecode( $guid ); require_once( PDFANNOTATOR_CODE_PATH . 'image.php' ); } public function overview( $guid=null ) { if (!is_null( $guid )) $_GET['guid'] = rawurldecode( $guid ); require_once( PDFANNOTATOR_CODE_PATH . 'overview.php' ); } public function upload_document() { require_once( PDFANNOTATOR_CODE_PATH . 'upload.php' ); } public function wait() { require_once( PDFANNOTATOR_CODE_PATH . 'wait.php' ); } public function delete() { require_once( PDFANNOTATOR_CODE_PATH . 'delete.php' ); } public function image_tools( $page=null, $command=null ) { $_GET['i'] = $page; $_GET['command'] = $command; require_once( PDFANNOTATOR_CODE_PATH . 'image-tools.php' ); } public function line( $size=null, $direction=null, $color=null ) { $_GET['s'] = $size; $_GET['a'] = $direction; $_GET['c'] = $color; require_once( PDFANNOTATOR_CODE_PATH . 'line.php' ); } public function download() { require_once( PDFANNOTATOR_CODE_PATH . 'download.php' ); } public function annotations() { require_once( PDFANNOTATOR_CODE_PATH . 'annotations.php' ); } public function upload_url_set() { require_once( PDFANNOTATOR_CODE_PATH . 'upload-url-set.php' ); } public function upload_url_set_deelplan( $deelplan_id ) { // get deelplan $this->load->model( 'deelplan' ); if (!($deelplan = $this->deelplan->get( $deelplan_id ))) throw new Exception( 'Ongeldig deelplan ID opgegeven.' ); // bake data structure $documents = array(); foreach ($deelplan->get_bescheiden( false ) as $bescheiden) { $document = (object)array( 'filename' => $bescheiden->bestandsnaam, 'pages' => array(), 'external_data' => array( 'document_id' => $bescheiden->id, ), ); $local_filename = dirname(__FILE__) . '/pdfview-cache/bescheiden/' . $bescheiden->id . '.jpg'; if (file_exists( $local_filename )) $document->pages[] = (object)array( 'local' => $local_filename, 'filename' => $bescheiden->bestandsnaam . '.jpg', ); else { if (!preg_match( '/(\..*?)$/', $bescheiden->bestandsnaam, $matches )) $extension = ''; else $extension = strtolower( $matches[1] ); // geen JPG of PNG bestand? dan niks doen (nog niet geconverteerd!) if (!in_array( $extension, array( '.jpg', '.jpeg', '.png' ))) continue; $bescheiden->laad_inhoud(); if (!strlen( $bescheiden->bestand )) throw new Exception( 'Kon bescheiden ' . $bescheiden->id . ' niet laden.' ); $document->pages[] = (object)array( 'contents' => base64_encode( $bescheiden->bestand ), 'filename' => $bescheiden->bestandsnaam, ); } $documents[] = $document; } // setup POST data and load PDF annotator code $_POST['quality'] = 'high'; $_POST['documents'] = json_encode( $documents ); require_once( PDFANNOTATOR_CODE_PATH . 'upload-url-set.php' ); } public function store_photo() { try { // upload goed gegaan? if (!isset( $_FILES['photo'] ) || !$_FILES['photo']['size'] || $_FILES['photo']['error'] ) throw new Exception( 'Upload mislukt.' ); // upload inladen if (false === ($contents = @file_get_contents( $_FILES['photo']['tmp_name'] ))) throw new Exception( 'Server schijffout bij verwerken van upload.' ); // laad deelplan $this->load->model( 'deelplan' ); if (!($deelplan = $this->deelplan->get( @$_POST['deelplan_id'] ))) throw new Exception( 'Ongeldig deelplan ID.' ); // laad vraag $this->load->model( 'vraag' ); if (!($vraag = $this->vraag->get( @$_POST['vraag_id'] ) )) throw new Exception( 'Ongeldig vraag ID.' ); // bestandsnaam voor de foto if (!($filename = @$_POST['filename'])) throw new Exception( 'Lege bestandsnaam niet toegestaan.' ); // opslaan! $this->load->model( 'deelplanupload' ); $this->db->trans_start(); $du = $this->deelplanupload->add( $deelplan->id, $vraag->id, $filename, $contents ); if (!$du) { $this->db->_trans_status = false; $this->db->trans_complete(); throw new Exception( 'Fout bij opslaan van annotatie foto in de database (1).' ); } if (!$this->db->trans_complete()) throw new Exception( 'Fout bij opslaan van annotatie foto in de database (2).' ); die( $du->id . ':' . json_encode((object)array( 'id' => $du->id, 'filename' => htmlentities( $du->filename ), 'url' => htmlentities( $du->get_download_url() ), 'thumbnail_url' => htmlentities( $du->get_download_url( true ) ), 'delete_url' => htmlentities( $du->get_delete_url() ), 'auteur' => $du->get_auteur(), 'has_thumbnail' => 1, 'uploaded_at' => date('Y-m-d H:i:s'), ) ) ); } catch (Exception $e) { die( $e->getMessage() ); } } } <file_sep>ALTER TABLE project_mappen ADD COLUMN is_bw BOOLEAN DEFAULT 0 AFTER is_active; <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_beheer')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('grondslag_document_beheer'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <form method="POST"> <table style="min-width: 500px"> <tr> <th style="text-align:left">Grondslag</th> <th style="text-align:left">Document ID</th> <th style="text-align:left">Account</th> </tr> <? foreach ($grondslagen as $grondslag): ?> <tr style="<?=$grondslag->quest_document ? '' : 'color:red;'?>"> <td><?=$grondslag->grondslag?></td> <td><input type="text" name="documentid[<?=$grondslag->id?>]" value="<?=$grondslag->quest_document?>" size="40" maxlength="64" /></td> <td><?=$grondslag->get_klant()->naam?></td> <td> <? if ($grondslag->quest_document): ?> <a target="_blank" href="http://quest.bris.nl/DocumentVersion/Details/<?=$grondslag->quest_document?>">Bekijk in Quest</a> <? endif; ?> </td> </tr> <? endforeach; ?> <tr> <td></td> <td><input type="submit" value="<?=tgg('form.opslaan')?>" /></td> </tr> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class DeelplanVraagAandachtspuntResult extends BaseResult { function DeelplanVraagAandachtspuntResult( &$arr ) { parent::BaseResult( 'deelplanvraagaandachtspunt', $arr ); } } class DeelplanVraagAandachtspunt extends BaseModel { function DeelplanVraagAandachtspunt() { parent::BaseModel( 'DeelplanVraagAandachtspuntResult', 'deelplan_vraag_ndchtspntn', true ); } public function check_access( BaseResult $object ) { // disabled for model } function add( $deelplan_id, $deelplan_aandachtspunt_id, $vraag_id ) { /* if (!$this->dbex->is_prepared( 'DeelplanVraagAandachtspunt::add' )) $this->dbex->prepare( 'DeelplanVraagAandachtspunt::add', 'INSERT INTO deelplan_vraag_ndchtspntn (deelplan_id, deelplan_aandachtspunt_id, vraag_id) VALUES (?, ?, ?)' ); $args = array( 'deelplan_id' => $deelplan_id, 'deelplan_aandachtspunt_id' => $deelplan_aandachtspunt_id, 'vraag_id' => $vraag_id, ); $this->dbex->execute( 'DeelplanVraagAandachtspunt::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'deelplan_id' => $deelplan_id, 'deelplan_aandachtspunt_id' => $deelplan_aandachtspunt_id, 'vraag_id' => $vraag_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function get_by_deelplan_id( $deelplan_id ) { return $this->search( array( 'deelplan_id' => $deelplan_id ) ); } } <file_sep>-- chmod 777 application/libraries/imageprocessor -- -- run of watch (via crontab): -- php index.php /cli/convert_bescheiden <file_sep>UPDATE `bt_vragen` SET aanwezigheid = NULL WHERE aanwezigheid = 31; <file_sep>ALTER TABLE `bt_richtlijnen` ADD `url_beschrijving` VARCHAR( 256 ) NULL DEFAULT NULL AFTER `url` ; <file_sep><? require_once 'base.php'; class WebserviceAccountRechtResult extends BaseResult { function WebserviceAccountRechtResult( &$arr ) { parent::BaseResult( 'webserviceaccountrecht', $arr ); } function get_webservice_account() { $this->_CI->load->model( 'webserviceaccount' ); return $this->_CI->webserviceaccount->get( $this->webservice_account_id ); } function get_webservice_component() { $this->_CI->load->model( 'webservicecomponent' ); return $this->_CI->webservicecomponent->get( $this->webservice_component_id ); } } class WebserviceAccountRecht extends BaseModel { function WebserviceAccountRecht() { parent::BaseModel( 'WebserviceAccountRechtResult', 'webservice_account_rechten', true ); } public function check_access( BaseResult $object ) { // disabled for model } public function get_by_webservice_account( $webservice_account_id ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_by_webservice_account'; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE webservice_account_id = ?' ); $res = $CI->dbex->execute( $stmt_name, array( $webservice_account_id ) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row, false ); $res->free_result(); return $result; } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'deelplannen')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Importeren', 'width' => '900px' )); ?> <p> Met deze functionaliteit kunt u dossiers importeren.<br/> </p> <p> <img src="<?=site_url('/files/images/letop.png')?>"/> LET OP! Lees de beperkingen van deze functionaliteit. <img src="<?=site_url('/files/images/letop.png')?>"/> <ul> <li>U kunt alleen identificatienummer, een dossiernaam, locatie gegevens, de aanmaakdatum en de geplande datum importeren.</li> <li>Het systeem herkent bestaande dossiers op basis van het identificatienummer, geimporteerde dossiers worden <b>toegevoegd</b> als het kenmerk onbekend is, of <b>bijgewerkt</b> als het al voorkomt! <li>U kunt uitsluitend CSV bestanden importeren, geen Excel bestanden.</li> </ul> </p> <p> <input type="checkbox" name="gelezen" /> Ik heb bovenstaande beperkingen gelezen en begrepen. </p> <p> <input type="button" name="volgende" value="Volgende" /> </p> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <script type="text/javascript"> $(document).ready(function(){ $('input[type=button][name=volgende]').click(function(){ if ($('input[type=checkbox][name=gelezen]')[0].checked) { location.href = '/dossiers/importeren/2'; } else alert( 'U heeft nog niet aangegeven de lijst van beperkingen te hebben gelezen.' ); }); }); </script> <? $this->load->view('elements/footer'); ?><file_sep> -- deelplan_checklisten CREATE TABLE bck_20151221_deelplan_checklisten SELECT * FROM deelplan_checklisten; DROP TABLE deelplan_checklisten; CREATE TABLE deelplan_checklisten ( id int(11) NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, checklist_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, toezicht_gebruiker_id int(11) DEFAULT NULL, matrix_id int(11) DEFAULT NULL, initiele_datum date DEFAULT NULL, initiele_start_tijd char(8) DEFAULT NULL, initiele_eind_tijd char(8) DEFAULT NULL, voortgang_percentage int(11) NOT NULL DEFAULT 0, voortgang_gestart_op datetime DEFAULT NULL, PRIMARY KEY (id), INDEX checklist_id (checklist_id), INDEX matrix_id (matrix_id), INDEX toezicht_gebruiker_id (toezicht_gebruiker_id), UNIQUE INDEX UK_deelplan_checklisten_dcb (deelplan_id, checklist_id, bouwnummer_id), CONSTRAINT deelplan_checklisten_ibfk_4 FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_5 FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_6 FOREIGN KEY (toezicht_gebruiker_id) REFERENCES gebruikers (id) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT deelplan_checklisten_ibfk_7 FOREIGN KEY (matrix_id) REFERENCES matrices (id) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET latin1; INSERT INTO deelplan_checklisten SELECT NULL, deelplan_id, checklist_id, NULL, toezicht_gebruiker_id, matrix_id, initiele_datum, initiele_start_tijd, initiele_eind_tijd, voortgang_percentage, voortgang_gestart_op FROM bck_20151221_deelplan_checklisten; -- DROP TABLE bck_20151221_deelplan_checklisten; -- supervision_moments_cl CREATE TABLE bck_20151221_supervision_moments_cl SELECT * FROM supervision_moments_cl; DROP TABLE supervision_moments_cl; CREATE TABLE supervision_moments_cl ( id int(10) UNSIGNED NOT NULL AUTO_INCREMENT, deelplan_id int(11) NOT NULL, checklist_id int(11) NOT NULL, bouwnummer_id int(11) DEFAULT NULL, supervision_start datetime NOT NULL, supervision_end datetime DEFAULT NULL, progress_start float NOT NULL, progress_end float DEFAULT NULL, supervisor_user_id int(11) NOT NULL, PRIMARY KEY (id), INDEX checklist_id (checklist_id), INDEX deelplan_id (deelplan_id), INDEX supervisor_user_id (supervisor_user_id), CONSTRAINT FK_s_m_cl__cl_id FOREIGN KEY (checklist_id) REFERENCES bt_checklisten (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_s_m_cl__d_id FOREIGN KEY (deelplan_id) REFERENCES deelplannen (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_s_m_cl__g_id FOREIGN KEY (supervisor_user_id) REFERENCES gebruikers (id) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; INSERT INTO supervision_moments_cl SELECT id, deelplan_id, checklist_id, NULL, supervision_start, supervision_end, progress_start, progress_end, supervisor_user_id FROM bck_20151221_supervision_moments_cl; -- DROP TABLE bck_20151221_supervision_moments_cl; -- deelplan_vragen ALTER TABLE `deelplan_vragen` DROP KEY `UK__deelplan_vragen__d_id__v_id`; ALTER TABLE `deelplan_vragen` ADD COLUMN bouwnummer_id int(11) DEFAULT NULL AFTER `vraag_id`; -- deelplan_uploads ALTER TABLE `deelplan_uploads` ADD COLUMN bouwnummer_id int(11) DEFAULT NULL AFTER `gebruiker_id`; -- deelplan_vraag_geschiedenis ALTER TABLE `deelplan_vraag_geschiedenis` DROP FOREIGN KEY `deelplan_vraag_geschiedenis_ibfk_7`; ALTER TABLE `deelplan_vraag_geschiedenis` ADD COLUMN bouwnummer_id int(11) DEFAULT NULL AFTER `vraag_id`; <file_sep>-- Add the following columns to the 'dossiers' table so we can make a 1-on-1 association between BT and BTZ dossiers. ALTER TABLE dossiers ADD COLUMN `bt_dossier_id` int(11) DEFAULT NULL; ALTER TABLE dossiers ADD COLUMN `bt_dossier_hash` varchar(40) DEFAULT NULL; -- Add indexes for them too. ALTER TABLE dossiers ADD KEY `idx_bt_dossier_id` (`bt_dossier_id`); ALTER TABLE dossiers ADD KEY `idx_bt_dossier_hash` (`bt_dossier_hash`); <file_sep>ALTER TABLE `gebruikers` ADD `app_toegang` TINYINT NOT NULL DEFAULT '0'; ALTER TABLE `gebruikers` ADD `app_toegang_laatste_tijdstip` DATETIME NULL DEFAULT NULL ; <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.bekijken::open_close_alle_deelplannen', 'Open / close alle deelplannen', NOW(), 0);<file_sep><? require_once 'base.php'; class RolResult extends BaseResult { function RolResult( &$arr ) { parent::BaseResult( 'rol', $arr ); } function get_rol_rechten() { return get_instance()->rolrecht->get_by_rol( $this->id ); } function to_string() { return $this->naam; } } class Rol extends BaseModel { function Rol() { parent::BaseModel( 'RolResult', 'rollen' ); } public function check_access( BaseResult $object ) { if ($object && $object->klant_id==null) return; return parent::check_access( $object ); } function add( $klant_id, $naam ) { /* if (!$this->dbex->is_prepared( 'add_rol' )) $this->dbex->prepare( 'add_rol', 'INSERT INTO rollen (klant_id, naam, gemaakt_door_gebruiker_id) VALUES (?, ?, ?)' ); $args = array( 'klant_id' => $klant_id, 'naam' => $naam, 'gemaakt_door_gebruiker_id' => $this->login->get_user_id(), ); $res = $this->dbex->execute( 'add_rol', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'klant_id' => $klant_id, 'naam' => $naam, 'gemaakt_door_gebruiker_id' => $this->login->get_user_id(), ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function get_for_klant( $klant_id, $search=null ) { $this->_CI->dbex->prepare( 'Rol::get_for_klant', $query = ' SELECT * FROM rollen WHERE ' . (is_null($klant_id) ? 'klant_id IS NULL' : 'klant_id = ?') . ' AND is_lease=0 AND naam LIKE ? ' ); $args = is_null( $klant_id ) ? array() : array( $klant_id ); $args[] = '%' . $search . '%'; $res = $this->dbex->execute( 'Rol::get_for_klant', $args ); $result = array(); foreach ($res->result() as $row) $result[ $row->id ] = $this->getr( $row ); return $result; } public function get_toekenbare_rollen_for_huidige_klant() { $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); if (!$gebruiker) return array(); $klant = $gebruiker->get_klant(); //OLD FUNCTIONALITY START /*if ($klant->get_lease_configuratie()) { // The following call did not correctly take the lease configuration restrictions into account for roles of which 'is_lease' is set to '1', but // that belong to different client's lease confifurations, causing roles to be fetched that belong to other lease configurations, which in turn // results in a security exception being thrown, because access is requested to a role that doesn't belong to the current client. // Passing the added $extra_query SQL part (i.e. the second parameter) solves this. //return $this->search( array( 'is_lease' => 1 ), null, true ); if($klant->parent_id){ return $this->search( array( 'is_lease' => 0 ), "(klant_id IS NULL) OR (klant_id = {$klant->id})", true ); } else return $this->search( array( ), "(klant_id IS NULL) OR (klant_id = {$klant->id})", true ); }*/ //OLD FUNCTIONALITY END $allow_systeem_rollen = $this->rechten->geef_recht_modus( RECHT_TYPE_SITEBEHEER ) != RECHT_MODUS_GEEN; // For some reason the 'client specific' roles were not requested correctly, as the second parameter was set to 'true' whereas a textual search string // is expected in the 'get_for_klant' method! This caused the situation that no client specific roles could be found! //$result = $this->get_for_klant( $gebruiker->klant_id, true ); $result = $this->get_for_klant( $gebruiker->klant_id, '' ); $r2 = $this->get_for_klant( null, '' ); foreach ($r2 as $rol_id => $rol) if ($allow_systeem_rollen || $rol->type != 'systeem') $result[$rol_id] = $rol; uasort( $result, function( $a, $b ) { return strcasecmp( $a->naam, $b->naam ); }); return $result; } public function get_gebruik_tellers() { $res = $this->db->query( ' SELECT COUNT(*) AS count, rol_id FROM gebruikers GROUP BY rol_id '); $result = array(); foreach ($res->result() as $row) $result[$row->rol_id] = $row->count; $res->free_result(); return $result; } public function get_beheer_default() { $res = $this->_CI->db->query( 'SELECT * FROM rollen WHERE is_beheer_default = 1' ); if ($res->num_rows() != 1) throw new Exception( 'Niet 1, maar ' . $res->num_rows() . ' beheer default rollen gevonden. Niet toegestaan.' ); $row = reset($res->result()); $result = $this->getr( $row ); $res->free_result(); return $result; } public function get_toezichthouder_default() { $res = $this->_CI->db->query( 'SELECT * FROM rollen WHERE is_toezichthouder_default = 1' ); if ($res->num_rows() != 1) throw new Exception( 'Niet 1, maar ' . $res->num_rows() . ' toezichthouder default rollen gevonden. Niet toegestaan.' ); $row = reset($res->result()); $result = $this->getr( $row ); $res->free_result(); return $result; } } <file_sep><?php class CI_GoogleMaps { private $CI; private $_curl; public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'curl' ); $this->_curl = $this->CI->curl->create(); } /** Attepts to return a directions summary for the route with the given parameters, * returns a GoogleMapsDirectionsSummary object. * * @param $params Direction parameters * @param $on_exception Optional, if specified must be callable, only called when things fail, * if omitted an exception is thrown during errors. * @return An instance of GoogleMapsDirectionsSummary containing the summary */ public function get_directions_summary( GoogleMapsDirectionsParameters $params, $on_exception=null ) { $url = 'https://maps.googleapis.com/maps/api/directions/json' . $params->get_url_string(); $this->_curl->set_url( $url ); try { $result = $this->_curl->execute( true ); if (!is_object( $data = @json_decode( $result ) )) throw new Exception( 'Google Maps call did not yield proper JSON object, but: ' . $result ); if (!is_array( $data->routes ) || empty( $data->routes )) throw new Exception( 'Google Maps call did not return any routes' ); $route = $data->routes[0]; if (!is_array( $route->legs ) || empty( $route->legs )) throw new Exception( 'Google Maps call did not return any legs in first route' ); $leg = $route->legs[0]; if (!isset( $leg->distance ) || !isset( $leg->duration ) || !isset( $leg->end_location )) throw new Exception( 'Google Maps call did not return any distance or duration information in first route\'s first leg' ); $summary = new GoogleMapsDirectionsSummary(); $summary->distance_km = round( $leg->distance->value / 1000 ); $summary->duration_mins = round( $leg->duration->value / 60 ); $summary->end_location_lat = $leg->end_location->lat; $summary->end_location_lng = $leg->end_location->lng; return $summary; } catch (Exception $e) { if (is_callable( $on_exception )) return $on_exception( $e ); throw $e; } } public function geocode( GoogleMapsGeocodeParameters $params, $on_exception=null ) { $url = 'https://maps.googleapis.com/maps/api/geocode/json' . $params->get_url_string(); $this->_curl->set_url( $url ); try { $result = $this->_curl->execute( true ); if (!is_object( $data = @json_decode( $result ) )) throw new Exception( 'Google Maps call did not yield proper JSON object, but: ' . $result ); if (!is_array( $data->results ) || empty( $data->results )) throw new Exception( 'Google Maps call did not return any results' ); $result = $data->results[0]; if (!isset( $result->geometry )) throw new Exception( 'Google Maps call did not return any result with geometry' ); if (!isset( $result->geometry->location )) throw new Exception( 'Google Maps call did not return any result with geometry location' ); if (!isset( $result->geometry->location->lat ) || !isset( $result->geometry->location->lng )) throw new Exception( 'Google Maps call did not return any result with geometry location data' ); $summary = new GoogleMapsGeocodeSummary(); $summary->lat = $result->geometry->location->lat; $summary->lng = $result->geometry->location->lng; return $summary; } catch (Exception $e) { if (is_callable( $on_exception )) return $on_exception( $e, $result ); throw $e; } } } class GoogleMapsDirectionsParameters { public $origin; public $destination; public function __construct( $origin, $destination ) { $this->origin = $origin; $this->destination = $destination; } public function get_url_string( $prefix='?' ) { return $prefix . 'sensor=false&origin=' . rawurlencode($this->origin) . '&destination=' . rawurlencode($this->destination); } } class GoogleMapsDirectionsSummary { public $distance_km; public $duration_mins; public $end_location_lat; public $end_location_lng; } class GoogleMapsGeocodeParameters { public $address; public function __construct( $address ) { $this->address = $address; } public function get_url_string( $prefix='?' ) { return $prefix . 'sensor=false&address=' . rawurlencode($this->address); } } class GoogleMapsGeocodeSummary { public $lat; public $lng; }<file_sep>#!/usr/bin/php <?php try { require_once "version.php"; if (isset( $argv[1] )) $view_filename = $argv[1]; else $view_filename = '../../application/views/pdf-annotator/html-head.php'; // get list (and proper order) of js files $header = @file_get_contents( $view_filename ); if ($header === false) throw new Exception( 'Failed to load ' . $view_filename . ', optionally specify filename as first paramter to this script.' ); if (!preg_match_all( '/^\s*\'(.*?\.js)\',?\s*$/msi', $header, $matches )) die( 'Couldn\'t find js file array in ' . $view_filename ); $jsfiles = $matches[1]; // concatenate into one big ass string echo "Concatenating...\n"; $fulljs = ''; foreach ($jsfiles as $jsfile) { $js = file_get_contents( 'js/' . $jsfile ); if (preg_match( '#,(?=\s*[\\)\\}\\]])#ms', $js, $matches, PREG_OFFSET_CAPTURE )) { $offset = $matches[0][1]; $line = 1; for ($i=0; $i<$offset; ++$i) if ($js[$i] == "\n") ++$line; echo( 'Found a trailing , in file ' . $jsfile . " on line $line: '" . $matches[0][0] . "'!\n" ); } $fulljs .= '/** @SOURCE: ' . $jsfile . ' */' . "\n" . $js . "\n"; } // write to disk $fullpath = 'js/PDFAnnotator-' . PDFANNOTATOR_VERSION . '.js'; file_put_contents( $fullpath, $fulljs ); // compress that file echo "Compressing " . $fullpath . "...\n"; exec( 'java -jar ../../docs/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar ' . escapeshellarg($fullpath) . ' -o ' . escapeshellarg($fullpath) ); // echo compression rate $oldsize = strlen($fulljs); $newsize = filesize($fullpath); echo 'Compression: from ' . $oldsize . ' to ' . $newsize. ' (' . round(100 * $newsize / $oldsize) . '% left)' . "\n"; // check if there's still changes to be committed exec( 'svn st js | grep -v ?', $lines ); if (!empty( $lines )) die( 'The js/ directory is not (svn) clean. Commit first!' . "\n" ); // add compressed file exec( 'svn add ' . escapeshellarg($fullpath) ); // remove old files echo "Deleting original js/ files...\n"; foreach ($jsfiles as $jsfile) exec( 'svn delete ' . escapeshellarg( 'js/' . $jsfile ) ); } catch (Exception $e) { error_log( "ERROR: " . $e->getMessage() ); exit(1); } <file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoanalyse')); ?> <form name="form" method="post"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => tg('effecten') . ' - ' . htmlentities( $checklist->naam, ENT_COMPAT, 'UTF-8'), 'width' => '920px' ) ); ?> <h2>MATRIX: <?=htmlentities($matrix->naam, ENT_COMPAT, 'UTF-8')?></h2> <? $list_view_data = array( 'minwidth' => '880px', 'height' => '300px', 'headers' => array( array( 'text' => '', 'width' => '50px', 'align' => 'right' ), array( 'text' => tg('effect'), 'width' => '500px', 'align' => 'left' ), array( 'text' => tg('factor'), 'width' => '150px', 'align' => 'left' ), array( 'text' => tg('acties'), 'width' => '100px', 'align' => 'left' ), ), 'rows' => array( ), 'flat' => true, 'listclasses' => array( 'editlist' ), ); $i=0; foreach ($effecten as $effect) { $opties = array( '<a href="javascript:void(0);" onclick="if (confirm( \'Wilt u dit effect werkelijk verwijderen? Als er al een ingevulde risicoanalyse aanwezig is voor dit effect, zult u die gegevens kwijt raken!\')) location.href=\'' . site_url('/instellingen/risicoanalyse_effect_verwijderen/'.$checklist->id.'/'.$matrix->id.'/'.$effect->get_id()). '\';"><img src="' . site_url('/content/png/delete'). '" /></a>', '<a href="' . site_url('/instellingen/risicoanalyse_effect_omhoog/'.$checklist->id.'/'.$matrix->id.'/'.$effect->get_id()). '"><img src="' . site_url('/content/png/up'). '" /></a>', '<a href="' . site_url('/instellingen/risicoanalyse_effect_omlaag/'.$checklist->id.'/'.$matrix->id.'/'.$effect->get_id()). '"><img src="' . site_url('/content/png/down'). '" /></a>', ); $list_view_data['rows'][] = array( 'values' => array( ++$i, '<input type="text" name="effect[' . $effect->get_id(). ']" value="' . htmlentities( $effect->get_effect(), ENT_COMPAT, 'UTF-8' ). '" size="40" maxlength="128"/>', '<input type="text" name="waarde[' . $effect->get_id(). ']" value="' . number_format( $effect->get_waarde(), 2, '.', '' ). '" size="8" maxlength="8" />', implode( ' ', $opties ), ), ); } $this->load->view( 'elements/laf-blocks/generic-list', $list_view_data ); ?> <input type="submit" value="<?=tgng('form.opslaan')?>" name="action" /> <?=htag('effecten_opslaan')?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Nieuw effect', 'width' => '920px' ) ); ?> <table> <tr> <td>Effect</td> <td><input type="text" name="effect_nieuw" size="40" maxlength="128"/></td> </tr> <tr> <td>Factor</td> <td><input type="text" name="waarde_nieuw" size="8" value="1.00" maxlength="8" /></td> </tr> </table> <input type="submit" value="<?=tgng('form.opslaan')?>" name="action" /> <?=htag('nieuw_opslaan')?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view( 'beheer/risicoanalyse_buttons', array( 'prev' => false, 'next' => true, 'colspan' => 3, ) ); ?> </form> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <? // Initialisation //$total_jan = $total_feb = $total_mrt = $total_apr = $total_mei = $total_jun = $total_jul = $total_aug = $total_sep = $total_okt = $total_nov = $total_dec = 0; for ($cnt = 1 ; $cnt <= 12 ; $cnt++) { $total_str = "total_{$cnt}"; $$total_str = 0; } $cur_year = date("Y"); $cur_month = date("n"); $use_year = ($use_year > $cur_year) ? $cur_year : $use_year; $use_month = ($use_year >= $cur_year) ? $cur_month : 12; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Actieve gebruikers van klant ' . $klant->naam . ' in ' . $use_year, 'width' => '920px' ) ); ?> <!-- TODO: add a year selector <p> <input type="button" value="Gebruiker toevoegen" onclick="location.href='<?=site_url('/admin/account_gebruiker_toevoegen/' . $klant->id)?>';"> </p> --> <table class="admintable" width="100%" cellpadding="3" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Gebruiker</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Jan</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Feb</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Mrt</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Apr</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Mei</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Jun</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Jul</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Aug</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Sep</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Okt</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Nov</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Dec</th> </tr> <? foreach ($gebruikers as $i => $gebruiker): // Logic in a view is of course not very nice, but well, it's really only some simple display stuff. Possibly we move this to a model later. // Extract the periods and store them in an array $user_periods = array( 'periods' => array(), 'periods_str' => '' ); // At present we make use of 5 fixed fields for this, but this can easily be extended to use a more elegant mechanism with flexible periods. for ($i = 1 ; $i <= 5 ; $i++) { // Start with determining the start of the period, if no start is defined, we skip the rest $cur_start_str = "active_period_{$i}_begin"; $cur_start = $gebruiker->$cur_start_str; // If a start has been defined for a period, include that period (regardless of whether it has an end date or not). if (!is_null($cur_start)) { // Create an array with the values we need $cur_period = array(); // Store the start as a timestamp $cur_period['start_date'] = strtotime($cur_start); // Store the other values too, make sure to properly handle null values $cur_end_str = "active_period_{$i}_end"; $cur_end = $gebruiker->$cur_end_str; $cur_period['end_date'] = (!is_null($cur_end)) ? strtotime($cur_end) : 0; // Textual values for the screen $cur_start_date_str = ($cur_period['start_date'] > 0) ? date("d-m-Y", $cur_period['start_date']) : '-'; $cur_end_date_str = ($cur_period['end_date'] > 0) ? date("d-m-Y", $cur_period['end_date']) : '-'; if (!empty($user_periods['periods_str'])) { $user_periods['periods_str'] .= ', '; } $user_periods['periods_str'] .= $cur_start_date_str . ' t/m ' . $cur_end_date_str; // Extract the start and end months and years $cur_period['start_date_month'] = ($cur_period['start_date'] > 0) ? date("n", $cur_period['start_date']) : 0; $cur_period['start_date_year'] = ($cur_period['start_date'] > 0) ? date("Y", $cur_period['start_date']) : 0; $cur_period['end_date_month'] = ($cur_period['end_date'] > 0) ? date("n", $cur_period['end_date']) : 0; $cur_period['end_date_year'] = ($cur_period['end_date'] > 0) ? date("Y", $cur_period['end_date']) : 0; // If a start date was specified, and an end date was not, assume the end date and month to be the current year and month if ( ($cur_period['start_date'] > 0) && ($cur_period['end_date'] == 0) ) { $cur_period['end_date_year'] = $cur_year; $cur_period['end_date_month'] = $cur_month; } // Store this period to the set $user_periods['periods'][] = $cur_period; // If no end date was set for the period we just processed, signal that as the last (valid!) period in our set, and do not add further // periods to it. if ($cur_period['end_date'] == 0) { continue; } } } // Perform the calculations for ($cnt = 1 ; $cnt <= 12 ; $cnt++) { // First calculate the month value (i.e. 0 or 1) $month_str = "month_{$cnt}"; $$month_str = 0; // Loop over the defined periods foreach ($user_periods['periods'] as $cur_period) { // Extract the required variables $start_date_year = $cur_period['start_date_year']; $end_date_year = $cur_period['end_date_year']; $start_date_month = $cur_period['start_date_month']; $end_date_month = $cur_period['end_date_month']; // Now handle the counters as required. if ($cur_period['start_date'] == 0) { // No start date specified, make sure EVERY month value is set to 0, by doing nothing here. } if ( ($use_year > $end_date_year) || ($use_year < $start_date_year) ) { // The chosen year is either completely after the end, or before the beginning of the active users year, so do nothing. } else if ( ($use_year < $end_date_year) && ($use_year > $start_date_year) ) { // The chosen year falls completely within the period between start and end year of the user, so always add 1 $$month_str = 1; } else if ( ( ($use_year > $start_date_year) || (($use_year == $start_date_year) && ($cnt >= $start_date_month)) ) && ( ($use_year < $end_date_year) || (($use_year == $end_date_year) && ($cnt <= $end_date_month)) ) ) { $$month_str = 1; } // Get the proper 'total' variable for the current column $total_str = "total_{$cnt}"; // Check if the combination of year + month does not lie in a future month + year combination. If it does, signal it with a '-' so we // can properly distinguish between a '0' or '1' and an -as of yet- unknown value. Otherwise, we add the value to the total. if ( ($use_year > $cur_year) || (($use_year == $cur_year) && ($cnt > $cur_month)) ) { $$total_str = $$month_str = '-'; } else { // Add it to the proper total //$$total_str += (is_int($$month_str)) ? $$month_str : 0; $$total_str += $$month_str; } } } ?> <tr class="<?=($i % 2)?'':'zebra'?>"> <td style="" valign="top"><h5><a href="<?=site_url('/admin/account_user_edit/' . $gebruiker->id)?>"><?=$gebruiker->get_status()?></a></h5> (<?=$user_periods['periods_str']?>)</td> <td style="" valign="top"><?=$month_1?></td> <td style="" valign="top"><?=$month_2?></td> <td style="" valign="top"><?=$month_3?></td> <td style="" valign="top"><?=$month_4?></td> <td style="" valign="top"><?=$month_5?></td> <td style="" valign="top"><?=$month_6?></td> <td style="" valign="top"><?=$month_7?></td> <td style="" valign="top"><?=$month_8?></td> <td style="" valign="top"><?=$month_9?></td> <td style="" valign="top"><?=$month_10?></td> <td style="" valign="top"><?=$month_11?></td> <td style="" valign="top"><?=$month_12?></td> </tr> <? endforeach; ?> <tr> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;">TOTAAL</th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_1?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_2?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_3?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_4?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_5?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_6?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_7?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_8?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_9?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_10?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_11?></th> <th style="text-align:left; padding-left: 0px; border-top:2px solid #777; border-bottom:2px solid #777;"><?=$total_12?></th> </tr> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('nav.lease_beheer', 'Lease beheer', '2013-08-22 17:26:57', 0), ('nav.lease_bewerken', 'Lease bewerken', '2013-08-22 17:50:17', 0); <file_sep><? $this->load->view('elements/header', array('page_header'=>'prioriteiten')); ?> <? $test_niveaus = $risico_handler->get_risico_shortnames(); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Prioriteitenmatrix - ' . htmlentities( $checklistgroep->naam, ENT_COMPAT, 'UTF-8'), 'onclick' => '', 'expanded' => true, 'group_tag' => 'prioriteiten_matrix', 'width' => '100%', 'height' => '100%' ) ); ?> <? $this->load->view( 'beheer/prioriteitstelling_matrix_js' ) ?> <? $this->load->view( 'beheer/prioriteitstelling_legenda' ); ?> <form name="form" method="post" class="vamiddle"> <table> <tr> <? if (!$readonly): ?> <td> <input type="submit" value="<?=tgng('form.opslaan')?>"/> <input type="button" value="<?=tgng('form.annuleren')?>" onclick="location.href='<?=site_url('/instellingen/matrixbeheer')?>';"/> <?=htag('opslaan')?> </td> <? endif; ?> <td style="text-align: right"> <input type="button" value="Bestuurlijke weergave" onclick="if (confirm( 'Niet-opgeslagen wijzigingen gaan verloren. Bestuurlijke weergave nu tonen?' )) location.href='<?=site_url('/instellingen/prioriteitstelling_matrix/' . $checklistgroep->id . '/' . $matrix->id . '/bestuurlijk')?>';" /> <?=htag('eenvoudige weergave')?> <input type="button" value="Legenda" onclick=" modalPopup({ width: 800, height: 400, html: $('.legenda').html() })" /> <?=htag('legenda')?> </td> </tr> </table> <div style="width:<?=$this->is_Mobile ? 950 : 1150?>px; overflow:auto"> <table width="100%" cellspacing="0" cellpadding="0" class="prioriteitmatrix"> <tr> <th style="border:0"> </th> <? foreach ($unieke_hoofdgroepen as $hoofdgroep_naam => $unused): ?> <th rowspan="2"><img src="<?=site_url( '/content/verttext/' . rawurlencode( rawurlencode( rawurlencode( $hoofdgroep_naam ) ) ) . '/10/000000/f3f4f6/200' )?>" /></th> <? endforeach; ?> </tr> <tr> <th class="first">Checklist</th> </tr> <? $last_checklist_index = array_pop( array_keys( $checklisten ) ); ?> <? foreach ($checklisten as $i => $checklist): ?> <? $cl_editbaar = !$readonly && $editbaar[$checklist->id]; ?> <tr> <td style="min-width: 300px;" class="first <?=$i==$last_checklist_index?'last':''?>"> <? if (!$readonly): ?> <a href="javascript:void(0);" onclick="if (confirm( 'Nu naar de risicoanalyse voor deze checklist gaan? U verliest eventuele niet opgeslagen wijzigingen aan de matrix!' )) location.href='<?=site_url('/instellingen/risicoanalyse_effecten/' . $checklist->id . '/' . $matrix->id)?>';"><?=htmlentities($checklist->naam, ENT_COMPAT, 'UTF-8')?><a> <? else: ?> <?=htmlentities($checklist->naam, ENT_COMPAT, 'UTF-8')?> <? endif; ?> <? if (!$readonly && !$cl_editbaar): ?> <img src="<?=site_url('/files/images/letop.png')?>" title="Deze prioriteitstelling is op een risico analyse gebaseerd." style="float:right; margin-right:5px;"> <a style="float:right; margin-right:5px;" href="javascript:void(0);" onclick="if (confirm( 'De risico analyse voor deze checklist werkelijk verwijderen? U kunt deze actie NIET ongedaan maken!' )) location.href='<?=site_url('/instellingen/risicoanalyse_verwijderen/' . $checklist->id . '/' . $matrix->id)?>';" title="Deze risico analyse voor deze checklist verwijderen." style="float:right; margin-right:5px;"> <img src="<?=site_url('/files/images/delete.png')?>"> </a> <? endif; ?> </td> <? foreach ($unieke_hoofdgroepen as $hoofdgroep_naam => $hoofdgroep_data): $hoofdgroep = @$hoofdgroep_data['checklist_map'][$checklist->id]; ?> <td class="<?=$i==$last_checklist_index?'last':''?>"> <? $p = $hoofdgroep ? $prioriteitstellingen[$checklist->id]->get_gemiddelde_waarde( $hoofdgroep->id ) : false; ?> <? if ($hoofdgroep && $p!==false): ?> <? if (!array_key_exists( $p, $test_niveaus )) $p = 'zeer_hoog'; $hoofdthemas = $hoofdgroep->get_hoofdthemas(); ?> <div style="min-width: 10px; height: 15px;" class="prio_<?=$p?> hoofdgroep<?=sizeof($hoofdthemas)<=1?'1':'N'?>"><?=$test_niveaus[$p]?></div> <? if ($cl_editbaar): ?> <? if (sizeof( $hoofdthemas )<=1): ?> <select style="display:none" name="checklist1[<?=$checklist->id?>][<?=$hoofdgroep->id?>]"> <option <?=$p=='zeer_laag'?'selected':''?> value="zeer_laag"><?=$test_niveaus['zeer_laag']?></option> <option <?=$p=='laag' ?'selected':''?> value="laag"><?=$test_niveaus['laag']?></option> <option <?=$p=='gemiddeld'?'selected':''?> value="gemiddeld"><?=$test_niveaus['gemiddeld']?></option> <option <?=$p=='hoog' ?'selected':''?> value="hoog"><?=$test_niveaus['hoog']?></option> <option <?=$p=='zeer_hoog'?'selected':''?> value="zeer_hoog"><?=$test_niveaus['zeer_hoog']?></option> </select> <? else: ?> <div style="height:auto; display:none; text-align: left;" class="selectNdiv"> <table style="border-spacing:0;margin:0;padding:0;border:0;width:100%;"> <? foreach ($hoofdthemas as $hoofdthema): ?> <? $p = $prioriteitstellingen[$checklist->id]->get_waarde( $hoofdgroep->id, $hoofdthema['hoofdthema']->id ); if (!array_key_exists( $p, $test_niveaus )) $p = 'zeer_hoog'; ?> <tr> <td style="text-align:left;margin:0;padding:0;border:0;"> <?=htmlentities( $hoofdthema['hoofdthema']->naam, ENT_COMPAT, 'UTF-8' )?>: </td> <td style="text-align:left;margin:0;padding:0;border:0;"> <select name="checklist[<?=$checklist->id?>][<?=$hoofdgroep->id?>][<?=$hoofdthema['hoofdthema']->id?>]" aantal_vragen="<?=$hoofdthema['aantal_vragen']?>"> <option <?=$p=='zeer_laag'?'selected':''?> value="zeer_laag"><?=$test_niveaus['zeer_laag']?></option> <option <?=$p=='laag' ?'selected':''?> value="laag"><?=$test_niveaus['laag']?></option> <option <?=$p=='gemiddeld'?'selected':''?> value="gemiddeld"><?=$test_niveaus['gemiddeld']?></option> <option <?=$p=='hoog' ?'selected':''?> value="hoog"><?=$test_niveaus['hoog']?></option> <option <?=$p=='zeer_hoog'?'selected':''?> value="zeer_hoog"><?=$test_niveaus['zeer_hoog']?></option> </select> </td> </tr> <? endforeach; ?> </table> </div> <? endif; ?> <? endif; ?> <? else: ?> - <? endif; ?> </td> <? endforeach;?> </tr> <? endforeach; ?> </table> </div> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? if (!empty($risico_grafieken)): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Grafische weergave', 'onclick' => '', 'expanded' => false, 'group_tag' => 'prioriteiten_matrix', 'width' => '100%', 'height' => '100%' ) ); ?> <? // Output the "risk graphs" (if any) foreach ($risico_grafieken as $checklist_naam => $filename) { if (!empty($filename)) { echo "$checklist_naam"; ?> <br /><img src='<?=$filename?>'><br /><br /> <? } // if (!empty($filename)) } // foreach ($risico_grafieken as $checklist_naam => $risico_grafiek) ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endif; ?> <script type="text/javascript"> var curhoofdgroepN; /* * Hoofdgroepen met slechts 1 hoofdthema. */ $('.hoofdgroep1').click(function(evt){ if (curhoofdgroepN) onChangeOrBlurN(); var div = $(this); var sel = $(this).siblings('select'); if (sel.size() == 0) { <? if (!$readonly): ?> alert( 'Deze prioriteitstelling is gebaseerd op een risico analyse, u kunt deze daarom niet wijzigen.\nKlik op de naam van de checklist om in een nieuw scherm naar de risico analyse te gaan.' ); <? endif; ?> return; } div.hide(); sel.show(); sel.focus(); sel[0].click(); }); var onChangeOrBlur1 = function(evt){ var sel = $(this); var div = $(this).siblings('div'); var newtext; for (var i in this.options) if (this.options[i].value == sel.val()) { newtext = this.options[i].text || this.options[i].label; break; } sel.hide(); div.show(); div.removeClass( 'prio_zeer_laag prio_laag prio_gemiddeld prio_hoog prio_zeer_hoog' ); div.html( newtext ); div.addClass( 'prio_' + $(this).val() ); } $('.hoofdgroep1').siblings('select').change(onChangeOrBlur1); $('.hoofdgroep1').siblings('select').blur(onChangeOrBlur1); /* * Hoofdgroepen met meerdere hoofdthema's. */ $('.hoofdgroepN').click(function(evt){ if (curhoofdgroepN) onChangeOrBlurN(); var div = $(this); var selDiv = $(this).siblings('div'); if (selDiv.size() == 0) { <? if (!$readonly): ?> alert( 'Deze prioriteitstelling is gebaseerd op een risico analyse, u kunt deze daarom niet wijzigen.\nKlik op de naam van de checklist om in een nieuw scherm naar de risico analyse te gaan.' ); <? endif; ?> return; } div.hide(); selDiv.show(); selDiv.find('select:first').focus(); selDiv.find('select:first').click(); curhoofdgroepN = this; }); var onChangeOrBlurN = function(){ var div = $(curhoofdgroepN); var selDiv = $(curhoofdgroepN).siblings('div'); div.show(); selDiv.hide(); var totalPrio = 0; var totalCount = 0; selDiv.find('select').each(function(){ var aantal_vragen = parseInt( $(this).attr( 'aantal_vragen' ) ); totalCount += aantal_vragen; switch ($(this).val()) { case 'zeer_laag': totalPrio += 1 * aantal_vragen; break; case 'laag': totalPrio += 2 * aantal_vragen; break; case 'gemiddeld': totalPrio += 3 * aantal_vragen; break; case 'hoog': totalPrio += 4 * aantal_vragen; break; case 'zeer_hoog': totalPrio += 5 * aantal_vragen; break; } }); var newval = Math.round( totalPrio / totalCount ); var newtext, newprio; if (newval == 1) { newtext = 'S'; newprio = 'zeer_laag'; } else if (newval == 2) { newtext = '1'; newprio = 'laag'; } else if (newval == 3) { newtext = '2'; newprio = 'gemiddeld'; } else if (newval == 4) { newtext = '3'; newprio = 'hoog'; } else { newtext = '4'; newprio = 'zeer_hoog'; } div.removeClass( 'prio_zeer_laag prio_laag prio_gemiddeld prio_hoog prio_zeer_hoog' ); div.html( newtext ); div.addClass( 'prio_' + newprio ); curhoofdgroepN = null; }; </script> <? $this->load->view('elements/footer'); ?> <file_sep>PDFAnnotator.AttachedRotatedLine = PDFAnnotator.Base.extend({ init: function( line, rotation, length, at_start ) { this._super(); /* initialize object */ this.rotation = rotation; this.atStart = at_start ? true : false; this.myline = new PDFAnnotator.Line( line.container, line.color, line.from, line.from ); this.targetline = line; this.length = length; /* listen to update event from target line */ var thiz = this; this.targetline.on( 'update', function(){ thiz.update(); }); this.update(); }, update: function() { // get the direction of the line var lineDirection = new PDFAnnotator.Math.Vector2( this.targetline.to.x - this.targetline.from.x, this.targetline.to.y - this.targetline.from.y ).normalized(); var source = new PDFAnnotator.Math.Vector2( this.atStart ? this.targetline.from.x : this.targetline.to.x, this.atStart ? this.targetline.from.y : this.targetline.to.y ); // calc positions of our line var ourDirection = lineDirection.rotated( this.rotation ).multiplied( this.length ); var toPos = source.added( ourDirection ); this.myline.update( source, toPos ); }, remove: function() { this.myline.destroy(); } }); <file_sep><? $this->load->view('elements/header', array('page_header'=>'admin.tool_fix_deelplan')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Prioriteiten tools', 'width' => '920px' ) ); ?> <form name="form" method="post" onsubmit="return confirm('Weet je zeker dat je de prioriteiten wil kopieren van de geselecteerde klant naar de andere geselecteerde klant? Deze actie is niet ongedaan te maken!');"> <input type="hidden" name="action" value="copy" /> <table width="100%"> <tr> <td id="form_header">Kopieer prioriteiten van klant</td> </tr> <tr> <td id="form_value"> <select name="bron_klant_id"> <option style="background-color:#800" value="0" disabled selected>--- selecteer een klant ---</option> <? foreach ($klanten as $klant): ?> <option value="<?=$klant->id?>"><?=$klant->volledige_naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form_header">naar klant</td> </tr> <tr> <td id="form_value"> <select name="doel_klant_id"> <option style="background-color:#800" value="0" disabled selected>--- selecteer een klant ---</option> <? foreach ($klanten as $klant): ?> <option value="<?=$klant->id?>"><?=$klant->volledige_naam?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form_button"><input type="submit" value="Uitvoeren"/> (vraagt om bevestiging)</td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoprofielen.risicoprofielenlist','map_view'=>true)); ?> <h1><?=tgg('risicoprofielen.headers.risicoprofielenlist')?></h1> <div class="main"> <?if(count($list) > 0):?> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==sizeof($list)-1) ? 'bottom' : ''; ?> <li class="entry top left right <?=$bottom?>" matrix_id="<?=$entry->matrix_id ?>" bt_riskprofiel_id="<?=$entry->bt_riskprofiel_id ?>"> <div class="list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <?else:?> <div style="padding-top:10px;padding-left:5px;font-weight:bold;"><?=tgg('list.noitems') ?></div> <?endif ?> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $(document).ready(function(){ $('li[matrix_id]').click(function(){ location.href = '<?=site_url('/risicoprofielen/risicoprofielenmapping/').'/'?>'+$(this).attr('matrix_id')+"/"+$(this).attr('bt_riskprofiel_id'); }); //------------------------------------------------------------------------------ }); </script> <file_sep><? require_once 'base.php'; class NotificatieResult extends BaseResult { function NotificatieResult( &$arr ) { parent::BaseResult( 'notificatie', $arr ); } function get_dossier() { $this->_CI->load->model( 'dossier' ); return $this->_CI->dossier->get( $this->dossier_id ); } function get_deelplan() { $this->_CI->load->model( 'deelplan' ); return $this->_CI->deelplan->get( $this->deelplan_id ); } function get_gebruiker() { return $this->_CI->gebruiker->get( $this->gebruiker_id ); } } class Notificatie extends BaseModel { function Notificatie() { parent::BaseModel( 'NotificatieResult', 'notificaties', true ); } public function check_access( BaseResult $object ) { if ($object->gebruiker_id) $this->check_relayed_access( $object, 'gebruiker', 'gebruiker_id' ); } public function get_my_notificaties() { $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); if (!$gebruiker) return array(); return $this->convert_results( $this->_CI->db->query( ' SELECT n.* FROM notificaties n LEFT JOIN gebruikers g ON n.gebruiker_id = g.id LEFT JOIN dossiers do ON n.dossier_id = do.id LEFT JOIN gebruikers dog ON do.gebruiker_id = dog.id LEFT JOIN deelplannen de ON n.deelplan_id = de.id LEFT JOIN dossiers dedo ON de.dossier_id = dedo.id LEFT JOIN gebruikers dedog ON dedo.gebruiker_id = dedog.id WHERE ( g.id = ' . intval($gebruiker->id) . ' OR g.klant_id = ' . intval($gebruiker->klant_id) . ' OR dog.klant_id = ' . intval($gebruiker->klant_id) . ' OR dedog.klant_id = ' . intval($gebruiker->klant_id) . ' ) AND n.id NOT IN ( SELECT notificatie_id FROM notificaties_bekeken WHERE gebruiker_id = ' . intval($gebruiker->id) . ' ) ORDER BY n.datum DESC ') ); } public function add_dossier_notificatie( $dossier_id, $bericht, $klikbaar=true ) { // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_CI->db->query($q = ' INSERT INTO notificaties (dossier_id, datum, bericht, klikbaar) VALUES (' . intval($dossier_id) . ', '.$now_func.', ' . $this->_CI->db->escape( $bericht ) . ', ' . ($klikbaar ? 1 :0) . ') '); } public function add_deelplan_notificatie( $deelplan_id, $bericht, $klikbaar=true ) { // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_CI->db->query(' INSERT INTO notificaties (deelplan_id, datum, bericht, klikbaar) VALUES (' . intval($deelplan_id) . ', '.$now_func.', ' . $this->_CI->db->escape( $bericht ) . ', ' . ($klikbaar ? 1 :0) . ') '); } public function add_gebruiker_specifieke_notificatie( $gebruiker_id, $bericht ) { // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_CI->db->query(' INSERT INTO notificaties (gebruiker_id, datum, bericht) VALUES (' . intval($gebruiker_id) . ', '.$now_func.', ' . $this->_CI->db->escape( $bericht ) . ') '); } public function add_opdrachten_notificatie($deelplan_id, $bericht, $klikbaar=true, $vraag_id=null){ // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->_CI->db->query(' INSERT INTO notificaties (deelplan_id, datum, bericht, klikbaar, is_opdracht, gebruiker_id, vraag_id) VALUES ('.intval($deelplan_id).','.$now_func.','.$this->_CI->db->escape( $bericht ).','.($klikbaar ? 1 :0).',1,'.$gebruiker->id.','.$vraag_id.')'); } } <file_sep> ALTER TABLE supervision_moments_cl CHANGE COLUMN bouwnummer_id bouwnummer varchar(100) DEFAULT ''; ALTER TABLE deelplan_checklisten CHANGE COLUMN bouwnummer_id bouwnummer varchar(100) DEFAULT ''; ALTER TABLE deelplan_vragen CHANGE COLUMN bouwnummer_id bouwnummer varchar(100) DEFAULT ''; ALTER TABLE deelplan_vraag_geschiedenis CHANGE COLUMN bouwnummer_id bouwnummer varchar(100) DEFAULT ''; ALTER TABLE deelplan_uploads CHANGE COLUMN bouwnummer_id bouwnummer varchar(100) DEFAULT ''; -- <file_sep><script type="text/javascript"> function annuleren() { closePopup(); } function archiveren() { location.href = "<?=site_url('/dossiers/archiveren/'.$dossiers->id.'/confirm')?>"; } </script> <table width="100%" cellspacing="0" cellpadding="5"> <tr> <td colspan="2"><h2>Checklist archiveren</h2></td> </tr> <tr> <td colspan="2" id="form"> Weet u zeker dat u deze checklist wilt archiveren? U kunt deze actie niet ongedaan maken! </td> </tr> <tr> <td id="form"><input type="button" onclick="archiveren();" value="Archiveren" /></td> <td id="form" style="text-align:right"><input type="button" onclick="annuleren();" value="<?=tgng('form.annuleren')?>" /></td> </tr> </table> <file_sep><? require_once 'base.php'; class DeelplanBescheidenResult extends BaseResult { function DeelplanBescheidenResult( &$arr ) { parent::BaseResult( 'deelplanbescheiden', $arr ); } function get_dossier_bescheiden() { return $this->_CI->dossierbescheiden->get( $this->dossier_bescheiden_id ); } } class DeelplanBescheiden extends BaseModel { function DeelplanBescheiden() { parent::BaseModel( 'DeelplanBescheidenResult', 'deelplan_bescheiden' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossierbescheiden', 'dossier_bescheiden_id' ); } function get_by_deelplan( $deelplan_id ) { if (!$this->dbex->is_prepared( 'get_bescheiden_by_deelplan' )) $this->dbex->prepare( 'get_bescheiden_by_deelplan', ' SELECT * FROM deelplan_bescheiden WHERE deelplan_id = ? ORDER BY id ' ); $res = $this->dbex->execute( 'get_bescheiden_by_deelplan', array( $deelplan_id ) ); $result = array(); foreach ($res->result() as $row) $result[ $row->dossier_bescheiden_id ] = $this->getr( $row ); return $result; } function set_for_deelplan( $deelplan_id, array $dossier_bescheiden_ids, array $current_bescheiden ) { // changes? $change_detected = false; if (sizeof( $current_bescheiden ) == sizeof( $dossier_bescheiden_ids )) { foreach ($dossier_bescheiden_ids as $dossier_bescheiden_id) if (!isset( $current_bescheiden[$dossier_bescheiden_id] )) { $change_detected = true; break; } if (!$change_detected) return; } // delete current $this->db->from( 'deelplan_bescheiden' ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->delete(); // add new foreach ($dossier_bescheiden_ids as $dossier_bescheiden_id) $this->add( $deelplan_id, $dossier_bescheiden_id ); } function add( $deelplan_id, $dossier_bescheiden_id ) { if (!$this->dbex->is_prepared( 'set_deelplan_bescheiden' )) $this->dbex->prepare( 'set_deelplan_bescheiden', 'INSERT INTO deelplan_bescheiden (deelplan_id, dossier_bescheiden_id) VALUES (?, ?)' ); $args = array( 'deelplan_id' => $deelplan_id, 'dossier_bescheiden_id' => $dossier_bescheiden_id, ); return $this->dbex->execute( 'set_deelplan_bescheiden', $args ); } } <file_sep>PDFAnnotator.Tool.Camera = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'camera' ); /* initialize runtime data */ this.currentForm = null; this.currentUpload = null; this.currentEditable = null; /* handle mouse clicks to start new forms */ this.on( 'mouseclick', function( tool, data ){ if (!tool.currentEditable) tool.clickedToAddPhoto( data ); else tool.finishDirectionArrow(); }); /* handle drag move */ this.on( 'mousemove', function( tool, data ){ if (tool.currentEditable) tool.updateDirectionArrow( data ); }); this.on( 'dragmove', function( tool, data ){ if (tool.currentEditable) tool.updateDirectionArrow( data ); }); this.on( 'dragend', function( tool, data ){ if (tool.currentEditable) tool.finishDirectionArrow(); }); /* handle situation when tool is deselected */ this.on( 'deselect', function( tool, data ){ // remove old form if no longer in use! if (tool.currentForm) { tool.currentForm.remove(); tool.currentForm = null; tool.currentUpload = null; } // remove old editable if still set (means unfinished) if (tool.currentEditable) { tool.currentEditable.container.removeObject( tool.currentEditable ); tool.currentEditable = null; } }); }, getNewForm: function( data ) { var formTemplate = this.engine.gui.tools.toolsconfig.camera.form; var form = $(formTemplate.outerHTML()).appendTo( $('body') ); var upload = form.find( 'input[type=file]' ); var thiz = this; upload.change( function() { thiz.photoSelected( data ); }); return { form: form, upload: upload }; }, clickedToAddPhoto: function( data ) { // remove old form if no longer in use! if (this.currentForm) { this.currentForm.remove(); this.currentForm = null; this.currentUpload = null; } // does the server (i.e. app) allow us to add a photo to this layer? if (!PDFAnnotator.Server.prototype.instance.mayAddPhoto( this.engine.getActiveLayer() )) return; // build new form and get upload reference var formdata = this.getNewForm( data ); this.currentForm = formdata.form; this.currentUpload = formdata.upload; // on some platforms this only works if the upload is visible this.currentForm.show(); this.currentUpload.trigger( 'click' ); this.currentForm.hide(); }, photoSelected: function( data ) { if (this.currentEditable) throw 'PDFAnnotator.Tool.Camera.photoSelected: this.currentEditable is not null, it should be!'; var cameraConfig = this.engine.gui.tools.toolsconfig.camera; this.currentEditable = new PDFAnnotator.Editable.Photo({ position: data.position.subtracted( cameraConfig.imageSize.divided( 2 ) ), imageSrc: cameraConfig.imageSrc, imageSize: cameraConfig.imageSize }); if (!data.container.addObject( this.currentEditable )) { this.currentEditable = null; } }, finishDirectionArrow: function() { /* register file upload */ PDFAnnotator.Server.prototype.instance.handleFormUpload( this.currentForm, this.currentUpload, this.currentEditable ); /* reset state */ this.currentForm = null; this.currentUpload = null; this.currentEditable = null; }, updateDirectionArrow: function( data ) { if (!this.currentEditable) throw 'PDFAnnotator.Tool.Camera.photoSelected: this.currentEditable is null, it shouldn\'t be!'; var centerPos = this.currentEditable.data.position.added( this.currentEditable.data.imageSize.divided( 2 ) ); var newPos = data.position; var vec1 = new PDFAnnotator.Math.IntVector2( 1, 0 ); var vec2 = newPos.subtracted( centerPos ); var angle = vec1.angle( vec2 ); if (centerPos.y < newPos.y) angle = 2*Math.PI - angle; this.currentEditable.setDirection( angle ); } }); <file_sep><? require_once 'base.php'; class DeelplanVraagResult extends BaseResult { function DeelplanVraagResult( $arr ) { parent::BaseResult( 'deelplanvraag', $arr ); } function get_deelplan() { $this->_CI->load->model( 'deelplan' ); return $this->_CI->deelplan->get( $this->deelplan_id ); } function get_vraag() { $this->_CI->load->model( 'vraag' ); return $this->_CI->vraag->get( $this->vraag_id ); } } class DeelplanVraag extends BaseModel { function DeelplanVraag() { parent::BaseModel( 'DeelplanVraagResult', 'deelplan_vragen' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'deelplan', 'deelplan_id' ); } // Note: due to the addition of 'bouwnummers' the below may not always yield a unique result anymore! // Bouwnummers can be NULL, empty or have a value. // For this reason (as well as not to get unpredictable results with legacy code), instead of adding an optional $bouwnummer // parameter, the choice was made to create a specific method for it, called get_db_values_by_deelplan_and_vraag_and_bouwnummer function get_db_values_by_deelplan_and_vraag( $deelplan_id, $vraag_id ) { if (!$this->dbex->is_prepared( 'get_deelplanvraag_by_deelplan_and_vraag' )) $this->dbex->prepare( 'get_deelplanvraag_by_deelplan_and_vraag', ' SELECT * FROM deelplan_vragen WHERE (deelplan_id = ?) AND (vraag_id = ?) ' ); $res = $this->dbex->execute( 'get_deelplanvraag_by_deelplan_and_vraag', array( $deelplan_id, $vraag_id ) ); return $res; } function get_hoofgoep_value_by_vraag_and_deeplan($deelplan_id,$vraag_id){ if (!$this->dbex->is_prepared( 'get_hoofgoep_value_by_vraag_and_deeplan' )) $this->dbex->prepare( 'get_hoofgoep_value_by_vraag_and_deeplan', ' SELECT bc.hoofdgroep_id FROM deelplan_vragen LEFT JOIN bt_vragen bv ON deelplan_vragen.vraag_id=bv.id LEFT JOIN bt_categorieen bc ON bv.categorie_id=bc.id WHERE vraag_id=? AND deelplan_vragen.deelplan_id=? ' ); $res = $this->dbex->execute( 'get_hoofgoep_value_by_vraag_and_deeplan', array($vraag_id,$deelplan_id ) ); $result = array(); foreach ($res->result() as $row) { $result[] = $row->hoofdgroep_id; } return (empty($result)) ? null : $result[0]; } function get_db_values_by_deelplan_and_vraag_and_bouwnummer( $deelplan_id, $vraag_id, $bouwnummer ) { // !!! As we either pass 2 or 3 parameters, make sure to properly prepare the two different statements using different names! if (is_null($bouwnummer)) { $statement_name = 'get_deelplanvraag_by_deelplan_and_vraag_and_bouwnummer_null'; $bouwnummer_clause = ' (bouwnummer is null)'; $query_params = array( $deelplan_id, $vraag_id ); } else { $statement_name = 'get_deelplanvraag_by_deelplan_and_vraag_and_bouwnummer_not_null'; $bouwnummer_clause = ' (bouwnummer = ?)'; $query_params = array( $deelplan_id, $vraag_id, $bouwnummer ); } if (!$this->dbex->is_prepared( $statement_name )) $this->dbex->prepare( $statement_name, ' SELECT * FROM deelplan_vragen WHERE (deelplan_id = ?) AND (vraag_id = ?) AND ' . $bouwnummer_clause ); $res = $this->dbex->execute( $statement_name, $query_params ); return $res; } // Note: due to the addition of 'bouwnummers' the below may not always yield a unique result anymore! // Bouwnummers can be NULL, empty or have a value. // For this reason (as well as not to get unpredictable results with legacy code), instead of adding an optional $bouwnummer // parameter, the choice was made to create a specific method for it, called get_by_deelplan_and_vraag_and_bouwnummer function get_by_deelplan_and_vraag( $deelplan_id, $vraag_id ) { // First get the records using the deelplan ID and vraag ID $res = $this->get_db_values_by_deelplan_and_vraag($deelplan_id, $vraag_id); $result = array(); foreach ($res->result() as $row) { $result[] = $this->getr( $row ); } return (empty($result)) ? null : $result[0]; } function get_by_deelplan_and_vraag_and_bouwnummer( $deelplan_id, $vraag_id, $bouwnummer ) { // First get the records using the deelplan ID, vraag ID and bouwnummer $res = $this->get_db_values_by_deelplan_and_vraag_and_bouwnummer($deelplan_id, $vraag_id, $bouwnummer); $result = array(); foreach ($res->result() as $row) { $result[] = $this->getr( $row ); } return (empty($result)) ? null : $result[0]; } // Note: due to the addition of 'bouwnummers' the below may not always yield a unique result anymore! // Bouwnummers can be NULL, empty or have a value. // For this reason (as well as not to get unpredictable results with legacy code), instead of adding an optional $bouwnummer // parameter, the choice was made to create a specific method for it, called get_records_by_deelplan_and_vraag_and_bouwnummer function get_records_by_deelplan_and_vraag( $deelplan_id, $vraag_id ) { $res = $this->get_db_values_by_deelplan_and_vraag($deelplan_id, $vraag_id); $row = $res->result(); return $row; } function get_records_by_deelplan_and_vraag_and_bouwnummer( $deelplan_id, $vraag_id, $bouwnummer ) { $res = $this->get_db_values_by_deelplan_and_vraag_and_bouwnummer($deelplan_id, $vraag_id, $bouwnummer); $row = $res->result(); return $row; } }<file_sep><? require_once 'base.php'; class DeelplanUploadResult extends BaseResult { public function DeelplanUploadResult( &$arr ) { parent::BaseResult( 'deelplanupload', $arr ); } public function get_download_url( $thumbnail=FALSE ) { return '/deelplannen/deelplanupload_download/' . $this->id . ($thumbnail ? '/thumbnail' : ''); } public function get_delete_url() { return '/deelplannen/deelplanupload_delete/' . $this->id; } public function get_gebruiker() { get_instance()->gebruiker->setSkipCheck(); return $this->gebruiker_id ? get_instance()->gebruiker->get( $this->gebruiker_id ) : null; } public function get_auteur() { return $this->gebruiker_id ? $this->get_gebruiker()->get_status() : '(Onbekend)'; } public function get_data() { $deelPlanUpload = new DeelplanUpload(); $filepath = $deelPlanUpload->getUploadPath($this->deelplan_id) . '/' . $this->id; if( !file_exists($filepath) ) { throw new Exception('File not found: ' . $filepath); } return file_get_contents($filepath); } /* public function delete() { $deelPlanUpload = new DeelplanUpload(); $filepath = $deelPlanUpload->getUploadPath($this->deelplan_id) . '/' . $this->id; } * */ private static function delFolder( $path ){ $folder_items = scandir( $path ); foreach( $folder_items as $n=>$item ) if( $item == '.' || $item == '..' ) unset($folder_items[$n]); if( !count($folder_items) ) rmdir( $path ); } //------------------------------------------------------------------------------ private function removeUploaded( $path ){ $file = $path.'/'.$this->id; if( file_exists($file) ) unlink( $file ); self::delFolder( $path ); if( !preg_match( '/'.DIR_THUMBNAIL.'/', $path) ){ $dossier_id = $this->_CI->deelplanupload->_dossier_id;// defined in deelplanupload->getUploadPath $pos = strpos($path, $dossier_id ); $path = substr($path,0,$pos).$dossier_id; self::delFolder( $path ); } } //------------------------------------------------------------------------------ public function delete(){ if(!parent::delete()) throw new Exception('DB deletion failed.'); $upload_path = $this->_CI->deelplanupload->getUploadPath( $this->deelplan_id ); $this->removeUploaded( $upload_path.'/'.DIR_THUMBNAIL ); $this->removeUploaded( $upload_path ); return TRUE; } //------------------------------------------------------------------------------ }// Class end class DeelplanUpload extends BaseModel { private $_upload_path; public function DeelplanUpload() { parent::BaseModel( 'DeelplanUploadResult', 'deelplan_uploads' ); } public function check_access( BaseResult $object ) { if (IS_CLI) return; $query = 'SELECT d_s.id FROM deelplannen dp '. 'INNER JOIN dossiers d ON d.id = dp.dossier_id '. 'INNER JOIN dossier_subjecten d_s ON d_s.dossier_id = d.id '. 'WHERE dp.id = ' . $object->deelplan_id . ' AND d_s.gebruiker_id = ' . $object->gebruiker_id; $dossier_subject = $this->db->query($query)->row(0); if( isset($dossier_subject->id) ) { return; } $this->check_relayed_access( $object, 'gebruiker', 'gebruiker_id' ); } public function get_by_png_status( $status ) { if (!$this->dbex->is_prepared( 'get_deelplan_by_png_status' )) $this->dbex->prepare( 'get_deelplan_by_png_status', 'SELECT * FROM deelplan_uploads WHERE png_status = ?' ); $res = $this->dbex->execute( 'get_deelplan_by_png_status', array( $status ) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $res->free_result(); return $result; } public function get_by_deelplan( $deelplan_id, $vraag_id ) { if (!$this->dbex->is_prepared( 'get_upload_by_deelplan' )) $this->dbex->prepare( 'get_upload_by_deelplan', ' SELECT * FROM deelplan_uploads WHERE deelplan_id = ? AND vraag_id = ? ORDER BY id ' ); $res = $this->dbex->execute( 'get_upload_by_deelplan', array( $deelplan_id, $vraag_id ) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function get_by_opdracht ( $opdracht_id ) { if (!$this->dbex->is_prepared( 'get_upload_by_opdracht' )) $this->dbex->prepare( 'get_upload_by_opdracht', ' SELECT du.* FROM `deelplan_uploads` du RIGHT JOIN `deelplan_opdrachten_uploads` dou ON du.id=dou.`upload_id` WHERE dou.`opdracht_id` = ? ORDER BY `du`.id DESC; ' ); $res = $this->dbex->execute( 'get_upload_by_opdracht', array( $opdracht_id ) ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function get_unique_by_deelplan_vraag_filename( $deelplan_id, $vraag_id, $filename, $bouwnummer='' ) { $args = array( $deelplan_id, $vraag_id, $filename ); if( $bouwnummer != '' ){ $bw_clause = 'AND bouwnummer = ? '; $args[] = $bouwnummer; }else{ $bw_clause = ''; } if (!$this->dbex->is_prepared( 'get_upload_by_deelplan' )) $this->dbex->prepare( 'get_upload_by_deelplan', 'SELECT * FROM deelplan_uploads '. 'WHERE 1=1 '. 'AND deelplan_id = ? '. 'AND vraag_id = ? '. 'AND filename = ? '. $bw_clause. 'ORDER BY `id`' ); $res = $this->dbex->execute( 'get_upload_by_deelplan', $args ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function find_by_deelplan( $deelplan_id, $bouwnummer='', $assoc_by_vraag_id=false ) { if (get_db_type() == 'oracle') { $preview_check_statement = ' ( CASE LENGTH(substr(utl_raw.cast_to_varchar2(dbms_lob.substr(preview,10,1)),0,1)) WHEN 1 THEN 1 ELSE 0 END )'; } else { $preview_check_statement = 'IF(preview IS NULL,0,LENGTH(preview)) > 0'; } if( $bouwnummer != '' ){ $bw_clause = 'AND bouwnummer = ? '; $args = array( $deelplan_id, $bouwnummer ); }else{ $bw_clause = ''; $args = array( $deelplan_id ); } if (!$this->dbex->is_prepared( 'find_by_deelplan' )) $this->dbex->prepare( 'find_by_deelplan', ' SELECT id, deelplan_id, gebruiker_id, vraag_id, filename, mimetype, datasize, uploaded_at, datatype, png_status, '.$preview_check_statement.' AS has_preview FROM deelplan_uploads WHERE 1=1 AND deelplan_id = ? '. $bw_clause. 'ORDER BY uploaded_at ' ); $res = $this->dbex->execute( 'find_by_deelplan', $args ); $result = array(); foreach ($res->result() as $row) { $object = $this->getr( $row ); if (!$assoc_by_vraag_id) $result[] = $object; else { if (!isset( $result[$row->vraag_id] )) $result[$row->vraag_id] = array(); $result[$row->vraag_id][] = $object; } } return $result; } public function add( $deelplan_id, $vraag_id, $filename, $data, $bouwnummer='', $gebruiker_id=null, $datatype='foto/video' ) { $CI = get_instance(); // The DB does not force us to have a unique combination of deelplan-vraag-file. Therefore, prevent this in code. $existing_files_with_given_combination = $this->get_unique_by_deelplan_vraag_filename( $deelplan_id, $vraag_id, $filename, $bouwnummer ); // Only proceed to add the file if the combination of the deelplan_id, vraag_id and the filename does not exist yet. if (empty($existing_files_with_given_combination)) { // get mimetype $CI->load->helper( 'file' ); $mimetype = get_mime_by_extension( strtolower( $filename ) ); if (!$mimetype) $mimetype = 'application/octet-stream'; // determine thumbnail $thumbnail = NULL; if (preg_match( '/\.(jpe?g|png|gif)$/', $filename )) { if (class_exists( 'Imagick' ) ) { try { $img = new Imagick(); $img->readImageBlob($data); $img = $this->_create_thumbnail( $img ); $img->setImageDepth( 24 ); $img->setImageFormat( 'jpeg' ); $thumbnail = $img->getImageBlob(); $img->destroy(); } catch (Exception $e) { $thumbnail = NULL; } } } // store // $last_insert_id = null; // if (!$this->dbex->is_prepared( 'add_upload_data' )) { // $this->dbex->prepare_with_insert_id( 'add_upload_data', 'INSERT INTO deelplan_upload_data (data) VALUES (?)', null, $last_insert_id ); // } // // $args = array( // 'data' => $data, // ); // // // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. // $force_types = (get_db_type() == 'oracle') ? 'b' : ''; // $this->dbex->execute( 'add_upload_data', $args, false, null, $force_types ); // Use the base model's 'insert' method. $values = array( 'deelplan_id' => $deelplan_id, 'gebruiker_id' => $gebruiker_id ? $gebruiker_id : $this->login->get_user_id(), 'vraag_id' => $vraag_id, 'filename' => $filename, 'datasize' => strlen( $data ), 'mimetype' => $mimetype, 'bouwnummer' => $bouwnummer, 'datatype' => $datatype, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. //$force_types = (get_db_type() == 'oracle') ? 'iiisiisbs' : ''; $force_types = (get_db_type() == 'oracle') ? 'iiisiss' : ''; $result = $this->insert( $values, '', $force_types ); // !!! TODO: REQUIRES ORACLE FIX UP!!!! //$last_id = $this->db->insert_id(); $last_id = (is_null($result)) ? 0 : $result->id; CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file($this->getUploadPath($deelplan_id) , $last_id, $data); if (!is_null($thumbnail)) { CI_Utils::store_file($this->getUploadPath( $deelplan_id ) . '/' . DIR_THUMBNAIL, $last_id, $thumbnail); } return $result; } else { // If the combination already exists, we do not store the file again but return an error message. // NOTE: We deliberately return an error message rather than 'false', so the caller has a more specific reason why the file was not added. // This is used in the 'toezicht' screen, when someone tries to upload a file that already exists for the passed deelplan/vraag combination. //return false; //return 'Het bestand bestaat reeds voor de combinatie van het huidige deelplan en de huidige vraag'; return 'Het bestand bestaat reeds bij de huidige vraag'; } } public function add_opdrachtupload ($opdracht_id, $upload_id) { // Can't use the base model for insert or we need to create a different model for this piece of code. // If deelplanopdrachtupload model will be added later, transfer this code to it $query = 'INSERT INTO deelplan_opdrachten_uploads (`opdracht_id`, `upload_id`) VALUES (?,?)'; $this->db->query($query, array($opdracht_id, $upload_id)); } public function getUploadPath( $deelplan_id) { if( isset($this->_upload_path) ) { return $this->_upload_path; } $query = 'SELECT dossier_id FROM deelplannen WHERE id = ?'; $this->_dossier_id = $dossier_id = $this->db->query($query, array($deelplan_id))->row()->dossier_id; $this->_upload_path = DIR_DEELPLAN_UPLOAD . '/' . $dossier_id . '/' .$deelplan_id; return $this->_upload_path; } public function add_using_data_id($deelplan_id, $vraag_id, $filename, $data_id, $datasize, $gebruiker_id = null, $datatype = 'foto/video') { // get mimetype $CI = get_instance(); $CI->load->helper( 'file' ); $mimetype = get_mime_by_extension( strtolower( $filename ) ); if (!$mimetype) { $mimetype = 'application/octet-stream'; } // Use the base model's 'insert' method. $data = array( 'deelplan_id' => $deelplan_id, 'gebruiker_id' => $gebruiker_id ? $gebruiker_id : $this->login->get_user_id(), 'vraag_id' => $vraag_id, 'filename' => $filename, // 'deelplan_upload_data_id' => $data_id, 'datasize' => $datasize, 'mimetype' => $mimetype, // 'preview' => $thumbnail, 'datatype' => $datatype, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. //$force_types = (get_db_type() == 'oracle') ? 'iiisiisbs' : ''; $force_types = (get_db_type() == 'oracle') ? 'iiisiss' : ''; $result = $this->insert( $data, '', $force_types ); $path = $this->getUploadPath($deelplan_id); $target = $path . '/' . $data_id; symlink($target, $path . '/' . $result->id); return $result; } private function _create_thumbnail( Imagick $im ) { $imW = $im->getImageWidth(); $imH = $im->getImageHeight(); $imR = (float)$imW / (float)$imH; $logoW = 100; $logoH = 56; $logoR = (float)$logoW / (float)$logoH; if ($imW != $logoW || $imH != $logoH) { // is the relation between height and width like we want it to be? if ($imR==$logoR) { // woohoo, easy scale! $im->resizeImage( $logoW, $logoH, imagick::FILTER_BOX, 0 ); } else { // what to scale? if ($imR < $logoR) { // scale by height $im->resizeImage( null, $logoH, imagick::FILTER_BOX, 0 ); $x = ($logoW - $im->getImageWidth()) / 2; $y = 0; } else { // scale by width $im->resizeImage( $logoW, null, imagick::FILTER_BOX, 0 ); $x = 0; $y = ($logoH - $im->getImageHeight()) / 2; } $whiteCol = new ImagickPixel( "rgb(255,255,255)" ); $im2 = new Imagick(); $im2->newImage( $logoW, $logoH, $whiteCol, 'png' ); $im2->setImageDepth( $im->getImageDepth() ); $im2->compositeImage( $im, imagick::COMPOSITE_DEFAULT, $x, $y ); $whiteCol->destroy(); $im->destroy(); $im = $im2; } } return $im; } }<file_sep><? require_once 'base.php'; class MatrixResult extends BaseResult { function MatrixResult( &$arr ) { parent::BaseResult( 'matrix', $arr ); } function copy_from( MatrixResult $rhs ) { // // **** prioriteitstellingen **** // // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... // copy all prioriteitstellingen $this->_CI->db->query( ' INSERT INTO bt_prioriteitstellingen (klant_id, checklist_id, matrix_id, gemaakt_op) SELECT klant_id, checklist_id, ' . $this->id . ', '.$now_func.' FROM bt_prioriteitstellingen WHERE matrix_id = ' . $rhs->id . ' ' ); // get all new prioriteitstellingen, and copy waardes $res = $this->_CI->db->query( ' SELECT ps1.id AS new_id, ps2.id AS old_id FROM bt_prioriteitstellingen ps1 JOIN bt_prioriteitstellingen ps2 ON (ps1.klant_id = ps2.klant_id AND ps1.checklist_id = ps2.checklist_id AND ps2.matrix_id = ' . $rhs->id . ') WHERE ps1.matrix_id = ' . $this->id . ' ' ); foreach ($res->result() as $ps) { $this->_CI->db->query( $query = ' INSERT INTO bt_prioriteitstelling_waarden (prioriteitstelling_id, hoofdgroep_id, hoofdthema_id, waarde) SELECT ' . $ps->new_id . ', hoofdgroep_id, hoofdthema_id, waarde FROM bt_prioriteitstelling_waarden ps WHERE prioriteitstelling_id = ' . $ps->old_id . ' ' ); } $res->free_result(); // // **** risicoanalyses **** // // !!! Query tentatively/partially made Oracle compatible. To be fully tested... // copy all risicoanalyses $this->_CI->db->query( ' INSERT INTO bt_risicoanalyses (klant_id, checklist_id, matrix_id, gemaakt_op) SELECT klant_id, checklist_id, ' . $this->id . ', '.$now_func.' FROM bt_risicoanalyses WHERE matrix_id = ' . $rhs->id . ' ' ); // get all new risicoanalyses, combined with old id's $res = $this->_CI->db->query( ' SELECT ra1.id AS new_id, ra2.id AS old_id FROM bt_risicoanalyses ra1 JOIN bt_risicoanalyses ra2 ON (ra1.klant_id = ra2.klant_id AND ra1.checklist_id = ra2.checklist_id AND ra2.matrix_id = ' . $rhs->id . ') WHERE ra1.matrix_id = ' . $this->id . ' ' ); $ras = array(); foreach ($res->result() as $row) $ras[$row->old_id] = $row->new_id; $res->free_result(); // copy kansen foreach ($ras as $old_id => $new_id) $this->_CI->db->query( $query = ' INSERT INTO bt_risicoanalyse_kansen (risicoanalyse_id, hoofdgroep_id, kans) SELECT ' . $new_id . ', hoofdgroep_id, kans FROM bt_risicoanalyse_kansen ps WHERE risicoanalyse_id = ' . $old_id . ' ' ); // copy effecten $effecten = array(); foreach ($ras as $old_id => $new_id) { $this->_CI->db->query( $query = ' INSERT INTO bt_risicoanalyse_effecten (risicoanalyse_id, effect, waarde, sortering) SELECT ' . $new_id . ', effect, waarde, sortering FROM bt_risicoanalyse_effecten ps WHERE risicoanalyse_id = ' . $old_id . ' ' ); // get all new risicoanalyses, combined with old id's $res = $this->_CI->db->query( ' SELECT ra1.id AS new_id, ra2.id AS old_id FROM bt_risicoanalyse_effecten ra1 JOIN bt_risicoanalyse_effecten ra2 ON (ra1.effect = ra2.effect AND ra1.waarde = ra2.waarde AND ra1.sortering = ra2.sortering AND ra2.risicoanalyse_id = ' . $old_id . ') WHERE ra1.risicoanalyse_id = ' . $new_id . ' ' ); $effecten = array(); foreach ($res->result() as $row) $effecten[$row->old_id] = $row->new_id; $res->free_result(); // copy waardes foreach ($effecten as $old_effect_id => $new_effect_id) $this->_CI->db->query( $query = ' INSERT INTO bt_risicoanalyse_waardes (risicoanalyse_id, hoofdgroep_id, risicoanalyse_effect_id, waarde) SELECT ' . $new_id . ', hoofdgroep_id, ' . $new_effect_id . ', waarde FROM bt_risicoanalyse_waardes ps WHERE risicoanalyse_id = ' . $old_id . ' AND risicoanalyse_effect_id = ' . $old_effect_id . ' ' ); } } public function get_klant() { $CI = get_instance(); return $CI->klant->get( $this->klant_id ); } } class Matrix extends BaseModel { function __construct() { parent::__construct( 'MatrixResult', 'matrices', true ); } public function check_access( BaseResult $object ) { // Relay naar checklistgroep, ook al hebben we zelf een klant_id! Maar // toegang tot de checklistgroep betekent, toegang tot elke matrix die erbij // hoort, dus dit is beter zo :) $this->check_relayed_access( $object, 'checklistgroep', 'checklist_groep_id' ); } function add( $klant_id, $checklist_groep_id, $naam, $is_standaard ) { /* if (!$this->dbex->is_prepared( 'Matrix::add' )) $this->dbex->prepare( 'Matrix::add', 'INSERT INTO matrices (klant_id, checklist_groep_id, naam, is_standaard) VALUES (?, ?, ?, ?)' ); $args = array( 'klant_id' => $klant_id, 'checklist_groep_id' => $checklist_groep_id, 'naam' => $naam, 'is_standaard' => $is_standaard, ); $this->dbex->execute( 'Matrix::add', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // The SOAP code that generates reports (i.e. the 'soapDossier' service, in the 'soapGetDeelplanResults' method) comes across this point without being // logged in. At that time it is not possible to successfully determine the proper 'klant_id' which results in a DB error. // Make sure to properly detect and trap this situation, and to use an overridden klant_id! if ( defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_klant_id'])) { $klant_id = $_POST['overridden_klant_id']; } // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'klant_id' => $klant_id, 'checklist_groep_id' => $checklist_groep_id, 'naam' => $naam, 'is_standaard' => $is_standaard, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } function zet_standaard_matrix_voor_checklist_groep( ChecklistGroepResult $checklistgroep, $matrix_id ) { foreach ($this->geef_matrices_voor_checklist_groep( $checklistgroep, true ) as $matrix) { $nieuwe_standaard_waarde = ($matrix->id == $matrix_id) ? 1 : 0; if ($matrix->is_standaard != $nieuwe_standaard_waarde) { $matrix->is_standaard = $nieuwe_standaard_waarde; if (!$matrix->save( 0, 0, 0 )) throw new Exception( 'Database fout bij zetten van nieuwe standaard matrix.' ); } } } function geef_standaard_matrix_voor_checklist_groep( ChecklistGroepResult $checklistgroep ) { $klant_id = $this->session->userdata( 'kid' ); // The SOAP code that generates reports (i.e. the 'soapDossier' service, in the 'soapGetDeelplanResults' method) comes across this point without being // logged in. At that time it is not possible to successfully determine the proper 'klant_id'. // Make sure to properly detect and trap this situation, and to use an overridden klant_id! if ( defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_klant_id'])) { $klant_id = $_POST['overridden_klant_id']; } // doorloop lijst van lokale (prive) matrices voor deze checklistgroep, als hier een standaard // matrix tussen zit, dan deze teruggeven foreach ($this->geef_matrices_voor_checklist_groep( $checklistgroep, true ) as $matrix) { if ($matrix->is_standaard) { return $matrix; } } // maak standaard matrix aan return $this->add( $klant_id, $checklistgroep->id, 'Standaard', 1 ); } function geef_matrices_voor_checklist_groep( ChecklistGroepResult $checklistgroep, $only_private_ones=false, $assoc=false ) { $klant_id = $this->session->userdata( 'kid' ); // The SOAP code that generates reports (i.e. the 'soapDossier' service, in the 'soapGetDeelplanResults' method) comes across this point without being // logged in. At that time it is not possible to successfully determine the proper 'klant_id'. // Make sure to properly detect and trap this situation, and to use an overridden klant_id! if ( defined('IS_WEBSERVICE') && IS_WEBSERVICE && !empty($_POST['overridden_klant_id'])) { $klant_id = $_POST['overridden_klant_id']; } // build statement $stmt_name = 'geef_matrices_voor_checklist_groep'; if ($only_private_ones) { $this->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->_table . ' WHERE klant_id = ? AND checklist_groep_id = ?' ); $args = array( $klant_id, $checklistgroep->id ); } else { $this->dbex->prepare( $stmt_name, ' SELECT * FROM ' . $this->_table . ' WHERE (klant_id = ? OR klant_id = ?) AND checklist_groep_id = ? ' ); $args = array( $klant_id, $checklistgroep->klant_id, $checklistgroep->id ); } // execute $res = $this->dbex->execute( $stmt_name, $args ); // build result array $result = array(); foreach ($res->result() as $row) if ($assoc) $result[$row->id] = $this->getr( $row ); else $result[] = $this->getr( $row ); $res->free_result(); // done! return $result; } } <file_sep>ALTER TABLE `bt_richtlijnen` CHANGE `data` `data` LONGBLOB NULL DEFAULT NULL ; ALTER TABLE `bt_richtlijnen` ADD `url` VARCHAR( 1024 ) NULL DEFAULT NULL AFTER `data` ; <file_sep><?php class CI_RisicoGrafiek { private $_CI = null; public function __construct() { $this->_CI = get_instance(); define( 'TTF_DIR', APPPATH . 'libraries/grafieken/fonts/' ); $this->_CI->load->helper( 'jpgraph' ); } public function generate_risico_grafiek ($graph_title = 'Risicoprofiel ', $data_kans = array(), $data_effect = array(), $data_legenda = array()) { // Set the filename that the graph should use $path = APPPATH . '/../'; $filename = $graph_title.implode('-',$data_kans).implode('-',$data_effect).implode('-',$data_legenda); $filename = '/files/cache/grafieken/' . sha1( $filename) . '.png'; if( file_exists($path.$filename) ) { return $filename; } // Define the 'border values' for the risk areas. $waardenRisico = array( 20 => array("plotColor" => "#05CBFC", "dataY" => array()), 70 => array("plotColor" => "#309A6A", "dataY" => array()), 200 => array("plotColor" => "#FEFF99", "dataY" => array()), 400 => array("plotColor" => "#F5A000", "dataY" => array()), 10000 => array("plotColor" => "#FE0002", "dataY" => array()), ); $waardenRisicoKeys = array_keys($waardenRisico); // Now calculate the data set for the border line plots. This is done with variable 'Kans' and 'Effect' values, in increments of 1. // We first iterate over the X direction (i.e. 'Effect'), and then per 'effect', checking if the currently calculated value passes one // of the "risk" borders, and the "kans" value to the Y positions of the correct color. $dataYRed = $dataYOrange = $dataYYellow = $dataYGreen = $dataYBlue = array(); $maxEffectValue = $maxKansValue = 100; for ($effectCnt = 0 ; $effectCnt <= $maxEffectValue ; $effectCnt++) //for ($effectCnt = 0 ; $effectCnt <= $maxEffectValue ; $effectCnt+=0.1) { $previousRisico = 0; // Initialise the booleans that keep track of whether a specific risk has been found or not. //$riskBlueFound = $riskGreenFound = $riskYellowFound = $riskOrangeFound = $riskRedFound = false; foreach ($waardenRisicoKeys as $riskBorderValue) { $riskBorderFoundStr = 'riskBorder' . $riskBorderValue . 'Found'; $$riskBorderFoundStr = false; } // Now iterate 'upwards' over the 'kansen' //for ($kansCnt = 0 ; $kansCnt <= $maxKansValue ; $kansCnt++) for ($kansCnt = 0 ; $kansCnt <= $maxKansValue ; $kansCnt+=0.1) { // Calculate the current value. $currentRisico = $effectCnt * $kansCnt; // Check in which area the current value falls, and whether a border is crossed (for the first time!) or not. foreach ($waardenRisicoKeys as $riskBorderValue) { $riskBorderFoundStr = 'riskBorder' . $riskBorderValue . 'Found'; if ( ($previousRisico < $riskBorderValue) && ($currentRisico >= $riskBorderValue) && !$$riskBorderFoundStr ) { $waardenRisico["$riskBorderValue"]["dataY"][] = $kansCnt; $$riskBorderFoundStr = true; } } // Update the 'previous' value, for the next iteration. $previousRisico = $currentRisico; } // for ($kansCnt = 0 ; $kansCnt <= $maxKansValue ; $kansCnt++) // When all 'kans' values have been traversed, we check for 'missing' values. If present, we set them to the highest 'kans' value. foreach ($waardenRisicoKeys as $riskBorderValue) { $riskBorderFoundStr = 'riskBorder' . $riskBorderValue . 'Found'; if (!$$riskBorderFoundStr) { $waardenRisico["$riskBorderValue"]["dataY"][] = $maxKansValue; } } } // for ($effectCnt = 0 ; $effectCnt <= $maxEffectValue ; $effectCnt++) // Create the graph itself. Apply a correction if necessary for adjusting for the legend height. // If the legend contains more than 1 row of legend entries (i.e. max. $legend_columns entries), add 15 pixels for each additional row. $legend_columns = 4; $legend_correction = ((sizeof($data_legenda))/4 * 15); $graph = new Graph(900,600+$legend_correction); //$graph->SetScale("textlin"); $graph->SetScale("linlin"); $graph->SetShadow(); $graph->img->SetMargin(40,30,20,40); // Since the plots need to be added in reverse order, we first get the inverse of the dataset. $waardenRisicoDescending = array_reverse($waardenRisico); //d($waardenRisicoDescending); // Now generate the filled line plots and add them to the graph foreach ($waardenRisicoDescending as $riskBorderValue => $riskPlotSet) { $lPlotStr = 'linePlot' . $riskBorderValue; $$lPlotStr = new LinePLot($riskPlotSet["dataY"]); $$lPlotStr->SetFillColor($riskPlotSet["plotColor"]); $graph->Add($$lPlotStr); } /* // Scatterplot data $sp1 = new ScatterPlot($data_effect, $data_kans); $sp1->mark->SetType(MARK_FILLEDCIRCLE); $sp1->mark->SetFillColor("purple"); $sp1->mark->SetWidth(8); $graph->Add($sp1); * */ for ($idx = 0 ; $idx < sizeof($data_effect) ; $idx++) { // Create the linear plot $lineplot = new LinePlot(array($data_effect[$idx]), array($data_kans[$idx])); //$lineplot->mark->SetType(MARK_UTRIANGLE); //$lineplot->mark->SetColor('blue'); //$lineplot->mark->SetFillColor('red'); $lineplot->mark->SetType(MARK_FILLEDCIRCLE); $lineplot->mark->SetFillColor("purple"); $lineplot->mark->SetWidth(8); // Create the legend entry. Shorten the legend entries, if necessary. $mark_number = ($idx + 1); $max_legend_text_length = 25; //$data_legenda[$idx] = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $legend_entry = (strlen($data_legenda[$idx]) <= $max_legend_text_length) ? $data_legenda[$idx] : substr($data_legenda[$idx], 0, $max_legend_text_length).'...'; $lineplot->SetLegend("{$mark_number}: " . $legend_entry); // Add the number of the entry to the data point itself in the graph. $txt = new Text("{$mark_number}"); $text_pos_x = $data_kans[$idx] + -0.5; $text_pos_y = $data_effect[$idx] + 1.85; // Make sure that the text positions are between 0-100% as otherwise either of the scales is automatically extended, which we do not want to happen! $text_pos_x = ($text_pos_x > 0) ? $text_pos_x : 0; $text_pos_y = ($text_pos_y > 0) ? $text_pos_y : 0; $text_pos_x = ($text_pos_x <= 100) ? $text_pos_x : 100; $text_pos_y = ($text_pos_y <= 100) ? $text_pos_y : 100; $txt->SetScalePos($text_pos_x, $text_pos_y); // Set color and font for the text //$txt->SetColor('black'); $txt->SetColor('white'); $txt->SetFont(FF_FONT2,FS_BOLD); // ... and add the text to the graph $graph->AddText($txt); // Add the plot to the graph $graph->Add($lineplot); } // Use 50% blending //$graph->ygrid->SetFill(true,'#EFEFEF@0.5','#BBCCFF@0.5'); $graph->ygrid->SetLineStyle('dotted'); $graph->ygrid->Show(); //$graph->xgrid->SetFill(true,'#EFEFEF@0.5','#BBCCFF@0.5'); $graph->xgrid->SetLineStyle('dotted'); $graph->xgrid->Show(); //$graph->xaxis->SetTextTickInterval(2); $graph->xaxis->SetTextTickInterval(1); $graph->xaxis->SetTextLabelInterval(1); // Force the X-axis to show ticks for every 5% and labels for every 10% values. $graph->xaxis->SetTickPositions(array(0,10,20,30,40,50,60,70,80,90,100), array(5,15,25,35,45,55,65,75,85,95)); $graph->xaxis->HideLine(false); $graph->xaxis->HideTicks(false,false); //$graph->title->Set("Risicoprofiel volgens Fine and Kinney model"); $graph->title->Set($graph_title); $graph->xaxis->title->Set("Effect"); $graph->yaxis->title->Set("Kans"); $graph->title->SetFont(FF_FONT1,FS_BOLD); $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD); $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD); $graph->legend->SetColumns($legend_columns); $graph->legend->SetMarkAbsSize(6); // $filename = '/files/cache/grafieken/' . sha1( mt_rand() . microtime(true) ) . '.png'; //if (!file_put_contents( $path . $filename, strval( $png_data ) )) // Generate the graph //$graph->Stroke(); $graph->Stroke( $path.$filename); return $filename; } // public function generate_risico_grafiek ($graph_title = 'Risicoprofiel ', $data_kans = array(), $data_effect = array(), $data_legenda = array()) } // class CI_RisicoGrafiek <file_sep><?php class ExportExcel { protected $_CI; private $_output_format; // Document content private $documents = array(); private $excel_content = ''; private $soap_method = 'soapGenerateGenericDocument'; private $soap_parameters = array(); public function __construct($output_format = 'xlsx') { $this->_CI = get_instance(); $this->_output_format = $output_format; } /******************************************************************************** * * * MAIN FUNCTIONS * * * ********************************************************************************/ public function get_excel_content() { return $this->excel_content; } public function _generate($documents = array()) { // initialize progress //$this->_init_progress(); if ($documents) { $this->documents = $documents; $this->_soap_call(); } } private function _soap_call () { get_instance()->load->helper( 'soapclient' ); // Get the proper location of the webservice we need to call. Note: this must be specified in the application/config/config.php file! $randval = rand(); $this->soap_wsdl = $this->_CI->config->item('ws_url_wsdl_brimo_soapdocument') . '/' . $randval; // Construct the compound set of parameters that the SOAP call expects $this->soap_parameters['licentie_naam'] = 'BTZ'; $this->soap_parameters['licentie_wachtwoord'] = 'BTZ'; $this->soap_parameters['documents'] = $this->documents; // Instantiate a wrapped SoapClientHelper for generating the report using BRIMO. // Note: for 'silent' connections that do not generate output, the following settings should be used. $debug = false; $silent = true; // Note: for 'chatty' debug connections that generate output, the following settings should be used. //$debug = true; //$silent = false; $randval = rand(); $wrappedSoapClient = getWrappedSoapClientHelper($this->soap_wsdl."/{$randval}", $this->soap_method, $debug, $silent); // If no SOAP errors were encountered during the connection set-up, we continue. Otherwise we error out. if (empty($wrappedSoapClient->soapErrors)) { // No time limit, export might take a while! // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit( 3600 ); $wsResult = $wrappedSoapClient->soapClient->CallWsMethod('', $this->soap_parameters); if (empty($wsResult)) { echo "De webservice aanroep heeft geen data geretourneerd!<br /><br />"; //exit; } } else { echo "Foutmelding(en) bij maken connectie:<br />\n"; echo "<br />\n"; foreach ($wrappedSoapClient->soapErrors as $curError) { echo $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } // Return early, so no attempt is made to proceed (which would fail anyway). return; } // If no SOAP errors were encountered during the webservice method call, we continue. Otherwise we error out. $errorsDuringCall = $wrappedSoapClient->soapClient->GetErrors(); if (!empty($errorsDuringCall)) { echo "Foutmelding(en) bij RPC aanroep:<br />\n"; echo "<br />\n"; foreach ($errorsDuringCall as $curError) { echo $curError . "<br />\n"; //$this->data['errorsText'] .= $curError . "<br />"; } d($wrappedSoapClient); echo "+++++++++++++<br /><br />"; echo $wrappedSoapClient->soapClient->GetRawLastResponse() . '<br /><br />'; // Return early, so no attempt is made to proceed (which would fail anyway). return; } $this->excel_content = $wsResult; } } <file_sep>ALTER TABLE `bt_checklisten` DROP `standaard_checklist_status`; <file_sep>DROP TABLE kennisid_tijden; <file_sep>-- update deelplan_vragen ALTER TABLE `deelplan_vragen` CHANGE `status` `status` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL; UPDATE deelplan_vragen SET status = 'w00' WHERE status = 'in_behandeling'; UPDATE deelplan_vragen SET status = 'w01' WHERE status = 'nvt'; UPDATE deelplan_vragen SET status = 'w02' WHERE status = 'nader_onderzoek_nodig'; UPDATE deelplan_vragen SET status = 'w03' WHERE status = 'niet_kunnen_controleren'; UPDATE deelplan_vragen SET status = 'w04' WHERE status = 'niet_gecontroleerd'; UPDATE deelplan_vragen SET status = 'w04s' WHERE status = 'niet_gecontroleerd_ivm_steekproef' OR status = 'niet_gecontroleerd_ivm_steekproe'; UPDATE deelplan_vragen SET status = 'w10' WHERE status = 'voldoet'; UPDATE deelplan_vragen SET status = 'w11' WHERE status = 'bouwdeel_voldoet'; UPDATE deelplan_vragen SET status = 'w12' WHERE status = 'gelijkwaardig'; UPDATE deelplan_vragen SET status = 'w13' WHERE status = 'voldoet_na_aanwijzingen'; UPDATE deelplan_vragen SET status = 'w20' WHERE status = 'voldoet_niet'; UPDATE deelplan_vragen SET status = 'w21' WHERE status = 'voldoet_niet_niet_zwaar'; ALTER TABLE `deelplan_vragen` CHANGE `status` `status` VARCHAR( 4 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL; -- update deelplan_vraag_geschiedenis ALTER TABLE `deelplan_vraag_geschiedenis` CHANGE `status` `status` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL; UPDATE deelplan_vraag_geschiedenis SET status = 'w00' WHERE status = 'in_behandeling' OR status = ''; UPDATE deelplan_vraag_geschiedenis SET status = 'w01' WHERE status = 'nvt'; UPDATE deelplan_vraag_geschiedenis SET status = 'w02' WHERE status = 'nader_onderzoek_nodig'; UPDATE deelplan_vraag_geschiedenis SET status = 'w03' WHERE status = 'niet_kunnen_controleren'; UPDATE deelplan_vraag_geschiedenis SET status = 'w04' WHERE status = 'niet_gecontroleerd'; UPDATE deelplan_vraag_geschiedenis SET status = 'w04s' WHERE status = 'niet_gecontroleerd_ivm_steekproef' OR status = 'niet_gecontroleerd_ivm_steekproe'; UPDATE deelplan_vraag_geschiedenis SET status = 'w10' WHERE status = 'voldoet'; UPDATE deelplan_vraag_geschiedenis SET status = 'w11' WHERE status = 'bouwdeel_voldoet'; UPDATE deelplan_vraag_geschiedenis SET status = 'w12' WHERE status = 'gelijkwaardig'; UPDATE deelplan_vraag_geschiedenis SET status = 'w13' WHERE status = 'voldoet_na_aanwijzingen'; UPDATE deelplan_vraag_geschiedenis SET status = 'w20' WHERE status = 'voldoet_niet'; UPDATE deelplan_vraag_geschiedenis SET status = 'w21' WHERE status = 'voldoet_niet_niet_zwaar'; ALTER TABLE `deelplan_vraag_geschiedenis` CHANGE `status` `status` VARCHAR( 4 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL; <file_sep>ALTER TABLE deelplan_checklisten ADD `toezicht_gebruiker_id` int(11) DEFAULT NULL, ADD `matrix_id` int(11) DEFAULT NULL, ADD `initiele_datum` date DEFAULT NULL, ADD `voortgang_percentage` int(11) NOT NULL DEFAULT '0'; ALTER TABLE `deelplan_checklisten` ADD INDEX ( `toezicht_gebruiker_id` ); ALTER TABLE `deelplan_checklisten` ADD INDEX ( `matrix_id` ) ; ALTER TABLE `deelplan_checklisten` ADD FOREIGN KEY ( `toezicht_gebruiker_id` ) REFERENCES `gebruikers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; ALTER TABLE `deelplan_checklisten` ADD FOREIGN KEY ( `matrix_id` ) REFERENCES `matrices` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; <file_sep>ALTER TABLE lease_configuraties ADD url VARCHAR(255) NOT NULL; ALTER TABLE lease_configuraties ADD email_sender VARCHAR(255) NOT NULL;<file_sep><?php require_once( APPPATH . 'helpers/jpgraph/src/jpgraph.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_bar.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_pie.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_pie3d.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_date.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_line.php' ); require_once( APPPATH . 'helpers/jpgraph/src/jpgraph_scatter.php' ); <file_sep>ALTER TABLE `rollen` ADD `is_lease` TINYINT NOT NULL DEFAULT '0'; UPDATE `rollen` SET is_lease = 1 WHERE naam LIKE '[BL]%'; <file_sep><div class="nlaf_TabContent"> <table cellpadding="5" cellspacing="1" class="opdrachten-tabel"> <tr class="header"> <th style="width:300px"><?=tg('opdrachten.opdracht')?></th> <th style="width:130px"><?=tg('opdrachten.locatie')?></th> <th style="width:130px"><?=tg('opdrachten.betrokkene')?></th> <th style="width:70px"><?=tg('opdrachten.datum')?></th> <th style="width:70px"><?=tg('opdrachten.gereed')?></th> <th style="width:50px"></th> </tr> </table> <div class="opdrachten-tabel"> <table cellpadding="5" cellspacing="1" class="opdrachten-tabel rows"> </table> </div> <div class="toolbar" style="width:877px"> <div class="regular_button noselect inlineblock" onclick="BRISToezicht.Toets.Opdracht.openPopup();" style="margin-left: 8px; float: left;"> <?=tg('opdrachten.nieuw')?> </div> <div style="float:right; margin-right: 10px; margin-top: 7px;"> <label> <nobr> <input type="radio" name="opdracht-filter" value="relevant" checked onclick="BRISToezicht.Toets.Opdracht.toonRelevant();" /> <?=tg('relevant')?> </nobr> </label> <label> <nobr> <input type="radio" name="opdracht-filter" value="alles" onclick="BRISToezicht.Toets.Opdracht.toonAlles();" /> <?=tg('alles')?> </nobr> </label> </div> </div> </div> <file_sep><? $this->load->view('elements/header', array('page_header'=>'risicoprofielen.dmmlist','map_view'=>true)); ?> <h1><?=$name?></h1> <h4><?=tgg('risicoprofielen.dmmlist.select')?></h4> <div class="main"> <? if(count($list) > 0):?> <ul id="sortable" class="list mappen" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==sizeof($list)-1) ? 'bottom' : ''; ?> <li id="dmm_<?=$entry->id ?>" class="entry top left right <?=$bottom?>" entry_id="<?=$entry->id ?>"> <div class="list-entry" style="margin-top:10px;padding-left:5px;font-weight:bold;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <div id="volgende_btn" class="button" style="float:right;margin-top: 15px;"> <?=tgg('mappingen.buttons.volgende')?> </div> <?else:?> <div style="padding-top:10px;padding-left:5px;font-weight:bold;"><?=tgg('list.noitems') ?></div> <?endif ?> </div> <? $this->load->view('elements/footer'); ?> <script type="text/javascript"> $(document).ready(function(){ var dmm_selected_id =<?=((bool)$dmm_id?$dmm_id:'null')?> ; if(dmm_selected_id!=null){ $("#dmm_"+dmm_selected_id) .removeClass("entry") .addClass("entry-selected"); } //------------------------------------------------------------------------------ $('li[entry_id]').click(function(){ if(dmm_selected_id!=null){ $("#dmm_"+dmm_selected_id) .removeClass("entry-selected") .addClass("entry"); } dmm_selected_id = $(this).attr('entry_id'); $(this) .removeClass("entry") .addClass("entry-selected"); }); //------------------------------------------------------------------------------ $("#volgende_btn").click(function(){ if(dmm_selected_id==null){ showMessageBox({ message: "DMM not selected.", type: 'error', buttons: ['ok'] }); return; } location.href = '<?=site_url('/risicoprofielen/generate_risicoprofielen/').'/'?>'+dmm_selected_id; <?php /* ?> location.href = '<?=site_url('/risicoprofielen/btrisicoprofielenlist/').'/'.$drsm->id.'/'?>'+dmm_selected_id; <?php /* */ ?> }); }); </script> <file_sep>/** * Observable class, implements events, listeners and dispatchers */ var Observable = Class.extend({ init: function() { this.listeners = {}; }, registerEventType: function( type ) { if (this.listeners[ type ] == undefined) this.listeners[ type ] = []; }, on: function( type, listener ) { if (this.listeners[ type ] == undefined) throw 'Observable.on: event type ' + type + ' not registered'; if (indexOfArray( this.listeners[ type ], listener ) === -1) this.listeners[ type ].push( listener ); }, dispatchEvent: function( type, properties ) { if (properties == undefined) properties = {}; properties.type = type; for ( var listener in this.listeners[ type ] ) this.listeners[ type ][ listener ]( this, properties ); }, removeListener: function( type, listener ) { var index = indexOfArray( this.listeners[ type ], listener ); if ( index !== -1 ) this.listeners[ type ].splice( index, 1 ); }, removeAllListeners: function( type ) { delete this.listeners[ type ]; this.registerEventType( type ); } }); <file_sep><?php require_once 'base.php'; class OrgKenmerkenResult extends BaseResult { function OrgKenmerkenResult( $arr ){ // parent::BaseResult( 'org_kenmerken', $arr ); foreach ($arr as $k => $v) $this->$k = $v; } function get_dossier() { return $this->_CI->dossier->get( $this->dossier_id ); } }// Class end class Org_kenmerken extends BaseModel { function Org_kenmerken(){ parent::BaseModel( 'OrgKenmerkenResult', 'cust_rep_data_155_org_kenm' ); } public function get_for_dossier( DossierResult $dossier ){ return $this->search( array( 'dossier_id' => $dossier->id )); } public function add( DossierResult $dossier, array $postdata ){ $postdata['dossier_id'] = $dossier->id; return $this->insert( $postdata ); } //------------------------------------------------------------------------------ public function save( DossierResult $dossier, array $postdata ){ $postdata['dossier_id'] = $dossier->id; if( $postdata['id'] == '' ){ return $this->insert( $postdata ); }else{ return parent::save( (object)$postdata ); } } //------------------------------------------------------------------------------ public function check_access( BaseResult $object ){ $this->check_relayed_access( $object, 'org_kenmerken', 'dossier_id' ); } // "SELECT * FROM cust_rep_data_155_org_kenm WHERE dossier_id = ? LIMIT 1" function get_by_dossier( $dossier_id, $assoc=false ) { if (!$this->dbex->is_prepared( 'get_org_kenmerken_by_dossier' )) $this->dbex->prepare( 'get_org_kenmerken_by_dossier', "SELECT * FROM cust_rep_data_155_org_kenm WHERE dossier_id = ?" ); $res = $this->dbex->execute( 'get_org_kenmerken_by_dossier', array( $dossier_id ) ); $result = $res->result(); if( !is_array($result) ) throw new Exception( 'DB error' ); if(count($result) > 0 ) return new OrgKenmerkenResult($result[0]); else return NULL; // $result = array(); // foreach ($res->result() as $row) // if ($assoc) // $result[ $row->id ] = $this->getr( $row ); // else // $result[] = $this->getr( $row ); // return $result; } }// Class end <file_sep>PDFAnnotator.Tool.Pan = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'pan' ); this.on( 'select', function( tool, data ){ var layer = tool.engine.getActiveLayer(); if (!layer) return; layer.forEachContainer(function( container ){ container.disableDragEvents(); }); }); this.on( 'deselect', function( tool, data ){ var layer = tool.engine.getActiveLayer(); if (!layer) return; layer.forEachContainer(function( container ){ container.enableDragEvents(); }); }); } }); <file_sep>ALTER TABLE klanten ADD COLUMN not_automaticly_select_betrokkenen INT(11) DEFAULT 0; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('klant.not_automaticly_select_betrokkenen', 'Do not automaticly select all Betrokkenen.', NOW(), 0); <file_sep><? if (!is_null( @$height )): ?> </div> </div> <? else: ?> </div> <? endif; ?><file_sep>ALTER TABLE `deelplan_vragen` CHANGE `status` `status` ENUM( 'onbeoordeeld', 'voldoet', 'voldoet_niet', 'gelijkwaardig', 'nvt', 'bouwdeel_voldoet', 'voldoet_na_aanwijzingen', 'voldoet_niet_niet_zwaar', 'nader_onderzoek_nodig', 'niet_gecontroleerd', 'niet_gecontroleerd_ivm_steekproef' ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL; CREATE TABLE IF NOT EXISTS `steekproeven` ( `id` int(11) NOT NULL AUTO_INCREMENT, `klant_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, `teller` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `klant_id` (`klant_id`,`vraag_id`), KEY `vraag_id` (`vraag_id`) ) ENGINE=InnoDB; ALTER TABLE `steekproeven` ADD CONSTRAINT `steekproeven_ibfk_1` FOREIGN KEY (`klant_id`) REFERENCES `klanten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `steekproeven_ibfk_2` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `klanten` ADD `steekproef_interval` INT NOT NULL DEFAULT '10'; ALTER TABLE `klanten` DROP `management_tijd_info_bijhouden`; <file_sep>-- Note: previously a table rename was performed such that the bt_checklist_groep_verantwtkstn was renamed to bt_checklist_groep_veranttkstn so it -- would not exceed Oracle's 30 character identifier limit. This, however, was not done for the other tables ending in 'verantwtkstn', causing trouble -- in several parts of the code. -- The proper way to fix this and maintain Oracle compatibility would be to complete that change and rename the other tables and the code references too, -- however, at this moment it is quite possible that Oracle no longer needs to be supported and therefore until further notice the path of least resistance -- is chosen by 'undoing' the previous rename actions. /* -- Previous rename actions: -- First step: drop the foreign keys that refer to tables/fields that need to renamed: -- ALTER TABLE ... DROP FOREIGN KEY ...; ALTER TABLE bt_checklist_groep_verantwtkstn DROP FOREIGN KEY `bt_checklist_groep_verantwtkstn_ibfk_1`; -- Now rename the table(s): RENAME TABLE bt_checklist_groep_verantwtkstn TO bt_checklist_groep_veranttkstn; -- Create the keys again, using the new names: ALTER TABLE bt_checklist_groep_veranttkstn ADD CONSTRAINT `FK_b_c_g_v__checklist_groep_id` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; */ -- "rename undo actions": -- First step: drop the foreign keys that refer to tables/fields that need to renamed: -- ALTER TABLE ... DROP FOREIGN KEY ...; ALTER TABLE bt_checklist_groep_veranttkstn DROP FOREIGN KEY `FK_b_c_g_v__checklist_groep_id`; -- Now rename the table(s): RENAME TABLE bt_checklist_groep_veranttkstn TO bt_checklist_groep_verantwtkstn; -- Create the keys again, using the new names: ALTER TABLE bt_checklist_groep_verantwtkstn ADD CONSTRAINT `FK_b_c_g_v__checklist_groep_id` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><?php function page_stats() { global $class, $method; $CI = get_instance(); // Get the proper DB function for determining the current date/time $now_func = get_db_now_function(); // gebruik last request update if ($user_id = $CI->login->get_user_id()) { $CI->db->query( 'UPDATE gebruikers SET laatste_request = '.$now_func.' WHERE id = ' . intval( $user_id) ); } // disable page statistics if (FALSE) { // page stat if (!$CI->dbex->is_prepared( 'pagina_stats_update' )) $CI->dbex->prepare( 'pagina_stats_update', 'UPDATE stats_paginas SET aantal = aantal + 1 WHERE pagina = ? AND functie = ?' ); $args = array( $class, $method ); $res = $CI->dbex->execute( 'pagina_stats_update', $args ); if ($CI->db->affected_rows()==0) { if (!$CI->dbex->is_prepared( 'pagina_stats_insert' )) $CI->dbex->prepare( 'pagina_stats_insert', 'INSERT INTO stats_paginas (pagina, functie, aantal) VALUES (?, ?, 1)' ); $CI->dbex->execute( 'pagina_stats_insert', $args ); } // uri stat $time = time(); if (!$CI->dbex->is_prepared( 'add_uri_stats' )) $CI->dbex->prepare( 'add_uri_stats', 'INSERT INTO stats_uris (ip, uri, timestamp) VALUES (?,?,?)' ); $args = array( $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], $time ); $CI->dbex->execute( 'add_uri_stats', $args ); // uri stat cleanup if (mt_rand( 0, 50 ) == 30) { if (!$CI->dbex->is_prepared( 'del_uri_stats' )) $CI->dbex->prepare( 'del_uri_stats', 'DELETE FROM stats_uris WHERE timestamp < ?' ); $args = array( $time - (24*60*60) ); $CI->dbex->execute( 'del_uri_stats', $args ); } } }<file_sep>CREATE TABLE IF NOT EXISTS `stats_nokia_maps` ( `id` int(11) NOT NULL AUTO_INCREMENT, `jaar` int(11) NOT NULL, `maand` int(11) NOT NULL, `aantal` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `jaar` (`jaar`,`maand`) ) ENGINE=InnoDB; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <form method="POST"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Inloggen systeembeheer', 'width' => '920px' ) ); ?> Systeembeheer wachtwoord:<br/> <input type="password" name="wachtwoord" size="30" /> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <br/> <p> <input type="submit" value="Inloggen" /> </p> </form> <script type="text/javascript"> $('select[name^=checklistgroepen]').change(function(){ var cg_id = $(this).attr('cg_id'); var value = this.value; $('div.cg' + cg_id + ', tr.cg' + cg_id).hide(); $('div.cg' + cg_id + '.' + value + ', tr.cg' + cg_id + '.' + value).show(); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class SupervisionMomentsClgResult extends BaseResult { public function __construct($arr) { parent::BaseResult('supervisionmomentsclg', $arr); } } class SupervisionMomentsClg extends BaseModel { public function __construct() { parent::BaseModel('SupervisionMomentsClgResult', 'supervision_moments_clg'); } // silly method only for overwrite their parent public function check_access(BaseResult $object) { if( isset($object->klant_id) ) { parent::check_access($object); } } }<file_sep><? $tab = 200; ?> <form name="pbm_form" id="pbm_form" method="post" action="/dossiers/save_pbm/<?=$dossier->id?>"> <input type="hidden" name="id" id="id" value="<?=isset($func->id)?$func->id:''?>" /> <table class="rapportage-filter pago_pmo_form_tbl"> <tr><td class="column"><?=tg('kritieke_taak')?></td><td class="input"><input type="text" name="pbm_taak_name" id="kritieke_taak" value="<?=isset($func->pbm_taak_name)?$func->pbm_taak_name:''?>" /></td></tr> <tr><td><button type="submit">Opslaan</button></td><td><button type="button" onclick="cancel_pago_pbm_form();">Annuleren</button></td></tr> </table> </form> <script> $('#pbm_form').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), dataType: 'json', success: function (data) { alert( '<?=tg('successfully_saved')?>' ); var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pbm/' . $dossier->id)?>' ); }, error: function() { alert( '<?=tg('error_not_saved')?>' ); } }); }); function cancel_pago_pbm_form(){ var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pbm/' . $dossier->id)?>' ); } </script><file_sep><? $this->load->view('elements/header', array('page_header'=>'intro')); ?> <? foreach ($versies as $i => $n): ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => $n['versie'] . '<span style="float:right"><i>' . $n['datum'] . '</i></span>', 'onclick' => '', 'expanded' => !$i, 'group_tag' => 'nieuws', 'width' => '100%', 'height' => '300px' ) ); ?> <?=nl2br( $n['tekst'] )?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? endforeach; ?> <? $this->load->view('elements/footer'); ?><file_sep>-- stap 1 ALTER TABLE `deelplan_vragen` ADD `hercontrole_datum` DATE NULL DEFAULT NULL AFTER `last_updated_at` ; ALTER TABLE `deelplannen` ADD `initiele_datum` DATE NULL DEFAULT NULL AFTER `aangemaakt_op` ; UPDATE deelplannen SET initiele_datum = (SELECT IF(gepland_datum='1970-01-01',NULL,gepland_datum) FROM dossiers WHERE dossiers.id = deelplannen.dossier_id); -- stap 2 ALTER TABLE dossiers DROP `gepland_datum`; -- stap 3 ALTER TABLE `deelplan_checklist_groepen` ADD `initiele_datum` DATE NULL DEFAULT NULL; UPDATE deelplan_checklist_groepen SET initiele_datum = (SELECT initiele_datum FROM deelplannen WHERE deelplannen.id = deelplan_checklist_groepen.deelplan_id); -- stap 4 ALTER TABLE `deelplannen` DROP `initiele_datum`; <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.vraag_volgorde')?></h1> <? $this->load->view( 'checklistwizard/_volgorde', array( 'entries' => $vragen, 'get_id' => function( $v ) { return $v->id; }, 'get_image' => function( $v ) use ($checklistgroep) { return $checklistgroep->get_image(); }, 'get_naam' => function( $v ) { return $v->tekst; }, 'store_url' => '/checklistwizard/vraag_volgorde/' . $hoofdgroep->id, 'return_url' => '/checklistwizard/vragen/' . $hoofdgroep->id, ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $col_widths = $col_description = array(); if ($allow_klanten_edit) { $col_widths['klant'] = 200; $col_description['klant'] = 'Klant'; } $col_widths = array_merge( $col_widths, array( 'naam' => 200, 'gebruik' => 100, 'opties' => 100, ) ); $col_description = array_merge( $col_description, array( 'naam' => 'Sjabloon naam', 'gebruik' => 'Gebruik', 'opties' => 'Opties', ) ); $rows = array(); foreach ($sjablonen as $i => $sjabloon) { $row = (object)array(); $row->onclick = "location.href='" . site_url('/instellingen/scopesjabloon_bewerken/' . $sjabloon->id) . "'"; $row->data = array(); if ($allow_klanten_edit) $row->data['klant'] = ($sjabloon->klant_id && isset($klanten[$sjabloon->klant_id])) ? $klanten[$sjabloon->klant_id]->naam : '- alle -'; $row->data['naam'] = htmlentities( $sjabloon->naam, ENT_COMPAT, 'UTF-8' ); $row->data['gebruik'] = isset($gebruik[$sjabloon->id]) ? $gebruik[$sjabloon->id] . 'x' : '- nog niet -'; $row->data['opties'] = '<a href="javascript:void(0);" onclick="if (confirm(\'Scope sjabloon werkelijk verwijderen?\')) location.href=\'' . site_url('/instellingen/scopesjabloon_verwijderen/'.$sjabloon->id) . '\';"><img src="' . site_url('/content/png/delete') . '" title="Scope sjabloon verwijderen" /></a>'; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'rows' => $rows, 'new_button_js' => null, 'url' => '/instellingen/scopesjablonen', 'scale_field' => 'naam', 'do_paging' => true, ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class LeaseConfiguratieResult extends BaseResult { function LeaseConfiguratieResult( &$arr ) { parent::BaseResult( 'leaseconfiguratie', $arr ); } public function zet_systeem_instellingen() { define( 'APPLICATION_TITLE', $this->pagina_titel ); define( 'APPLICATION_HAVE_MATRIX', $this->gebruik_matrixbeheer == 'ja' ); define( 'APPLICATION_HAVE_MANAGEMENT', $this->gebruik_management_rapportage == 'ja' ); define( 'APPLICATION_HAVE_INSTELLINGEN', $this->gebruik_instellingen == 'ja' ); define( 'APPLICATION_HAVE_ROLLENBEHEER', $this->gebruik_rollenbeheer == 'ja' ); define( 'APPLICATION_HAVE_DOSSIER_RAPPORTAGE', $this->gebruik_dossier_rapportage == 'ja' ); define( 'APPLICATION_HAVE_DEELPLAN_EMAIL', $this->gebruik_deelplan_email == 'ja' ); } static public function zet_standaard_systeem_instellingen() { define( 'APPLICATION_TITLE', 'BRIStoezicht' ); define( 'APPLICATION_HAVE_MATRIX', true ); define( 'APPLICATION_HAVE_MANAGEMENT', true ); define( 'APPLICATION_HAVE_INSTELLINGEN', true ); define( 'APPLICATION_HAVE_ROLLENBEHEER', true ); define( 'APPLICATION_HAVE_DOSSIER_RAPPORTAGE', true ); define( 'APPLICATION_HAVE_DEELPLAN_EMAIL', false ); define( 'APPLICATION_HAVE_DISTRIBUTEUR', true ); } public function get_aantal_klanten() { $res = $this->_CI->db->query( 'SELECT COUNT(*) AS count FROM klanten WHERE lease_configuratie_id = ' . intval( $this->id ) ); $rows = $res->result(); $count = reset($rows)->count; $res->free_result(); return $count; } public function get_klanten() { return $this->_CI->klant->search( array( 'lease_configuratie_id' => $this->id ), null, true ); } public function get_status() { // check naam $naam = trim($this->naam); if (!$naam) return 'lege naam'; if (!preg_match( '/^[a-z0-9]+$/i', $naam )) return 'ongeldige tekens in naam'; // check kleuren if (strlen( $this->achtergrondkleur ) != 6 || !preg_match( '/^[a-f0-9]+$/i', $this->achtergrondkleur )) return 'ongeldige HTML achtergrondkleur'; if (strlen( $this->voorgrondkleur ) != 6 || !preg_match( '/^[a-f0-9]+$/i', $this->voorgrondkleur )) return 'ongeldige HTML voorgrondkleur'; // check files foreach ($this->get_image_files() as $file) if (!file_exists( APPPATH . '..' . $file )) return 'missend bestand ' . $file; return true; } public function get_image_files() { $files = array( '/files/images/background-green-topbar-%s.png', '/files/images/tableft-selected-%s.png', '/files/images/tabmid-selected-%s.png', '/files/images/tabright-selected-%s.png', '/files/images/greenbutton-left-%s.png', '/files/images/greenbutton-mid-%s.png', '/files/images/greenbutton-right-%s.png', '/files/images/nlaf/green-button-%s.png', '/files/images/lease/%s.png', '/files/images/nlaf/tab-aandachtspunten-selected-%s.png', '/files/images/nlaf/tab-documenten-selected-%s.png', '/files/images/nlaf/tab-fotos-selected-%s.png', '/files/images/nlaf/tab-opdrachten-selected-%s.png', '/files/images/nlaf/tab-oog-selected-%s.png', '/files/images/nlaf/tab-oog-%s.png', ); foreach ($files as $i => $file) $files[$i] = sprintf( $file, $this->naam ); return $files; } public function get_speciaal_veld_waarden() { return preg_split( "/\r?\n/", strval( $this->speciaal_veld_waarden ), 0, PREG_SPLIT_NO_EMPTY ); } } class LeaseConfiguratie extends BaseModel { private static $_lc; function LeaseConfiguratie() { parent::BaseModel( 'LeaseConfiguratieResult', 'lease_configuraties', true ); } public function check_access( BaseResult $object ) { } public function get($lc_id, $is_force = false ) { if( is_null(self::$_lc) || $is_force ) { self::$_lc = parent::get($lc_id); } return self::$_lc; } public function reset() { self::$_lc = null; } }<file_sep><?php class timer { private $_start; private $_tag; private $_substart; private $_subtag; private $_durations = array(); public function tag( $tag ) { if ($this->_tag) $this->finish(); $this->_tag = $tag; $this->_start = microtime( true ); if (!isset( $this->_durations[$this->_tag] )) $this->_durations[$this->_tag] = 0; return $this; } public function sub( $sub ) { if (!$this->_tag) return; if ($this->_subtag) $this->subfinish(); $this->_subtag = '::' . $this->_tag . '@' . $sub; $this->_substart = microtime( true ); if (!isset( $this->_durations[ $this->_subtag ] )) $this->_durations[$this->_subtag] = 0; return $this; } public function finish() { if ($this->_subtag) $this->subfinish(); if ($this->_tag) { $this->_durations[$this->_tag] += microtime( true ) - $this->_start; $this->_tag = null; } return $this; } public function subfinish() { if ($this->_subtag) { $this->_durations[$this->_subtag] += microtime( true ) - $this->_substart; $this->_subtag = null; } return $this; } public function __toString() { switch (sizeof( $this->_durations )) { case 0: return '0ms'; case 1: return reset( $this->_durations ) . 'ms'; default: $s = ''; foreach ($this->_durations as $tag => $duration) if (substr( $tag, 0, 2 ) == '::') $s .= "\n --> " . sprintf( "%6dms", 1000 * $duration ) . ' ' . substr( strstr( $tag, '@' ), 1 ); else $s .= "\n" . sprintf( "%6dms", 1000 * $duration ) . ' ' . $tag; return $s; } } public function total() { return round( 1000 * array_sum( $this->_durations ) ); } public function get( $k ) { return round( 1000 * $this->_durations[$k] ); } } $__RequestTimer = new timer(); $__RequestTimer->tag( 'startup' ); register_shutdown_function(function() use ($__RequestTimer){ if (!IS_CLI) { $__RequestTimer->finish(); if ($f = fopen( dirname(__FILE__) . '/performance.log', 'a' )) { fwrite( $f, "---------------------------------------------------------------------------------\n" . $_SERVER['REQUEST_URI'] . ': ' . $__RequestTimer . "\n" ); fclose( $f ); } } }); <file_sep><? require_once 'base.php'; class DeelplanstandardDocumentsResult extends BaseResult { function DeelplanstandardDocumentsResult( &$arr ) { parent::BaseResult( 'deelplanstandarddocuments', $arr ); } } class Deelplanstandarddocuments extends BaseModel { private $_cache = array(); function deelplanstandarddocuments(){ parent::BaseModel( 'DeelplanstandardDocumentsResult', 'deelplan_standard_documents'); } public function check_access( BaseResult $object ) { //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_by_document_id($document_id,$assoc=false){ $docs = $this->db->where('standard_document_id', $document_id ) ->get( $this->_table ) ->result(); $result = array(); foreach( $docs as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } } <file_sep>UPDATE `bt_checklist_groepen` SET `standaard_toezicht_moment` = 'Algemeen', `standaard_fase` = 'Algemeen'; ALTER TABLE `bt_checklist_groepen` CHANGE `standaard_vraag_aanwezigheid` `standaard_aanwezigheid` INT( 11 ) NULL DEFAULT NULL ; ALTER TABLE `bt_checklisten` CHANGE `standaard_vraag_aanwezigheid` `standaard_aanwezigheid` INT( 11 ) NULL DEFAULT NULL ; ALTER TABLE `bt_hoofdgroepen` CHANGE `standaard_vraag_aanwezigheid` `standaard_aanwezigheid` INT( 11 ) NULL DEFAULT NULL ; <file_sep>ALTER TABLE `bt_hoofdgroepen` ADD `naam_kort` VARCHAR( 20 ) NULL DEFAULT NULL AFTER `naam` ; <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account verwijderen')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Account verwijderen', 'width' => '920px' ) ); ?> Account <i>'<?=$klant->volledige_naam?>'</i> echt verwijderen? Deze actie kan <b>niet</b> ongedaan gemaakt worden!<br/><br/> <form method="post"> <input type="submit" name="delete" value="Ja"> <input type="submit" value="Nee"> <input type="hidden" name="referer" value="<?=$referer?>" /> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>var MessageBoxImpl = function( props ){ this.props = props; this.outerModalPopupDiv = null; this.blockModalPopupDiv = null; this.returnValue = null; }; MessageBoxImpl.prototype = { stack: [], nextZIndex: 100, open: function() { // push ourselves onto the messagebox stack MessageBoxImpl.prototype.stack.push( this ); // make sure this.props contains all required values var defaults = { align:'center', top:100, width:500, height:500, padding:10, disableColor:'#666666', disableOpacity:40, backgroundColor:'#ffffff', borderColor:'#000000', borderWeight:4, borderRadius:5, fadeOutTime:300, url:null, html:null, loadingImage:'/files/images/loading.gif', onClose: function(){}, onOpen: function(){} }; for (var k in defaults) if (!this.props[k] && defaults[k]) this.props[k] = defaults[k]; // set "thiz" reference so that functions can easily reference this messagebox object var thiz = this; /* for references inside functions */ // setup basic div structure this.outerModalPopupDiv = $('<div class="outerModalPopupDiv" style="display:block; border-width:0px; position:absolute; z-index:' + MessageBoxImpl.prototype.nextZIndex + '; ">') .append( this.innerModalPopupDiv = $('<div class="innerModalPopupDiv">') .append( this.contentModalPopupDiv = $('<div style="overflow:auto; ">') ) ); this.blockModalPopupDiv = $('<div class="blockModalPopupDiv" style="width:100%; border:0px; padding:0px; margin:0px; z-index:' + (MessageBoxImpl.prototype.nextZIndex-1) + '; position:fixed; top:0px; left:0px; ">'); $('body').append( this.outerModalPopupDiv ).append( this.blockModalPopupDiv ); // update next z index so that new messageboxes will always be on top // on any prior messageboxes MessageBoxImpl.prototype.nextZIndex += 2; // setup a data reference so that we can always find this object // again from the "outside" (see closePopup) this.contentModalPopupDiv.data( 'msgbox', this ); // setup the handler for closing this messagebox // NOTE: the closePopup function will also trigger this event handler, // so however we close, it will always be through this function this.blockModalPopupDiv.click(function() { // if we have an onclose function, call it now; if it returns // false (exactly, see the triple ===), then we refuse to close! var return_value = thiz.returnValue; if (typeof(thiz.props.onClose) == 'function') if (thiz.props.onClose( return_value )===false) return; // make the messagebox and the "gray out layer" disappear thiz.outerModalPopupDiv.fadeOut(thiz.props.fadeOutTime, function(){ thiz.outerModalPopupDiv.remove(); }); thiz.blockModalPopupDiv.fadeOut(thiz.props.fadeOutTime, function(){ thiz.blockModalPopupDiv.remove(); }); // remove ourselves from the stack var index = indexOfArray( MessageBoxImpl.prototype.stack, thiz ); if (index != -1) MessageBoxImpl.prototype.stack.splice( index, 1 ); }); // setup CSS for our various components this.outerModalPopupDiv .css({ top: $(document).scrollTop()+this.props.top, width: this.props.width + 'px', padding: this.props.borderWeight, background: this.props.borderColor, borderRadius: this.props.borderRadius, MozBorderRadius: this.props.borderRadius, WebkitBorderRadius: this.props.borderRadius }); this.innerModalPopupDiv.css({ padding: this.props.padding, background: this.props.backgroundColor, borderRadius: this.props.borderRadius - 3, MozBorderRadius: this.props.borderRadius - 3, WebkitBorderRadius: this.props.borderRadius - 3 }); this.contentModalPopupDiv.css({ height: this.props.height + 'px' }); this.blockModalPopupDiv.css({ background: this.props.disableColor, opacity: this.props.disableOpacity / 100, filter: 'alpha(Opacity=' + this.props.disableOpacity + ')' }); if(this.props.align=="center") { this.outerModalPopupDiv.css({ marginLeft: (-1 * (this.props.width / 2)) + 'px', left: '50%' }); } else if(this.props.align=="left") { this.outerModalPopupDiv.css({ marginLeft: '0px', left: '10px' }); } else if(this.props.align=="right") { this.outerModalPopupDiv.css({ marginRight: '0px', right: '10px' }); } else { this.outerModalPopupDiv.css({ marginLeft: (-1 * (this.props.width / 2)) + 'px', left: '50%' }); } this.blockModalPopupDiv.css({ height: screen.height+'px', display: 'block' }); // fill the messagebox with content if (this.props.html) { this.contentModalPopupDiv.html( this.props.html ); } else if (this.props.url.search(/\.(jpg|jpeg|gif|png|bmp)/i) != -1) { this.contentModalPopupDiv.html('<div align="center"><img src="' + url + '" border="0" /></div>'); } else { this.contentModalPopupDiv.html('<div align="center"><img src="' + this.props.loadingImage + '" border="0" /></div>'); $.get(this.props.url, function(R,stat){ while (match = /<script.*?>(.*?)<\/script>/.exec(R)) { if (match[1]) eval( match[1] ); } thiz.contentModalPopupDiv.html(R); }, 'html'); } // if we have an onOpen handler, fire it now if (typeof( this.props.onOpen ) == 'function') this.props.onOpen(); // return the content DIV! return this.contentModalPopupDiv; }, close: function( retVal ) { this.returnValue = retVal; this.blockModalPopupDiv.trigger( 'click' ); } } function modalPopup(props) { var msgbox = new MessageBoxImpl( props ); return msgbox.open(); } function getPopup() { if (!MessageBoxImpl.prototype.stack.length) return null; return MessageBoxImpl.prototype.stack[MessageBoxImpl.prototype.stack.length-1].contentModalPopupDiv; } function closePopup( optional_return_value ) { // NOTE: option_return_value can only be a string or int value! var popup = getPopup(); if (popup) popup.data( 'msgbox' ).close( optional_return_value ); } function showMessageBox(props) { var defaults = { width: 350, height: 160, message: 'Geen bericht ingevuld.', type:'notice', // set to notice, error, warning or none buttons: ['ok','cancel'] // can contain yes/no/ok/cancel in any combination }; for (var k in defaults) if (!props[k] && defaults[k]) props[k] = defaults[k]; if (!props.url && !props.html) props.html = '<table width="100%" height="100%" class="messagebox">'+ '<tr>' + (props.type != 'none' ? '<td class="icon ' + props.type + '"></td>' : '') + '<td class="message">' + props.message + '</td>' + '</tr>' + '<tr>' + '<td class="buttons" colspan="2">' + (indexOfArray( props.buttons, 'yes') != -1 ? '<input type="button" value="Ja" onclick="closePopup(\'yes\')" />' : '') + (indexOfArray( props.buttons, 'no') != -1 ? '<input type="button" value="Nee" onclick="closePopup(\'no\')" />' : '') + (indexOfArray( props.buttons, 'ok') != -1 ? '<input type="button" value="OK" onclick="closePopup(\'ok\')" />' : '') + (indexOfArray( props.buttons, 'doorgaan') != -1 ? '<input type="button" value="Doorgaan" onclick="closePopup(\'doorgaan\')" />' : '') + (indexOfArray( props.buttons, 'cancel') != -1 ? '<input type="button" value="Annuleren" onclick="closePopup(\'cancel\')" />' : '') + '</td>' + '</tr>' + '</table>'; modalPopup(props); // focus first text-input element (if present) var el = getPopup().find('input[type=text], textarea').focus(); } function showPleaseWait() { var pleaseWait = $('#pleasewait'); if (!pleaseWait.size()) { $('body').append( '<div id="pleasewait" style="position:fixed; left:0px; top: 0px; width: 100%; height: 100%; z-index:10000; opacity: 0.85; background-color: #444; display: none; text-align: center;">' + '<div style="display: inline-block; *display: inline; *zoom: 1; width: 300px; opacity: 1; background-color: #fff; border: 1px solid #777; height: 200px; margin-top: 300px; text-align: center;">' + '<img src="/files/images/loading.gif" style="margin-top: 75px; "/><br/> Even geduld a.u.b...' + '</div>' + '</div>' ); pleaseWait = $('#pleasewait'); } pleaseWait.fadeIn(); } function hidePleaseWait() { $('#pleasewait').fadeOut(); } <file_sep><? require_once 'base.php'; class DeelplanUploadDataResult extends BaseResult { function DeelplanUploadDataResult( &$arr ) { parent::BaseResult( 'deelplanuploaddata', $arr ); } public function laad_inhoud() { if (isset( $this->data )) return; $res = $this->_CI->db->query( 'SELECT data FROM deelplan_upload_data WHERE id = ' . intval( $this->id ) ); if (!$res) throw new Exception( 'Fout bij ophalen deelplan upload inhoud (1).' ); if ($res->num_rows() != 1) throw new Exception( 'Fout bij ophalen deelplan upload inhoud (2) (' . $res->num_rows() . ').' ); $rows = $res->result(); $res->free_result(); $this->data = reset( $rows )->data; unset( $rows ); } public function geef_inhoud_vrij() { unset( $this->data ); } } class DeelplanUploadData extends BaseModel { function DeelplanUploadData() { parent::BaseModel( 'DeelplanUploadDataResult', 'deelplan_upload_data' ); } public function check_access( BaseResult $object ) { // no references available } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('standaard_deelplannen.headers.standaard_deelplannen')?></h1> <div class="checklistwizard lijst-nieuwe-stijl"> <? $this->load->view( 'standard_deelplannen/_list'); ?> </div> <? $this->load->view('elements/footer'); ?> <file_sep><? require_once 'base.php'; class VraagRichtlijnResult extends BaseResult { function VraagRichtlijnResult( &$arr ) { parent::BaseResult( 'vraagrichtlijn', $arr ); } function get_richtlijn() { $CI = get_instance(); $CI->load->model( 'richtlijn' ); return $CI->richtlijn->get( $this->richtlijn_id ); } public function rename( $richtlijn_id ) { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'VraagRichtlijnResult::rename', 'UPDATE bt_vraag_rchtlnn SET richtlijn_id = ? WHERE id = ?', $db ); $CI->dbex->execute( 'VraagRichtlijnResult::rename', array( $richtlijn_id, $this->id ), $db ); $this->richtlijn_id = $richtlijn_id; } } class VraagRichtlijn extends BaseModel { function VraagRichtlijn() { parent::BaseModel( 'VraagRichtlijnResult', 'bt_vraag_rchtlnn' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'vraag', 'vraag_id' ); } function get_by_vraag( $vraag_id ) { if (!$this->dbex->is_prepared( 'VraagRichtlijnResult::get_by_vraag' )) $this->dbex->prepare( 'VraagRichtlijnResult::get_by_vraag', 'SELECT * FROM '.$this->_table.' WHERE vraag_id = ?', $this->get_db() ); $args = func_get_args(); $res = $this->dbex->execute( 'VraagRichtlijnResult::get_by_vraag', $args, false, $this->get_db() ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); return $result; } public function add( $vraag_id, $richtlijn_id ) { /* $db = $this->get_db(); $this->dbex->prepare( 'VraagRichtlijn::add', 'INSERT INTO bt_vraag_rchtlnn (vraag_id, richtlijn_id) VALUES (?,?)', $db ); $args = array( 'vraag_id' => $vraag_id, 'richtlijn_id' => $richtlijn_id, ); $this->dbex->execute( 'VraagRichtlijn::add', $args, false, $db ); $args['id'] = $db->insert_id(); return new $this->_model_class( $args ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'vraag_id' => $vraag_id, 'richtlijn_id' => $richtlijn_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } } <file_sep>ALTER TABLE `bt_vraag_grondslagen` DROP FOREIGN KEY `bt_vraag_grondslagen_ibfk_2` ; ALTER TABLE `bt_vraag_grondslagen` DROP `grondslag_id`, DROP `artikel`, DROP `tekst`, DROP `itp_id`;<file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_instellingen')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Instellingen', 'expanded' => true, 'width' => '920px', 'height' => '300px' ) ); ?> <form name="form" method="post"> <table> <tr> <td id="form_header" style="width:200px"><?=tg('speciaal.veld.waarden')?>:</td> <td> <textarea name="waarden" style="width: 600px; height: 250px;"><?=htmlentities( implode("\n", $waarden), ENT_COMPAT, 'UTF-8' )?></textarea> </td> </tr> <tr> <td></td> <td><input type="submit" value="<?=tgng('form.opslaan')?>"/></td> </tr> </table> </form> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Checklistgroepbeheer', 'width' => '100%' ) ); ?> <p> Via deze pagina kan worden ingesteld welke klanten checklistgroepen en checklisten mogen publiceren voor gebruik door andere klanten. Klanten mogen niet zelf bepalen of hun checklistgroep zichtbaar is voor anderen, dit gebeurt door de systeembeheerders van BRIStoezicht. Wel mogen klanten zelf bepalen welke checklisten binnen de door BRIStoezicht aangewezen checklistgroepen prive, publiek voor iedereen, of beperkt publiek zijn. </p> <p> Om afbeeldingen te uploaden die kunnen worden gekoppeld aan deze checklistgroepen, klik <a href="<?=site_url('/admin/image_beheer')?>">hier</a>. </p> <br> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <br> <? $col_widths = array( 'naam' => 200, ); $col_description = array( 'naam' => 'Naam', ); $col_unsortable = array( 'naam' ); $rows = array(); foreach ($klanten as $klant) { if (empty( $checklistgroepen[$klant->id] )) continue; $row = (object)array(); $row->onclick = "location.href='" . site_url('/admin/checklistgroep_detail_beheer/' . $klant->id) . "'"; $row->data = array( 'naam' => $klant->naam, ); $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'new_button_js' => null, 'url' => '/instellingen/prioriteiten', 'scale_field' => 'naam', 'do_paging' => false, 'disable_search' => true, 'header' => 'Klanten', ) ); ?> <script type="text/javascript"> $('select[name^=checklistgroepen]').change(function(){ var cg_id = $(this).attr('cg_id'); var value = this.value; $('div.cg' + cg_id + ', tr.cg' + cg_id).hide(); $('div.cg' + cg_id + '.' + value + ', tr.cg' + cg_id + '.' + value).show(); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Accountbeheer', 'width' => '920px' ) ); ?> <p> <input type="button" value="Account toevoegen" onclick="location.href='<?=site_url('/admin/account_toevoegen')?>';"> </p> <table class="admintable" width="100%" cellpadding="0" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Klant naam</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Contact&nbsp;persoon</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">E-mail/telefoon</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Laatste gebruik</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;" width="100">Acties</th> </tr> <? $now = time(); $parent_admin = $this->login->verify( 'admin', 'parentadmin' ); ?> <? foreach ($data as $i => $acc): ?> <tr class="<?=($i % 2)?'':'zebra'?>"> <td valign="top"><h5><?=$acc->volledige_naam?></h5></td> <td valign="top"><?=$acc->contactpersoon_naam?></td> <td valign="top"><?=$acc->contactpersoon_email?>, <?=$acc->contactpersoon_telefoon?></td> <td valign="top"> <? if (isset( $last_requests[$acc->id] )): ?> <? $diff = $now - strtotime( $last_requests[$acc->id] ); if ($diff < 86400) echo "Laatste 24 uur"; else if ($diff < 7 * 86400) echo "Laatste week"; else if ($diff < 30 * 86400) echo "Laatste maand"; else { $maand = round( $diff / (30 * 86400), 1 ); echo "<span style=\"color:red\">$maand maand geleden</color>"; } ?> <? else: ?> <i>nooit</i> <? endif; ?> </td> <td valign="top"> <? if ( !$parent_admin ): ?> <a href="<?=site_url('/admin/account_edit/'.$acc->id)?>"><img src="<?=site_url('/content/png/edit')?>" title="Bewerken" alt="Bewerken" /></a> <? endif; ?> <a href="<?=site_url('/admin/account_verwijderen/geaccepteerd/'.$acc->id)?>"><img src="<?=site_url('/content/png/delete')?>" title="Verwijderen" alt="Verwijderen" /></a> <a href="<?=site_url('/admin/account_list_users/'.$acc->id)?>"><img src="<?=site_url('/content/png/login_as')?>" title="Inloggen als" alt="Inloggen als" /></a> <!-- <a href="<?=site_url('/admin/account_list_active_users/'.$acc->id)?>"><img src="<?=site_url('/content/png/user_group')?>" title="Actieve gebruikers" alt="Actieve gebruikers" /></a> --> </td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php class Toezichtmomenten extends Controller { public function __construct(){ parent::__construct(); $this->navigation->push( 'nav.instellingen', '/instellingen' ); $this->navigation->push( 'nav.toezichtmomenten', '/toezichtmomenten' ); $this->navigation->set_active_tab( 'beheer' ); } public function index(){ redirect( '/toezichtmomenten/checklistgroepen' ); } protected static function getCommonImgUrl(){ //XXX For function from which this code was got see ...\application\views\checklistwizard\_lijst.php $instace = get_instance(); if( $lc = $instace->session->_loginSystem->get_lease_configuratie_id() ) { $instace->load->model( 'leaseconfiguratie' ); $lease_name = $instace->leaseconfiguratie->get($lc)->naam; $img_url_common = '/files/images/lease/checklistgroep-icon_' . $lease_name . '.png'; }else $img_url_common = site_url('/files/checklistwizard/checklistgroep-icon.png'); return $img_url_common; } public function checklistgroepen(){ $toon_alle_beschikbare_checklistgroepen = $this->session->userdata( 'toon_alle_beschikbare_checklistgroepen' ); $img_url_common = self::getCommonImgUrl(); $this->load->model( 'checklistgroep' ); $this->load->view( 'toezichtmomenten/checklistgroepen', array( 'list' => $this->checklistgroep->get_for_huidige_klant( false, !$toon_alle_beschikbare_checklistgroepen ), 'img_url_common' => $img_url_common, ) ); } public function checklisten( $checklistgroep_id=null ){ $this->load->model( 'checklistgroep' ); if (!$checklistgroep = $this->checklistgroep->get( $checklistgroep_id )) throw new Exception( 'Ongeldig checklist groep ID ' . $checklistgroep_id ); $this->navigation->push( 'nav.toezichtmomenten.checklistgroepen', '/toezichtmomenten/checklistgroepen', array( $checklistgroep->naam ) ); $image = $checklistgroep->get_image(); $image_url = $image != NULL ? $image->get_url() : self::getCommonImgUrl(); $this->load->view( 'toezichtmomenten/checklisten', array( 'checklistgroep_id' => $checklistgroep_id, 'list' => $checklistgroep->get_checklisten(), 'image_url' => $image_url, ) ); } public function momenten( $checklistgroep_id=null, $checklist_id=null ){ $this->load->model( 'checklistgroep' ); if (!($checklistgroep = $this->checklistgroep->get( $checklistgroep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklistgroep_id ); $this->navigation->push( 'nav.toezichtmomenten.checklistgroepen', '/toezichtmomenten/checklisten/'.$checklistgroep_id, array( $checklistgroep->naam ) ); $image_url_obj = $checklistgroep->get_image(); $image_url = $image_url_obj ? $image_url_obj->get_url() : FALSE; $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); $this->navigation->push( 'nav.toezichtmomenten.checklisten', '/toezichtmomenten/momenten', array( $checklist->naam ) ); $this->load->view( 'toezichtmomenten/momenten', array( 'checklistgroep_id' => $checklistgroep_id, 'checklist_id' => $checklist_id, 'list' => $checklist->get_toezichtmomenten(), 'image_url' => ($image_url ? $image_url : self::getCommonImgUrl()) ) ); } public function hoofdgroepen( $checklistgroep_id, $checklist_id, $toezichtmomentId=null, $message='', $messType='notice' ){ $this->load->model( 'checklistgroep' ); if (!($checklistgroep = $this->checklistgroep->get( $checklistgroep_id ))) throw new Exception( 'Ongeldig checklist groep ID ' . $checklistgroep_id ); $this->navigation->push( 'nav.toezichtmomenten.checklistgroepen', '/toezichtmomenten/checklisten/'.$checklistgroep_id, array( $checklistgroep->naam ) ); $image = $checklistgroep->get_image(); $image_url = $image != NULL ? $image->get_url() : self::getCommonImgUrl(); $this->load->model( 'checklist' ); if (!($checklist = $this->checklist->get( $checklist_id ))) throw new Exception( 'Ongeldig checklist ID ' . $checklist_id ); $this->navigation->push( 'nav.toezichtmomenten.checklisten', '/toezichtmomenten/momenten/'.$checklistgroep_id.'/'.$checklist_id, array( $checklist->naam ) ); $this->load->model( 'toezichtmoment' ); if( $toezichtmomentId == null ){ $arr = array(); $codekey_val = $naam_val = ''; $naam_progress = 'Nieuw toezichtmoment'; }else{ if (!($toezichtmoment = $this->toezichtmoment->get( $toezichtmomentId ))) throw new Exception( 'Ongeldig toezichtmoment ID ' . $toezichtmomentId ); $naam_val = $naam_progress = $toezichtmoment->naam; $codekey_val = $toezichtmoment->codekey; } $this->navigation->push( 'nav.toezichtmomenten.hoofdgroepen', '/toezichtmomenten/hoofdgroepen', array( $naam_progress ) ); $this->load->model( 'hoofdgroep' ); $this->load->view( 'toezichtmomenten/hoofdgroepen', array( 'checklistgroep_id' => $checklistgroep_id, 'checklist_id' => $checklist_id, 'toezichtmoment_id' => $toezichtmomentId, 'naam' => $naam_val, 'codekey' => $codekey_val, 'list' => $this->hoofdgroep->get_for_toezichtmoment_creation( $toezichtmomentId, $checklist_id ), 'message' => $message, 'mess_type' => $messType, 'image_url' => $image_url ) ); } public function save_toezichtmoment( $checklistgroepId, $checklistId, $toezichtmomentId=null ){ $codekey= trim( $_POST['codekey'] ); $naam = trim( $_POST['naam'] ); $this->load->model( 'toezichtmoment' ); $is_codekey_exists = (bool)count( $this->toezichtmoment->db ->where('codekey',$codekey) ->where('id !=', (int)$toezichtmomentId) ->limit(1)->get( 'bt_toezichtmomenten' )->result() ); if($is_codekey_exists){ $this->hoofdgroepen( $checklistgroepId, $checklistId, $toezichtmomentId, 'Codekey must be unique', 'error' ); return FALSE; } if( $is_new = !(bool)$toezichtmomentId ){ $obj = $this->toezichtmoment->add( $codekey, $naam, $checklistId ); $toezichtmomentId = $obj->id; } if (!($toezichtmoment = $this->toezichtmoment->get( $toezichtmomentId ))) throw new Exception( 'Ongeldig toezichtmoment ID ' . $checklistId ); $hoofdgroepen = array(); if( isset($_POST['hoofdgroepen'])) foreach( $_POST['hoofdgroepen'] as $id => $on ) $hoofdgroepen[] = $id; $data = array( 'naam' => $naam, 'hoofdgroepen' => $hoofdgroepen, 'codekey' => $codekey, 'is_new' => $is_new ); try{ $toezichtmoment->save_all( $data ); $this->hoofdgroepen( $checklistgroepId, $checklistId, $toezichtmomentId, 'Saved successfully.' ); }catch (Exception $e){ $this->hoofdgroepen( $checklistgroepId, $checklistId, $toezichtmomentId, $e->getMessage() ); } } }// Class end. <file_sep>PDFAnnotator.Editable.Path = PDFAnnotator.Editable.extend({ lines: [], init: function( config ) { this._super( null, true /* fake editable, do not check tool reference! */ ); this.setData( config, { kleur: '#ff0000' }, [ 'locaties' ] ); this.line = null; this.origData = config; var locaties = (''+this.data.locaties).split(','); for (var i=0; i<locaties.length; i+=2) { this.lines.push( new PDFAnnotator.Math.IntVector2( locaties[i], locaties[i+1] ) ); } }, render: function() { var base = $('<div>') .css( 'position', 'absolute' ) .css( 'left', '0px' ) .css( 'top', '0px' ) .css( 'padding', '0' ) .css( 'margin', '0' ); var startLine = null; for (var i=0; i<this.lines.length; ++i) { if (startLine) { var line = new PDFAnnotator.Line( this.container, this.data.kleur, startLine, this.lines[i] ); base.append( line.dom ); } startLine = this.lines[i]; } this.addVisual( base ); }, /** !!override!! */ getHandle: function( type ) { return null; }, /* !!overide!! */ rawExport: function() { return this.origData; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.Path(data); }, /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { } }); <file_sep><?php class ExportChecklistgroep { private $CI; private $exported = array(); public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } public function __construct() { $this->CI = get_instance(); $this->CI->load->model( 'checklistgroep' ); $this->CI->load->model( 'checklist' ); $this->CI->load->model( 'klant' ); $this->CI->load->model( 'richtlijn' ); $this->CI->load->model( 'hoofdthema' ); $this->CI->load->model( 'thema' ); $this->CI->load->model( 'grondslagtekst' ); $this->CI->load->model( 'grondslag' ); $this->CI->load->model( 'image' ); } private function _escape( $value ) { if (is_null( $value )) return 'NULL'; if (!is_string( $value )) return strval($value); $binary = false; $maxlen = min( strlen($value), 128 ); for ($i=0; !$binary && $i<$maxlen; ++$i) if (ord($value[$i]) < 32 || ord($value[$i]) > 127) $binary = true; if (!$binary) return $this->CI->db->escape( $value ); else { $str = "X'"; $len = strlen($value); for ($i=0; $i<$len; ++$i) { $v = ord( $value[$i] ); $s = dechex( $v ); if (strlen($s) == 1) $s = '0' . $s; $str .= $s; } $str .= "'"; return $str; } } private function _get_table( $table, array $wheres ) { foreach ($wheres as $k => $v) $this->CI->db->where( $k, $v ); $res = $this->CI->db->get( $table ); if (!$res) throw new Execption( 'Failed to read table ' . $table ); $result = $res->result(); $res->free_result(); return $result; } private function _produce_insert( $row, $table=null, $where_not_exists=false, $sql_name=null ) { $replaces = array( 'klant_id' => '@klant_id', 'checklist_groep_id' => '@cg_id', 'checklist_id' => '@cl_id', 'hoofdgroep_id' => '@h_id', 'categorie_id' => '@c_id', 'vraag_id' => '@v_id', ); if ($row instanceof BaseResult) { $table = $row->get_model()->get_table(); $row = $row->get_array_copy(); // strips object's _ values } else if (!$table) throw new Exception( 'Missing table name for non-Model object/array' ); if (!is_array( $row )) $row = (array)$row; if (isset( $row['richtlijn_id'] )) $replaces['richtlijn_id'] = $this->_export_richtlijn_conditionally( $row['richtlijn_id'] ); if (isset( $row['grondslag_tekst_id'] )) $replaces['grondslag_tekst_id'] = $this->_export_grondslagtekst_conditionally( $row['grondslag_tekst_id'] ); if (isset( $row['grondslag_id'] )) $replaces['grondslag_id'] = $this->_export_grondslag_conditionally( $row['grondslag_id'] ); if (isset( $row['thema_id'] )) $replaces['thema_id'] = $this->_export_thema_conditionally( $row['thema_id'] ); if (isset( $row['hoofdthema_id'] )) $replaces['hoofdthema_id'] = $this->_export_hoofdthema_conditionally( $row['hoofdthema_id'] ); if (isset( $row['standaard_thema_id'] )) $replaces['standaard_thema_id'] = $this->_export_thema_conditionally( $row['standaard_thema_id'] ); if (isset( $row['standaard_hoofdthema_id'] )) $replaces['standaard_hoofdthema_id'] = $this->_export_hoofdthema_conditionally( $row['standaard_hoofdthema_id'] ); if (isset( $row['image_id'] )) $replaces['image_id'] = $this->_export_image_conditionally( $row['image_id'] ); $query = 'INSERT INTO ' . $table . ' ('; foreach ($row as $k => $v) if ($k != 'id') $query .= $k . ','; $query = substr( $query, 0, -1 ) . ')'; if (!$where_not_exists) $query .= ' VALUES ('; else $query .= ' SELECT '; foreach ($row as $k => $v) if ($k != 'id') { if (isset( $replaces[$k] )) $query .= $replaces[$k]; else $query .= $this->_escape( $v ); $query .= ','; } $query = substr( $query, 0, -1 ); if (!$where_not_exists) $query .= ')'; else { $select = 'SELECT * FROM ' . $table . ' WHERE '; $c=0; foreach ($row as $k => $v) if ($k != 'id') { $select .= $c++ ? ' AND ' : ''; if (is_null( $v )) { $select .= $k . ' IS NULL '; } else { $select .= $k . ' = '; if (isset( $replaces[$k] )) $select .= $replaces[$k]; else $select .= $this->_escape( $v ); } } $query .= ' FROM dual WHERE NOT EXISTS (' . $select . ')'; } $query .= ";\n"; if ($sql_name) { if (!$where_not_exists) $query .= "SET " . $sql_name . " = LAST_INSERT_ID();\n"; else $query .= "SET " . $sql_name . " = (" . preg_replace( '/^SELECT \*/', 'SELECT id', $select ) . ");\n"; } return $query; } private function _export_richtlijn_conditionally( $richtlijn_id ) { return $this->_export_conditionally( 'richtlijn', 'rl', $richtlijn_id ); } private function _export_grondslagtekst_conditionally( $grondslag_tekst_id ) { return $this->_export_conditionally( 'grondslagtekst', 'gst', $grondslag_tekst_id ); } private function _export_grondslag_conditionally( $grondslag_id ) { return $this->_export_conditionally( 'grondslag', 'gs', $grondslag_id ); } private function _export_thema_conditionally( $thema_id ) { return $this->_export_conditionally( 'thema', 't', $thema_id ); } private function _export_hoofdthema_conditionally( $hoofdthema_id ) { return $this->_export_conditionally( 'hoofdthema', 'ht', $hoofdthema_id ); } private function _export_image_conditionally( $image_id ) { return $this->_export_conditionally( 'image', 'im', $image_id ); } private function _export_conditionally( $modelname, $prefix, $id ) { if (!isset( $this->exported[$modelname] )) $this->exported[$modelname] = array(); $obj = $this->CI->$modelname->get( $id ); $varname = "@" . $prefix . $obj->id . "_id"; if (!in_array( $id, $this->exported[$modelname] )) { $this->exported[$modelname][] = $id; echo $this->_produce_insert( $obj, null, true, $varname ); } return $varname; } public function run( $cg_id ) { $this->exported = array(); if (!($cg = $this->CI->checklistgroep->get( $cg_id ))) throw new Exception( 'Geef checklistgroep id op als parameter, ongeldige waarde: ' . $cg_id ); $klant = $this->CI->klant->get( $cg->klant_id ); $gebruiker = reset( $klant->get_gebruikers() ); $this->CI->login( $klant->id, $gebruiker->id ); echo "-- is @klant_id gezet??!?!\n"; echo "SET NAMES 'utf8';\n"; echo "SET CHARACTER SET 'utf8';\n"; echo "SET AUTOCOMMIT=0;\n"; echo "BEGIN;\n"; // export checklistgroep echo $this->_produce_insert( $cg, null, false, '@cg_id' ); foreach ($this->_get_table( 'bt_checklist_groep_ndchtspntn', array( 'checklist_groep_id' => $cg->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_groep_ndchtspntn' ); foreach ($this->_get_table( 'bt_checklist_groep_grndslgn', array( 'checklist_groep_id' => $cg->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_groep_grndslgn' ); foreach ($this->_get_table( 'bt_checklist_groep_rchtlnn', array( 'checklist_groep_id' => $cg->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_groep_rchtlnn' ); foreach ($this->_get_table( 'bt_checklist_groep_opdrachten', array( 'checklist_groep_id' => $cg->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_groep_opdrachten' ); // export checklisten $themas = array(); foreach ($cg->get_checklisten() as $checklist) { echo $this->_produce_insert( $checklist, null, false, '@cl_id' ); foreach ($this->_get_table( 'bt_checklist_ndchtspntn', array( 'checklist_id' => $checklist->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_ndchtspntn' ); foreach ($this->_get_table( 'bt_checklist_grndslgn', array( 'checklist_id' => $checklist->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_grndslgn' ); foreach ($this->_get_table( 'bt_checklist_rchtlnn', array( 'checklist_id' => $checklist->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_rchtlnn' ); foreach ($this->_get_table( 'bt_checklist_opdrachten', array( 'checklist_id' => $checklist->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_checklist_opdrachten' ); // export hoofdgroepen foreach ($checklist->get_hoofdgroepen() as $hoofdgroep) { echo $this->_produce_insert( $hoofdgroep, null, false, '@h_id' ); foreach ($this->_get_table( 'bt_hoofdgroep_ndchtspntn', array( 'hoofdgroep_id' => $hoofdgroep->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_hoofdgroep_ndchtspntn' ); foreach ($this->_get_table( 'bt_hoofdgroep_grndslgn', array( 'hoofdgroep_id' => $hoofdgroep->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_hoofdgroep_grndslgn' ); foreach ($this->_get_table( 'bt_hoofdgroep_rchtlnn', array( 'hoofdgroep_id' => $hoofdgroep->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_hoofdgroep_rchtlnn' ); foreach ($this->_get_table( 'bt_hoofdgroep_opdrachten', array( 'hoofdgroep_id' => $hoofdgroep->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_hoofdgroep_opdrachten' ); // export categorieen foreach ($hoofdgroep->get_categorieen() as $categorie) { echo $this->_produce_insert( $categorie, null, false, '@c_id' ); // export vragen foreach ($categorie->get_vragen() as $vraag) { echo $this->_produce_insert( $vraag ); echo "SET @v_id = LAST_INSERT_ID();\n"; foreach ($this->_get_table( 'bt_vraag_ndchtspntn', array( 'vraag_id' => $vraag->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_vraag_ndchtspntn' ); foreach ($this->_get_table( 'bt_vraag_grndslgn', array( 'vraag_id' => $vraag->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_vraag_grndslgn' ); foreach ($this->_get_table( 'bt_vraag_rchtlnn', array( 'vraag_id' => $vraag->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_vraag_rchtlnn' ); foreach ($this->_get_table( 'bt_vraag_opdrachten', array( 'vraag_id' => $vraag->id ) ) as $row) echo $this->_produce_insert( $row, 'bt_vraag_opdrachten' ); } } } } echo "ROLLBACK;\n"; } } <file_sep><? load_view( 'header.php' ); ?> <? load_view( 'footer.php' ); ?> <file_sep>PDFAnnotator.EditableContainer = PDFAnnotator.Base.extend({ /** Constructor */ init: function( engine, pagenum, domObj, drawingObj ) { /* initialize base class */ this._super(); /* the engine object we belong to */ this.engine = engine; this.pagenum = pagenum; this.layer = null; /* the dom object that makes up the container for this object, wrapped in a jquery collection */ if (!(domObj instanceof jQuery)) domObj = $(domObj); if (!(drawingObj instanceof jQuery)) drawingObj = $(drawingObj); this.dom = domObj; this.drawing = drawingObj; /* install event handlers on dom object */ this.installEventHandlers(); /* our array of PDFAnnotator.Editable objects */ this.objects = []; /* register a few event types */ this.registerEventType( 'beforeaddobject' ); this.registerEventType( 'afteraddobject' ); this.registerEventType( 'beforeremoveobject' ); this.registerEventType( 'afterremoveobject' ); }, /* returns true when layers contains >0 objects. */ hasObjects: function() { return this.objects.length > 0; }, setLayer: function( layer ) { if (!(layer instanceof PDFAnnotator.Layer)) throw 'PDFAnnotator.EditableContainer.setLayer: layer is not a PDFAnnotator.Layer object'; this.layer = layer; }, /** Add an object to this container */ addObject: function( obj, force ) { if (!(this.layer instanceof PDFAnnotator.Layer)) throw 'PDFAnnotator.EditableContainer.addObject: no active layer'; /* * DISABLED op 16-07-2013 wegens bugs in iPad foto toevoegen, dan lockt heel safari (oops...) * if (!force && !this.layer.engine.isPageTransformLocked()) { if (!confirm( 'Na het aanbrengen van uw eerste annotatie kunt u de tekening niet meer roteren of spiegelen. Wilt u doorgaan?' )) { return false; } } */ if (!(obj instanceof PDFAnnotator.Editable)) throw 'PDFAnnotator.EditableContainer.addObject: obj is not a PDFAnnotator.Editable object'; // layer can be visible, but not activated, in which case we should do nothing! if (!force && !this.layer.isActivated()) { delete obj; return false; } this.dispatchEvent('beforeaddobject',{object:obj, container: this}); this.objects.push( obj ); obj.setContainer( this ); this.dispatchEvent('afteraddobject',{object:obj, container: this}); return true; }, /** Remove an object from this container */ removeObject: function( obj ) { if (!(obj instanceof PDFAnnotator.Editable)) throw 'PDFAnnotator.EditableContainer.removeObject: obj is not a PDFAnnotator.Editable object'; var index = indexOfArray( this.objects, obj ); if (index == -1) throw 'PDFAnnotator.EditableContainer.removeObject: obj is not in this container'; obj.preremove(); this.dispatchEvent('beforeremoveobject',{object:obj, container: this}); this.objects.splice( index, 1 ); obj.setContainer( null ); this.dispatchEvent('aftereremoveobject',{object:obj, container: this}); }, /** Convert a container position (i.e. with a position relative to the top left corner * of this container) to a screen position. */ containerToScreen: function( intvec2 ) { var offset = this.findDomElementOffset( this.dom[0] ); var newpos = intvec2.added( offset ); return newpos; }, /** Convert a screen position (i.e. with a position relative to the top left corner * of the screen) to a container position. */ screenToContainer: function( intvec2 ) { var offset = this.findDomElementOffset( this.dom[0] ); var newpos = intvec2.subtracted( offset ); return newpos; }, /** Installs mouse move, click, drag, etc. handlers that get send to the active tool. */ installEventHandlers: function() { if (!this.dom.size()) return; var thiz = this; this.dom.mousemove(function( e ){ thiz.dispatchToolEvent( 'mousemove', thiz.buildEventData( e ) ); }); this.dom.click(function( e ){ thiz.dispatchToolEvent( 'mouseclick', thiz.buildEventData( e ) ); }); this.enableDragEvents(); }, /** Builds event data for the given javascript event */ buildEventData: function ( jse ) { if (typeof( jse.pageX ) != 'undefined' && typeof( jse.pageY ) != 'undefined' && typeof( jse.currentTarget ) != 'undefined' && typeof( jse.currentTarget.offsetParent ) != 'undefined' ) { // apply grid? if (true) { jse.pageX = Math.round( jse.pageX / 5 ) * 5; jse.pageY = Math.round( jse.pageY / 5 ) * 5; } return { event: jse, container: this, position: this.screenToContainer( new PDFAnnotator.Math.IntVector2( jse.pageX, jse.pageY ) ), target: jse.currentTarget }; } else return null; }, /** Dispatches event on the active tool, if it is set. */ dispatchToolEvent: function( name, data ) { var tool = this.engine.getActiveTool(); if (tool) tool.dispatchEvent( name, data ); }, /** Execute a function for every editable on this container */ forEachEditable: function( functor, userdata ) { for (var i=0; i<this.objects.length; ++i) functor( this.objects[i], userdata ) }, /** Enable/Disable drag events */ enableDragEvents: function() { var thiz = this; this.dom.drag('start', function(e){ thiz.dispatchToolEvent( 'dragstart', thiz.buildEventData( e ) ); }); this.dom.drag(function(e){ thiz.dispatchToolEvent( 'dragmove', thiz.buildEventData( e ) ); }); this.dom.drag('end', function(e){ thiz.dispatchToolEvent( 'dragend', thiz.buildEventData( e ) ); }); }, /** Enable/Disable drag events */ disableDragEvents: function() { this.dom.unbind('draginit dragstart drag dragend'); }, /* Exports to raw data format */ rawExport: function() { var data = []; this.forEachEditable(function(editable){ data.push( editable.rawExport() ); }); return data; }, /* static */ rawImport: function( data ) { for (var i=0; i<data.length; ++i) { var rawannotation = data[i]; var annotation = null; switch (rawannotation.type) { case 'image': annotation = PDFAnnotator.Editable.Image.prototype.rawImport( rawannotation ); break; case 'text': annotation = PDFAnnotator.Editable.Text.prototype.rawImport( rawannotation ); break; case 'line': annotation = PDFAnnotator.Editable.Line.prototype.rawImport( rawannotation ); break; case 'quad': annotation = PDFAnnotator.Editable.Quad.prototype.rawImport( rawannotation ); break; case 'circle': annotation = PDFAnnotator.Editable.Circle.prototype.rawImport( rawannotation ); break; case 'photo': annotation = PDFAnnotator.Editable.Photo.prototype.rawImport( rawannotation ); break; case 'photoassignment': annotation = PDFAnnotator.Editable.PhotoAssignment.prototype.rawImport( rawannotation ); break; case 'measureline': annotation = PDFAnnotator.Editable.MeasureLine.prototype.rawImport( rawannotation ); break; case 'path': annotation = PDFAnnotator.Editable.Path.prototype.rawImport( rawannotation ); break; case 'compound': annotation = PDFAnnotator.Editable.Compound.prototype.rawImport( rawannotation ); break; } if (annotation) this.addObject( annotation, true ); } }, show: function() { this.dom.show(); }, hide: function() { this.dom.hide(); }, remove: function() { if (this.dom) { this.dom.remove(); this.dom = null; } } }); <file_sep> ALTER TABLE bt_toezichtmomenten ADD COLUMN codekey VARCHAR(5) UNIQUE DEFAULT NULL AFTER `id`; <file_sep><?php require_once( APPPATH . '/libraries/dossierexport/base.php' ); class CI_DossierExport { private $_CI; private $_progress; public function __construct() { $this->_CI = get_instance(); $this->_progress = new ExportProgress( 'dossierexport' ); } public function export( DossierResult $dossier, $doc_type, array $filter_data, &$deelplan_objecten=null ) { // see if template exists $path = APPPATH . '/libraries/dossierexport/' . $doc_type . '.php'; if (!is_file( $path )) throw new Exception( 'Ongeldige template naam: ' . $doc_type ); require_once( $path ); // see if class exists $classname = 'DossierExport' . $doc_type; if (!class_exists( $classname )) throw new Exception( 'Ongeldig geimplementeerde template: ' . $doc_type ); $exporter = new $classname( $dossier, $filter_data ); if (!($exporter instanceof DossierExportBase)) throw new Exception( 'Ongeldig geconfigureerde template: ' . $doc_type ); // go! $res = $exporter->generate(); // haal gebruikte deelplan objecten op, dit is by reference, dus mss // hebben we hier niks aan, maar boeie $deelplan_objecten = $exporter->get_deelplannen(); // geef resultaat terug return $res; } public function output_filter_form( $doc_type, DossierResult $dossier ) { // see if template exists $path = APPPATH . '/libraries/dossierexport/filter-forms/' . $doc_type . '.php'; if (!is_file( $path )) { return; } $this->_CI->load->model( 'gebruiker' ); $gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker(); include( $path ); } public function set_progress( $download_tag, $progress /* tussen 0 en 1 */, $action_description ) { $this->_progress->set_progress( $download_tag, $progress, $action_description ); } } <file_sep>CREATE TABLE IF NOT EXISTS `sjablonen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `klant_id` int(11) DEFAULT NULL, `naam` varchar(256) NOT NULL, PRIMARY KEY (`id`), KEY `klant_id` (`klant_id`) ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `sjabloon_checklisten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sjabloon_id` int(11) NOT NULL, `checklist_groep_id` int(11) NOT NULL, `checklist_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `sjabloon_id` (`sjabloon_id`), KEY `checklist_groep_id` (`checklist_groep_id`), KEY `checklist_id` (`checklist_id`) ) ENGINE=InnoDB; ALTER TABLE `sjablonen` ADD CONSTRAINT `sjablonen_ibfk_1` FOREIGN KEY (`klant_id`) REFERENCES `klanten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `sjabloon_checklisten` ADD CONSTRAINT `sjabloon_checklisten_ibfk_3` FOREIGN KEY (`checklist_id`) REFERENCES `bt_checklisten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `sjabloon_checklisten_ibfk_1` FOREIGN KEY (`sjabloon_id`) REFERENCES `sjablonen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `sjabloon_checklisten_ibfk_2` FOREIGN KEY (`checklist_groep_id`) REFERENCES `bt_checklist_groepen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `deelplannen` ADD `sjabloon_id` INT NULL DEFAULT NULL , ADD INDEX ( `sjabloon_id` ); ALTER TABLE `deelplannen` ADD FOREIGN KEY ( `sjabloon_id` ) REFERENCES `sjablonen` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; ALTER TABLE `deelplannen` ADD `sjabloon_naam` VARCHAR( 256 ) NULL DEFAULT NULL ; <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossiers.rapportage::rapportage.file_naam', 'Bestandsnaam', NOW(), 0);<file_sep><?php require_once('docx.php'); class DossierExportDocxPdf extends DossierExportDocx { /******************************************************************************** * * * MAIN FUNCTIONS * * * ********************************************************************************/ // Simply call the parent constructor, switching the output format from 'docx' to 'pdf' public function __construct( DossierResult $dossier, array $filter_data, $output_format = 'pdf' ) { parent::__construct( $dossier, $filter_data, $output_format ); } protected function _generate() { // Just let the main DOCX implementation do all of the work first. The resulting 'pdf' file will // be properly streamed to the browser from the DOCX base implementation. parent::_generate(); } } <file_sep><? require_once 'base.php'; class Steekproef extends Model { const STMT_SELECT = 'Steekproef::Select'; const STMT_REPLACE = 'Steekproef::Replace'; public function __construct() { parent::__construct(); $this->dbex->prepare( self::STMT_SELECT, 'SELECT teller FROM steekproeven WHERE klant_id = ? AND vraag_id = ?' ); //$this->dbex->prepare( self::STMT_REPLACE, 'REPLACE INTO steekproeven (klant_id, vraag_id, teller) VALUES (?, ?, ?)' ); $this->dbex->prepare_replace_into( self::STMT_REPLACE, 'REPLACE INTO steekproeven (klant_id, vraag_id, teller) VALUES (?, ?, ?)', null, array('id', 'klant_id', 'vraag_id') ); } function increase( $vraag_id, $klant_id=null ) { if (!$klant_id) $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $res = $this->dbex->execute( self::STMT_SELECT, array( $klant_id, $vraag_id ) ); if (!$res) throw new Exception( 'Fout bij opvragen tellerstand voor steekproeven.' ); if ($res->num_rows > 0) $aantal = 1 + reset($res->result())->teller; else $aantal = 1; $res->free_result(); $res = $this->dbex->execute( self::STMT_REPLACE, array( $klant_id, $vraag_id, $aantal ) ); if (!$res) throw new Exception( 'Fout bij bijwerken tellerstand voor steekproeven.' ); return $aantal; } } <file_sep>PDFAnnotator.Upload = PDFAnnotator.Base.extend({ uploader: null, uploading: false, start: function( form, onComplete, onError ) { if (this.uploading) return false; var thiz = this; thiz.uploading = true; if (!this.uploader) this.uploader = { frame : function(c) { var n = 'f' + Math.floor(Math.random() * 99999); var d = document.createElement('DIV'); d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="PDFAnnotator.Upload.prototype.uploader.loaded(\''+n+'\')"></iframe>'; document.body.appendChild(d); var i = document.getElementById(n); if (c && typeof(c.onComplete) == 'function') { i.onComplete = c.onComplete; } return n; }, form : function(f, name) { f.setAttribute('target', name); }, submit : function(f, c) { this.form(f, this.frame(c)); if (c && typeof(c.onStart) == 'function') { return c.onStart(); } else { return true; } }, loaded : function(id) { thiz.uploading = false; var i = document.getElementById(id); if (i.contentDocument) { var d = i.contentDocument; } else if (i.contentWindow) { var d = i.contentWindow.document; } else { var d = window.frames[id].document; } if (d.location.href == "about:blank") { return; } if (typeof(i.onComplete) == 'function') { i.onComplete(d.body.innerHTML); i.onComplete = null; } } }; this.uploader.submit( form, {'onStart' : function() {}, 'onComplete' : onComplete}) try { form.submit(); return true; } catch (err) { if (typeof( onError ) == 'function') onError( err ); thiz.uploading = false; return false; } } }); <file_sep><?php // voor security if (!defined( 'IS_WEBSERVICE' )) define('IS_WEBSERVICE', true); // definieer hier alle component, de naam moet 1-op-1 overeen komen met wat er in de database staat define('WS_COMPONENT_KLANTEN_KOPPELING', 'Klanten koppeling'); define('WS_COMPONENT_ZAKEN_KOPPELING', 'Zaken koppeling'); define('WS_COMPONENT_BRISTOETS_KOPPELING', 'BRIStoets koppeling'); define('WS_COMPONENT_BTZAPP_KOPPELING', 'BTZapp koppeling'); // include helper files require_once( dirname(__FILE__) . '/webservice/exceptions.php' ); require_once( dirname(__FILE__) . '/webservice/tools.php' ); require_once( dirname(__FILE__) . '/webservice/module.php' ); // include actual components require_once( dirname(__FILE__) . '/webservice/klanten.php' ); require_once( dirname(__FILE__) . '/webservice/zaken.php' ); /* for now for SSO only */ require_once( dirname(__FILE__) . '/webservice/bristoets.php' ); require_once( dirname(__FILE__) . '/webservice/btzapp.php' ); class Webservice extends Controller { private $_account = null; private $_request; // original POST request private $_data; // parsed data private $_log; // webservicelog instance private $_module; // WebserviceModule private function _initialize_module_and_account( $recht_naam ) { // check username & password $this->load->model( 'webserviceaccount' ); if (!($account = $this->webserviceaccount->find_by_username_and_password( $this->_data->WebserviceAccount, $this->_data->WebservicePassword ))) throw new DataSourceException( 'Ongeldige gebruikersnaam en wachtwoord.' ); if (!$account->actief) throw new DataSourceException( 'Opgegeven webserviceaccount is geblokkeerd.' ); if (!$account->get_applicatie()->actief) throw new DataSourceException( 'Opgegeven webserviceapplicatie is geblokkeerd.' ); $this->_account = $account; // check if account has requested recht if (!$this->_account->mag_bij_component( $recht_naam )) throw new ServerSourceException( 'Opgegeven webserviceaccount heeft onvoldoende rechten voor deze actie.' ); // initialize module $this->_module = WebserviceModule::get_module( $recht_naam ); $this->_module->initialize( $this->_data, $this->_account, $this->_log ); } public function _exception_handler( $exception ) { $this->_rollback_transactions(); $data = array( 'ErrorMessage' => preg_replace( '#</?.*?>#', '', $exception->getMessage() ), 'UserMessage' => 'Het verzoek kon niet worden afgehandeld.', ); if ($exception instanceof SourceException) $data['Source'] = $exception->get_source(); else $data['Source'] = 'server'; // fallback for exceptions that are not thrown in this code, do not use as a lazy fallback!! $this->_output_json( $data ); } public function _error_handler( $errno, $errstr, $errfile, $errline ) { if (error_reporting() & $errno) { $this->_rollback_transactions(); $this->_output_json( array( 'ErrorMessage' => $errno . ': ' . $errstr . ' in ' . basename( $errfile ) . ':' . $errline, 'UserMessage' => 'Het verzoek kon niet worden afgehandeld door een fout in de webservice.', 'Source' => 'server' ) ); } } private function _rollback_transactions() { while ($this->db->_trans_depth > 0) { $this->db->_trans_status = false; $this->db->trans_complete(); } } private function _locallog( $msg ) { if ($this->_module) $this->_module->locallog( $msg ); } public function _output_json( $value ) /* yes public, because WebserviceModule uses it, and starts with _ to make it unreachable via webserver! */ { $this->_locallog( 'outputting json' ); $json = json_encode( $value ); $this->_locallog( 'outputting json: strlen=' . strlen($json) ); try { if ($this->_log) { $this->_locallog( 'storing response' ); $this->_log->response = $json; if ($this->_account) $this->_log->webservice_account_id = $this->_account->id; $this->_locallog( 'storing response: saving' ); unset( $this->_log->request ); // might be very large, omit from UPDATE query $res = $this->_log->save( false, null, false ); $this->_locallog( 'storing response: done' ); } } catch (Exception $e) { // fail silently error_log( 'OUTPUT JSON ERROR: ' . $e->getMessage() ); } $headers = function_exists( 'apache_request_headers' ) ? apache_request_headers() : array(); $supports_gzip = isset( $headers['Accept-Encoding'] ) && in_array( 'gzip', preg_split( '/\s*,\s*/', strtolower($headers['Accept-Encoding']), -1, PREG_SPLIT_NO_EMPTY ) ); if ($supports_gzip) { header( 'Content-Encoding: gzip' ); echo gzencode( $json ); } else { header( 'Content-Type: text/json' ); echo $json; } exit; } public function __construct() { parent::__construct(); global $method; if(0){ $this->_request = '{"WebserviceAccount":"btzapp","WebservicePassword":"<PASSWORD>"}'; $this->_data = json_decode( $this->_request ); $this->load->model( 'webservicelog' ); $this->_log = $this->webservicelog->add( $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], $this->_request, '', null, $_SERVER['SERVER_PORT'] == 443 ); return true; } if ($method != 'test') { set_exception_handler( array( $this, '_exception_handler' ) ); set_error_handler( array( $this, '_error_handler' ) ); } error_reporting( E_ALL & ~(E_DEPRECATED) ); $this->load->model( 'webservicelog' ); if ($method != 'test') { // get request string $this->_request = file_get_contents( 'php://input' ); // store right away, before error logging starts $this->_log = $this->webservicelog->add( $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], $this->_request, '', null, $_SERVER['SERVER_PORT'] == 443 ); // check input if (!isset( $_SERVER['REQUEST_METHOD'] ) || $_SERVER['REQUEST_METHOD']!='POST') throw new DataSourceException( 'Only POST requests are processed.' ); if (!$this->_request) throw new DataSourceException( 'Empty POST request.' ); $this->_data = json_decode( $this->_request ); if (!is_object( $this->_data )) throw new DataSourceException( 'POST request did not contain a valid json object.' ); if (!isset( $this->_data->WebserviceAccount ) || !isset( $this->_data->WebservicePassword )) throw new DataSourceException( 'POST request did not contain webservice account credentials.' ); } } /**************************************************************************************************** * * * * * BOOTSTRAP FUNCTIONS * * * * * ****************************************************************************************************/ // --------- klant module --------------------------------------------------------------------------- public function GeefKlanten() { $this->_initialize_module_and_account( WS_COMPONENT_KLANTEN_KOPPELING ); $this->_module->GeefKlanten(); } public function GeefGebruikers() { $this->_initialize_module_and_account( WS_COMPONENT_KLANTEN_KOPPELING ); $this->_module->GeefGebruikers(); } // --------- zaken module --------------------------------------------------------------------------- public function DossierToevoegen() { $this->_initialize_module_and_account( WS_COMPONENT_ZAKEN_KOPPELING ); $this->_module->DossierToevoegen(); } public function DossierBewerken() { $this->_initialize_module_and_account( WS_COMPONENT_ZAKEN_KOPPELING ); $this->_module->DossierBewerken(); } public function DossierBescheidenToevoegen() { $this->_initialize_module_and_account( WS_COMPONENT_ZAKEN_KOPPELING ); $this->_module->DossierBescheidenToevoegen(); } public function DossierBescheidenVerwijderen() { $this->_initialize_module_and_account( WS_COMPONENT_ZAKEN_KOPPELING ); $this->_module->DossierBescheidenVerwijderen(); } public function DossierArchiveren() { $this->_initialize_module_and_account( WS_COMPONENT_ZAKEN_KOPPELING ); $this->_module->DossierArchiveren(); } // --------- bristoets module ----------------------------------------------------------------------- public function AandachtspuntenToevoegen() { $this->_initialize_module_and_account( WS_COMPONENT_BRISTOETS_KOPPELING ); $this->_module->AandachtspuntenToevoegen(); } // --------- btzapp module ------------------------------------------------------------------------- public function GeefDossiersVoorToezichthouder() { $this->_initialize_module_and_account( WS_COMPONENT_BTZAPP_KOPPELING ); $this->_module->GeefDossiersVoorToezichthouder(); } public function GeefGebruikerInfo() { $this->_initialize_module_and_account( WS_COMPONENT_BTZAPP_KOPPELING ); $this->_module->GeefGebruikerInfo(); } public function GeefToezichtBescheiden() { $this->_initialize_module_and_account( WS_COMPONENT_BTZAPP_KOPPELING ); $this->_module->GeefToezichtBescheiden(); } public function GeefStempels() { $this->_initialize_module_and_account( WS_COMPONENT_BTZAPP_KOPPELING ); $this->_module->GeefStempels(); } /**************************************************************************************************** * * * * * TEST FUNCTION * * * * * ****************************************************************************************************/ public function test() { $this->load->library( 'curl' ); $functies = array(); foreach (get_class_methods( $this ) as $method) if (!in_array( $method, array( 'CI_Base', 'Controller' ))) if (preg_match( '/^[A-Z][A-Za-z0-9_]+$/', $method )) $functies[] = $method; $this->load->view( 'webservice/test', array( 'functies' => $functies, 'basisverzoek' => json_encode( array( 'WebserviceAccount' => '', 'WebservicePassword' => '', ) ), ) ); } } <file_sep><? require_once 'base.php'; class DeelplanChecklistToezichtmomentResult extends BaseResult { private $_hoofdgroepen = NULL; private $_dossier = NULL; private $_deelplan = NULL; public function DeelplanChecklistToezichtmomentResult( &$arr ){ parent::BaseResult( 'deelplanchecklisttoezichtmoment', $arr ); } // Small helper function to drill down to the dossier to which this toezichtmoment belongs public function get_dossier() { $dossier = null; $this->_CI->load->model( 'deelplanchecklist' ); $deelplanchecklist = $this->_CI->deelplanchecklist->get($this->deelplan_checklist_id); if (!is_null($deelplanchecklist)) { $deelplan = $deelplanchecklist->get_deelplan(); if (!is_null($deelplanchecklist)) { $dossier = $deelplan->get_dossier(); } // if (!is_null($deelplanchecklist)) } // if (!is_null($deelplanchecklist)) return $dossier; } public function get_deelplan() { if($this->_deelplan != NULL) { return $this->_deelplan; } $this->_CI->load->model( 'deelplan' ); $this->_CI->load->model( 'deelplanchecklist' ); $dp_checklist = $this->_CI->deelplanchecklist->get( $this->deelplan_checklist_id ); $this->_deelplan = $this->_CI->deelplan->get( $dp_checklist->deelplan_id ); return $this->_deelplan; } // Small helper function to drill down to the deelplan checklist to which this toezichtmoment belongs public function get_deelplan_checklist() { $deelplanchecklist = null; $this->_CI->load->model( 'deelplanchecklist' ); $deelplanchecklist = $this->_CI->deelplanchecklist->get($this->deelplan_checklist_id); return $deelplanchecklist; } // Small helper function to drill down to the deelplan checklist to which this toezichtmoment belongs public function get_toezichtmoment() { $toezichtmoment = null; $this->_CI->load->model( 'toezichtmoment' ); $toezichtmoment = $this->_CI->toezichtmoment->get($this->bt_toezichtmoment_id); return $toezichtmoment; } private static function get_tag( &$tags ) { $tag = md5(rand()); while(in_array($tag, $tags )){$tag = md5(rand());} $tags[] = $tag; return $tag; } public function get_hoofdgroepen(){ if( $this->_hoofdgroepen != NULL && is_array($this->_hoofdgroepen) ) { return $this->_hoofdgroepen; } $this->_CI->load->model( 'hoofdgroep' ); $this->_hoofdgroepen = $this->_CI->hoofdgroep->get_by_toezichtmoment_not_getr( $this->bt_toezichtmoment_id ); return $this->_hoofdgroepen; } //--------------------------------- public function generate_deelplan_opdrachten() { $this->_CI->load->model( 'deelplan' ); $this->_CI->load->model( 'deelplanchecklist' ); $this->_CI->load->model( 'hoofdgroep' ); $this->_CI->load->model( 'categorie' ); $this->_CI->load->model( 'vraag' ); $this->_CI->load->model( 'dossiersubject' ); $this->_CI->load->model( 'vraagopdracht' ); $this->_CI->load->model( 'deelplanopdracht' ); $this->_CI->load->model( 'deelplanvraag' ); // Skip toezichtmomenten for which insufficient data has been set. if ( empty($this->voornaam_uitvoerende) || empty($this->achternaam_uitvoerende) || empty($this->email_uitvoerende) ) { throw new Exception ('Niet alle verplichte velden zijn aanwezig - opdrachten kunnen niet gegenereerd worden.'); } $dossier = $this->get_dossier(); $doss_subj_naam = $this->voornaam_uitvoerende.' '.$this->achternaam_uitvoerende; $doss_subjecten = $this->_CI->dossiersubject->get_by_dossier( $dossier->id ); foreach( $doss_subjecten as $doss_subject ) { if( $doss_subj_exists = $doss_subject->naam == $doss_subj_naam ) { break; } } if( !$doss_subj_exists ) { $useMobielNummer = (empty($this->mobiele_nummer_uitvoerende) || is_null($this->mobiele_nummer_uitvoerende)) ? '' : $this->mobiele_nummer_uitvoerende; $doss_subject = $this->_CI->dossiersubject->insert( array( 'dossier_id' => $dossier->id, 'rol' => 'Uitvoerende', 'naam' => $doss_subj_naam, 'telefoon' => $useMobielNummer, 'email' => $this->email_uitvoerende ) ); } $deelplan = $this->get_deelplan(); $tags = array(); // Determine who gets selected as the person who is the 'opdrachtgever'. If a 'toezichthouder' was specified for this // deelplan_checklist_toezichtmoment use that person, otherwise use the dossier_verantwoordelijke as a fallback value. // Note that leaving the 'opdrachtgever_gebruiker_id' field below empty results in invalid opdrachten that cause trouble // elsewhere in the logic. $useOpdrachtGeverId = (!is_null($this->toezichthouder_woningborg_gebruiker_id)) ? $this->toezichthouder_woningborg_gebruiker_id : $dossier->gebruiker_id; $hoofdgroepen = $this->get_hoofdgroepen(); foreach( $hoofdgroepen as $hoofdgroep ) { $categorien = $this->_CI->categorie->get_by_hoofdgroep( $hoofdgroep->id ); foreach( $categorien as $categorie ) { $vragen = $this->_CI->vraag->get_by_categorie( $categorie->id ); foreach( $vragen as $vraag ) { $vraagopdrachten = $this->_CI->vraagopdracht->get_by_vraag( $vraag->id ); foreach( $vraagopdrachten as $vraagopdracht ) { // We only generate opdrachten for vragen that are featured in the filtered set of deelplanvragen, as // those are the only ones we need to generate them for! // This is very important, as the process of specifying an 'opdracht' as finalised (i.e. 'gereed') has to update // the corresponding deelplanvraag, and if no such record exists, it fails with an error. $deelplanChecklist = $this->_CI->deelplanchecklist->get($this->deelplan_checklist_id); $bouwnummer = $deelplanChecklist->bouwnummer; $deelplanVraag = $this->_CI->deelplanvraag->get_by_deelplan_and_vraag_and_bouwnummer( $deelplan->id, $vraag->id, $bouwnummer ); //d($deelplan->id); //d($vraag->id); //d($bouwnummer); //d($deelplanVraag); // Only generate an opdracht if a corresponding deelplanvrag exists! if (!is_null($deelplanVraag)) { $data = array( 'deelplan_id' => $deelplan->id, 'vraag_id' => $vraag->id, 'dossier_subject_id'=> $doss_subject->id, 'opdracht_omschrijving' => $vraagopdracht->opdracht, 'deelplan_checklist_id' => $this->deelplan_checklist_id, 'opdrachtgever_gebruiker_id' => $useOpdrachtGeverId, 'datum_begin' => $this->datum_begin, 'datum_einde' => $this->datum_einde, 'gereed_datum' => $this->datum_einde, 'tag' => self::get_tag( $tags ) ); //d($data); $this->_CI->deelplanopdracht->insert( $data ); } } } } } } //--------------------------------- }// Class end class DeelplanChecklistToezichtmoment extends BaseModel { public function DeelplanChecklistToezichtmoment(){ parent::BaseModel( 'DeelplanChecklistToezichtmomentResult', 'deelplan_checklist_toezichtmomenten' ); } public function check_access( BaseResult $object ){ return; } // This method is intended to be used in conjunction with the 'generate_deelplan_opdrachten' call. This method gets the // deelplan-checklist-toezichtmomenten for which deelplan-opdrachten need to be generated, and the 'generate_deelplan_opdrachten' call // can then be used for each of the retrieved deelplan-checklist-toezichtmomenten to actually generate them. public function get_for_generate_deelplan_opdrachten() { //$parameters = array($btzDossierId, $btzDossierHash); $parameters = array(); $stmt_name = 'get_for_generate_deelplan_opdrachten'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT * FROM deelplan_checklist_toezichtmomenten WHERE (opdrachten_gegenereerd = 0) AND (datum_begin = (CURDATE() + INTERVAL 1 DAY))'); $deelplanChecklistToezichtmomenten = $this->convert_results( $this->_CI->dbex->execute($stmt_name, $parameters) ); return $deelplanChecklistToezichtmomenten; } // public function get_for_generate_deelplan_opdrachten() /** * gets the deelplancheclisttoezichmomenten. * If $bt_tmoment_id != null then only one entry in array!!! * @param integer $deelplanChecklistId * @param integer $bt_tmoment_id * @param boolean $assoc * @return array */ public function get_by_deelplanchecklist( $deelplanChecklistId, $bt_tmoment_id=null, $assoc=false ){ $tmomenten = $this->db->where('deelplan_checklist_id', $deelplanChecklistId ); if($bt_tmoment_id != null ) $tmomenten->where('bt_toezichtmoment_id', $bt_tmoment_id ); $tmomenten = $tmomenten->order_by('naam') ->get( $this->_table ) ->result(); $result = array(); foreach( $tmomenten as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } }// Class end <file_sep><form method="POST" action="<?=PDFANNOTATOR_UPLOAD_PHOTO_URL?>" enctype="multipart/form-data" class="CameraForm Hidden"> <input type="file" name="photo"> </form><file_sep><?php /** * File: /application/helper/soapclient.php * Author: <NAME> * Company: Millennics * Date: April 16th, 2013 * * Remarks: * */ class SoapClientHelper { private $debug = false; private $silent = true; private $soapConnectOutput = ''; private $errors = array(); private $wsdlLocation = ''; private $wsMethod = ''; private $rawLastResponse = ''; private $wsOk; private $wsClient = null; public function GetDebug() { return $this->debug; } public function SetDebug($debug) { $this->debug = $debug; } public function GetSilent() { return $this->silent; } public function SetSilent($silent) { $this->silent = $silent; } public function GetSoapConnectOutput() { return $this->soapConnectOutput; } public function SetSoapConnectOutput($soapConnectOutput) { $this->soapConnectOutput = $soapConnectOutput; } public function GetErrors() { return $this->errors; } public function SetErrors($errors) { $this->errors = $errors; } private function StoreError($errorMessage) { $this->errors[] = $errorMessage; } public function GetWsdlLocation() { return $this->wsdlLocation; } public function SetWsdlLocation($wsdlLocation) { $this->wsdlLocation = $wsdlLocation; } public function GetWsMethod() { return $this->wsMethod; } public function SetWsMethod($wsMethod) { $this->wsMethod = $wsMethod; } public function GetRawLastResponse() { return $this->rawLastResponse; } public function SetRawLastResponse($rawLastResponse) { $this->rawLastResponse = $rawLastResponse; } public function GetWsOk() { return $this->wsOk; } public function SetWsOk($wsOk) { $this->wsOk = $wsOk; } public function GetWsClient() { return $this->wsClient; } public function SetWsClient($wsClient) { $this->wsClient = $wsClient; } public function __construct($wsdlLocation = '', $wsMethod = '', $debug = false, $silent = true) { $this->SetSilent($silent); $this->SetDebug($debug); $this->SetWsLocationAndMethod($wsdlLocation, $wsMethod); // Make the connection, if a WSDL was specified if (!empty($this->wsdlLocation)) { if ($this->GetSilent()) { $oldErrorReportingLevel = error_reporting(0); } $this->Connect(); if ($this->GetSilent()) { error_reporting($oldErrorReportingLevel); } } } // public function __construct($wsdlLocation = '', $wsMethod = '') public function SetEndPoint($newEndPoint) { if (!is_null($this->wsClient)) { $oldEndPoint = $this->wsClient->__setLocation($newEndPoint); if ($this->GetDebug() && !$this->GetSilent()) { echo 'Changed endpoint from: ' . $oldEndPoint . ' to new endpoint: ' . $newEndPoint . '<br /><br />'; } } else { $curErrorMessage = 'SOAP Client does not yet exist - cannot set new endpoint: ' . $newEndPoint; $this->StoreError($curErrorMessage); if (!$this->GetSilent()) { echo $curErrorMessage . '<br /><br />'; } } } // public function SetWsLocationAndMethod($wsdlLocation = '', $wsMethod = '') public function SetWsLocationAndMethod($wsdlLocation = '', $wsMethod = '') { $this->SetWsdlLocation($wsdlLocation); $this->SetWsMethod($wsMethod); } // public function SetWsLocationAndMethod($wsdlLocation = '', $wsMethod = '') public function Connect($wsdlLocation = '') { // In silent mode we suppress the raw output when connecting, etc. if ($this->GetSilent()) { ob_start(); } // Allow the user to directly pass in (or override) the WSDL location if (!empty($wsdlLocation)) { $this->SetWsdlLocation($wsdlLocation); } // Make the connection if (!empty($this->wsdlLocation)) { $this->SetWsOk(true); //$oldErrorReportingLevel = error_reporting(0); try { // Instantiate the actual SoapClient if ($this->GetDebug()) { // In order to be able to show the exact request data, we must connect // with the 'trace' parameter set to 1. if (!$this->GetSilent()) { echo 'Connecting to WSDL: ' . $this->wsdlLocation . '<br /><br />'; } $wsClient = new SoapClient($this->wsdlLocation, array('trace' => 1)); } else { // Note: in order to keep track of failed SOAP requests we now always connect in trace mode // so we can retrieve the raw last response too; a thing that was needed for certain failed calls. //$wsClient = new SoapClient($this->wsdlLocation); $wsClient = new SoapClient($this->wsdlLocation, array('trace' => 1)); } //error_reporting($oldErrorReportingLevel); // Register the SoapClient $this->SetWsClient($wsClient); } catch (Exception $e) { // Failure. Notify the user. //error_reporting($oldErrorReportingLevel); $this->SetWsOk(false); //echo 'Webservice FAILED! Caught exception: ', $e->getMessage(), '<br /><br />'; $curErrorMessage = 'Webservice FAILED! Caught exception: ' . $e->getMessage(); $this->StoreError($curErrorMessage); if (!$this->GetSilent()) { echo $curErrorMessage . '<br /><br />'; } } } else { //echo 'A WSDL location needs to be specified before you can connect!<br /><br />'; $curErrorMessage = 'A WSDL location needs to be specified before you can connect!'; $this->StoreError($curErrorMessage); if (!$this->GetSilent()) { echo $curErrorMessage . '<br /><br />'; } } // In silent mode we set the raw output in the member for that if ($this->GetSilent()) { $this->SetSoapConnectOutput = trim(ob_get_clean()); } } // public function Connect($wsdlLocation = '') private function debugOutput($mixed) { echo '<pre>'; var_dump($mixed); echo '</pre>'; } // private function debugOutput($mixed) public function TestWs() { echo "<br />Test webservice: {$this->GetWsMethod()}<br />"; if ($this->GetWsOk()) { echo 'Webservice O.K.!<br /><br />'; if ($this->GetDebug()) { echo 'Interface:<br />'; $this->debugOutput($this->GetWsClient()->__getFunctions()); echo '<br /><br />'; echo 'Types:<br />'; $this->debugOutput($this->GetWsClient()->__getTypes()); echo '<br /><br />'; } } else { $curErrorMessage = 'No (valid) connection has been made yet. Please connect first!'; $this->StoreError($curErrorMessage); //if (!$this->GetSilent()) { echo $curErrorMessage . '<br /><br />'; //} } return $this->GetWsOk(); } // public function TestWs() public function CallWsMethod($wsMethod = '', $wsParameters = array()) { if ($this->GetSilent()) { $oldErrorReportingLevel = error_reporting(0); } // Initialise the return value to an empty string $wsReply = ''; // Check whether to use the currently registered method, or one that was passed in // explicitly (i.e. an overriding method name). $wsMethodToUse = (empty($wsMethod)) ? $this->GetWsMethod() : $wsMethod; // Debug output if ($this->GetDebug()) { echo "<br />Calling webservice method: {$wsMethodToUse}<br />"; echo "<br />Parameters:"; $this->debugOutput($wsParameters); } // Perform the call and return the received reply if ($this->GetWsOk()) { try { // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit(3600); $wsReply = $this->GetWsClient()->{$wsMethodToUse}($wsParameters); if (is_null($wsReply)) { //$wsReply = $this->GetWsClient()->__getLastResponse(); $this->SetRawLastResponse($this->GetWsClient()->__getLastResponse()); } if ($this->GetDebug()) { echo 'Webservice O.K.! request:<br />'; $this->debugOutput($this->GetWsClient()->__getLastRequest()); echo '<br />response:<br />'; $this->debugOutput($wsReply); echo '<br /><br />'; } } catch (Exception $e) { // Failure. Notify the user. //$this->SetWsOk(false); $curErrorMessage = 'Call to "' . $wsMethodToUse . '" failed!' . "\nCaught exception: " . $e->getMessage() . "\nUsed parameters: " . var_export($wsParameters, true); $this->StoreError($curErrorMessage); //echo "+-+-+"; //$this->SetRawLastResponse($this->GetWsClient()->__getLastResponse()); //$this->SetRawLastResponse($this->GetWsClient()->__last_response()); if (!$this->GetSilent()) { echo nl2br($curErrorMessage) . '<br /><br />'; } } } else { $curErrorMessage = 'No (valid) connection has been made yet. Please connect first!'; $this->StoreError($curErrorMessage); if (!$this->GetSilent()) { echo $curErrorMessage . '<br /><br />'; } } if ($this->GetSilent()) { error_reporting($oldErrorReportingLevel); } // Return the received reply return $wsReply; } // public function CallWsMethod($wsMethod = '', $wsParameters = array()) } // class SoapClientHelper // Helper function that returns the SOAP client helper object, along with specific extracted information // from it. The same information could be retrieved (repeatedly) from the helper class itself too, but the // wrapper allows for additional information, and if so desired for additional error handling, etc. function getWrappedSoapClientHelper($wsdlLocation = '', $wsMethod = '', $debug = false, $silent = true) { $soapOutput = ''; $soapErrors = array(); $soapClient = null; if ($silent) { $oldErrorReportingLevel = error_reporting(0); } //echo "+old+"; //d($oldErrorReportingLevel); //echo "+new+"; //d(error_reporting()); // Instantiate a SoapClientHelper. Pass the parameters that we received. $soapClient = new SoapClientHelper($wsdlLocation, $wsMethod, $debug, $silent); $soapOutput = $soapClient->GetSoapConnectOutput(); $soapErrors = $soapClient->GetErrors(); $soapClientHelperWrapper = new stdClass(); $soapClientHelperWrapper->soapClient = $soapClient; $soapClientHelperWrapper->soapOutput = $soapOutput; $soapClientHelperWrapper->soapErrors = $soapErrors; if ($silent) { error_reporting($oldErrorReportingLevel); } return $soapClientHelperWrapper; } // function getWrappedSoapClientHelper($wsdlLocation = '', $wsMethod = '', $debug = false, $silent = true) /* function callWrappedWsMethod($wrappedSoapClient, $wsMethod = '', $wsParameters = array()) { $wsResult = $wrappedSoapClient->soapClient->CallWsMethod($wsMethod, $wsParameters); return $wsResult; } * */<file_sep>ALTER TABLE `deelplan_opdrachten` CHANGE `overzicht_afbeelding` `overzicht_afbeelding_0` LONGBLOB NULL DEFAULT NULL, ADD `overzicht_afbeelding_1` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_0`, ADD `overzicht_afbeelding_2` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_1`, ADD `overzicht_afbeelding_3` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_2`, ADD `overzicht_afbeelding_4` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_3`, ADD `overzicht_afbeelding_5` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_4`, ADD `overzicht_afbeelding_6` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_5`, ADD `overzicht_afbeelding_7` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_6`, ADD `overzicht_afbeelding_8` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_7`, ADD `overzicht_afbeelding_9` LONGBLOB NULL DEFAULT NULL AFTER `overzicht_afbeelding_8`; <file_sep><div class="menubar"><input type="submit" value="afsluiten" />BRISToezicht - Deelplannen</div> Selecteer een deelplan: <? if (sizeof( $objecten )): ?> <? foreach ($objecten as $deelplan):?> <form method="post" action=""> <!--replace with <details> when tag becomes widely accepted --> <div class="details"> <button type="submit"> <input type="hidden" name="page" value="toezichtmomenten"> <input type="hidden" name="parent_id" value="<?=$deelplan->id?>"> <!--replace with <summary> when tag becomes widely accepted --> <div class="summary"> <p><b><?//=tg('dossiers.kies.adres')?></b></p> </div> <!--TODO: einddatum tonen --> <div class="table"> <div class="tr"> <span class="td"><?=htmlentities( $deelplan->naam, ENT_COMPAT, 'UTF-8' )?></b></span> </div> <div class="tr"> <span class="td">Aantal: x</span><span class="td <?//=$class kan leeg zijn of alert?>">Hercontrole: dd-mm-yyyy</span><span class="td">Einddatum: dd-mm-yyyy</span> </div> </div> </button> </div> </form> <? endforeach; ?> <? else: ?> <div class="melding">Er zijn momenteel geen opdrachten voor u ingepland.</div> <? endif; ?> <div class="menubar"><div class="bottom"> <form method="post" action=""><input type="hidden" name="page" value="dossiers"><input type="submit" value="terug" /><input type="submit" value="opslaan" /></form> </div></div> <file_sep>PDFAnnotator.Editable = PDFAnnotator.Base.extend({ /* constructor */ init: function( tool, fake_editable /* for path */ ) { /* initialize base class */ this._super(); /* the container we're on, initially null until we're added to a contanier, which * will call setContainer on us. */ this.container = null; /* this should hold the basic (simple) data that will be serialized to a server */ this.data = {}; /* the tool that created us */ if (!fake_editable) if (!(tool instanceof PDFAnnotator.Tool)) throw 'PDFAnnotator.Editable.init: specified tool not deriving from PDFAnnotator.Editable'; this.tool = tool; /* a jQuery collection of dom objects that visually represent this editable object. */ this.visuals = $([]); /* register and handle events */ this.registerEventType( 'click' ); if (this.tool) { this.on( 'click', function( editable, data ){ var activeTool = editable.container.engine.getActiveTool(); if (activeTool == editable.tool) { data.event.stopPropagation(); data.editable = editable; activeTool.dispatchEvent( 'editableclick', data ); } }); } /* create register of handles, they're created as they're required */ this.handles = {}; }, /* sets data based on user config, defaults and required fields */ setData: function( config /* object */, defaults /* object */, required /* array */ ) { for (var i in defaults) this.data[i] = (!config || typeof( config[i] ) == 'undefined') ? defaults[i] : config[i]; for (var i=0; i<required.length; ++i) if (!config || typeof( config[required[i]] ) == 'undefined') { throw 'PDFAnnotator.Editable.setData: missing value for "' + required[i] + '" in config'; } else this.data[required[i]] = config[required[i]]; }, /* sets the container for this editable */ setContainer: function( container ) { if (!container) { this.visuals.remove(); this.visuals = $([]); this.container = null; } else { if (!(container instanceof PDFAnnotator.EditableContainer)) throw 'PDFAnnotator.Editable.setContainer: container not a PDFAnnotator.EditableContainer object'; this.container = container; this.render(); } }, /* moves the visual objects to a relative position, i.e. move a number of pixels up/down/left/right */ moveRelative: function( relx, rely ) { this.visuals.each(function(){ var thiz = $(this); thiz.css({ left: parseInt( thiz.css('left') ) + relx, top: parseInt( thiz.css('top') ) + rely }); }); }, /* resizes the visual objects to a relative size, i.e. make all objects a few pixels wider or higher */ resizeRelative: function( relx, rely ) { this.visuals.each(function(){ var thiz = $(this); thiz.css({ width: parseInt( thiz.css('width') ) + relx, height: parseInt( thiz.css('height') ) + rely }); }); }, /* called whenever the object needs to be rendered, should add objects to this.visuals * implemented in deriving classes */ render: function() { }, /* call to add a visual (e.g. a text, an img or a line) to this editable */ addVisual: function( dom ) { // make sure dom is a jquery collection if (!(dom instanceof jQuery )) dom = $(dom); if (!dom.size()) return; // convert the element positions from container to screen var container = this.container; dom.each(function(){ var thiz = $(this); var pos = new PDFAnnotator.Math.IntVector2( thiz.css( 'left' ), thiz.css( 'top' ) ); // pos = container.containerToScreen( pos ); thiz.css( 'left', pos.x ); thiz.css( 'top', pos.y ); }); // add collection of visuals this.visuals = this.visuals.add( dom ); // append it to our container's dom object, actually making it visible! this.container.dom.append( dom ); }, getHandle: function( type ) { if (typeof( this.handles[type] ) == 'undefined') { var handle; switch (type) { case 'delete': handle = new PDFAnnotator.Handle.Delete( this ); break; case 'move': handle = new PDFAnnotator.Handle.Move( this ); break; case 'resize': handle = new PDFAnnotator.Handle.Resize( this ); break; case 'ChangeVraag': handle = new PDFAnnotator.Handle.ChangeVraag( this ); break; default: throw 'PDFAnnotator.Editable.getHandle: type "' + type + '" not supported.'; } this.handles[type] = handle; } return this.handles[type]; }, /* destroys all currently created handles for this editable, by removing them from * the dom, and removing the accompanying Handle objects. */ resetHandles: function() { for (var i in this.handles) this.handles[i].remove(); this.handles = {}; }, /* can be called after setting zoom level to reposition any visible handles. */ repositionHandles: function() { for (var i in this.handles) if (this.handles[i].visible()) this.handles[i].show(); }, /* called whenever the object needs to be exported to raw data to send to the server, should be overridden by deriving classes */ rawExport: function() { }, /* called just before editable is removed from containr */ preremove: function() { }, /* called when "zoom" level changes in engine. */ /* !!overide!! */ setZoomLevel: function( oldlevel, newlevel ) { var newPos = this.data.position.multiplied( newlevel / oldlevel ); this.moveRelative( newPos.x - this.data.position.x, newPos.y - this.data.position.y ); this.repositionHandles(); } }); <file_sep>ALTER TABLE `project_mappen` ADD COLUMN `toezichtmoment_id` int(11) DEFAULT NULL ; <file_sep><? require_once 'base.php'; class ToezichtmomenthoofdgroepResult extends BaseResult { public function ToezichtmomenthoofdgroepResult( &$arr ){ parent::BaseResult( 'toezichtmomenthoofdgroep', $arr ); } } class Toezichtmomenthoofdgroep extends BaseModel { public function Toezichtmomenthoofdgroep(){ parent::BaseModel( 'ToezichtmomenthoofdgroepResult', 'bt_toezichtmomenten_hoofdgroepen' ); } public function check_access( BaseResult $object ){ //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function delete( Array $where ){ $this->db->delete( $this->_table, $where ); } }// Class end <file_sep><div class="page"> <div id="header" class="menubar"> <form method="post"> <input type="hidden" name="page" value="afsluiten"> <input id="close" type="submit" value="afsluiten" hidden/><label for="close">Afsluiten</label>BRISToezicht - Opdracht opslaan </form> </div> <div class="objects"> <?=$objecten['result'] ?> </div> <form method="post"> <input type="hidden" name="page" value="opdracht"> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input type="hidden" name="bouwnummer_id" value="<?=$bouwnummer?>"> <input type="hidden" name="hoofdgroep_id" value="<?=$hoofdgroep?>"> <input type="hidden" name="opdracht_id" value="<?=$opdracht?>"> <input id="opdracht" type="submit" value="Opdracht" hidden /> </form> <div id="footer" class="menubar"> <form method="post"> <input type="hidden" name="page" value="dossiers"> <input id="dossiers" type="submit" value="Dossiers" hidden /> <label for="dossiers">Dossiers</label> <label for="opdracht">Opdracht</label> </form> </div> </div><file_sep><?php function _DgetDateTime(){ $mkarr = gettimeofday() ; $mktime = (int)$mkarr['usec']; if( $mktime < 10 ){ $mktime = '00000'.$mktime; }elseif( $mktime < 100 ){ $mktime = '0000'.$mktime; }elseif( $mktime < 1000 ){ $mktime = '000'.$mktime; }elseif( $mktime < 10000 ){ $mktime = '00'.$mktime; }elseif( $mktime < 100000 ){ $mktime = '0'.$mktime; } return date('d-m-Y H:i:s', (int)$mkarr['sec'] ).'.'.$mktime; } //______________________________________________________________________________ function _dLog( $message, $place='' ){ $place = '*** '.$place.' ***'; $message = "\n\n"._DgetDateTime().' *** '.$_SERVER['DOCUMENT_ROOT'].' '.$place."\n". "------------------------------------------------------------------------\n".$message; $fhandle = fopen( 'logs/debug.log', 'a' ); fwrite( $fhandle, $message ); fclose( $fhandle); } function _objP( $obj ){ $o_vars = get_object_vars($obj); $v_names = array(); foreach ($o_vars as $name => $value) { $v_names[] = $name; } return $v_names; } <file_sep>ALTER TABLE notificaties ADD COLUMN is_opdracht INT DEFAULT 0; ALTER TABLE notificaties ADD COLUMN vraag_id INT DEFAULT NULL;<file_sep><?php require_once( APPPATH . '/libraries/marap/base.php' ); class CI_Marap { private $_CI; private $_progress; public function __construct() { $this->_CI = get_instance(); $this->_progress = new ExportProgress( 'marap' ); } public function export( $doc_type, $tag, GrafiekPeriode $periode, array $checklistgroepen, array $checklisten, array $grafiek_types, $theme='', $postcode=null ) { // see if template exists $path = APPPATH . '/libraries/marap/' . $doc_type . '.php'; if (!is_file( $path )) throw new Exception( 'Ongeldige template naam: ' . $doc_type ); require_once( $path ); // see if class exists $classname = 'Marap' . $doc_type; if (!class_exists( $classname )) throw new Exception( 'Ongeldig geimplementeerde template: ' . $doc_type ); $exporter = new $classname( $tag, $periode, $checklistgroepen, $checklisten, $grafiek_types, $theme,$postcode); if (!($exporter instanceof MarapBase)) throw new Exception( 'Ongeldig geconfigureerde template: ' . $doc_type ); // go! return $exporter->generate(); } public function set_progress( $download_tag, $progress /* tussen 0 en 1 */, $action_description ) { $this->_progress->set_progress( $download_tag, $progress, $action_description ); } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer_gebruiker_beheer')); ?> <? if ($gebruiker->is_super_admin()): ?> <div style="position: relative;"> <div style="position: absolute; width: 10px; height: 10px; background-color: <?=$are_special_fields_visible?'#fbb':'#eee'?>; padding: 0; border: 0; top: -15px; right: 10px; z-index: 10; cursor: pointer; " onclick="location.href='<?=site_url('/admin/backlog_toggle_special_fields')?>';"> </div> </div> <? endif; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => tg('backlog'), 'expanded' => true, 'width' => '100%', 'height' => 'auto', 'defunct' => true ) ); ?> <div style="padding: 10px; border: 1px solid #777; height: auto; margin-bottom: 10px;"> <span style="font-weight: bold; padding-right: 30px;">LEGENDA:</span> <span style="color:#f00">Bugs</span> | <span style="color:#000">Concrete opdrachten</span> | <span style="color:#080">Wensen / suggesties / idee&euml;n / nog niet uitgewerkt</span> </div> <? $col_widths = array( 'id' => 40, 'gebruiker_id' => 110, 'verbeterpunt' => 120, 'actie' => ($gebruiker->is_super_admin() && $are_special_fields_visible) ? 280 : 380, 'prioriteit' => 70, // was 100 'ureninschatting' => 70, // was 120 'status' => 150, 'afgerond' => 40, 'actie_voor' => 70, 'uploads' => 70, ); $col_description = array( 'id' => '#', 'gebruiker_id' => tgg('backlog.gebruiker_id'), 'verbeterpunt' => tgg('backlog.verbeterpunt'), 'actie' => tgg('backlog.actie'), 'prioriteit' => tgg('backlog.prioriteit'), 'ureninschatting' => tgg('backlog.ureninschatting'), 'status' => tgg('backlog.status'), 'afgerond' => tgg('backlog.afgerond'), 'actie_voor' => tgg('backlog.actie_voor'), 'uploads' => tgg('backlog.uploads'), ); if (get_instance()->is_Mobile) { $col_widths['actie'] = ($gebruiker->is_super_admin() && $are_special_fields_visible) ? 200 : 300; $col_widths['status'] = 100; unset( $col_widths['gebruiker_id'] ); unset( $col_description['gebruiker_id'] ); } if ($gebruiker->is_super_admin() && $are_special_fields_visible) { $uw = array_pop( $col_widths ); $ud = array_pop( $col_description ); $col_widths['programmeur'] = 100; $col_description['programmeur'] = tgg('backlog.programmeur'); $col_widths['uploads'] = $uw; $col_description['uploads'] = $ud; } $col_unsortable = array( 'opties' ); $rows = array(); foreach ($data as $i => $bl) { if (preg_match( '/bug/i', $bl->verbeterpunt )) $color = '#f00'; else if ($bl->is_wens) $color = '#080'; else $color = '#000'; $row = (object)array(); $row->onclick = "location.href='" . site_url('/admin/backlog_edit/' . $bl->id) . "'"; $row->data = array(); $row->data['id'] = $bl->id; if (!get_instance()->is_Mobile) $row->data['gebruiker_id'] = $bl->gebruiker_id ? $this->gebruiker->get($bl->gebruiker_id)->volledige_naam : '-'; $row->data['verbeterpunt'] = htmlentities( $bl->verbeterpunt, ENT_COMPAT, 'UTF-8' ); $row->data['actie'] = htmlentities( $bl->actie, ENT_COMPAT, 'UTF-8' ); $row->data['prioriteit'] = htmlentities( $bl->prioriteit, ENT_COMPAT, 'UTF-8' ); $row->data['ureninschatting'] = htmlentities( $bl->ureninschatting, ENT_COMPAT, 'UTF-8' ); $row->data['status'] = htmlentities( $bl->status, ENT_COMPAT, 'UTF-8' ); $row->data['afgerond'] = $bl->afgerond ? 'ja' : 'nee'; $row->data['actie_voor'] = $bl->actie_voor_gebruiker_id ? $gebruikers[$bl->actie_voor_gebruiker_id] : ''; if ($gebruiker->is_super_admin() && $are_special_fields_visible) { $row->data['programmeur'] = htmlentities( $bl->programmeur, ENT_COMPAT, 'UTF-8' ); $row->data['prioriteit'] .= '/' . htmlentities( $bl->prio_nr_imotep, ENT_COMPAT, 'UTF-8' ) . '/' . htmlentities( $bl->prio_nr_bris, ENT_COMPAT, 'UTF-8' ); $row->data['ureninschatting'] .= '/' . htmlentities( $bl->ureninschatting_intern, ENT_COMPAT, 'UTF-8' ); } $row->data['uploads'] = '<a href="javascript:void(0);" onclick="location.href=\'' . site_url('/admin/backlog_uploads/' . $bl->id ) . '\'; eventStopPropagation(event); ">' . '<nobr><img src="/files/images/magnifier.png"> ' . (intval(@$backloguploads[$bl->id])) . (get_instance()->is_Mobile ? '' : ' uploads') . '</nobr>' . '</a>'; foreach ($row->data as $k => $v) $row->data[$k] = '<span style="color:' . $color . '">' . $v . '</span>'; $rows[] = $row; } $this->load->view( 'elements/laf-blocks/generic-searchable-list', array( 'col_widths' => $col_widths, 'col_description' => $col_description, 'col_unsortable' => $col_unsortable, 'rows' => $rows, 'config' => array( 'mode' => $viewdata['mode'], 'wens' => $viewdata['wens'], 'alleen_mijn' => $viewdata['alleen_mijn'], ), 'new_button_js' => 'location.href=\'/admin/backlog_nieuw\';', 'url' => '/admin/backlog', 'scale_field' => 'uploads', 'do_paging' => false, 'header' => ' <input type="radio" ' . ($viewdata['mode']=='actief' ? 'checked' : '') . ' name="filter" value="actief" /> ' . tg('toon_actieve_backlog') . ' <input type="radio" ' . ($viewdata['mode']=='alle' ? 'checked' : '') . ' name="filter" value="alle" /> ' . tg('toon_alle_backlog') . ' <span style="padding:0px 10px 0px 20px;">|</span> <input type="radio" ' . ($viewdata['wens']=='alle' ? 'checked' : '') . ' name="wens" value="alle" /> ' . tg('toon_wens_alle') . ' <input type="radio" ' . ($viewdata['wens']=='alleen-opdrachten' ? 'checked' : '') . ' name="wens" value="alleen-opdrachten" /> ' . tg('toon_wens_nee') . ' <input type="radio" ' . ($viewdata['wens']=='alleen-wensen' ? 'checked' : '') . ' name="wens" value="alleen-wensen" /> ' . tg('toon_wens_ja') . ' <span style="padding:0px 10px 0px 20px;">|</span> <input type="radio" ' . ($viewdata['alleen_mijn']=='nee' ? 'checked' : '') . ' name="alleen_mijn" value="nee" /> ' . tg('toon_alleen_mijn_nee') . ' <input type="radio" ' . ($viewdata['alleen_mijn']=='ja' ? 'checked' : '') . ' name="alleen_mijn" value="ja" /> ' . tg('toon_alleen_mijn_ja') . ' ', ) ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end', array( 'height' => 'auto' ) ); ?> <p style="font-style:italic; color: #777;"> <?=sizeof($data)?> backlog item(s) getoond. </p> <script type="text/javascript"> $(document).ready(function(){ // handle backlog filter by active state $('input[type=radio][name=filter]').click(function(){ var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'mode', this.value ); }); // handle backlog filter by "wens" state $('input[type=radio][name=wens]').click(function(){ var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'wens', this.value ); }); // handle backlog filter by "alleen_mijn" state $('input[type=radio][name=alleen_mijn]').click(function(){ var listDiv = BRISToezicht.SearchableList.getListDiv( this ); if (listDiv) BRISToezicht.SearchableList.updateCurrentConfig( listDiv, 'alleen_mijn', this.value ); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php class MarapStandaard extends MarapPDFBase { const FONTNAME = 'dejavusans'; const FONTSIZE = 9; const FONTHEADERSIZE = 12; public function get_tcpdf_classname() { return 'MarapStandaardTCPDF'; } public function get_leaseconfiguratie(){ return $this->_CI->gebruiker->get_logged_in_gebruiker()->get_klant()->get_lease_configuratie(); } public function get_klant_name(){ if(isset($this->get_leaseconfiguratie()->pagina_titel)){ $name=$this->get_leaseconfiguratie()->pagina_titel; } else { $name="BRIStoezicht"; } return $name; } protected function _generate() { // make sure our own custom TCPDF object knows what klant we're dealing with, // and get a reference to ourself, for page headers with logo's and stuff :) $this->_tcpdf->set_references( $this ); // set creator, author, etc. $this->_initialize_meta_data(); // generate content $this->_generate_front_page(); $this->_generate_disclaimer_page(); $this->_generate_grafieken_pages(); // generate TOC $this->_generate_toc(); } private function _initialize_meta_data() { $this->_tcpdf->SetCreator($this->get_klant_name()); $this->_tcpdf->SetAuthor($this->get_klant_name()); $this->_tcpdf->SetTitle('Management Rapportage ' . $this->get_periode()->get_human_description()); $this->_tcpdf->SetSubject('Management Rapportage'); $this->_tcpdf->SetKeywords($this->get_klant_name()); // some defaults $this->_tcpdf->SetImageScale(PDF_IMAGE_SCALE_RATIO); $this->_tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $this->_tcpdf->SetFontSubsetting( false ); } private function _generate_front_page() { $this->_tcpdf->SetPrintHeader( false ); $this->_tcpdf->SetPrintFooter( false ); $this->_tcpdf->AddPage(); // BRIStoezicht logo at top right //$logofile = APPPATH . 'files/images/lease/'.$this->get_leaseconfiguratie()->naam.'.png'; //$logofile = "/files/images/lease/background_".$this->get_leaseconfiguratie()->naam.".png)"; //$this->_tcpdf->Image( $logofile, 156, 3, 50, null, 'PNG', 'https://bristoezicht.nl', 'T', true ); // Rapportage tekst $this->_tcpdf->SetFont( self::FONTNAME, 'B', 32 ); $this->_tcpdf->SetXY( 0, 100 ); $this->_tcpdf->WriteHTML( '<span style="text-align:center">Management Rapportage</span>' ); // Klant logo $klant = $this->get_klant(); if ($klant->logo) { $imgfilename = $this->make_temp_image( $klant->logo ); $this->_tcpdf->WriteHTML( '<span style="text-align:center"><img src="' . $imgfilename . '" width="400" /></span>' ); } // Info on frontpage left bottom $this->_tcpdf->SetY( 240 ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->WriteHTML( '<br/>' . 'Periode: ' . $this->get_periode()->get_human_description() . '<br/>' . 'Scopes: ' . implode( ', ', array_map( function( $a ) { return $a->naam; }, $this->get_checklistgroepen() ) ) . '<br/>' . 'Datum: ' . date( 'd-m-Y' ) . '<br/>', true, false, true ); $this->_tcpdf->EndPage(); } private function _generate_disclaimer_page() { // output page headers and page footers from now on $this->_tcpdf->SetPrintHeader(true); $this->_tcpdf->SetPrintFooter(true); $this->_tcpdf->SetMargins(10, 30, 10); $this->_tcpdf->SetAutoPageBreak( TRUE, PDF_MARGIN_BOTTOM ); // add new page! $this->_tcpdf->AddPage(); // add text! $this->_tcpdf->WriteHTML( '<b>Disclaimer</b><br/>' . '<span style="text-align:justify">Deze rapportage is automatisch gegenereerd door '.$this->get_klant_name().'. '. ''.$this->get_klant_name().' ondersteunt en bevordert professioneel toezicht. '. 'Het systeem treedt in geen geval in de plaats van de deskundigheid van een toezichthouder. '. ''.$this->get_klant_name().' is met de grootste zorg samengesteld. '. 'BRIS bv aanvaardt echter geen enkele aansprakelijkheid voor schade die het gevolg is van onjuistheid of onvolledigheid (in de meest ruime zin des woords) van deze applicatie en de gegenereerde rapportages.</span>', true, false, true ); // end page! $this->_tcpdf->EndPage(); } private function _generate_grafieken_pages() { // genereer grafieken $thiz = $this; // The graph height used to be set to 350 pixels, but at least one client (<NAME>) ran into trouble there, as several graphs had chopped off legends, making the graphs // of little value. A graph height of minimally 800 pixels is required to properly handle the seen graphs where this issue occurred. At a height of 800 pixels, the // auto-spacing already puts precisely 1 graph per page in the PDF, so instead of sticking with 800 pixels, we use the maximum height that we can get away with before the // PDF starts showing empty pages after each graph. This maximum seems to lie around 1000 pixels. //$afmeting = new GrafiekAfmeting( 900, 350 ); //$afmeting = new GrafiekAfmeting( 900, 800 ); $afmeting = new GrafiekAfmeting( 900, 800 ); $grafieken = $this->_CI->grafiek->maak_grafieken( $this->get_periode(), $afmeting, $this->get_checklistgroepen(), $this->get_checklisten(), $this->get_grafiek_types(), $this->get_theme(), function( $grafiek, $i, $total ) use ($thiz) { $thiz->set_progress( $i / ($total + 2), 'Grafiek: ' . $grafiek->get_groeptitle() ); },$this->get_postcode() ); $c = sizeof($this->get_grafiek_types()); $thiz->set_progress( ($c + 1) / ($c + 2), 'Exporteren naar PDF' ); // output grafieken $cur_categorie = null; $groeptag = null; $no_new_page = false; foreach ($grafieken as $grafiek) { if ($cur_categorie != $grafiek['categorie']) { $cur_categorie = $grafiek['categorie']; if ($cur_categorie) $this->_tcpdf->EndPage(); $this->_tcpdf->AddPage(); $this->_output_header1( $cur_categorie ); $no_new_page = true; } if ($grafiek['groep'] && $grafiek['groeptag'] != $groeptag) { if (!$no_new_page) { $this->_tcpdf->EndPage(); $this->_tcpdf->AddPage(); } else $no_new_page = false; $groeptag = $grafiek['groeptag']; $this->_output_header2( $grafiek['title'], false,$grafiek['description'] ); } if (!$grafiek['groep']) { if (!$no_new_page) { $this->_tcpdf->EndPage(); $this->_tcpdf->AddPage(); } else $no_new_page = false; $this->_output_header2( $grafiek['title'], false, $grafiek['description'] ); } // make tempimage for Grafiek, so it gets automatically cleaned up $this->_tcpdf->WriteHTML( '<span style="text-align:left"><img src="' . $this->make_temp_image( APPPATH . '/../' . $grafiek['filename'] ) . '" width="900" /></span>' ); } if ($cur_categorie) $this->_tcpdf->EndPage(); } private function _generate_toc() { $this->_tcpdf->addTOCPage(); // write the TOC title $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTHEADERSIZE ); $this->_tcpdf->MultiCell(0, 0, 'Inhoudsopgave', 0, 'C', 0, 1, '', '', true, 0); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->_tcpdf->Ln(); // add TOC $this->_tcpdf->addTOC( 3, self::FONTNAME, '.', 'Inhoudsopgave', 'B', array(0,0,0)); // end of TOC page $this->_tcpdf->endTOCPage(); } private function _output_header1( $text, $top_of_page=true ) { $this->_output_header( $text, 0, $top_of_page, self::FONTHEADERSIZE ); } private function _output_header2( $text, $top_of_page=true, $description=null ) { $this->_output_header( $text, 1, $top_of_page, self::FONTHEADERSIZE-1,$description ); } private function _output_header3( $text, $top_of_page=true ) { $this->_output_header( $text, 2, $top_of_page, self::FONTHEADERSIZE-2 ); } private function _output_subheader( $text ) { // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', self::FONTSIZE+1 ); $this->_tcpdf->SetTextColor( 0, 0, 0 ); $this->_tcpdf->WriteHTML( $this->hss( $text ), true, false, true ); $this->_tcpdf->SetFont( self::FONTNAME, '', self::FONTSIZE ); } private function _output_header( $text, $level, $top_of_page, $fontsize, $description=null) { // set font & color, and output text $this->_tcpdf->SetFont( self::FONTNAME, 'B', $fontsize ); $this->_tcpdf->SetTextColor( 0, 204, 171 ); // #00ccab $this->_tcpdf->WriteHTML( $this->hss( $text), true, false, true ); // reset color to black $this->_tcpdf->SetTextColor( 0, 0, 0 ); $this->_tcpdf->WriteHTML( $this->hss( $description ), true, false, true ); $this->_tcpdf->Bookmark( $text, $level, $top_of_page ? 0 : -1 ); // additional empty line $this->_tcpdf->Ln(); } } class MarapStandaardTCPDF extends TCPDF { const FONTNAME = MarapStandaard::FONTNAME; const FONTSIZE = MarapStandaard::FONTSIZE; private $_export; public function set_references( MarapBase $export ) { $this->_export = $export; } public function Header() { $this->SetFont( self::FONTNAME, '', self::FONTSIZE ); $klant = $this->_export->get_klant(); /* if (isset($klant->logo_klein)) { $imgfilename = $this->_export->make_temp_image( $klant->logo_klein ); $this->Image( $imgfilename, 5, 5, null, null, null, null, 'B', true ); } */ $this->SetY( 15 ); $this->Cell( 0, 7, $klant->naam, '', 2, 'R', false ); $this->SetPageMark(); } public function Footer() { $this->SetFont( self::FONTNAME, '', self::FONTSIZE ); $this->SetY( -15 ); $this->Cell( 0, 7, 'Pagina '.$this->getAliasNumPage().' van '.$this->getAliasNbPages(), '', 2, 'C', false ); $this->SetY( -15 ); $this->Cell( 0, 7, 'Periode: ' . $this->_export->get_periode()->get_human_description(), '', 2, 'R', false ); } } <file_sep><? require_once 'base.php'; class WebserviceComponentResult extends BaseResult { function WebserviceComponentResult( &$arr ) { parent::BaseResult( 'webservicecomponent', $arr ); } } class WebserviceComponent extends BaseModel { function WebserviceComponent() { parent::BaseModel( 'WebserviceComponentResult', 'webservice_components', true ); } public function check_access( BaseResult $object ) { // disabled for model } } <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | */ #$config['base_url'] = "http://dev.bristoezicht.mobieltoezicht.nl/"; $config['base_url'] = "http://btz.localhost/"; $config['development_version'] = true; $config['is_ut_defined'] = true; // DEVELOPMENT values $config['ws_url_wsdl_brimo_soapdocument'] = 'http://brimo.localhost/soapdocument/wsdl'; $config['ws_url_wsdl_mtmi_soapdossier'] = 'http://btz.localhost/soapdossier/wsdl'; $config['ws_url_wsdl_bt_soapdossier'] = 'https://ota.bristoets.nl/soapdossier?wsdl'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ""; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of "AUTO" works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = IS_CLI ? "REQUEST_URI" : "REQUEST_URI"; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ""; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = "english"; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = "UTF-8"; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the "hooks" feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = TRUE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = ''; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string "words" that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['enable_query_strings'] = FALSE; $config['directory_trigger'] = 'd'; // experimental not currently in use $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class or the Sessions class with encryption | enabled you MUST set an encryption key. See the user guide for info. | */ $config['encryption_key'] = ""; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'session_cookie_name' = the name you want for the cookie | 'encrypt_sess_cookie' = TRUE/FALSE (boolean). Whether to encrypt the cookie | 'session_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 0; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | */ $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/"; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = TRUE; /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not "echo" any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are "local" or "gmt". This pref tells the system whether to use | your server's local time as the master "now" reference, or convert it to | GMT. See the "date helper" page of the user guide for information | regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = TRUE; /* |-------------------------------------------------------------------------- | Security config |-------------------------------------------------------------------------- */ require_once(dirname(__FILE__) . '/security.php'); /* |-------------------------------------------------------------------------- | Logo |-------------------------------------------------------------------------- */ $config['logo_width'] = 800; $config['logo_height'] = 500; $config['logo_display_width'] = 100; $config['logo_display_height'] = 62; /* |-------------------------------------------------------------------------- | (Remote) Document generation |-------------------------------------------------------------------------- */ $config['rapportage_formats'] = array( 'pdf' => array( 'Portable Document Format (PDF)', true ), 'doc' => array( 'Microsoft Word (DOC)', 'heeft_word_export_licentie' ), ); $config['rapportage_fabid'] = array( '192.168.240.99',7778 ); $config['rapportage_fabid_enabled'] = false; $config['rapportage_abicollab_soap_enabled'] = false; // doesn't work ATM (images), although it's faster than fabid! $config['libre_office_executable'] = 'C:/Program Files (x86)/LibreOffice 4/program/soffice.exe'; // Live value /* |-------------------------------------------------------------------------- | eBB config |-------------------------------------------------------------------------- */ $config['rapporten_per_pagina'] = 10; $config['toon_bouwbesluit'] = false; $config['toon_handleidingen'] = false; $config['toon_beheer_financien'] = false; $config['toon_beheer_resellers'] = false; $config['functies_snelkeuzes_toestaan'] = false; $config['functies_smartfunctie_toestaan'] = true; require_once( dirname(__FILE__) . '/version.php' ); $config['application_version'] = BRIS_TOEZICHT_VERSION; /* |-------------------------------------------------------------------------- | PDF annotator config |-------------------------------------------------------------------------- */ $config['pdf_annotator_import_url'] = 'http://pdfeditor.foddex.net/import.php'; $config['pdf_annotator_convert_url'] = 'http://pdfeditor.foddex.net/convert.php'; $config['pdf_annotator_cleanup_url'] = 'http://pdfeditor.foddex.net/delete.php'; $config['pdf_annotator_image_base_url'] = 'http://pdfeditor.foddex.net'; $config['filelock_path'] = dirname(__FILE__) . '/'; /* |-------------------------------------------------------------------------- | Mail config |-------------------------------------------------------------------------- */ $config['mail_sender'] = '<EMAIL>'; /* |-------------------------------------------------------------------------- | KennisID config |-------------------------------------------------------------------------- */ $config['kennisid_maak_klanten'] = true; $config['kennisid_cache_dir'] = '/tmp'; $config['kennisid_cache_time'] = 86400*30 /* 30 dagen */; $config['application_name'] = 'bris'; // This line set only in my local environment require_once( dirname(__FILE__) . '/debug_utils.php' ); <file_sep><?php get_instance()->load->helper( 'export' ); require_once APPPATH . 'libraries/Exportexcel.php'; class CI_DossierOverzicht { protected $_CI; private $_progress; private $_download_tag; private $item_count; private $item_number; private $klant; private $content; private $filename; private $content_type; private $documents = Array(); private $sections = Array(); private $tables = Array(); private $columns = 0; private $rows = Array(); private $cells = Array(); private $fields = Array(); public function __construct() { $this->_CI = get_instance(); $this->_progress = new ExportProgress( 'dossieroverzicht' ); $this->_init_progress(); } public function get_contents() { return $this->content; } public function get_filename() { return $this->filename; } public function get_contenttype() { return $this->content_type; } public function export($doc_type, $gebruiker, $download_tag) { // The 'Encoding' helper is used in the _add_section method and must therefore always be loaded, instead of conditionally // being loaded $this->_CI->load->helper( 'encoding' ); $this->_gebruiker = $gebruiker; $this->klant = $gebruiker->get_klant(); $this->_download_tag = $download_tag; $this->_progress = new ExportProgress( 'dossieroverzicht' ); switch($doc_type) { case 'xlsx': $this->_set_progress("initialiseren"); $this->_generate_excel(); $this->_CI->load->library( 'exportexcel' ); $this->_set_progress("Gegevens verzameld, document wordt aangemaakt"); // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit(3600); $this->_CI->exportexcel->_generate ($this->documents); $document_content = $this->_CI->exportexcel->get_excel_content(); $this->content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'; break; } if ($document_content) { $this->content = $document_content; $this->filename = sprintf( '(%s) %s.'.$doc_type, date('d-m-Y'), preg_replace( '/\W/', '-', 'Dossieroverzicht_'.$this->klant->naam)); $this->_set_progress("dossier gegenereerd"); } else { $this->_set_progress("Er is een fout opgetreden"); } } private function _generate_excel() { $den_haag = $this->klant->id == '131'; $this->_set_progress("lopende dossiers ophalen"); $actieve_dossiers = $this->klant->get_dossieroverzicht ('0'); if ($den_haag) { $this->fields = $this->klant->get_dossieroverzicht_velden(); $header_array = preg_grep("/#/i", $this->fields, PREG_GREP_INVERT); } else { $this->fields = preg_grep("/DH_/i", $this->klant->get_dossieroverzicht_velden(), PREG_GREP_INVERT); $header_array = preg_grep("/#/i", $this->fields, PREG_GREP_INVERT); } $this->columns = count($header_array); // First sheet $this->_add_headerrow ($header_array); $this->_process_fields ($actieve_dossiers); // Add table to section $section_header = $this->_create_section_header(1, 'Werkvoorraad'); $this->_add_section ('text', $this->tables, $section_header); // Second sheet $this->_set_progress("gearchiveerde dossiers ophalen"); $gearchiveerde_dossiers = $this->klant->get_dossieroverzicht('1'); if ($den_haag) { $this->fields = $this->klant->get_dossieroverzicht_velden(); $header_array = preg_grep("/#/i", $this->fields, PREG_GREP_INVERT); } else { $this->fields = preg_grep("/DH_/i", $this->klant->get_dossieroverzicht_velden(), PREG_GREP_INVERT); $header_array = preg_grep("/#/i", $this->fields, PREG_GREP_INVERT); } $this->columns = count($header_array); $this->_add_headerrow ($header_array); $this->_process_fields ($gearchiveerde_dossiers); // Add table to section $section_header = $this->_create_section_header(1, 'Gearchiveerde dossiers'); $this->_add_section ('text', $this->tables, $section_header); // Add sections to document $this->_add_document ('xlsx', $this->sections, "Dossieroverzicht ".$this->klant->naam); } // private function _generate_excel() private function _process_fields($dossiers) { $den_haag = $this->klant->id == '131'; if ($dossiers) { //create dossieroverzicht rows foreach ($dossiers as $dossier) { foreach ($this->fields as $field) { $value = $content_type = ''; // reset value and content_type to prevent duplicates if ($den_haag && $field == '#dossier_opmerkingen') { $this->_split_opmerkingen ($dossier, $dossier[$field]); } else { if ($dossier[$field]) { $value = $dossier[$field]; } else { $value = ''; } } // Check content type $content_type = $this->_get_cell_contenttype($field, $value); // Don't add hidden fields if (substr($field, 0,1) !='#') { $this->_add_cell ($value, $content_type); } } $this->_add_row ($this->cells); } // Add rows to table $this->_add_table ($this->rows, $this->columns); } } // Determine the appropriate content_type for the specified cell private function _get_cell_contenttype ($field, &$value) { if ((bool)strtotime($value)) { return 'date'; } else { switch ($field) { case 'Status Scope': $value = number_format((float)$value, 2)/100; return 'percentage'; break; case 'DH_Grondslag': if (!is_numeric($value)) { $value = implode('',explode('.',$value)); $value = implode('.',explode(',',$value)); } return 'currency'; break; default: return 'string'; } } } // Get Den Haag specific fields private function _split_opmerkingen (&$dossier, $opmerkingen) { // Based on example: // Overige vergunningen BAG id: 518200000651032, X: 87978,119, Y: 453443,525, // Beschikking: Verlenen standaard (ev), Grondslag: 12.100,00 $regular_expressions = array ( 'DH_Grondslag' => '/(?:grondslag:)(?:\s?)(?!0)((?:\d{1,3}(?:\.\d{3}){0,}|(?:\d+))(?:\,\d\d)?)(?:\,|$)/i', 'DH_Beschikking' => '/(?:beschikking:)(?:\s?)([a-zA-Z].+)(?:\,|$)/iU', 'DH_BAG id' => '/(?:bag id:)(?:\s?)(\d+)(?:\,|$)/iU' ); foreach ($regular_expressions as $field=>$reg_exp) { preg_match($reg_exp, $opmerkingen, $match); if ($match) { $dossier[$field] = $match[1]; } } } // Helper function to create a section header. private function _create_section_header($level =1, $text = '', $style = '') { $section_header = array(); $section_header['text'] = $text; // The actual text // The following properties are currently not used, but are required to make a succesfull soal call. $section_header['level'] = $level; // (numeric header level, 1, 2, etc.) $section_header['style'] = $style; // 'auto'|<overriding type - string> ('auto' = use templates heading styles) return $section_header; } private function _add_document($type, $sections = array(), $title = '') { $document= array(); $document['type'] = $type; // 'DOCX'|'PDF'|'XLSX' $document['sections'] = $sections; // the sections to be used in this document $document['title'] = $title; // title (optional) // The following properties are currently not used, but are required to make a succesfull soal call. $document['template'] = ''; // template name (optional) $document['pageheaders'] = array(); // content for the page headers on 'all', 'odd', 'even' and/or 'first' pages $document['pagefooters'] = array(); // content for the page footers on 'all', 'odd', 'even' and/or 'first' pages $document['images'] = array(); // <array([Image type])> (use something like 'cid' references in the HTML content to include them) $this->documents[] = $document; // Empty sections array $this->sections = array(); } // Helper function to add a section to a passed set of sections. // Note: this method directly adds the passed section to the globally registered (total) set of sections, as we presently do not allow sections to be nested. private function _add_section($content_type = 'text', $tables = array(), $section_header = '') { // [Section type] $section = array(); $section['content_type'] = $content_type; // 'text'|'html' $section['tables'] = $tables; // <array([Table type]) $section['section_header'] = $section_header; // [SectionHeader type] // The following properties are currently not used, but are required to make a succesfull soal call. $section['content'] = ''; // (text or HTML) $section['section_type'] = 'normal'; // 'normal'|'TOC'|'front'|'summary' $section['size'] = 'A4'; // 'A4', 'A3', 'letter', 'legal' $section['orientation'] = 'landscape'; // 'portrait'|'landscape', $section['page_break'] = 'none'; // 'none'|'after'|'before' $section['perform_cleanup']= 'true'; // 'true' = perform clean-up actions (like 'HTML Tidy', etc.), 'false' = use the content "as-is". Aim for using 'false' as much as possible. $section['use_word_styles'] = 'true'; // 'true' = use the mapping to 'true Word styles' as defined in the template, 'false' = ignore assigned word styles. Aim for using 'true' as much as possible. $section['ignore_css'] = 'false'; // 'true' = ignore applied css $section['images'] = array(); // <array([Image type])> (use something like 'cid' references in the HTML content to include them) $this->sections[] = $section; // Empty table and section_header array $this->tables = array(); } // Helper function to add a table to a passed set of tables. private function _add_table($content_rows = array(), $table_columns = 'auto', $table_headers = '') { $table = array(); $table['columns'] = $table_columns; // 'auto'|<number> ('auto' = iterate per row. This means its much slower!) $table['content_rows'] = $content_rows; //<array([Row type]) $table['headers'] = $table_headers; // Headers to put above the tables // The following properties are currently not used, but are required to make a succesfull soal call. $table['content_type'] = ''; // 'mixed'|'html' ('mixed' = not just one large HTML fragment, but a fully broken down structure) $table['content_html'] = ''; // (<html fragment, being the full table, if the content_type is set to 'html')> $this->tables[] = $table; // Empty rows array $this->rows = array(); } // Helper function to add a row to a passed set of rows. public function _add_row($cells = array()) { $row = array(); $row['columns'] = 'auto'; // 'auto'|<number> ('auto' = use the amount of colums present in the row) $row['content_cells'] = $cells; // <array([Cell type]) $this->rows[] = $row; // Empty cells array $this->cells = array(); } // Helper function to add a cell to a passed set of cells. private function _add_cell($content = '', $content_type = 'string', $col_spans = 0, $row_spans =0, $width ='auto', $height ='auto', $horizontal_align ='left', $vertical_align = 'top') { $cell = array(); //make sure we have UTF-8 encoded content $content = Encoding::toUTF8($content); $cell['content'] = $content; // cell content $cell['content_type'] = $content_type; // 'string' (default), 'date', 'currency', 'percentage') $cell['col_spans'] = $col_spans; // 0 or 1 means "no colspans", higher numbers will span precisely that amount of columns $cell['row_spans'] = $row_spans; // 0 or 1 means "no rowspans", higher numbers will span precisely that amount of rows $cell['width'] = $width; // 'auto'|<number> $cell['height'] = $height; // 'auto'|<number> $cell['horizontal_align'] = $horizontal_align; // 'left'|'center'|'right' $cell['vertical_align'] = $vertical_align; // 'top'|'center'|'bottom' // The following properties are currently not used, but are required to make a succesfull soal call. $cell['images'] = array(); // (use something like 'cid' references in the HTML content to include them) $this->cells[] = $cell; } private function _add_headerrow ($header_array) { foreach ($header_array as $field) { if (substr($field, 0, 3) == 'DH_') { $this->_add_cell (substr($field, 3)); } else { $this->_add_cell ($field); } } $this->_add_row ($this->cells); } private function _init_progress() { foreach (array("initialiseren", "document aanmaken", "lopende dossiers ophalen", "gearchiveerde dossiers ophalen","document gegenereerd") as $onderdeel) { $this->item_count++; } } private function _set_progress( $action_description ) { $this->item_number++; $progress_num = min( 1, $this->item_count ? $this->item_number / $this->item_count : 0 ); $this->_progress->set_progress( $this->_download_tag, $progress_num, $action_description ); if ($progress_num == 1) { $this->_progress->clear_progress($download_tag); } } } <file_sep>BRISToezicht.Telefoon = { // constants PAGE_NONE : -1, PAGE_DOSSIERS : 0, PAGE_DEELPLANNEN : 1, PAGE_OPDRACHTEN : 2, PAGE_TOEZICHT : 3, PAGE_AFSLUITEN : 4, // initial command initial_command: null, // slider state & config pageDivs: [], currentDiv: null, currentDivIndex: -1, slideTime: 500, // lower is faster // bottombar config bottomBar: null, prevButton: null, exitButton: null, nextButton: null, // dossier & deelplan selection state currentDossierId: null, currentDeelplanId: null, currentOpdrachtId: null, // image viewer imageviewer: null, initialize: function() { // load page divs this.pageDivs = [ $('#TelefoonPaginaDossiers'), $('#TelefoonPaginaDeelplannen'), $('#TelefoonPaginaOpdrachten'), $('#TelefoonPaginaToezicht'), $('#TelefoonPaginaAfsluiten') ]; this.bottomBar = $('#telefoon .bottombar'); this.prevButton = $('#telefoon .bottombar .prev'); this.exitButton = $('#telefoon .bottombar .exit'); this.nextButton = $('#telefoon .bottombar .next'); this.imageviewer = $('#imageviewer'); // handle initial command if (this.initial_command && this.initial_command.length) { if (this.initial_command.match( /^deelplan=(\d+)\,(\d+)/ )) { var dossier_id = RegExp.$1; var deelplan_id = RegExp.$2; this.selectDossier( dossier_id ); this.selectDeelplan( deelplan_id ); this.jumpToPage( this.PAGE_OPDRACHTEN ); } } // show first page if nothing is visible if (this.currentDivIndex == -1) this.jumpToPage( this.PAGE_DOSSIERS ); }, jumpToPage: function( index, params ) { // handle params if (params != undefined) { switch (index) { case this.PAGE_DEELPLANNEN: this.selectDossier( params ); break; case this.PAGE_OPDRACHTEN: this.selectDeelplan( params ); break; case this.PAGE_TOEZICHT: this.selectOpdracht( params ); break; } } // reselect current? then do nothing if (index == this.currentDivIndex) return; // do we have a current DIV visible? if (this.currentDiv) { // slight old panel from 0 to -width (i.e. slide left) var hideDiv = this.currentDiv; if (index > this.currentDivIndex) { this.currentDiv.animate({left:-this.currentDiv.width()}, this.slideTime, function(){ hideDiv.hide(); }); } // slight old panel from 0 to width (i.e. slide right) else { this.currentDiv.animate({left:this.currentDiv.width()}, this.slideTime, function(){ hideDiv.hide(); }); } } // set the new one visible var newDiv = this.pageDivs[index]; if (this.currentDiv) { // slight new panel from width to 0 (i.e. slide left) if (index > this.currentDivIndex) { newDiv.css({left: newDiv.width() }); newDiv.show(); newDiv.animate({left:0}, this.slideTime); } // slight new panel from -width to 0 (i.e. slide right) else { newDiv.css({left: -newDiv.width() }); newDiv.show(); newDiv.animate({left:0}, this.slideTime); } } else { // nothing visible yet, just show the current! newDiv.show(); } // update current div and index this.currentDiv = newDiv; this.currentDivIndex = index; // scroll to top of page $('html, body').animate({scrollTop:0}, 0); // auto hide-show next/prev buttons this.nextButton[ this.currentDivIndex == this.PAGE_TOEZICHT ? 'show' : 'hide' ](); this.prevButton[ this.currentDivIndex == this.PAGE_TOEZICHT ? 'show' : 'hide' ](); this.bottomBar[ this.currentDivIndex == this.PAGE_AFSLUITEN ? 'hide' : 'show' ](); // exception, call func after going to AFSLUITEN page if (index == this.PAGE_AFSLUITEN) this.afsluiten(); }, selectDossier: function( dossier_id ) { this.pageDivs[this.PAGE_DEELPLANNEN].find('[dossier_id]').hide(); this.pageDivs[this.PAGE_DEELPLANNEN].find('[dossier_id=' + dossier_id + ']').show(); this.currentDossierId = dossier_id; }, selectDeelplan: function( deelplan_id ) { this.pageDivs[this.PAGE_OPDRACHTEN].find('[deelplan_id]').hide(); this.pageDivs[this.PAGE_OPDRACHTEN].find('[deelplan_id=' + deelplan_id + ']').show(); this.currentDeelplanId = deelplan_id; }, selectOpdracht: function( opdracht_id ) { this.pageDivs[this.PAGE_TOEZICHT].find('[opdracht_id]').hide(); this.pageDivs[this.PAGE_TOEZICHT].find('[opdracht_id=' + opdracht_id + ']').show(); this.currentOpdrachtId = opdracht_id; // scroll to top of page $('html, body').animate({scrollTop:0}, 0); // update gereed/opnieuw button this.updateToezichtStatusVoorHuidigeOpdracht(); }, onNext: function() { var cur = this.pageDivs[this.PAGE_TOEZICHT].find('[opdracht_id=' + this.currentOpdrachtId + ']'); var next = cur; while ( (next = next.next()).size() ) { if (next.attr( 'deelplan_id' ) == this.currentDeelplanId) { this.selectOpdracht( next.attr( 'opdracht_id' ) ); return; } } this.selectOpdracht( this.pageDivs[this.PAGE_TOEZICHT].find('[deelplan_id=' + this.currentDeelplanId + ']:first').attr( 'opdracht_id' ) ); }, onPrevious: function() { var cur = this.pageDivs[this.PAGE_TOEZICHT].find('[opdracht_id=' + this.currentOpdrachtId + ']'); var prev = cur; while ( (prev = prev.prev()).size() ) { if (prev.attr( 'deelplan_id' ) == this.currentDeelplanId) { this.selectOpdracht( prev.attr( 'opdracht_id' ) ); return; } } this.selectOpdracht( this.pageDivs[this.PAGE_TOEZICHT].find('[deelplan_id=' + this.currentDeelplanId + ']:last').attr( 'opdracht_id' ) ); }, updateToezichtStatusVoorHuidigeOpdracht: function() { // kijk of huidige vraag gereed is var base = this.geefBaseVoorHuidigeOpdracht(); var gereed = base.find('[name^=gereed]').val() == '1'; // zet opnieuw/gereed button goed if (gereed) { $('.gereed').hide(); $('.opnieuw').show(); } else { $('.gereed').show(); $('.opnieuw').hide(); } // is dit een foto opdracht? var fotoinput = base.find('[name^=foto]'); var is_foto_opdracht = fotoinput.size() > 0; $('.header .foto')[is_foto_opdracht ? 'show' : 'hide'](); if (is_foto_opdracht) { if (!fotoinput.val() || !fotoinput.val().length) { base.find('.foto-not-yet-taken').show(); base.find('.foto-taken').hide(); } else { base.find('.foto-not-yet-taken').hide(); base.find('.foto-taken').show(); } } }, geefBaseVoorHuidigeOpdracht: function() { return $('#telefoon div[opdracht_id=' + this.currentOpdrachtId + ']'); }, opdrachtGereedZetten: function() { // kijk of we de huidige opdracht kennen var base = this.geefBaseVoorHuidigeOpdracht(); if (!base.size()) return; // is deze foto al gereed gezet? dan niks doen! if (base.find('[name^=gereed]').val() == '1') return; // is er een antwoord gezet? var status = base.find('[name^=status]').val(); var is_status_gezet = status && status.length; var foto = base.find('[name^=foto]'); var is_foto_opdracht = base.attr('is_foto_vraag') == '1'; var is_foto_gemaakt = foto.val() && foto.val().length; // we willen minstens OF een status, OF een foto if (!is_status_gezet && !is_foto_gemaakt) { showMessageBox({ message: $('[error=geen-status]').text(), type: 'warning', buttons: ['ok'], top: 50, width: 250, height: 150 }); return; } // is dit een foto opdracht? zo ja, dan MOET er een foto gemaakt worden if (is_foto_opdracht && !is_foto_gemaakt) { showMessageBox({ message: $('[error=geen-foto]').text(), type: 'warning', buttons: ['ok'], top: 50, width: 250, height: 150 }); return; } // update icon in opdrachten lijst var imgBase = $('#TelefoonPaginaOpdrachten [opdracht_id=' + this.currentOpdrachtId + ']'); imgBase.find('.opdracht-gereed').show(); imgBase.find('.opdracht-niet-gereed').hide(); // finish state base.find('[name^=status], textarea, input[type=file]') .attr('readonly','readonly') .attr('disabled','disabled'); base.find('[name^=gereed]').val('1'); this.updateToezichtStatusVoorHuidigeOpdracht(); }, opdrachtTerugZetten: function() { // kijk of we de huidige opdracht kennen var base = this.geefBaseVoorHuidigeOpdracht(); if (!base.size()) return; // update icon in opdrachten lijst var imgBase = $('#TelefoonPaginaOpdrachten [opdracht_id=' + this.currentOpdrachtId + ']'); imgBase.find('.opdracht-gereed').hide(); imgBase.find('.opdracht-niet-gereed').show(); // finish state base.find('[name^=status], textarea, input[type=file]') .removeAttr('readonly') .removeAttr('disabled') .val(''); base.find('[name^=gereed]').val('0'); this.updateToezichtStatusVoorHuidigeOpdracht(); }, displayImage: function( img ) { var origParent = img.parent(); var origWidth = img.css('width'); var origHeight = img.css('height'); var imageViewer = this.imageviewer; var bottomBar = this.bottomBar; img .detach() .appendTo( imageViewer ) .click(function(){ img .unbind( 'click' ) .detach() .appendTo( origParent ); imageViewer.hide(); bottomBar.show(); }); imageViewer.show() bottomBar.hide(); }, afsluiten: function() { // kijk of er vragen zijn die op gereed staan, zo niet, dan speciaal venster tonen var base = $('#TelefoonPaginaToezicht'); var afsluitBase = $('#TelefoonPaginaAfsluiten'); var vragen = base.find('[name^=gereed][value=1]'); if (!vragen.size()) { afsluitBase.find('.niets-te-synchroniseren').show(); return; } // haal DOM element op waarin we de voortgang gaan zetten afsluitBase.find('.klaar-om-te-synchroniseren').show(); var voortgang = afsluitBase.find('.voortgang'); var startBtn = afsluitBase.find('.start').click(function(){ // disable start button $(this).attr( 'disabled', 'disabled' ); // zet alle inputs op disabled :) dit is een "truc" die // we nodig hebben bij het 1-voor-1 uploaden van foto's (te grote // uploads gaan vaak fout via 3G): disabled components worden niet // geupload, en dus kunnen we in nextCycle simpelweg de file uploads // een voor een enablen, en klaar is kees ;) var form = base.find('form'); form.find( 'input, select, textarea' ).attr( 'disabled', 'disabled' ); // maak lijst van foto's die we moeten uploaden var fotoInputs = $(); vragen.each(function(){ var fileinput = $(this).parent().find('[name^=foto]'); if (fileinput.val()) fotoInputs = fotoInputs.add( fileinput ); }); // start de utility BRISToezicht.Telefoon.uploadUtility.initialize( voortgang, fotoInputs, form ); BRISToezicht.Telefoon.uploadUtility.nextCycle(); }); afsluitBase.find('.opnieuw').click(function(){ startBtn.removeAttr( 'disabled' ); $('#TelefoonPaginaAfsluiten .klaar-om-te-synchroniseren').show(); $('#TelefoonPaginaAfsluiten .fout-bij-synchroniseren').hide(); }); }, uploadUtility: { voortgang: null, fileinputs: null, form: null, index: 0, initialize: function( voortgang, fileinputs, form ) { this.voortgang = voortgang.show(); this.fileinputs = fileinputs; this.form = form; }, setVoortgang: function( text ) { this.voortgang.text( text ); }, nextCycle: function() { // niks meer te uploaden? dan form uploaden, laatste stap! if (this.index >= this.fileinputs.size()) { this.uploadForm(); return; } // update voortgang var fileinput = $(this.fileinputs[this.index]); this.setVoortgang( $('[progress=foto-uploaden]').text().replace( /\$1/, ''+this.index ).replace( /\$2/, ''+this.fileinputs.size() ) ); // action & target zijn nodig voor de uploader fileinput.removeAttr( 'disabled' ); this.form.attr( 'action', '/telefoon/upload' ); this.form.removeAttr( 'target' ); // start upload! var thiz = this; BRISToezicht.Upload.start( this.form[0], function( dataraw ){ try { var data = JSON.parse( dataraw ); if (data && data.success) { // file upload was succesvol! haal deze input uit de form door hem weer // op disabled te zetten fileinput.attr('disabled','disabled'); // next cycle! oftewel, ga door naar volgende file, // of upload de rest van de data BRISToezicht.Telefoon.uploadUtility.index++; BRISToezicht.Telefoon.uploadUtility.nextCycle(); } else { // stop de cycle, er is iets fout gegaan... BRISToezicht.Telefoon.uploadUtility.showError( data.error ); } } catch (e) { // stop de cycle, er is iets fout gegaan... BRISToezicht.Telefoon.uploadUtility.showError( 'De server gaf een onverwacht resultaat terug bij het uploaden van een foto: "' + e + '".' ); } }, function( result ) { // stop de cycle, er is iets fout gegaan... BRISToezicht.Telefoon.uploadUtility.showError( 'Er is fout gegaan bij het uploaden van een foto: "' + result + '".' ); }); }, uploadForm: function() { // update voortgang this.setVoortgang( $('[progress=form-uploaden]').text() ); // error handler var showError = function( details ) { $('#TelefoonPaginaAfsluiten .klaar-om-te-synchroniseren').hide(); $('#TelefoonPaginaAfsluiten .fout-bij-synchroniseren').show(); $('#TelefoonPaginaAfsluiten .fout-bij-synchroniseren .error').text( details || 'Geen nadere fout details.' ); }; // enable alle componenten! this.form.find( 'input[type!=file], select, textarea' ).removeAttr( 'disabled' ); // go! $.ajax({ url: '/telefoon/post', type: 'POST', data: this.form.serialize(), dataType: 'json', success: function( data ) { if (data && data.success) { $('#TelefoonPaginaAfsluiten .klaar-om-te-synchroniseren').hide(); $('#TelefoonPaginaAfsluiten .synchroniseren-afgerond').show(); } else { BRISToezicht.Telefoon.uploadUtility.showError( data.error ); } }, error: function() { BRISToezicht.Telefoon.uploadUtility.showError( 'Fatale fout op server, of geen werkende internetverbinding.' ); } }); }, showError: function( details ) { $('#TelefoonPaginaAfsluiten .klaar-om-te-synchroniseren').hide(); $('#TelefoonPaginaAfsluiten .fout-bij-synchroniseren').show(); $('#TelefoonPaginaAfsluiten .fout-bij-synchroniseren .error').text( details || 'Geen nadere fout details.' ); } } }; <file_sep><? function initSpecialCIVars() { global $CI; if (!isset( $_SERVER['HTTP_USER_AGENT'] )) $_SERVER['HTTP_USER_AGENT'] = ''; $CI->is_IE6or7 = preg_match( '/MSIE\s+[67]/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE6or7or8 = $CI->is_IE6or7 || preg_match( '/MSIE\s+8/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_IE = $CI->is_IE6or7or8 || preg_match( '/MSIE/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_Mobile = preg_match( '/(Mobile|Android)/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_Safari = preg_match( '/Safari/', $_SERVER['HTTP_USER_AGENT'] ); $CI->is_iPad = $CI->is_Mobile && $CI->is_Safari; // other global $class, $method; $CI->is_Wizard = $class=='checklistwizard'; } function checkAccess() { $debug_checkaccess = false; //$debug_checkaccess = true; if ($debug_checkaccess) echo "+++ CA: 1 +++<br />"; initSpecialCIVars(); if ($debug_checkaccess) echo "+++ CA: 2 +++<br />"; // we need the current controller object, which is in global variable $CI global $CI; // we need the current class & method variables, which are in $class and $method global $class, $method; // no access rules for CLI if (IS_CLI) return; if ($debug_checkaccess) echo "+++ CA: 3 +++<br />"; // and use it to verify access to this class & method; if access not allowed // verify updates class & method if (!$CI->login->verify( $class, $method )) { if ($debug_checkaccess) echo "+++ CA: 4 +++<br />"; if (!$CI->login->logged_in() && ($class != 'gebruikers' && $method != 'inloggen') && (!($class == 'extern' && $method == 'login'))) { if ($debug_checkaccess) echo "+++ CA: 5 +++<br />"; // if there isn't a request waiting to be restored, store the current // request before we redirect $CI->load->helper( 'requestrestore' ); $rr = new RequestRestore(); if (!$rr->has_request_to_restore()) { if ($debug_checkaccess) echo "+++ CA: 6 +++<br />"; $rr->store_request(); } if ($debug_checkaccess) { echo "+++ CA: 7 +++<br />"; exit; } if ($class == 'extern') { // Check if a token was passed $token_segment = explode("=",$CI->uri->segments[3]); if ($token_segment[0] == 'token') { $segments = $CI->uri->segments; $post_login_location = implode ("/",array_splice($segments, count($segments)-3)); redirect('/extern/inloggen/'.$post_login_location); } else { redirect('/extern/inloggen/'); } } else { redirect( '/gebruikers/inloggen' ); } } if ($debug_checkaccess) echo "+++ CA: 8 +++<br />"; show_error( 'Geen toegang tot de gevraagde pagina: /' . $class . '/' . $method ); exit; } else { if ($debug_checkaccess) echo "+++ CA: 9 +++<br />"; if ($CI->login->logged_in()) { if ($debug_checkaccess) echo "+++ CA: 10 +++<br />"; $rr = new RequestRestore(); if ($rr->has_request_to_restore()) { if ($debug_checkaccess) { echo "+++ CA: 11 +++<br />"; exit; } redirect( REQUEST_RESTORE_REDIRECT ); } } } } ?><file_sep>-- toevoegen aan deelplan ALTER TABLE `deelplannen` ADD `olo_nummer` VARCHAR( 64 ) NULL DEFAULT NULL ; -- overnemen van dossier UPDATE deelplannen SET olo_nummer = (SELECT olo_nummer FROM dossiers WHERE id = deelplannen.dossier_id); -- verwijderen uit dossier ALTER TABLE `dossiers` DROP `olo_nummer`;<file_sep> <div id="header" class="menubar"> <form method="post"> <input type="hidden" name="page" value="afsluiten"> <input id="close" type="submit" value="afsluiten" hidden/><label for="close">Afsluiten</label>BRISToezicht - Toezichtmomenten </form> </div> <div class="objects"> <p>Selecteer een toezichtmoment:</p> <? if (sizeof( $objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'] )):?> <p><b>Dossier: <?=$objecten[$klant]['dossiers'][$dossier]['naam']; ?></b></p> <? foreach ($objecten[$klant]['dossiers'][$dossier]['hoofdgroepen'] as $bouwnummer=>$hoofdgroepen):?> <? if($bouwnummer):?> <p><b>Bouwnummer: <?=$bouwnummer; ?></b></p> <?endif;?> <? foreach ($hoofdgroepen as $id=>$hoofdgroep):?> <form method="post"> <button type="submit" class="object_details"> <input type="hidden" name="page" value="opdrachten"> <input type="hidden" name="klant_id" value="<?=$klant?>"> <input type="hidden" name="dossier_id" value="<?=$dossier?>"> <input type="hidden" name="bouwnummer_id" value="<?=$bouwnummer?>"> <input type="hidden" name="hoofdgroep_id" value="<?=$id?>"> <span><b><?=htmlentities( $hoofdgroep['naam'], ENT_COMPAT, 'UTF-8' )?></b></span><br /> <span>Aantal: <?=$hoofdgroep['aantal'] ?></span><br /> <?if (isset($hoofdgroep['recheck'])):?><span class="alert">Hercontrole: <?=$hoofdgroep['recheck'];?></span><br /><?endif?> <span<?if (isset($hoofdgroep['deadline']) && $hoofdgroep['deadline'] < date("Y-m-d")):?> class="alert"<?endif?>>Einddatum: <?if(isset($hoofdgroep['deadline'])):?><?=$hoofdgroep['deadline'];?><?endif?></span> </button> </form> <br /> <? endforeach; ?> <? endforeach; ?> <? else: ?> <div class="melding">Er zijn momenteel geen opdrachten voor u ingepland.</div> <? endif; ?> </div> <div id="footer" class="menubar"> <form method="post"> <input type="hidden" name="page" value="dossiers"> <input id="terug" type="submit" value="terug" hidden /> <label id="back" for="terug">Terug</label> </form> </div> <file_sep>CREATE TABLE `bt_vraag_aandachtspunten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `vraag_id` int(11) NOT NULL, `aandachtspunt` varchar(1024) NOT NULL, PRIMARY KEY (`id`), KEY `vraag_id` (`vraag_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `bt_vraag_aandachtspunten` ADD CONSTRAINT FOREIGN KEY ( `vraag_id` ) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; INSERT INTO bt_vraag_aandachtspunten (vraag_id, aandachtspunt) SELECT (SELECT w.id FROM bt_vragen w WHERE v.categorie_id = w.categorie_id AND w.sortering > v.sortering ORDER BY sortering LIMIT 1), v.tekst FROM bt_vragen v WHERE aandachtspunt = 'ja'; DELETE FROM bt_vragen WHERE aandachtspunt = 'ja'; ALTER TABLE bt_vragen DROP aandachtspunt; ALTER TABLE `bt_vragen` ADD `vraag_type` ENUM( 'meerkeuzevraag', 'invulvraag' ) NULL DEFAULT NULL, ADD `toezicht_moment` VARCHAR( 128 ) NULL, ADD `fase` VARCHAR( 128 ) NULL, ADD `waardeoordeel_tekst_00` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_00` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_01` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_01` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_02` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_02` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_03` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_03` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_04` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_04` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_10` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_10` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_11` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_11` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_12` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_12` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_13` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_13` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_14` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_14` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_20` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_20` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_21` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_21` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_22` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_22` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_23` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_23` ENUM('groen','oranje','rood') NULL DEFAULT NULL, ADD `waardeoordeel_tekst_24` VARCHAR(32) NULL DEFAULT NULL, ADD `waardeoordeel_kleur_24` ENUM('groen','oranje','rood') NULL DEFAULT NULL; ALTER TABLE `bt_vragen` ADD `waardeoordeel_is_leeg_00` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_00`, ADD `waardeoordeel_is_leeg_01` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_01`, ADD `waardeoordeel_is_leeg_02` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_02`, ADD `waardeoordeel_is_leeg_03` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_03`, ADD `waardeoordeel_is_leeg_04` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_04`, ADD `waardeoordeel_is_leeg_10` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_10`, ADD `waardeoordeel_is_leeg_11` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_11`, ADD `waardeoordeel_is_leeg_12` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_12`, ADD `waardeoordeel_is_leeg_13` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_13`, ADD `waardeoordeel_is_leeg_14` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_14`, ADD `waardeoordeel_is_leeg_20` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_20`, ADD `waardeoordeel_is_leeg_21` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_21`, ADD `waardeoordeel_is_leeg_22` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_22`, ADD `waardeoordeel_is_leeg_23` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_23`, ADD `waardeoordeel_is_leeg_24` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_tekst_24`; ALTER TABLE `bt_vragen` ADD `waardeoordeel_standaard` ENUM('00','01','02','03','04','10','11','12','13','14','20','21','22','23','24') NULL DEFAULT NULL, ADD `waardeoordeel_steekproef` ENUM('00','01','02','03','04','10','11','12','13','14','20','21','22','23','24') NULL DEFAULT NULL; <file_sep><? require_once 'base.php'; class DossierRapportResult extends BaseResult { function DossierRapportResult( &$arr ) { parent::BaseResult( 'dossierrapport', $arr ); } public function getContent() { $filepath = DIR_DOSSIER_RAPPORT . '/' . $this->dossier_id . '/' . $this->id; if( file_exists($filepath) ) { return file_get_contents($filepath); } throw new Exception('File not found: ' . $filepath); } public function geef_inhoud_vrij() { unset( $this->bestand ); } public function get_download_url() { return site_url( '/dossiers/rapportage_geschiedenis_download/' . $this->id ); } function get_gebruiker() { return $this->_CI->gebruiker->get( $this->gebruiker_id ); } function get_dossier() { return $this->_CI->dossier->get( $this->dossier_id ); } } class DossierRapport extends BaseModel { function DossierRapport() { parent::BaseModel( 'DossierRapportResult', 'dossier_rapporten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'dossier', 'dossier_id' ); } protected function _get_select_list() { // alles behalve bestand, zie DossierRapportResult::geef_inhoud_vrij functie return 'id, dossier_id, bestandsnaam, aangemaakt_op, gebruiker_id, instellingen, doc_type, target, omschrijving'; } public function add( DossierResult $dossier, $bestandsnaam, $bestandsdata, array $postdata, $doc_type, $target, array $deelplan_objecten, $gebruiker_id=null ) { // build data $CI = get_instance(); if (is_null( $gebruiker_id )) $gebruiker_id = $CI->login->get_user_id(); $omschrijving = ''; foreach(array_values( $deelplan_objecten ) as $i => $deelplan) { $omschrijving .= ($i ? ', ' : '') . $deelplan->naam; } $data = array( 'dossier_id' => $dossier->id, 'bestandsnaam' => $bestandsnaam, 'bestandsgrootte' => strlen($bestandsdata), 'aangemaakt_op' => (get_db_type() == 'oracle') ? array('format_string' => get_db_literal_for_datetime("?"), 'data' => date('Y-m-d H:i:s')) : date('Y-m-d H:i:s'), 'gebruiker_id' => $gebruiker_id, 'instellingen' => json_encode( $postdata ), 'doc_type' => $doc_type, 'target' => $target, 'omschrijving' => $omschrijving ); try { $this->get_db()->trans_begin(); $model = $this->insert($data); CI_Base::get_instance()->load->library('utils'); CI_Utils::store_file(DIR_DOSSIER_RAPPORT . '/' . $dossier->id, $model->id, $bestandsdata); $this->get_db()->trans_complete(); } catch (Exception $e){ throw new Exception('Could not save dossier_rapport '. $e->getMessage()); } return $model; } public function get_for_dossier( DossierResult $dossier ) { return $this->search( array( 'dossier_id' => $dossier->id ), $extra_query=null, $assoc=false, $operator='AND', $order_by='aangemaakt_op DESC' ); } }<file_sep><? $this->load->view('elements/header', array('page_header'=>'wettenregelgeving.main')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Wetteksten en regelgeving', 'expanded' => true, 'width' => '920px', 'height' => '100%', 'panel_outer_class' => 'groupcontenttight', 'panel_inner_class' => 'groupcontenttightinner' ) ); ?> Welkom bij het wettekst- en regelgevingbeheer. Selecteer een grondslag om de wetteksten en regelgevingen voor te bewerken. <? $list_view_data = array( 'minwidth' => '500px', 'height' => '300px', 'headers' => array( array( 'text' => 'Grondslag', 'width' => '200px', 'align' => 'left' ), array( 'text' => 'Artikelen', 'width' => '150px', 'align' => 'left' ), array( 'text' => 'In gebruik', 'width' => '150px', 'align' => 'left' ), array( 'text' => 'Toegevoegd op', 'width' => '150px', 'align' => 'left' ), ), 'rows' => array( ), 'flat' => true, ); foreach ($grondslagen as $grondslag) { $list_view_data['rows'][] = array( 'values' => array( $grondslag->grondslag, '<b>' . $artikel_stats[$grondslag->id] . '</b>', 'Bij <b>' . $vraag_stats[$grondslag->id] . '</b> vragen', $grondslag->toegevoegd_op, ), 'onclick' => "location.href='" . site_url('/wettenregelgeving/grondslag/' . $grondslag->id) . "'; ", ); } $this->load->view( 'elements/laf-blocks/generic-list', $list_view_data ); //$this->load->view( 'elements/laf-blocks/generic-searchable-list', $list_view_data ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'wettenregelgeving.main')); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Wetteksten en regelgeving - ' . $grondslag->grondslag, 'expanded' => true, 'width' => '920px', 'height' => '100%' ) ); ?> Er zijn <b><?=sizeof($grondslagteksten)?></b> artikelen voor deze grondslag. <form method="POST"> <table> <tr> <th style="text-align:left">Artikel </th> <th style="text-align:left">Grondslag</th> <th style="text-align:left">Grondslag Artikel</th> <th style="text-align:left">Tekst</th> </tr> <? foreach ($grondslagteksten as $i => $grondslagtekst): ?> <? $art = $grondslagtekst->artikel; ?> <? $grondslag = $grondslagtekst->get_grondslag()->grondslag; ?> <tr class="<?=($i%2)?'zebra':''?>"> <td><?=htmlentities($grondslagtekst->artikel, ENT_COMPAT, 'UTF-8')?></td> <td><?=$grondslag?></td> <td><a target="_blank" href="<?=site_url('/wettenregelgeving/grondslag_gebruik/' . $grondslagtekst->id )?>"><?=$grondslag?>_<?=$art?></a></td> <td width="50%"> <span><?=substr( htmlentities($grondslagtekst->tekst, ENT_COMPAT, 'UTF-8') . (strlen($grondslagtekst->tekst)>50?'...':''), 0, 50 )?></span> <input type="button" value="Bewerken" onclick="$(this).siblings('textarea').show(); $(this).hide(); $(this).siblings('span').hide();" /> <textarea class="hidden" name="tekst[<?=$grondslagtekst->id?>]" cols="40" rows="5"><?=htmlentities($grondslagtekst->tekst, ENT_COMPAT, 'UTF-8')?></textarea> </td> </tr> <? endforeach; ?> <tr> <td colspan="5"><input type="submit" value="Opslaan" /></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php function translit($string) { $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', ' '=>'_', 'á' =>'a', 'é'=>'e', 'í'=>'i', 'ó' =>'o', 'ú'=>'u', 'ý'=>'y', 'ä' =>'a', 'ë'=>'e', 'ï'=>'i', 'ö' =>'o', 'ü'=>'u', 'ÿ'=>'y', 'à' =>'a', 'è'=>'e', 'ì'=>'i', 'ò' =>'o', 'ù'=>'u', 'â'=>'a', 'ê' =>'e', 'î'=>'i', 'ô'=>'o', 'û' =>'u', '.' =>'_', ',' =>'_', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '\'', 'Ы' => 'Y', 'Ъ' => '\'', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', 'Á' => 'A', 'É' => 'E', 'Í' => 'I', 'Ó' => 'O', 'Ú' => 'U', 'Ý' => 'Y', 'Ä' => 'A', 'Ë' => 'E', 'Ï' => 'I', 'Ö' => 'O', 'Ü' => 'U', 'Ÿ' => 'Y', 'À' => 'A', 'È' => 'E', 'Ì' => 'I', 'Ò' => 'Q', 'Ù' => 'U', 'Â' => 'A', 'Ê' => 'E', 'Î' => 'I', 'Ô' => 'O', 'Û' => 'U', ); return strtr($string, $converter); } function str2url($str) { $str = translit($str); $str = strtolower($str); $str = preg_replace('~[^-a-z0-9_]+~u', '_', $str); $str = trim($str, "-"); return $str; } function convert_file_name($file_name){ $base_file_name=explode(".",$file_name); $index=end($base_file_name); array_pop($base_file_name); $base_file_name=implode(".",$base_file_name); $base_file_name=str2url($base_file_name); if(!$base_file_name) $base_file_name="empty"; $convertered_file_name=str2url($base_file_name).".".$index; return $convertered_file_name; }<file_sep>UPDATE `webservice_components` SET `naam` = 'BTZapp koppeling' WHERE `webservice_components`.`naam` = 'Spotdog koppeling'; SET @comp_id = (SELECT id FROM `webservice_components` WHERE `naam` = 'BTZapp koppeling'); INSERT INTO `webservice_applicaties` (`id` ,`naam` ,`actief`) VALUES (NULL , 'BTZApp', '1'); SET @app_id = LAST_INSERT_ID(); INSERT INTO `webservice_accounts` (`id`, `webservice_applicatie_id`, `omschrijving`, `gebruikersnaam`, `wachtwoord`, `actief`, `alle_klanten`, `alle_components`) VALUES (NULL, @app_id, 'BTZ app', 'btzapp', SHA1('iha9Yrqoh'), '1', '1', '0'); SET @acc_id = (SELECT id FROM `webservice_accounts` WHERE `omschrijving` = 'BTZ app'); INSERT INTO `webservice_account_rechten` (`id` ,`webservice_account_id` ,`webservice_component_id`) VALUES (NULL , @acc_id, @comp_id); <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => '', 'width' => '920px' ) ); ?> <h2>ITP import <?=$is_testrun?'<i>TEST</i>':''?> succesvol afgerond!</h2> <? if ($is_testrun): ?> <p> <span style="color:red">Er is nog niets in de database opgeslagen!</span> Er is slechts een test uitgevoerd of de data te importeren viel. Om de data wel op te slaan in de database, ga opnieuw naar de ITP import pagina, selecteer de te uploaden bestand opnieuw en <b>vink de "test run" checkbox uit</b>. </p> <p> Bij de test zijn de volgende hoeveelheid objecten aangemaakt (en daarna weer verwijderd): </p> <? else: ?> <p> Aangemaakte objecten in de database: </p> <? endif; ?> <table style="width: 200px"> <? foreach ($nieuwe_objecten as $class => $aantal): ?> <tr> <th style="text-align:left"><?=$class?></th> <td style="text-align:right"><?=$aantal?></td> </tr> <? endforeach; ?> </table> <input type="button" value="Terug naar ITP import" onclick="location.href='/admin/itpimport';" /> <? if (!$is_testrun): ?> <input type="button" value="Naar checklist wizard" onclick="location.href='/checklistwizard';" /> <? endif; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep><? /** * Het model systeem in deze app is suboptimaal, dus dezelfde checklist zou maar zo meer dan eens kunnen * worden ingeladen. Zodoende deze functie, die de "is afgerond" status hoe dan ook max 1 keer bepaalt per * checklist. */ function is_checklist_afgerond( $checklist ) { // invalid value? then false if (!$checklist) return false; // check cache static $results = array(); $id = is_object( $checklist ) ? $checklist->id : $checklist; if (isset( $results[ $id ] )) return $results[ $id ]; // if it's not an object, load checklist now if (!is_object( $checklist )) if (!($checklist = get_instance()->checklist->get( $id ))) return false; // set and return value; return $results[ $checklist->id ] = $checklist->is_afgerond(); } class ChecklistResult extends BaseResult { private $_checklist_groep; function ChecklistResult( &$arr ) { parent::BaseResult( 'checklist', $arr ); } public function get_wizard_parent() { return $this->get_checklistgroep(); } public function get_wizard_veld_recursief( $veld ) { $value = $this->get_wizard_veld( $veld ); return is_null($value) ? $this->get_wizard_parent()->get_wizard_veld_recursief( $veld ) : $value; } public function get_wizard_veld( $veld ) { $veld = 'standaard_' . $veld; if (!property_exists( $this, $veld )) throw new Exception( 'Object van type ' . get_class($this) . ' bevat veld ' . $veld . ' niet!' ); return $this->$veld; } public function get_wizard_onderliggenden() { return $this->get_hoofdgroepen(); } public function is_wizard_readonly() { return $this->get_checklistgroep()->is_wizard_readonly(); } public function get_checklistgroep() { if (!$this->_checklist_groep) { $CI = get_instance(); $CI->load->model( 'checklistgroep' ); if (!$CI->dbex->is_prepared( 'get_checklistgroep' )) $CI->dbex->prepare( 'get_checklistgroep', 'SELECT * FROM ' . $CI->checklistgroep->get_table() . ' WHERE id = ? ORDER BY id' ); $res = $CI->dbex->execute( 'get_checklistgroep', array( $this->checklist_groep_id ) ); $rows = $res->result(); $row = reset( $rows ); $result = $CI->checklistgroep->getr( $row, false ); $res->free_result(); $this->_checklist_groep = $result; } return $this->_checklist_groep; } public function rename( $name, $korte_naam=null ) { // we use table locks, this autocommits any transactions, so be sure non are active $db = $this->get_model()->get_db(); if ($db->_trans_depth > 0) throw new Exception( 'ChecklistResult::rename: trans_depth > 0, not allowed' ); $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'ChecklistGroepResult::rename1', 'UPDATE bt_checklisten SET naam = ?, naam_kort = ? WHERE id = ?', $db ); $CI->dbex->execute( 'ChecklistGroepResult::rename1', array( $name, is_null($korte_naam) ? null : $korte_naam, $this->id ), $db ); $this->naam = $name; $this->naam_kort = $korte_naam; } public function get_hoofdgroepen() { $CI = get_instance(); $CI->load->model( 'hoofdgroep' ); return $CI->hoofdgroep->get_by_checklist( $this->id ); } function delete() { /* Op verzoek van Raoul: altijd kunnen verwijderen (checklistwizard upgrade 28-8-2013) if ($this->is_afgerond()) throw new Exception( 'Kan afgeronde checklist ' . $this->naam . ' niet verwijderen!' ); */ $CI = get_instance(); $db = $this->get_model()->get_db(); $db->trans_start(); $CI->dbex->prepare( 'ChecklistGroepResult::delete1', 'DELETE FROM bt_checklisten WHERE id = ?', $db ); $CI->dbex->execute( 'ChecklistGroepResult::delete1', array( $this->id ), $db ); return $db->trans_complete(); } function is_afgerond() { if (is_null( $this->status )) $status = $this->get_checklistgroep()->standaard_checklist_status; else $status = $this->status; return $status == 'afgerond'; } function is_in_gebruik() { return in_array( $this->id, $this->get_checklistgroep()->get_gebruikte_checklist_ids() ); } function afronden() { $this->status = 'afgerond'; $this->save(); return true; } function heropenen( $safe=true ) { try { $CI = get_instance(); $CI->load->library( 'prioriteitstelling' ); $CI->load->library( 'risicoanalyse' ); $db = $CI->db; // verwijder alle deelplannen die gebruik maken van deze checklist if ($safe) $db->Query( sprintf( 'UPDATE deelplannen SET verwijderd = 1 WHERE id IN (SELECT deelplan_id FROM deelplan_checklisten WHERE checklist_id = %d)', $this->id ) ); // verwijder risicoanalyse en prioriteitstelling if ($safe) { $matrices = $CI->matrix->geef_matrices_voor_checklist_groep( $this->get_checklistgroep() ); foreach ($matrices as $matrix) { $CI->risicoanalyse->delete( $matrix->id, $this->id ); $CI->prioriteitstelling->delete( $matrix->id, $this->id ); } } // update status & save $this->status = 'open'; $this->save(); // finish if (!$db->trans_complete()) throw new Exception( 'Database fout bij afronden van transactie.' ); return true; } catch (Exception $e) { return $e->getMessage(); } } function get_checklist_klanten() /* returns array of klant ID's that have access to this checklist, ONLY valid when beschikbaarheid = 'publiek-voor-beperkt' !! */ { if (!is_array( @$this->_checklist_klanten_cache )) { $this->_checklist_klanten_cache = array(); $CI = get_instance(); if (!($res = $CI->db->query( 'SELECT klant_id FROM bt_checklist_klanten WHERE checklist_id = ' . $this->id ))) throw new Exception( 'Fout bij ophalen klant/checklist relaties.' ); foreach ($res->result() as $row) $this->_checklist_klanten_cache[] = $row->klant_id; } return $this->_checklist_klanten_cache; } // If $set is not null, the prioriteiten are SET to that value. If it's NULL, nothing is initially done. // If $or is not null, the prioriteiten are OR'd with that value, making it easy to add e.g. "prio 5" to all existing prioriteiten, without changing the rest of the bits // If $clear is not null, the prioriteiten are AND (NOT $clear)'d, making it easy to remove e.g. "prio 3" from all existing prioriteiten, without changing the rest of the bits function verander_prioriteiten( $set=null, $or=null, $clear=null ) { if (is_null( $set ) && is_null( $or ) && is_null( $clear )) return; if ($this->is_afgerond()) return; foreach ($this->get_hoofdgroepen() as $hoofdgroep) $hoofdgroep->verander_prioriteiten( $set, $or, $clear ); } /** Kopieert deze checklist. Als er een ander checklist_groep ID wordt meegegeven, dan * komt de kopie onder die checklist_groep te hangen. Anders wordt het een identieke * kopie onder dezelfde checklist_groep. * Als een andere checklist_groep ID is opgegeven, verandert de sortering verder ook niet. * Wordt een checklist_groep ID weggelaten, dan wordt de sortering dusdanig aangepast dat * de kopie onderaan de checklist_groep komt te hangen. * * @return Geeft de kopie terug in object vorm. */ public function kopieer( $ander_checklist_groep_id=null ) { $checklist = kopieer_object( $this, 'checklist_groep_id', $ander_checklist_groep_id ); foreach ($this->get_hoofdgroepen() as $hoofdgroep) $hoofdgroep->kopieer( $checklist->id ); return $checklist; } public function find_hoofdgroep( $naam ) { foreach ($this->get_hoofdgroepen() as $hoofdgroep) if ($hoofdgroep->naam == $naam) return $hoofdgroep; } public function get_toezichtmomenten() { $CI = get_instance(); $CI->load->model( 'toezichtmoment' ); return $CI->toezichtmoment->get_by_checklist( $this->id ); } } class Checklist extends BaseModel { function Checklist() { parent::BaseModel( 'ChecklistResult', 'bt_checklisten' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'checklistgroep', 'checklist_groep_id' ); } public function add( $checklist_groep_id, $name ) { // we use table locks, this autocommits any transactions, so be sure non are active $db = $this->get_db(); // Determine which "null function" should be used $null_func = get_db_null_function(); // prepare statements //$this->dbex->prepare( 'Checklist::add1', 'INSERT INTO bt_checklisten (checklist_groep_id, naam, naam_kort, status, sortering, beschikbaarheid) VALUES (?, ?, ?, ?, ?, ?)', $db ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'Checklist::search', 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS m FROM bt_checklisten WHERE checklist_groep_id = ?', $db ); // lock, get max id, create new entries, and be done $res = $this->dbex->execute( 'Checklist::search', array( $checklist_groep_id ) ); $sortering = intval( reset( $res->result() )->m ); /* // lock, get max id, create new entries, and be done $args1 = array( 'checklist_groep_id' => $checklist_groep_id, 'naam' => $name, 'naam_kort' => NULL, 'status' => 'open', 'sortering' => $sortering, 'beschikbaarheid' => 'publiek-voor-iedereen', ); $this->dbex->execute( 'Checklist::add1', $args1, false, $db ); // return result object $obj = new $this->_model_class( $args1 ); $obj->id = $this->db->insert_id(); return $obj; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'checklist_groep_id' => $checklist_groep_id, 'naam' => $name, 'naam_kort' => NULL, 'status' => 'open', 'sortering' => $sortering, 'beschikbaarheid' => 'publiek-voor-iedereen', 'created_at' => date('Y-m-d') ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function get_for_huidige_klant( $assoc=false ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, 'SELECT c.* FROM ' . $this->get_table() . ' c JOIN bt_checklist_groepen cg ON c.checklist_groep_id = cg.id WHERE cg.klant_id = ? ORDER BY c.sortering' ); $res = $CI->dbex->execute( $stmt_name, array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[$row->id] = $this->getr( $row, false ); return $result; } /** Returns checklisten from other klanten that have been made available to this klant. */ public function get_also_beschikbaar_for_huidige_klant( $checklist_groep_id, $assoc=false ) { global $class; $CI = get_instance(); $stmt_name = get_class($this) . '::get_also_beschikbaar_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, $query = ' SELECT c.* FROM ' . $this->get_table() . ' c JOIN bt_checklist_groepen cg ON c.checklist_groep_id = cg.id WHERE cg.klant_id != ? AND (c.beschikbaarheid = \'publiek-voor-iedereen\' OR c.id IN ( SELECT c2.id FROM ' . $this->get_table() . ' c2 JOIN bt_checklist_klanten c2k ON c2.id = c2k.checklist_id WHERE c2.beschikbaarheid = \'publiek-voor-beperkt\' AND c2k.klant_id = ? AND c2.checklist_groep_id = ? )) AND c.checklist_groep_id = ? ORDER BY cg.sortering, c.sortering' ); $kid = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $res = $CI->dbex->execute( $stmt_name, array( $kid, $kid, $checklist_groep_id, $checklist_groep_id ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[ $row->id ] = $this->getr( $row, false ); return $result; } public function get_map_checklisten_by_klant( $klantId, $assoc=false ){ $result = array(); $checklisen = $this->db->select($this->_table.'.id AS id,checklist_groep_id,'.$this->_table.'.naam AS naam') ->join('bt_checklist_groepen', 'bt_checklist_groepen.id = '.$this->_table.'.checklist_groep_id', 'left' ) ->where('klant_id', $klantId) ->group_by($this->_table.'.id') ->order_by('naam') ->get( $this->_table ) ->result(); foreach( $checklisen as $row ){ $row = $this->getr( $row ); ($assoc) ? $result[$row->id] = $row : $result[] = $row; } return $result; } }//CLASS END <file_sep><table width="100%" height="100%" class="messagebox"> <tr> <td class="icon notice"></td> <td class="message"> <form soort="url" method="POST" enctype="multipart/form-data" action="<?=site_url('/checklistwizard/richtlijn_toevoegen')?>"> <h2>Bewerk een URL</h2> <p><input type="text" size="60" name="url" maxlength="1024" placeholder="URL" value="<?=htmlentities($rl->url, ENT_COMPAT, 'UTF-8')?>" /></p> <p><input type="text" size="60" name="url_beschrijving" maxlength="256" placeholder="Beschrijving" value="<?=htmlentities($rl->url_beschrijving, ENT_COMPAT, 'UTF-8')?>" /></p> <h2>Opslaan</h2> <input type="button" value="Opslaan" /> </form> </td> </tr> </table> <script type="text/javascript"> var popup = getPopup(); popup.find( 'form[soort=url] input[type=button]' ).click(function(){ var form = $(this).closest('form')[0]; var url = $(form).find('[name=url]').val(); var url_beschrijving = $(form).find('[name=url_beschrijving]').val(); if (url && url.length) { var showError = function(error) { // kan geen showMessageBox gebruiken, we zitten al in een popup... alert( 'Er is iets fout gegaan bij het toevoegen van de URL.\n\n' + error ); }; $.ajax({ url: form.action, type: 'POST', data: {type: 'url', url: url, url_beschrijving: url_beschrijving}, dataType: 'json', success: function( data ) { if (data.success) closePopup( data.richtlijn_id + ':' + ((data.url_beschrijving && data.url_beschrijving.length) ? data.url_beschrijving + ' [' + data.url + ']' : data.url) ); else showError( data.error ); }, error: function() { showError(''); } }); } }); </script> <file_sep><table class="editor" cellpadding="0" cellspacing="0" border="0"> <tr> <td colspan="2" class="header"><?=tg('toelichting')?></td> </tr> <tr> <td colspan="2"><textarea id="nlaf_ToelichtingTextarea"></textarea></td> </tr> <tr> <td colspan="2" class="nlaf_ToelichtingButtons"></td> </tr> <tr> <td> <input type="button" id="nlaf_NieuweToelichting" value="<?=tgn('nieuwe_toelichting')?>"> <input type="button" id="nlaf_KiesToelichting" value="<?=tgn('kies_een_standaard_tekst')?>"> </td> <td style="text-align: right"> <input type="button" id="nlaf_AnnuleerToelichting" value="<?=tgng('form.annuleren')?>"> <input type="button" id="nlaf_VoegToeToelichting" value="<?=tgng('form.opslaan')?>"> </td> </tr> </table> <table class="standaardtekst" cellpadding="0" cellspacing="0" border="0"> </table> <file_sep><?php class WetTekstFetcher { const LOCKNAME = 'wettekstfetcher'; private $CI; private $_filelock; public function __construct() { $this->CI = get_instance(); $this->CI->load->library( 'filelock' ); $this->CI->load->library( 'quest' ); $this->CI->load->model( 'grondslagtekst' ); $this->_filelock = $this->CI->filelock->create( self::LOCKNAME ); define( 'FORCE_QUEST_USE_MAGMA_TOKEN', true ); // see Quest library } public function run() { if ($this->_filelock->is_locked()) throw new Exception( "WetTekstFetcher::run: Filelock already locked" ); if ($this->_filelock->try_lock() != LOCKFILE_SUCCESS) throw new Exception( "WetTekstFetcher::run: Filelock failed, already locked or no write access" ); try { $this->_run(); $this->_filelock->unlock(); } catch (Exception $e) { $this->_filelock->unlock(); throw $e; } } private function _run() { $timestamp_now = date('Y-m-d H:i:s'); $timestamp_next_fetch = date('Y-m-d H:i:s', strtotime( $timestamp_now ) + 86400 * 7); $wetteksten = $this->_fetch_outdated_database_rows( $timestamp_now ); echo sizeof($wetteksten) . " gevonden\n"; foreach ($wetteksten as $i => $grondslagtekst) { echo sprintf( "%06d/%06d [%.2f]%% %s ... ", ($i+1), sizeof($wetteksten), 100 * (($i+1) / sizeof($wetteksten)), $grondslagtekst->get_grondslag()->grondslag . ' ' . $grondslagtekst->artikel ); $this->_update_row( $grondslagtekst, $timestamp_next_fetch ); echo "\n"; } } private function _fetch_outdated_database_rows( $timestamp ) { $res = $this->CI->db->query( 'SELECT * FROM bt_grondslag_teksten WHERE next_update_timestamp < ' . $this->CI->db->escape( date('Y-m-d H:i:s', strtotime( $timestamp ) ) ) . ' ORDER BY grondslag_id, artikel, id' ); if (!$res) throw new Exception( 'WetTekstFetcher::_fetch_outdated_database_rows: failed to fetch outdated rows' ); return $this->CI->grondslagtekst->convert_results( $res ); } private function _update_row( GrondslagTekstResult $grondslagtekst, $next_fetch_timestamp ) { // fetch data $gqd = new GrondslagQuestData(); $gqd->text_allow_caching( false ); // disable cache $gqd->text_allow_remote_fetch( true ); // and allow remote fetch $start = microtime(true); $tekst = $grondslagtekst->get_artikel_tekst( $gqd ); $end = microtime(true); // toegang issue? then fail! if ($tekst == GrondslagTekstResult::GEEN_TOEGANG_TEKST_KENNISID || $tekst == GrondslagTekstResult::GEEN_TOEGANG_TEKST_GEEN_KENNISID) throw new Exception( 'WetTekstFetcher::_update_row: quest access error!!' ); // if succesfull, update row $grondslagtekst->next_update_timestamp = $next_fetch_timestamp; // always update this, otherwise we'll be trying erroneous records continuously! if ($tekst != GrondslagTekstResult::NIET_ACTUEEL_TEKST && $tekst != GrondslagTekstResult::QUEST_FOUT_TEKST) { $grondslagtekst->tekst = $tekst; $grondslagtekst->last_fetch_time = $end - $start; echo "OK"; } else { echo "ERROR"; } if (!$grondslagtekst->save(0,0,0)) throw new Exception( 'WetTekstFetcher::_update_row: failed to update record ' . $grondslagtekst->id ); } } <file_sep><div class="scrolldiv hidden" id="TelefoonPaginaToezicht"> <div class="header"> <div class="regular_button terug" style="float:left; position: relative; top: -6px;"><?=tg('terug')?></div> <div class="foto" style="position: relative; top: -3px;"></div> <div class="regular_button geel gereed" style="float:right; position: relative; top: -6px;"><?=tg('gereed')?></div> <div class="regular_button groen hidden opnieuw" style="float:right; position: relative; top: -6px;"><?=tg('opnieuw')?></div> </div> <form method="POST" enctype="multipart/form-data"> <? foreach ($dossiers as $dossierdata): $dossier = $dossierdata['dossier']; $deelplannen = $dossierdata['deelplannen']; foreach ($deelplannen as $deelplandata): $deelplan = $deelplandata['deelplan']; $hoofdgroepen = $deelplandata['hoofdgroepen']; $j=0; foreach ($hoofdgroepen as $hoofdgroepdata): $hoofdgroep = $hoofdgroepdata['hoofdgroep']; $opdrachten = $hoofdgroepdata['opdrachten']; foreach ($opdrachten as $i => $opdracht): $vraag = $opdracht->get_vraag(); $type = $vraag->get_wizard_veld_recursief('vraag_type'); $gereed_datum = date('d-m-Y', strtotime( $opdracht->gereed_datum ) ); $is_foto_vraag = !is_null( $opdracht->annotatie_tag ); if ($type == 'meerkeuzevraag') { $opties = array(); for ($x=0; $x<3; ++$x) for ($y=0; $y<5; ++$y) if ($x && $y==4) continue; else if ($optie = $vraag->get_wizard_veld_recursief( 'wo_tekst_' . $x . $y )) $opties['w'.$x.$y] = $optie; } ?> <div class="content" opdracht_id="<?=$opdracht->id?>" deelplan_id="<?=$deelplan->id?>" is_foto_vraag="<?=$is_foto_vraag ? 1 : 0?>"> <input type="hidden" name="gereed[<?=$opdracht->id?>]" value="0" /> <h1><?=htmlentities( $vraag->tekst, ENT_COMPAT, 'UTF-8' )?></h1> <span><?=htmlentities( $opdracht->opdracht_omschrijving, ENT_COMPAT, 'UTF-8' )?></span><br/> <? if ($type == 'meerkeuzevraag'): ?> <select name="status[<?=$opdracht->id?>]" class="meerkeuzevraag" style="margin: 10px 0px;"> <option value="" selected><?=tgn('kies.een.waardeoordeel')?></option> <? foreach ($opties as $status => $optie): ?> <option value="<?=$status?>"><?=htmlentities( $optie, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <? elseif ($type == 'invulvraag'): ?> <input type="text" name="status[<?=$opdracht->id?>]" class="invulvraag" style="margin:10px 0px;" /> <? endif; ?> <? if ($is_foto_vraag): ?> <h2><?=tg('locatie')?></h2> <div class="hidden"> <div tag="overzicht<?=$opdracht->id?>"> <? for ($q=0; $q<$opdracht->get_overzicht_afbeelding_aantal(); ++$q): ?> <img style="cursor: pointer; margin: 0; width: inherit;" src="/files/images/s.gif" target_url="<?=$opdracht->get_overzicht_afbeelding_url( $q )?>"><br/> <? endfor; ?> </div> <img style="cursor: pointer; " src="/files/images/s.gif" target_url="<?=$opdracht->get_snapshot_afbeelding_url()?>" tag="snapshot<?=$opdracht->id?>"> </div> <img class="foto locatie" style="cursor: pointer; " src="/files/images/s.gif" target_url="<?=$opdracht->get_overzicht_afbeelding_preview_url( 100 )?>" use_tag="overzicht<?=$opdracht->id?>"> <img class="foto locatie" style="cursor: pointer; " src="/files/images/s.gif" target_url="<?=$opdracht->get_snapshot_afbeelding_preview_url( 100 )?>" use_tag="snapshot<?=$opdracht->id?>"> <? endif; ?> <h2><?=tg('foto')?></h2> <div style="position: fixed; left:-9999px; top: -9999px;"><? /* must be in removeable parent! */ ?> <input type="file" name="foto[<?=$opdracht->id?>]"> </div> <div class="foto-taken hidden" style="margin: 10px 0px"> <img src="<?=site_url('/files/images/telefoon/foto.png')?>" style="vertical-align: middle"> <?=tg('foto.gemaakt')?> </div> <div class="foto-not-yet-taken" style="margin: 10px 0px"> <img src="<?=site_url('/files/images/telefoon/foto-geen.png')?>" style="vertical-align: middle"> <? if ($is_foto_vraag): ?> <?=tg('foto.nog.niet.gemaakt.op.locatie', $opdracht->annotatie_tag)?> <? else: ?> <?=tg('foto.nog.niet.gemaakt')?> <? endif; ?> </div> <h2><?=tg('toelichting')?></h2> <textarea name="toelichting[<?=$opdracht->id?>]"></textarea> <h2><?=tg('gereed_datum')?></h2> <span><?=tg('gereed.datum.tekst', date('d-m-Y', strtotime($opdracht->gereed_datum)))?></span> </div> <? endforeach; endforeach; endforeach; endforeach; ?> </form> </div> <script type="text/javascript"> $(document).ready(function(){ var base = $('#TelefoonPaginaToezicht'); base.find('.terug').click(function(){ BRISToezicht.Telefoon.jumpToPage( BRISToezicht.Telefoon.PAGE_OPDRACHTEN ); }); base.find('.gereed').click(function(){ BRISToezicht.Telefoon.opdrachtGereedZetten(); }); base.find('.opnieuw').click(function(){ showMessageBox({ message: $('[warning=echt-opnieuw]').text(), type: 'warning', onClose: function(res) { if (res=='yes') BRISToezicht.Telefoon.opdrachtTerugZetten(); }, buttons: ['yes','no'], top: 50, width: 250, height: 150 }); }); base.find('.header .foto, .foto-taken, .foto-not-yet-taken').click(function(){ var base = BRISToezicht.Telefoon.geefBaseVoorHuidigeOpdracht(); if (!base.size()) return; if (base.find('[name^=gereed]').val() == '1') return; var fileinput = base.find('[name^=foto]'); if (!fileinput.size()) return; fileinput.trigger( 'click' ); }); base.find('[name^=foto]').change(function(){ BRISToezicht.Telefoon.updateToezichtStatusVoorHuidigeOpdracht(); }); base.find('div[opdracht_id] .locatie').click(function(){ var tag = $(this).attr( 'use_tag' ); var el = base.find( '[tag=' + tag + ']' ); BRISToezicht.Telefoon.displayImage( el ); }); }); </script> <file_sep><? require_once 'base.php'; class WebserviceLogResult extends BaseResult { function WebserviceLogResult( &$arr ) { parent::BaseResult( 'webservicelog', $arr ); } } class WebserviceLog extends BaseModel { function WebserviceLog() { parent::BaseModel( 'WebserviceLogResult', 'webservice_log', true ); } public function check_access( BaseResult $object ) { // disabled for model } public function add( $ip, $uri, $request, $response, $webservice_account_id, $secure ) { /* $args = array( 'ip' => $ip, 'request_uri' => $uri, 'request' => $request, 'response' => $response, 'webservice_account_id' => $webservice_account_id, 'secure' => $secure, ); $this->dbex->prepare( 'add_webservice_log', 'INSERT INTO webservice_log (ip, request_uri, request, response, webservice_account_id, secure) VALUES (?, ?, ?, ?, ?, ?)' ); $this->dbex->execute( 'add_webservice_log', $args ); $id = $this->db->insert_id(); if (!is_numeric($id)) return null; $data = array_merge( array( 'id' => $id ), $args ); return new $this->_model_class( $data ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'ip' => $ip, 'request_uri' => $uri, 'request' => $request, 'response' => $response, 'webservice_account_id' => $webservice_account_id, 'secure' => $secure, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'ssccii' : ''; $result = $this->insert( $data, '', $force_types ); return $result; } } <file_sep><div id="nlaf_LoadingScreen" style="z-index: 1000; position: absolute; width: 100%; height: 100%; opacity: 0.92; filter:alpha(opacity=80); background-color: #555; "></div> <div id="nlaf_LoadingScreenContent" style="z-index: 1001; position: absolute; width: 100%; height: 100%; text-align: center; "> <div class="offline-klaar" style="width: 250px; margin-left: auto; margin-right: auto; margin-top: 20px; border: 2px solid #777; background-color: #eee; padding: 20px; opacity: 1.0; filter:alpha(opacity=100); font-size: 200%; font-weight: bold;"> <span> <?=tgn('even-geduld-aub')?> </span> <span class="perc"></span> <img style="vertical-align: top; padding-top: 10px;" src="<?=site_url('/files/images/loading.gif');?>"> <div style="border:0; padding:0; margin:0px 40px;"> <table width="100%"> <? if (tg('ophalen.afbeeldingen')!='-'): ?> <tr> <td style="text-align: left;"><span style="font-size: 10pt;"><?=tg('ophalen.afbeeldingen')?>:</span></td><td style="text-align: right;"><img src="/files/images/offline-klaar-wel.png" class="hidden status-offline-tag-klaar-afbeeldingen"><img src="/files/images/offline-klaar-nog-niet.png" class="status-offline-tag-niet-klaar-afbeeldingen"></td> </tr> <? endif; ?> </table> </div> </div> </div><file_sep><?php class CI_Rechten { private $CI; private $_recht_definities = array(); private $_groep_definities = null; // zelfde data als $_recht_definities, maar anders opgebouwd private $_rol_rechten = array(); public function __construct() { $this->CI = get_instance(); $this->CI->load->model( 'rolrecht' ); // $lease_configuratie_id = $this->CI->session->_loginSystem->get_lease_configuratie_id(); // $leaseconfiguratie = $this->CI->leaseconfiguratie->get( $lease_configuratie_id ); $this->maak_recht_definitie( RECHT_TYPE_DOSSIER_LEZEN, 'Dossier lezen', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN | RECHT_GROUP_ONLY, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DOSSIER_SCHRIJVEN, 'Dossier schrijven', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_GROUP_ONLY | RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DOSSIER_AFMELDEN, 'Dossier afmelden', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_GROUP_ONLY | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DOSSIER_VERANTWOORDELIJKE_ZIJN, 'Dossierverantwoordelijke zijn',RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN | RECHT_GROUP_ONLY , 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DEELPLAN_LEZEN, 'Deelplan lezen', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DEELPLAN_SCHRIJVEN, 'Deelplan schrijven', RECHT_MODUS_GEEN | RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_SCOPE_LEZEN, 'Scope lezen', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE| RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_SCOPE_SCHRIJVEN, 'Scope schrijven', RECHT_MODUS_GEEN | RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_TOEZICHTBEVINDING_LEZEN, 'Toezichtbevinding lezen', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_TOEZICHTBEVINDING_SCHRIJVEN, 'Toezichtbevinding schrijven', RECHT_MODUS_GEEN | RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_TOEWIJZEN_TOEZICHTHOUDERS, 'Toewijzen toezichthouders', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_TOEZICHT_AFMELDEN, 'Toezicht afmelden', RECHT_MODUS_GEEN | RECHT_MODUS_EIGEN, 'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DEELPLAN_AFDRUKKEN, 'Deelplan afdrukken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_DOSSIERS_IMPORTEREN, 'Dossiers importeren', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_PDF_ANNOTATOR, 'PDF annotator gebruiken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN | RECHT_GROUP_ONLY,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_PHONE_INTERFACE, 'Telefoon interface gebruiken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN | RECHT_GROUP_ONLY,'Dossiers' ); $this->maak_recht_definitie( RECHT_TYPE_GRP_ADMINISTRATOR, 'Group managing', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_EIGEN, 'Beheer' ) ; $this->maak_recht_definitie( RECHT_TYPE_GEBRUIKERS_BEHEREN, 'Gebruikers beheren', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_GROUP_ONLY | RECHT_MODUS_EIGEN, 'Beheer' ); $this->maak_recht_definitie( RECHT_TYPE_MATRICES_BEWERKEN, 'Matrices bewerken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Beheer' ); $this->maak_recht_definitie( RECHT_TYPE_LICENTIES_UITGEVEN, 'Licenties uitgeven', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Beheer' ); $this->maak_recht_definitie( RECHT_TYPE_MANAGEMENT_INFO_BEKIJKEN, 'Management informatie bekijken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Beheer' ); $this->maak_recht_definitie( RECHT_TYPE_OVERIG_BEHEER, 'Overige beheersfuncties gebruiken',RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_GROUP_ONLY, 'Beheer' ); $this->maak_recht_definitie( RECHT_TYPE_SITEBEHEER, 'Sitebeheer uitvoeren', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); $this->maak_recht_definitie( RECHT_TYPE_NIEUWS_BEHEREN, 'Nieuws beheren', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); $this->maak_recht_definitie( RECHT_TYPE_BACKLOG_BEHEREN, 'Backlog beheren', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); $this->maak_recht_definitie( RECHT_TYPE_INLINE_EDIT_BESCHIKBAAR, 'Inline edit gebruiken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); $this->maak_recht_definitie( RECHT_TYPE_ADD_USER_OWN_COMPANY, 'Add Users(Own company only) ', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); // if($leaseconfiguratie->has_children_organisations) $this->maak_recht_definitie( RECHT_TYPE_PARENT_KLANT_ADMIN, 'Admin of parent klant ', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_MODUS_SYSAD_ONLY,'Sitebeheer' ); $this->maak_recht_definitie( RECHT_TYPE_CHECKLIST_WIZARD, 'Checklist wizard gebruiken', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE | RECHT_GROUP_ONLY ,'Checklist wizard' ); $this->maak_recht_definitie( RECHT_TYPE_LOGBOEK_SCHRIJVEN, 'Logboek schrijven', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Overig' ); $this->maak_recht_definitie( RECHT_TYPE_TOEZICHTMOMENTEN, 'Toezichtmomenten module', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Toezichtmomenten' ); $this->maak_recht_definitie( RECHT_TYPE_MAPPINGEN, 'Mappingen module', RECHT_MODUS_GEEN | RECHT_MODUS_ALLE, 'Mappingen' ); // $this->maak_recht_definitie( RECHT_TYPE_UT, 'UT module', RECHT_MODUS_SYSAD_ONLY , 'Ut' ); // } public function maak_recht_definitie( $id, $beschrijving, $modi, $groep ) { if (isset( $this->_recht_definities[$id] )) throw new Exception( 'Recht definitie met id ' . $id . ' reeds gedefinieerd als: "' . $this->_recht_definities[$id]->get_beschrijving() . '"' ); $this->_recht_definities[$id] = new RechtDefinitie( $id, $beschrijving, $modi, $groep ); if (!isset( $this->_groep_definities[ $groep ] )) $this->_groep_definities[ $groep ] = array(); $this->_groep_definities[ $groep ][] = $this->_recht_definities[$id]; } public function get_recht_definitie( $id ) { if (!isset( $this->_recht_definities[$id] )) throw new Exception( 'Recht definitie met id ' . $id . ' niet gedefinieerd' ); return $this->_recht_definities[$id]; } public function get_recht_definities() { return $this->_recht_definities; } private function _laad_rechten( $user_id ) { // laad rechten if (!isset( $this->_rol_rechten[$user_id] )) { $this->_rol_rechten[$user_id] = $this->CI->rolrecht->get_for_gebruiker( $user_id ); if (!is_array( $this->_rol_rechten[$user_id] )) throw new Exception( 'Fout bij het laden van de rol rechten voor gebruiker ' . $user_id ); } return $this->_rol_rechten[$user_id]; } public function geef_recht_modus( $id, $user_id=null ) { if( !$this->CI->login->logged_in() ){ return RECHT_MODUS_GEEN; } if(!$user_id) { $user_id = $this->CI->login->get_user_id(); } $rechten = $this->_laad_rechten( $user_id ); // als gebruiker dit recht uberhaupt niet gedefinieerd heeft (niet ingelogd?), dan geen rechten if (!isset( $rechten[ $id ] )) return RECHT_MODUS_GEEN; // geef terug wat rol recht zegt return $rechten[$id]->get_modus(); } public function geef_groepen() { return array_keys( $this->_groep_definities ); } public function geef_groep_recht_definities( $groep ) { if (!isset( $this->_groep_definities[ $groep ] )) return array(); return $this->_groep_definities[ $groep ]; } } // // definitie van een recht_definitie, niet een concreet recht_definitie van een gebruiker // class RechtDefinitie { private $id; private $beschrijving; private $modi = 0; private $groep; public function __construct( $id /* RECHT_TYPE_xxx constante */, $beschrijving /* human readable */, $modi /* bitcombinatie van RECHT_MODUS_xxx constanten */, $groep /* groep waar het recht bijhoort, puur voor visuele doeleinden */ ) { $this->id = $id; $this->beschrijving = $beschrijving; $this->modi = $modi; $this->groep = $groep; } public function get_id() { return $this->id; } public function get_beschrijving() { return $this->beschrijving; } public function get_modi() { return $this->modi; } } <file_sep><? require_once 'base.php'; class StandardDeeplanResult extends BaseResult { function StandardDeeplanResult( &$arr ) { parent::BaseResult( 'standarddeelplan', $arr ); } } class Standarddeelplan extends BaseModel { private $_cache = array(); function Standarddeelplan(){ parent::BaseModel( 'StandardDeeplanResult', 'standard_deelplannen'); } public function check_access( BaseResult $object ) { //$this->check_relayed_access( $object, 'distributeur', 'klant_id' ); return; } public function get_by_klant($klant_id,$assoc=false){ $deelp = $this->db->where('klant_id', $klant_id ) ->get( $this->_table ) ->result(); $result = array(); foreach( $deelp as $row ){ $row = $this->getr( $row ); if ($assoc) $result[ $row->id ] = $row; else $result[] = $row; } return $result; } public function find_standard_deelplan( $naam, $klant_id ) { foreach ($this->get_by_klant($klant_id) as $deelplan) if ($deelplan->naam == $naam) return $deelplan; } public function update(array $postdata ){ return parent::save( (object)$postdata ); } } //comment <file_sep>-- kopieer TEST backlog naar LIVE! <file_sep><!DOCTYPE html> <html> <head> <title><?=@$extra_title ? $extra_title : APPLICATION_TITLE?></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" /> <!-- css --> <link rel="stylesheet" href="<?=site_url('/files/css/extern.css')?>" type="text/css" /> <script type="text/javascript" src="<?=site_url('/files/js/upload.js')?>" ></script> </head> <body> <? $this->load->view('elements/errors'); ?> <file_sep><? class ChecklistGroepResult extends BaseResult { function ChecklistGroepResult( &$arr ) { parent::BaseResult( 'checklistgroep', $arr ); } public function get_wizard_parent() { return null; } public function get_wizard_veld( $veld ) { $veld = 'standaard_' . $veld; if (!property_exists( $this, $veld )) throw new Exception( 'Object van type ' . get_class($this) . ' bevat veld ' . $veld . ' niet!' ); return $this->$veld; } public function get_wizard_veld_recursief( $veld ) { return $this->get_wizard_veld( $veld ); } public function get_wizard_onderliggenden() { return $this->get_checklisten(); } public function is_wizard_readonly() { return $this->klant_id != get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id; } public function get_checklisten() { $CI = get_instance(); $CI->load->model( 'checklist' ); if ($this->klant_id == get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id) { // regular $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'get_checklisten', 'SELECT * FROM ' . get_instance()->checklist->get_table() . ' WHERE checklist_groep_id = ? ORDER BY sortering', $db ); $res = $CI->dbex->execute( 'get_checklisten', array( $this->id ), $db ); $result = array(); foreach ($res->result() as $row) $result[] = $CI->checklist->getr( $row, false ); $res->free_result(); return $result; } else { // check better security return $CI->checklist->get_also_beschikbaar_for_huidige_klant( $this->id ); } } public function rename( $name ) { $CI = get_instance(); $db = $this->get_model()->get_db(); $CI->dbex->prepare( 'ChecklistGroepResult::rename', 'UPDATE bt_checklist_groepen SET naam = ? WHERE id = ?', $db ); $CI->dbex->execute( 'ChecklistGroepResult::rename', array( $name, $this->id ), $db ); $this->naam = $name; } function get_checklist_klanten() /* returns array of klant ID's that have access to this checklistgroep, ONLY valid when beschikbaarheid = 'publiek-voor-beperkt' !! */ { if (!is_array( @$this->_checklistgroep_klanten_cache )) { $this->_checklistgroep_klanten_cache = array(); $CI = get_instance(); if (!($res = $CI->db->query( 'SELECT klant_id FROM bt_checklist_groep_klanten WHERE checklist_groep_id = ' . $this->id ))) throw new Exception( 'Fout bij ophalen klant/checklist relaties.' ); foreach ($res->result() as $row) $this->_checklistgroep_klanten_cache[] = $row->klant_id; } return $this->_checklistgroep_klanten_cache; } // If $set is not null, the prioriteiten are SET to that value. If it's NULL, nothing is initially done. // If $or is not null, the prioriteiten are OR'd with that value, making it easy to add e.g. "prio 5" to all existing prioriteiten, without changing the rest of the bits // If $clear is not null, the prioriteiten are AND (NOT $clear)'d, making it easy to remove e.g. "prio 3" from all existing prioriteiten, without changing the rest of the bits function verander_prioriteiten( $set=null, $or=null, $clear=null ) { if (is_null( $set ) && is_null( $or ) && is_null( $clear )) return; foreach ($this->get_checklisten() as $checklist) $checklist->verander_prioriteiten( $set, $or, $clear ); } public function get_klant() { $CI = get_instance(); return $CI->klant->get( $this->klant_id ); } public function get_image() { $CI = get_instance(); if (!isset( $CI->image )) $CI->load->model( 'image' ); return $CI->image->get( $this->image_id ); } /** Kopieert deze checklistgroep. * * @return Geeft de kopie terug in object vorm. */ public function kopieer() { $checklistgroep = kopieer_object( $this, 'klant_id', get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id ); foreach ($this->get_checklisten() as $checklist) $checklist->kopieer( $checklistgroep->id ); return $checklistgroep; } public function find_checklist( $naam ) { foreach ($this->get_checklisten() as $checklist) if ($checklist->naam == $naam) return $checklist; } /* geeft array terug met alle ids van checklisten die: * - vallen onder deze checklistgroep * - in gebruik zijn bij 1 of meer deelplannen */ public function get_gebruikte_checklist_ids() { if (!isset( $this->_gebruikte_checklist_ids )) { $this->_gebruikte_checklist_ids = array(); $res = $this->_CI->db->query( ' SELECT DISTINCT(cl.id) AS id FROM deelplan_checklisten dcl JOIN bt_checklisten cl ON dcl.checklist_id = cl.id WHERE cl.checklist_groep_id = ' . intval($this->id) . ' '); foreach ($res->result() as $row) $this->_gebruikte_checklist_ids[] = $row->id; } return $this->_gebruikte_checklist_ids; } public function is_afgerond() { $checklisten = $this->get_checklisten(); $num = sizeof( $checklisten ); $num_afgerond = 0; foreach ($checklisten as $checklist) if ($checklist->is_afgerond()) ++$num_afgerond; else if ($num_afgerond) return 'gedeeltelijk-actief'; // als er 1 of meer actief zijn, en nu blijkbaar 1tje niet actief, dan mixed return $num_afgerond ? true : false; // als we hier komen, zijn ze ofwel allemaal actief, ofwel allemaal niet actief } function get_risicoanalyse_handler() { get_instance()->load->library('risicoanalyse'); return RisicoAnalyseHandlerFactory::create($this->risico_model); } } class ChecklistGroep extends BaseModel { function ChecklistGroep() { parent::BaseModel( 'ChecklistGroepResult', 'bt_checklist_groepen' ); } public function check_access( BaseResult $object ) { global $class; if (IS_CLI || (defined('IS_WEBSERVICE') && IS_WEBSERVICE)) return true; if (!isset( $object->beschikbaarheid )) // spliksplinternieuw! return; if ($object->beschikbaarheid == 'publiek-voor-iedereen') return; if ($object->beschikbaarheid == 'publiek-voor-beperkt') { // MJ, 28-05-2016: added a check for cookie set klantid for external users that are not logged_in_gebruikers. if (isset($this->gebruiker->get_logged_in_gebruiker()->klant_id) && is_int($this->gebruiker->get_logged_in_gebruiker()->klant_id)) { $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; } else { $klant_id = $this->session->userdata('kid'); } if (in_array( $klant_id, $object->get_checklist_klanten() )) return; } return parent::check_access( $object ); } public function add( $name ) { // resolve thema stuff $CI = get_instance(); $CI->load->helper( 'wizard' ); $CI->load->model( 'thema' ); $CI->load->model( 'hoofdthema' ); $thema = resolve_thema( 'new', 'Algemeen', 'Algemeen' ); // Determine which "null function" should be used $null_func = get_db_null_function(); // prepare statements //$this->dbex->prepare( 'ChecklistGroep::add', 'INSERT INTO bt_checklist_groepen (naam, klant_id, sortering, standaard_thema_id) VALUES (?, ?, ?, ?)' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $this->dbex->prepare( 'ChecklistGroep::search', 'SELECT '.$null_func.'(MAX(sortering),-1) + 1 AS m FROM bt_checklist_groepen WHERE klant_id = ?' ); // lock, get max id, create new entries, and be done $res = $this->dbex->execute( 'ChecklistGroep::search', array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); $sortering = intval( reset( $res->result() )->m ); /* // lock, get max id, create new entries, and be done $args = array( 'naam' => $name, 'klant_id' => intval( $this->gebruiker->get_logged_in_gebruiker()->klant_id ), 'sortering' => $sortering, 'standaard_thema_id' => $thema->id, ); if (!($this->dbex->execute( 'ChecklistGroep::add', $args ))) throw new Exception( 'Fout bij toevoegen van checklistgroep.' ); // return result object $obj = new $this->_model_class( $args ); $obj->id = $this->db->insert_id(); $obj->image_id = null; return $obj; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'naam' => $name, 'klant_id' => intval( $this->gebruiker->get_logged_in_gebruiker()->klant_id ), 'sortering' => $sortering, 'standaard_thema_id' => $thema->id, 'created_at' => date('Y-m-d'), ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data ); return $result; } public function find( $checklistgroep ) { $db = $this->get_db(); $this->dbex->prepare( 'ChecklistGroep::find', 'SELECT * FROM bt_checklist_groepen WHERE naam = ? AND klant_id = ?', $db ); $args = array( $checklistgroep, $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $res = $this->dbex->execute( 'ChecklistGroep::find', $args, false, $db ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function get_for_huidige_klant( $assoc=false, $only_private_ones=false ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE klant_id = ? ORDER BY sortering' ); $res = $CI->dbex->execute( $stmt_name, array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[ $row->id ] = $this->getr( $row, false ); if (!$only_private_ones) { if ($assoc) { foreach ($this->get_also_beschikbaar_for_huidige_klant() as $cg) $result[$cg->id] = $cg; } else $result = array_merge( $result, $this->get_also_beschikbaar_for_huidige_klant() ); } return $result; } /** Returns checklistgroepen from other klanten that have been made available to this klant. */ public function get_also_beschikbaar_for_huidige_klant( $assoc=false ) { global $class; $CI = get_instance(); $stmt_name = get_class($this) . '::get_also_beschikbaar_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, ' SELECT * FROM ' . $this->get_table() . ' WHERE klant_id != ? AND (beschikbaarheid = \'publiek-voor-iedereen\' OR id IN ( SELECT cg.id FROM ' . $this->get_table() . ' cg JOIN bt_checklist_groep_klanten cgk ON cg.id = cgk.checklist_groep_id WHERE cg.beschikbaarheid = \'publiek-voor-beperkt\' AND cgk.klant_id = ? )) ORDER BY sortering' ); $kid = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $res = $CI->dbex->execute( $stmt_name, array( $kid, $kid ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[ $row->id ] = $this->getr( $row, false ); return $result; } } <file_sep><?php require_once('dossierbase.php'); class Dossiers extends DossierBase { function Dossiers() { parent::Controller(); $this->load->model( 'checklist' ); $this->navigation->push( 'nav.dossierbeheer', '/dossiers' ); $this->navigation->set_active_tab( 'dossierbeheer' ); // for bescheiden cache JPG's $this->_cache_path = dirname(__FILE__) . '/pdfview-cache'; } private function _check_dossier_security( $dossier, $throw_exception=false ) { $group_users=array(); if($this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_LEZEN )==RECHT_GROUP_ONLY){ $this->load->model( 'gebruiker' ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $my_group_users=cut_array($gebruiker->groups_users, "user_id"); $group_users=$this->dossier->get_by_gebruikers($my_group_users, $size, null ); } if ($dossier) $this->navigation->push( 'nav.bekijken', '/dossiers/bekijken/' . $dossier->id, array( $dossier->get_omschrijving() ) ); // fetch planning datum $this->load->library( 'planningdata' ); $dossier_planning = $this->planningdata->get_dossier_planning(); $dossier->gepland_datum = @$dossier_planning[$dossier->id]; // check if current dossier belongs to current user, if not, possible hack attempt if (!$this->login->logged_in() || $dossier->gebruiker_id != $this->login->get_user_id() || $dossier->verwijderd) { // if (!$dossier->verwijderd) // { // not owned by the user? then check if it belongs to a colleague, or if we are // set as a toezichthouder in any of them $size = null; $dossiers = array(); foreach (array_merge( $this->dossier->get_van_collegas( false, $size, true /* all! */, null, false ), $this->dossier->get_van_collegas( false, $size, true /* all! */, null, true ), $this->dossier->get_dossiers_by_toezichthouder( null, true ), $this->dossier->get_dossiers_by_toezichthouder( null, false ), $group_users ) as $dossier){ $dossier=(object)$dossier; $dossiers[$dossier->id] = $dossier; } // } if (!isset( $dossiers[$dossier->id] )) { if (!$throw_exception) redirect(''); else throw new Exception( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); } } } private function _check_dossierbescheiden_security( $dossierbescheiden_id, &$dossierbescheiden, &$dossier, $throw_exception=true ) { // check if dossier bescheiden exists, and if dossier belongs to us $this->load->model( 'dossierbescheiden' ); $dossierbescheiden = $this->dossierbescheiden->get( $dossierbescheiden_id ); if ($dossierbescheiden==null) { if (!$throw_exception) redirect(''); else throw new Exception( tgng( 'php.dossiers.geen.toegang.tot.dossier.bescheiden' ) ); } $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierbescheiden->dossier_id ); if ($dossier==null) { if (!$throw_exception) redirect(''); else throw new Exception( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); } $this->_check_dossier_security( $dossier, $throw_exception ); } private function _check_dossierbescheidenmap_security( $dossierbescheidenmap_id, &$dossierbescheidenmap=null, &$dossier=null, $throw_exception=true ) { if (!$dossierbescheidenmap_id) return; // check if dossier bescheiden exists, and if dossier belongs to us $this->load->model( 'dossierbescheidenmap' ); $dossierbescheidenmap = $this->dossierbescheidenmap->get( $dossierbescheidenmap_id ); if ($dossierbescheidenmap==null) { if (!$throw_exception) redirect(''); else throw new Exception( tgng( 'php.dossiers.geen.toegang.tot.dossier.bescheiden' ) ); } $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierbescheidenmap->dossier_id ); if ($dossier==null) { if (!$throw_exception) redirect(''); else throw new Exception( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); } $this->_check_dossier_security( $dossier, $throw_exception ); } function index( $mode=null, $pagenum=null, $pagesize=null, $sortfield=null, $sortorder=null, $search=null ) { // if not logged in, redirect go user login if (!$this->login->logged_in()) redirect( '/gebruikers/inloggen' ); // geen DOSSIER_LEZEN recht? dan geen toegang if ($this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_LEZEN ) == RECHT_MODUS_GEEN) redirect( '/intro/index' ); if($this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_LEZEN )==RECHT_GROUP_ONLY) $mode="only_group"; // get dossier list $data = $this->_dossier_list( $mode, $pagenum, $pagesize, $sortfield, $sortorder, $search ); $data['do_bel_import'] = $data['klant']->allow_bel_import(); $data['import_access'] = $this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIERS_IMPORTEREN ); $data['include_nokia_maps'] = true; $this->load->model('dossierbescheiden'); // //add export_tag to identify the export foreach ($data['dossiers'] as $i => $dossier) { $pdf_status = "green"; $result=$this->dossierbescheiden->get_by_dossier($data['dossiers'][$i]->id); if(empty($result)) $pdf_status="no_ico"; foreach ($result as $result_value) { $extention=end(explode(".", $result_value->bestandsnaam)); if ($extention != 'pdf') { $pdf_status = "red"; } elseif ($result_value->has_pdfa_copy == 0){ $pdf_status = "yellow"; } } $data['dossiers'][$i]->pdf_status = $pdf_status; } $this->load->library('dossierexport'); $data['download_tag'] = get_export_tag( 'dossieroverzicht' ); // load view $this->load->view('dossiers/index', $data ); } function importeren( $stap='' ) { // check if we have access $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); if (!$klant->allow_bel_import()) redirect(); // go! $this->navigation->push( 'nav.importeren', '/dossiers/importeren' ); switch ($stap) { case '2': $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // start transaction $this->db->trans_begin(); // go! $known_error = false; try { $csv = @$_FILES['csv']; if (!is_array( $csv ) || $_FILES['csv']['error'] || !$_FILES['csv']['size']) $errors[] = tgng( 'php.dossiers.geen.bestand.geupload.of.fout' ); else if (!preg_match( '/\.csv$/i', $csv['name'] )) $errors[] = tgng( 'php.dossiers.geen.bestand.geupload.of.geen.csv' ); else { $this->load->library( 'belimport' ); $import = $this->belimport->create( $csv['tmp_name'], 'fail' ); $import->run(); } } catch (Exception $e) { $known_error = true; $this->db->_trans_status = false; $errors[] = $e->getMessage(); } // finish, either rollback or commit if (!$this->db->trans_complete()) { if (!$known_error) $errors[] = tgng( 'php.database.interne.fout' ); } else if (is_object( @$import )) redirect( '/dossiers/importeren_afgerond/' . $import->get_import_count() ); } $this->load->view('import2', array( 'errors' => $errors, 'separator' => isset( $_POST['separator'] ) ? $_POST['separator'] : ',', ) ); break; default: $this->load->view('import' ); } } function importeren_afgerond( $num ) { // go! $this->navigation->push( 'nav.importeren', '/dossiers/importeren' ); $this->navigation->push( 'nav.afgerond', '/dossiers/importeren_afgerond' ); $this->load->view('import_afgerond', array( 'num' => $num, ) ); } function dossieroverzicht_genereren () { // check if we have access $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $download_tag = 0; if (isset( $_POST['download-tag'])) { $download_tag = $_POST['download-tag'] ; } $this->load->library('dossieroverzicht'); $this->load->helper('user_download'); // for now, only allow exports to excel $doc_type = 'xlsx'; // Now generate the report $docdata = $this->dossieroverzicht->export( $doc_type, $gebruiker, $download_tag); // before we output anything, clear all output buffers, so any PHP warnings // will automatically disappear! this is ugly, I know, but it's even more ugly // when people cannot download otherwise perfect PDF files... :/ while (ob_get_level()) ob_end_clean(); // output download if ($this->dossieroverzicht->get_contents()) { user_download( $this->dossieroverzicht->get_contents(), $this->dossieroverzicht->get_filename(), true, $this->dossieroverzicht->get_contenttype() ); } else { echo "Onze excuses: het document kon niet worden gegenereerd. Neem svp contact op met onze helpdesk om dit probleem aan te geven."; } exit; } function nieuw() { // get data from _POST // add dossier! $this->navigation->push( 'nav.bewerken', $_SERVER['REQUEST_URI'] ); $this->load->model('dossier'); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); $gebruikers = $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ); $this->load->view( 'dossiers/nieuw_dossier', array( 'open_tab_group' => '', 'reg_gegevens_bewerkbare' => $klant->heeft_toezichtmomenten_licentie == 'nee', 'klant_id' => $gebruiker->klant_id, 'gebruikers'=>$gebruikers, 'dossier_access' => '', 'form_access'=>'write', 'gebruiker_id' => $this->session->userdata( 'uid' )?$this->session->userdata( 'uid' ):$gebruiker->id, 'verplichte_velden' => array( 'beschrijving' => 'Dossiernaam', 'kenmerk' => 'Identificatienummer', 'locatie_adres' => 'Locatie adres', 'locatie_postcode' => 'Locatie postcode', 'locatie_woonplaats' => 'Locatie woonplaats', ), )); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){ $kenmerk = ''; $beschrijving = ''; $aanmaak_datum = time(); $locatie_adres = ''; $locatie_postcode = ''; $locatie_woonplaats = ''; $locatie_kadastraal = ''; $locatie_sectie = ''; $locatie_nummer = ''; $opmerkingen = NULL; $beschrijving=$_POST['beschrijving']; $kenmerk=$_POST['kenmerk']; $locatie_adres=$_POST['locatie_adres']; $locatie_postcode=$_POST['locatie_postcode']; $locatie_woonplaats=$_POST['locatie_woonplaats']; $locatie_kadastraal=$_POST['locatie_kadastraal']; $locatie_sectie=$_POST['locatie_sectie']; $locatie_nummer=$_POST['locatie_nummer']; $opmerkingen=$_POST['opmerkingen']; $bag_identificatie_nummer=$_POST['bag_identificatie_nummer']; $gebruiker_id=$_POST['gebruiker_id']; $xy_coordinaten=$_POST['xy_coordinaten']; $correspondentie_adres=$_POST['correspondentie_adres']; $correspondentie_postcode=$_POST['correspondentie_postcode']; $correspondentie_plaats=$_POST['correspondentie_plaats']; $dossier_id = $this->dossier->add( $kenmerk, $beschrijving, $aanmaak_datum, $locatie_adres, $locatie_postcode, $locatie_woonplaats, $locatie_kadastraal, $locatie_sectie, $locatie_nummer, $opmerkingen, '', 'handmatig', $gebruiker_id, $bag_identificatie_nummer, $xy_coordinaten, $correspondentie_adres, $correspondentie_postcode, $correspondentie_plaats); if( $this->session->userdata( 'is_std_deelpl' ) ){ $this->load->model('standarddeelplan'); $this->load->model('deelplan'); $std_deelplannen = $this->standarddeelplan->get_by_klant($this->session->userdata( 'kid' )); foreach( $std_deelplannen as $std_deelpl ){ $this->deelplan->add( $dossier_id, $std_deelpl->naam ); } } if($dossier_id){ redirect( '/dossiers/bewerken/' . $dossier_id ); } else { redirect( '/dossiers/'); } } //$dossier_id = $this->dossier->add( $kenmerk, $beschrijving, $aanmaak_datum, $locatie_adres, $locatie_postcode, $locatie_woonplaats, $locatie_kadastraal, $locatie_sectie, $locatie_nummer, $opmerkingen, '', 'handmatig' ); // log! // $dossier = $this->dossier->get( $dossier_id ); // $this->logger->add( $dossier, 'dossier', 'Nieuw dossier aangemaakt', $dossier->get_log_extra_info() ); // redirect! //redirect( '/dossiers/bewerken/' . $dossier_id ); } function bewerken( $dossier_id=null, $open_tab_group='' ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { $this->load->model('btbtzdossier'); $this->load->model('dossierbescheiden'); $this->load->model('dossierbescheidenmap'); $this->_check_dossier_security( $dossier ); $dossier_access = $dossier->get_access_to_dossier(); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); $this->navigation->push( 'nav.bewerken', $_SERVER['REQUEST_URI'] ); $this->load->model('dossiersubject'); $subjecten = $this->dossiersubject->get_by_dossier( $dossier_id ); $gebruikers = $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ); $btBtzDossier = $this->btbtzdossier->get_one_by_btz_dossier_id( $dossier->id ); // handle POST if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if ($dossier_access == 'write') { $voeg_notificatie_toe = strlen($dossier->kenmerk) == 0; if( $klant->heeft_toezichtmomenten_licentie == 'nee' ){ // updat geolocatie state when adres or woonplaats changed! if ($dossier->locatie_adres != $_POST['locatie_adres'] || $dossier->locatie_woonplaats != $_POST['locatie_woonplaats']) { $dossier->geo_locatie_id = NULL; $dossier->geo_locatie_opgehaald = 0; } // update info $dossier->kenmerk = $_POST['kenmerk']; $dossier->beschrijving = $_POST['beschrijving']; $dossier->bag_identificatie_nummer = ($bag = trim($_POST['bag_identificatie_nummer'])) ? $bag : null; $dossier->xy_coordinaten = ($xy = trim($_POST['xy_coordinaten'])) ? $xy : null; $dossier->locatie_adres = $_POST['locatie_adres']; $dossier->locatie_postcode = $_POST['locatie_postcode']; $dossier->locatie_woonplaats = $_POST['locatie_woonplaats']; $dossier->locatie_kadastraal = $_POST['locatie_kadastraal']; $dossier->locatie_sectie = $_POST['locatie_sectie']; $dossier->locatie_nummer = $_POST['locatie_nummer']; $dossier->opmerkingen = ($o = trim($_POST['opmerkingen'])) ? $o : NULL; $dossier->correspondentie_adres=$_POST['correspondentie_adres']; $dossier->correspondentie_postcode=$_POST['correspondentie_postcode']; $dossier->correspondentie_plaats=$_POST['correspondentie_plaats']; } // uploaded file? $dossierFotoData = ''; if (isset($_FILES['dossierfoto'])) { $im = new Imagick(); //if ($POST['logo']['tmp_name']) if($_FILES['dossierfoto']['tmp_name']) { try { $res = $im->readImage($_FILES['dossierfoto']['tmp_name']) ; } catch (ImagickException $e) {} if (!$res) { $errors[] = 'Het door u geuploade bestand kon niet worden ingelezen!'; $im->destroy(); $im = null; } elseif ($im!=null) { // resize image if necessary //$max_foto_width = '250px'; //$max_foto_height = '362px'; $max_foto_width = '250'; $max_foto_height = '362'; $imW = $im->getImageWidth(); $imH = $im->getImageHeight(); $imR = (float)$imW / (float)$imH; $maxfotoR = (float)$max_foto_width / (float)$max_foto_height; // what to scale? if ($imR < $maxfotoR) { // scale by height $im->resizeImage( null, $max_foto_height, imagick::FILTER_BOX, 0 ); $x = ($max_foto_width - $im->getImageWidth()) / 2; $y = 0; } else { // scale by width $im->resizeImage( $max_foto_width, null, imagick::FILTER_BOX, 0 ); $x = 0; $y = ($max_foto_height - $im->getImageHeight()) / 2; } if ($im!=null) { // set to 24 bits color png $im->setImageDepth( 24 ); $im->setImageFormat( 'png' ); // get foto string //$dossier->foto = $im->getImageBlob(); $dossierFotoData = $im->getImageBlob(); $im->destroy(); } } } } // see if user is allowed to set gebruiker_id, otherwise (isset( $_POST['gebruiker_id'] ) && isset( $gebruikers[$_POST['gebruiker_id']] ) ) ? $dossier->gebruiker_id = $_POST['gebruiker_id']:NULL; // Save the dossier first $dossier->save(); if($klant->heeft_toezichtmomenten_licentie == 'nee') { // If a picture was uploaded for this dossier, save it. if (!empty($dossierFotoData)) { $existingDossierFoto = $dossier->get_foto(); // If no photo exists yet, create one if (is_null($existingDossierFoto)) { $this->load->model( 'dossierfoto' ); $existingDossierFoto = $this->dossierfoto->add($dossier->id); } $existingDossierFoto->bestand = $dossierFotoData; $existingDossierFoto->save(); } ($voeg_notificatie_toe) ? $dossier->add_create_notificatie():NULL; } } // redirect! if (preg_match( '/bescheiden/i', @$_POST['target_state'] )) redirect( '/dossiers/bescheiden_toevoegen/' . $dossier_id ); redirect( '/dossiers/bekijken/' . $dossier_id ); } $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); $this->load->view( 'dossiers/bewerken', array( 'dossier' => $dossier, 'open_tab_group' => $open_tab_group, 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $dossier_id ), 'mappen' => $this->dossierbescheidenmap->get_by_dossier( $dossier->id ), 'gebruiker_id' => $dossier ? $dossier->gebruiker_id : $this->session->userdata( 'uid' ), 'dossier_access' => $dossier_access, 'subjecten' => $subjecten, 'gebruikers' => $gebruikers, 'klant_id' => $gebruiker->klant_id, 'is_riepair_user' => $gebruiker->is_riepair_user(), 'verplichte_velden' => array( 'beschrijving' => 'Dossiernaam', 'kenmerk' => 'Identificatienummer', 'locatie_adres' => 'Locatie adres', 'locatie_postcode' => 'Locatie postcode', 'locatie_woonplaats' => 'Locatie woonplaats', ), 'reg_gegevens_bewerkbare' => $klant->heeft_toezichtmomenten_licentie == 'nee', 'bristoets_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->bt_status : '', 'bristoezicht_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->btz_status : '', 'project_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->project_status : '' ) ); } } function bekijken( $dossier_id=null, $open_deelplan_id=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { $this->load->model('dossierbescheiden'); $this->load->model('btbtzdossier'); $this->_check_dossier_security( $dossier ); $this->load->model('deelplanthema'); $this->load->model('thema'); $this->load->model('checklistgroep'); $this->load->model('checklist'); $this->load->model('deelplanchecklistgroep'); $this->load->model('deelplanchecklist'); $this->load->model('gebruikerchecklistgroep'); $this->load->model('matrix'); $this->load->model('dossiersubject'); $this->load->helper('export'); // over hele dossier $alle_actieve_themas = $this->thema->get_alle_actieve_themas(); $checklistgroepen = $this->checklistgroep->get_for_huidige_klant( true ); $matrices = array(); foreach ($checklistgroepen as $checklistgroep) { $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ); $matrices[$checklistgroep->id] = $this->matrix->geef_matrices_voor_checklist_groep( $checklistgroep, false, true ); } $gebruikers = $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ); foreach ($gebruikers as $i => $gebruiker) if ($this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_VERANTWOORDELIJKE_ZIJN, $gebruiker->id ) == RECHT_MODUS_GEEN) unset( $gebruikers[$i] ); // For Woningborg we are not allowed to close ANY deelplan until the BtBtzDossier has project status 'toets afgerond'. // Instead of checking if the current client is Woningborg, etc. we simply check if the current dossier has a BtBtzDossier // and if so, take the logic from there. Use positive logic, assuming by default that the user is allowed to close deelplannen // unless specifically overriden. Currently, the only situation for those dossiers in which the user is allowed to close a // deelplan is then when the 'project status' equals 'toets afgerond'. In all other situations where a BtBtzDossier exists, // the user is NOT allowed to close deelplannen. $mag_deelplannen_afmelden = false; $btBtzDossier = $this->btbtzdossier->get_one_by_btz_dossier_id( $dossier->id ); if (!is_null($btBtzDossier) && ($btBtzDossier->project_status == 'toets afgerond')) { $mag_deelplannen_afmelden = true; } // per deelplan $deelplannen = array_reverse( $dossier->get_deelplannen() ); $mag_gebruiker_toekennen = array(); $current_themas = array(); $deelplanchecklistgroepen = array(); $deelplanchecklisten = array(); $scope_access = array(); $deelplan_access = array(); foreach ($deelplannen as $deelplan) { $deelplan_access[$deelplan->id] = $deelplan->get_access_to_deelplan(); $mag_gebruiker_toekennen[$deelplan->id] = $deelplan->get_toezichthouder_toekennen_access_to_deelplan() == 'write'; $current_themas[$deelplan->id] = $this->deelplanthema->get_by_deelplan( $deelplan->id ); $deelplanchecklistgroepen[$deelplan->id] = $this->deelplanchecklistgroep->get_by_deelplan( $deelplan->id ); $deelplanchecklisten[$deelplan->id] = $this->deelplanchecklist->get_by_deelplan( $deelplan->id ); $scope_access[$deelplan->id] = array(); foreach ($deelplanchecklistgroepen[$deelplan->id] as $deelplanchecklistgroep) $scope_access[$deelplan->id][$deelplanchecklistgroep->checklist_groep_id] = $deelplan->get_scope_access_to_deelplan( $deelplanchecklistgroep ); } $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); $this->load->view( 'dossiers/bekijken', array( 'dossier' => $dossier, 'deelplannen' => $deelplannen, 'open_deelplan_id' => $open_deelplan_id, 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $dossier_id ), 'mag_gebruiker_toekennen' => $mag_gebruiker_toekennen, 'mag_deelplannen_afmelden' => $mag_deelplannen_afmelden, 'gebruikers' => $gebruikers, 'gebruiker_id' => $dossier ? $dossier->gebruiker_id : $this->session->userdata( 'uid' ), 'themas' => $alle_actieve_themas, 'current_themas' => $current_themas, 'checklistgroepen' => $checklistgroepen, 'matrices' => $matrices, 'formaten' => $this->config->item('rapportage_formats'), 'deelplanchecklistgroepen' => $deelplanchecklistgroepen, 'deelplanchecklisten' => $deelplanchecklisten, 'dossier_access' => $dossier->get_access_to_dossier(), 'deelplan_access' => $deelplan_access, 'scope_access' => $scope_access, 'gebruiker_checklistgroepen' => $this->gebruikerchecklistgroep->all(), 'deelplan_checklistgroep_planning' => $this->planningdata->get_deelplan_checklistgroep_planning(), 'deelplan_checklist_planning' => $this->planningdata->get_deelplan_checklist_planning(), 'klant_id' => $gebruiker->klant_id, 'logged_in_gebruiker_id' => $gebruiker->id, 'blank' => $gebruiker->get_klant()->get_lease_configuratie() ? false : true, 'reg_gegevens_bewerkbare' => $klant->heeft_toezichtmomenten_licentie == 'nee', 'bristoets_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->bt_status : '', 'bristoezicht_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->btz_status : '', 'project_status' => (!is_null($btBtzDossier)) ? $btBtzDossier->project_status : '' ) ); } } function deelplan_toevoegen( $dossier_id=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { $this->_check_dossier_security( $dossier ); if ($dossier->get_access_to_dossier() == 'write') { $naam = trim( @$_POST['nieuw_deelplan'] ); if (!$naam) { $deelplannen = $dossier->get_deelplannen(); $naam = tgng('php.nieuwe_deelplan_naam', chr( ord('A') + sizeof($deelplannen) ) ); } $this->load->model( 'deelplan' ); if (!($deelplan_id = $this->deelplan->add( $dossier->id, $naam ))) throw new Exception( tgng( 'php.dossiers.database.fout.bij.toevoegen.deelplan' ) ); $deelplan = $this->deelplan->get( $deelplan_id ); if (!$deelplan) throw new Exception( "Failed to get deelplan id " . var_export($deelplan_id,true) . " after creating it..." ); $deelplan->add_create_notificatie(); // Upon creating a new 'deelplan' we always automatically associate ALL subjects with the deelplan. Do this by copying those of the // dossier to the deelplan. $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $gebruiker->get_klant(); if($klant->not_automaticly_select_betrokkenen==0){ $this->load->model( 'deelplansubject' ); $dossier_subject_ids = array(); foreach($dossier->get_subjecten() as $dossier_subject) { $dossier_subject_ids[] = $dossier_subject->id; } $this->deelplansubject->set_for_deelplan( $deelplan_id, $dossier_subject_ids, array() ); } // Upon creating a new 'deelplan' we always automatically associate ALL documents with the deelplan. Do this by copying those of the // dossier to the deelplan. $this->load->model( 'deelplanbescheiden' ); $dossier_bescheiden_ids = array(); foreach($dossier->get_bescheiden( TRUE ) as $dossier_bescheiden) { $dossier_bescheiden_ids[] = $dossier_bescheiden->id; } $this->deelplanbescheiden->set_for_deelplan( $deelplan_id, $dossier_bescheiden_ids, array() ); redirect( '/deelplannen/bewerken/' . $deelplan_id . '/1' ); } else redirect( '/dossiers/bekijken/'. $dossier->id ); } } function bescheiden_verwijderen_batch( $dossier_id, $parent_map_id=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) echo "Interne fout."; else { $this->_check_dossier_security( $dossier ); $this->_check_dossierbescheidenmap_security( $parent_map_id ); $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); $ids = @json_decode( $_POST['ids'] ); if (is_array( $ids )) { foreach ($ids as $dossierbescheiden_id) { try { if (preg_match( '/^m(\d+)$/', $dossierbescheiden_id, $matches )) { $dossier_bescheiden_map_id = $matches[1]; if ($map = $this->dossierbescheidenmap->get( $dossier_bescheiden_map_id )) $map->delete(); } else { // check if dossier bescheiden exists, and if dossier belongs to us $dossierbescheiden = null; $dossier = null; $this->_check_dossierbescheiden_security( $dossierbescheiden_id, $dossierbescheiden, $dossier, true ); if ($dossier->get_access_to_dossier() != 'write') redirect( '/dossiers/bewerken/' . $dossier->id ); // delete it! $dossierbescheiden->delete(); } } catch (Exception $e) { // fail silently } } } $this->_load_bescheiden_lijst( $dossier, $parent_map_id ); } } function bescheiden_bewerken( $dossierbescheiden_id=null ) { // check if dossier bescheiden exists, and if dossier belongs to us $dossierbescheiden = null; $dossier = null; $this->_check_dossierbescheiden_security( $dossierbescheiden_id, $dossierbescheiden, $dossier ); if ($dossier->get_access_to_dossier() == 'write') { $this->_process_bescheiden_data( $dossierbescheiden, true ); } $this->load->model( 'dossierbescheidenmap' ); $this->load->view( 'dossiers/bewerken-bescheiden', array( 'open_tab_group' => 'bescheiden', 'dossier' => $dossier, 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $dossier->id, false, $dossierbescheiden->dossier_bescheiden_map_id ), 'mappen' => $this->dossierbescheidenmap->get_by_dossier( $dossier->id, $dossierbescheiden->dossier_bescheiden_map_id ), 'dossier_bescheiden_map_id' => $dossierbescheiden->dossier_bescheiden_map_id, ) ); } function bescheiden_toevoegen( $dossier_id=null, $parent_map_id=null, $return_data=false ) { // get dossier $this->load->model( 'dossier' ); $this->load->model( 'dossierbescheiden' ); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); else { $this->_check_dossierbescheidenmap_security( $parent_map_id ); try { // We now allow multiple file uploads. The 'bestand' part in the $_FILES array has therefore been set to multi-mode, meaning // that each of the individual array keys of it no longer point to a single value, but rather to an array of values (1 entry per file). // Loop handily over the array and store the files as required. // Note: the DB transaction could be moved to wrap around the entire 'for' loop, but as there is no real reason to let the whole transaction // fail if a single file fails, it has been left on the inside of the loop. $amount_of_uploaded_files = sizeof($_FILES['bestand']['name']); for ($file_idx = 0 ; $file_idx < $amount_of_uploaded_files ; $file_idx++) { $this->db->trans_start(); $dossierbescheiden = $this->dossierbescheiden->add( $dossier->id ); $bescheiden_ids[]=$dossierbescheiden->id; $dossierbescheiden->dossier_bescheiden_map_id = $parent_map_id ? $parent_map_id : null; // _process_bescheiden_data will save! //$this->_process_bescheiden_data( $dossierbescheiden, false ); $this->_process_bescheiden_data( $dossierbescheiden, false , null, null, $file_idx); if (!$this->db->trans_complete()) throw new Exception( tgng( 'php.database.transactie.fout' ) ); // Now proceed to add the document to all of the currently existing deelplannen too $this->load->model( 'deelplanbescheiden' ); $deelplannen = $dossier->get_deelplannen(); foreach ($deelplannen as $deelplan) { // First get the current bescheiden for the currently processed deelplan $deelplan_bescheiden = $this->deelplanbescheiden->get_by_deelplan( $deelplan->id ); // Then extract the IDs of the corresponding dossier (!) bescheiden IDs $deelplan_bescheiden_ids = array(); foreach($deelplan_bescheiden as $deelplan_document) { $deelplan_bescheiden_ids[] = $deelplan_document->dossier_bescheiden_id; } // Add the new ID and store it $deelplan_bescheiden_ids[] = $dossierbescheiden->id; $this->deelplanbescheiden->set_for_deelplan( $deelplan->id, $deelplan_bescheiden_ids, $deelplan_bescheiden ); } } } catch (Exception $e) { $this->db->_trans_status = false; $this->db->trans_complete(); die( tgng( 'php.dossiers.fout.bij.toevoegen.bescheiden' ) . ': ' . $e->getMessage() ); } if($return_data===true) return $bescheiden_ids; $this->_load_bescheiden_lijst( $dossier, $parent_map_id ); } } public function save_documenten($dossier_id=null, $deelplan_id=null, $vraag_id=null){ if($dossier_id){ $res = $this->bescheiden_toevoegen($dossier_id, '', true); $this->load->model("dossierbescheiden"); $this->load->model( 'deelplanvraagbescheiden' ); foreach ($res as $bescheiden_id){ $bescheiden_data[]=$this->dossierbescheiden->get_by_bescheiden($bescheiden_id); if($dossier_id && $deelplan_id && $vraag_id!="undefined"){ $this->deelplanvraagbescheiden->add( $deelplan_id, $vraag_id, $bescheiden_id); } } echo json_encode($bescheiden_data); } } private function _load_bescheiden_lijst( DossierResult $dossier, $parent_map_id=null ) { $this->load->model( 'dossierbescheiden' ); $this->load->model( 'dossierbescheidenmap' ); $this->_check_dossierbescheidenmap_security( $parent_map_id ); $this->load->view( 'dossiers/bewerken-bescheiden', array( 'open_tab_group' => 'bescheiden', 'dossier' => $dossier, 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $dossier->id, false, $parent_map_id ), 'mappen' => $this->dossierbescheidenmap->get_by_dossier( $dossier->id, $parent_map_id ), 'dossier_bescheiden_map_id' => $parent_map_id, ) ); } // This method can now handle both single and multi file uploads, one at a time. For single uploads, make sure to pass nothing or the value -1 in // the $multi_file_index parameter, for multi uploads, pass the proper array index, starting at 0. private function _process_bescheiden_data( $dossierbescheiden, $allow_no_upload, $contents=null, $bestandsnaam=null, $multi_file_index = -1 ) { CI_Base::get_instance()->load->library('utils'); if (is_null( $contents )) { // Single file uploads are handled slightly differently from multi uploads, as the individual array entries point to arrays instead // of single values for multi uploads. // Note: the below distinction could have been compacted, by doing individual checks only where it matters rather than mostly repeating the same // actions, but the downside is that it makes the code less readable and more error-prone. As the code is short enough it is therefore repeated // so as to obtain a better maintainable piece of code, even if it's at the cost of some repetition. if ($multi_file_index == -1) { // if the extension is Not allowed => DIE. if( isset( $_FILES['bestand'] ) && !CI_Utils::check_extension($_FILES['bestand']['name'], explode(', ', ALLOWED_EXTENSIONS)) ) { die(tgng('php.dossiers.fout.ext.not.allowed')); } // The file was uploaded in single file mode, process it accordingly else if(isset( $_FILES['bestand'] ) && !$_FILES['bestand']['error'] && $_FILES['bestand']['size']) { $contents = @file_get_contents( $_FILES['bestand']['tmp_name'] ); if ($contents) { $dossierbescheiden->bestandsnaam = $_FILES['bestand']['name']; $dossierbescheiden->bestand = $contents; $dossierbescheiden->png_status = 'onbekend'; } else { die( tgng( 'php.dossiers.fout.bij.verwerken.bescheiden' ) ); } } else if (!$allow_no_upload) { die( tgng( 'php.dossiers.fout.bij.uploaden.bescheiden' ) ); } } else { // if the extension is Not allowed => DIE. if( isset( $_FILES['bestand'] ) && !CI_Utils::check_extension($_FILES['bestand']['name'][$multi_file_index], explode(', ', ALLOWED_EXTENSIONS)) ) { die(tgng('php.dossiers.fout.ext.not.allowed')); } // The file was uploaded in multi file mode, process it accordingly elseif( isset( $_FILES['bestand'] ) && !$_FILES['bestand']['error'][$multi_file_index] && $_FILES['bestand']['size'][$multi_file_index]) { $contents = @file_get_contents( $_FILES['bestand']['tmp_name'][$multi_file_index] ); if ($contents) { $file_name= $_FILES['bestand']['name'][$multi_file_index]; $this->load->helper("transliteration"); $dossierbescheiden->bestandsnaam = convert_file_name($file_name); $dossierbescheiden->bestand = $contents; $dossierbescheiden->png_status = 'onbekend'; } else { die( tgng( 'php.dossiers.fout.bij.verwerken.bescheiden' ) ); } } else if (!$allow_no_upload) { die( tgng( 'php.dossiers.fout.bij.uploaden.bescheiden' ) ); } } } else { $dossierbescheiden->bestandsnaam = $bestandsnaam; $dossierbescheiden->bestand = $contents; $dossierbescheiden->png_status = 'onbekend'; } // This method can either be called from a 'bescheiden_bewerken' or 'bescheiden_toevoegen' call. In the former situation we allow the situation where the // 'opslaan' button was clicked without making changes, but for 'bescheiden_toevoegen' we do not allow this. These two situations need to be handled correctly. // This means that the base 'save' method needs to be told whether to fail or not if nothing has changed. In order to do this, we first check here if we are // creating a new bescheiden or editing an existing one by checking for the presence of a specific member that is only set for existing ones. $error_on_no_changes = (!isset($dossierbescheiden->laatste_bestands_wijziging_op)); $dossierbescheiden->tekening_stuk_nummer = $_POST['tekening_stuk_nummer']; $dossierbescheiden->auteur = $_POST['auteur']; $dossierbescheiden->omschrijving = (!empty($_POST['omschrijving'])) ? $_POST['omschrijving'] : $dossierbescheiden->bestandsnaam; $dossierbescheiden->zaaknummer_registratie = $_POST['zaaknummer_registratie']; $dossierbescheiden->versienummer = $_POST['versienummer']; $dossierbescheiden->datum_laatste_wijziging = $_POST['datum_laatste_wijziging']; $dossierbescheiden->laatste_bestands_wijziging_op = date('Y-m-d H:i:s'); return $dossierbescheiden->save(true, null, $error_on_no_changes); } function bescheiden_downloaden( $dossierbescheiden_id=null ) { $this->load->helper( 'pdf' ); // check if dossier bescheiden exists, and if dossier belongs to us $dossierbescheiden = null; $dossier = null; $this->_check_dossierbescheiden_security( $dossierbescheiden_id, $dossierbescheiden, $dossier ); if ($dossier->get_access_to_dossier() == 'none') redirect( '/dossiers/bekijken/' . $dossier->id ); // attempt to convert the PDF document to a 1.5 version! $dossierbescheiden->laad_inhoud(); $bescheiden_contents = null; /* * OJG (10-11-2015): The conversion to PDF 1.5 no longer seems to be necessary and is in fact sometimes causing trouble on the * production server as it can cause a high server load. It is therefore disabled for now, and can probably be entirely removed, * unless it turns out to be needed still for working around incompatibility issues somewhere. Time (and tests) will have to tell. * if (preg_match( '/\.pdf$/i', $dossierbescheiden->bestandsnaam )) { try { $bescheiden_contents = converteer_pdf_contents_naar_pdf15( $dossierbescheiden->bestand ); } catch (Exception $e) { // fail silently } } * */ if (is_null( $bescheiden_contents ) || strlen($bescheiden_contents) == 0) $bescheiden_contents = $dossierbescheiden->bestand; // handle it if (is_null( $dossierbescheiden->bestand )) redirect( '/dossiers/bewerken/' . $dossier->id ); else { $this->load->helper( 'user_download' ); user_download( $bescheiden_contents, $dossierbescheiden->bestandsnaam ); } } function bescheiden_popup( $dossierbescheiden_id=null, $dossier_id="" ) { if($dossier_id){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); $dossier_access = $dossier->get_access_to_dossier(); } if ($dossierbescheiden_id) { // check if dossier bescheiden exists, and if dossier belongs to us $dossierbescheiden = null; $dossier = null; $this->_check_dossierbescheiden_security( $dossierbescheiden_id, $dossierbescheiden, $dossier ); $dossier_access=$dossier->get_access_to_dossier(); if ($dossier->get_access_to_dossier() == 'none') die( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); } else $dossierbescheiden = null; // kijk of dit bescheiden slices heeft if ($dossierbescheiden) { $this->load->library( 'imageprocessor' ); $this->imageprocessor->id( $dossierbescheiden_id ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( 'original' ); $this->imageprocessor->page_number( 1 ); $num_slices = $this->imageprocessor->count_slices(); } else $num_slices = null; $this->load->view( 'dossiers/bescheiden_popup', array( 'bescheiden' => $dossierbescheiden, 'num_slices' => $num_slices, 'dossier_access' => $dossier_access, ) ); } function bescheiden_verplaatsen( $dossier_bescheiden_id=null, $parent_map_id=null ) { try { // check access for this user $this->load->model('dossierbescheiden'); $this->_check_dossierbescheiden_security( $dossier_bescheiden_id, $dossierbescheiden, $dossier, true ); $this->_check_dossierbescheidenmap_security( $parent_map_id ); // verplaats! $dossierbescheiden->dossier_bescheiden_map_id = $parent_map_id ? $parent_map_id : null; if (!$dossierbescheiden->save(0,0,0)) throw new Exception( tgng( 'php.database.interne.fout' ) ); echo json_encode(array( 'success' => true, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage(), )); } } function bescheiden_map_toevoegen( $dossier_id=null, $parent_map_id=null ) { try { // get dossier $this->load->model( 'dossier' ); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) throw new Exception( tgng( 'php.dossiers.ongeldig.dossier.id' ) ); // check access for this user $this->load->model('dossierbescheiden'); $this->_check_dossier_security( $dossier, true ); $this->_check_dossierbescheidenmap_security( $parent_map_id ); // check map naam $mapnaam = trim(strval(@$_POST['mapnaam'])); if (!strlen($mapnaam)) throw new Exception( tgng( 'php.dossiers.lege.mapnaam.niet.toegestaan' ) ); // check of map al bestaat $this->load->model( 'dossierbescheidenmap' ); foreach ($this->dossierbescheidenmap->get_by_dossier( $dossier_id, $parent_map_id ) as $map) if (strtolower( $map->naam ) == strtolower($mapnaam)) throw new Exception( tgng( 'php.dossiers.map.bestaat.reeds' ) ); // voeg map toe! try { $this->dossierbescheidenmap->add( $dossier, $mapnaam, $parent_map_id ); } catch (Exception $e) { throw new Exception( tgng( 'php.dossiers.fout.bij.toevoegen.map' ) . ': ' . $e->getMessage() ); } echo json_encode(array( 'success' => true, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage(), )); } } function bescheiden_lijst( $dossier_id=null, $parent_map_id=null ) { // get dossier $this->load->model( 'dossier' ); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { // check access for this user $this->load->model('dossierbescheiden'); $this->_check_dossier_security( $dossier ); $this->_check_dossierbescheidenmap_security( $parent_map_id ); // show bescheiden lijst! $this->_load_bescheiden_lijst( $dossier, $parent_map_id ); } } function subject_verwijderen( $dossier_id=null, $dossiersubject_id=null ) { // get dossier $this->load->model( 'dossier' ); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { // check access for this user $this->load->model('dossierbescheiden'); $this->_check_dossier_security( $dossier ); if ($dossier->get_access_to_dossier() == 'write') { // get & delete dossier $this->load->model( 'dossiersubject' ); $dossiersubject = $this->dossiersubject->get( $dossiersubject_id ); if ($dossiersubject && $dossiersubject->dossier_id = $dossier->id) { $dossiersubject->delete(); } } $this->load->view( 'dossiers/bewerken-betrokkenen', array( 'dossier' => $dossier, 'subjecten' => $this->dossiersubject->get_by_dossier( $dossier_id ), 'open_tab_group' => 'betrokkenen', 'dossier_access' => $dossier->get_access_to_dossier(), 'gebruikers' => $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ), ) ); } } public function subject_bewerken( $dossier_id=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { $this->_check_dossier_security( $dossier ); if ($dossier->get_access_to_dossier() != 'write') redirect( '/dossiers/bewerken/' . $dossier->id ); // Check if we are trying to add a new KID user, or edit an existing one. If a 'subject_id' is set in the POST data, we are editing and existing // one, in which case we do not get them again from KennisID, but rather allow edits to be made to the existing record. // If, OTOH, we are trying to add a new user, we must do the KennisID look-up. //if( $_POST['subject_organisatie_type'] == SUBJECT_KID_ORG ) if ( ($_POST['subject_organisatie_type'] == SUBJECT_KID_ORG) && empty($_POST['subject_id']) ) { $this->load->model('gebruiker'); $this->load->library('kennisid'); $passport = $this->kennisid->getPassportByEmail($_POST['subject_email']); if( !$passport->exists() ) { echo json_encode(array('msg' => tgn('ext_user_not_found'))); return; } $gebruiker = $this->db->query('Select id, klant_id, rol_id, volledige_naam, intern FROM gebruikers WHERE kennis_id_unique_id = "' . $passport->UniqueId . '"')->row(0); $organization = $this->kennisid->getOrganisationById($passport->OrganisationId); // Get the role ID of the 'external assingments' role, as we need to assign this to users who are newly created or who do exist but do not // yet have a role. $rol_id = $this->db->query('Select id FROM rollen WHERE naam = "' . ROL_ASSIGNMENTS_NAME . '"')->row(0)->id; if(!$gebruiker) { if( !($client = $this->klant->get_by_kennisid_unique_id($organization->UniqueId)) ) { $client = $this->klant->add($organization->Name, $organization->UniqueId); } $gebruiker = $this->gebruiker->add($client->id, $passport->getName(), $rol_id, $passport->UniqueId, $_POST['subject_email'], KENNIS_ID_USER_EXTERNAL); $client_name = $client->naam; } else { // We explicitly do NOT allow users from the same organisation as that of the dossier owner to be added, as those should be added as // internal users. Therefore, if we reach this point, check that the selected user does not belong to the same "klant" as that to which // the dossier owner belongs. //if( $gebruiker->intern == KENNIS_ID_USER_INTERNAL ) if( $gebruiker->klant_id == $dossier->get_gebruiker()->klant_id ) { echo json_encode(array('msg' => tgn('ext_user_already_exists'))); return; } $client_name = $this->db->query('Select naam FROM klanten WHERE id = ' . $gebruiker->klant_id)->row(0)->naam; // Check if the existing user already has a rol_id value set! In some test situations somehow some users were chosen for whom a // role had not yet been set. If we then assign such a user, give them an assignment, and they then log in, they (righteously so) // get an error message when trying to use the telephone interface, as they have no role in the system! // Therefore, if we encounter an existing user at this point, who does not yet have a role, we grant them the 'external assignments' role. if (is_null($gebruiker->rol_id) || empty($gebruiker->rol_id)) { // Get the existing user as a proper active record and set their role to that of the 'external assignments' user. $gebruiker = $this->gebruiker->get($gebruiker->id); $gebruiker->rol_id = $rol_id; $gebruiker->save(); } } $data_subject = array( 'rol' => ROL_ASSIGNMENTS_NAME, 'organisatie' => $client_name, 'naam' => $gebruiker->volledige_naam, 'adres' => $organization->Address, 'postcode' => $organization->Postcode, 'woonplaats' => $organization->City, 'email' => $_POST['subject_email'], 'telefoon' => $passport->getAnyPhone(), 'gebruiker_id' => $gebruiker->id, 'mobiel' => $_POST['subject_mobiel'] ); } // if ( ($_POST['subject_organisatie_type'] == SUBJECT_KID_ORG) && empty($_POST['subject_id']) ) else { // 'gebruiker_id' => isset($_POST['subject_gebruiker_id']) ? intval($_POST['subject_gebruiker_id']) : null $data_subject = array( 'rol' => $_POST['subject_rol'], 'organisatie' => $_POST['subject_organisatie'], 'naam' => $_POST['subject_naam'], 'adres' => $_POST['subject_adres'], 'postcode' => $_POST['subject_postcode'], 'woonplaats' => $_POST['subject_woonplaats'], 'email' => $_POST['subject_email'], 'telefoon' => $_POST['subject_telefoon'], 'mobiel' => $_POST['subject_mobiel'] //'gebruiker_id' => isset($_POST['subject_gebruiker_id']) ? intval($_POST['subject_gebruiker_id']) : null ); // A strange situation occurs when editing an existing KID user: the user ID of the first internal user then gets passed, causing an incorrect association! // Correct this by only setting the 'gebruiker_id' value if we are editing an internal user. if ($_POST['subject_organisatie_type'] == SUBJECT_INTERN_ORG) { $data_subject['gebruiker_id'] = isset($_POST['subject_gebruiker_id']) ? intval($_POST['subject_gebruiker_id']) : null; } } // else of clause: if( $_POST['subject_organisatie_type'] == SUBJECT_INTERN_ORG ) // Retrieve or add a subject $this->load->model( 'dossiersubject' ); if (intval( $_POST['subject_id'] )) { $subject = $this->dossiersubject->get( $_POST['subject_id'] ); } else { // When the above actions have resulted in a user, we check if a dossier subject already exists for that user and the currently processed // dossier. If so, do not allow an additional record to be created and return an error. Otherwise, continue. // Note that we could also decide to simply retrieve the existing subject and continue, but that may be confusing to the end user. $current_dossier_subjects = $this->dossiersubject->get_by_dossier( $dossier->id ); foreach ($current_dossier_subjects as $current_dossier_subject) { if ( isset($data_subject['gebruiker_id']) && ($current_dossier_subject->gebruiker_id == $data_subject['gebruiker_id']) ) { echo json_encode(array('msg' => tgn('dossier_subject_already_exists'))); return; } } // Add the subject to the dossier first $subject = $this->dossiersubject->add( $dossier->id, '' ); // When adding users of 'andere organisaties', due to the changes in the logic for selecting/editing a user, no gebruiker_id is set in // the data subject. For those situations, we correct that here (it can't be done before, or we'll overwrite correct values). if (!isset($data_subject['gebruiker_id'])) { //$data_subject['gebruiker_id'] = isset($_POST['subject_gebruiker_id']) ? intval($_POST['subject_gebruiker_id']) : null; } // Now proceed to add the subject to all of the currently existing deelplannen too $this->load->model( 'deelplansubject' ); $deelplannen = $dossier->get_deelplannen(); foreach ($deelplannen as $deelplan) { // First get the current subjecten for the currently processed deelplan $deelplan_subjecten = $this->deelplansubject->get_by_deelplan( $deelplan->id ); // Then extract the IDs of the corresponding dossier (!) subject IDs $deelplan_subject_ids = array(); foreach($deelplan_subjecten as $deelplan_subject) { $deelplan_subject_ids[] = $deelplan_subject->dossier_subject_id; } // Add the new ID and store it $deelplan_subject_ids[] = $subject->id; $this->deelplansubject->set_for_deelplan( $deelplan->id, $deelplan_subject_ids, $deelplan_subjecten ); } } // Override the values in the existing object and save the changes foreach($data_subject as $key => $value) { $subject->$key = $value; } $subject->save(); $this->load->view( 'dossiers/bewerken-betrokkenen', array( 'dossier' => $dossier, 'subjecten' => $this->dossiersubject->get_by_dossier($dossier_id), 'open_tab_group' => 'betrokkenen', 'dossier_access' => $dossier->get_access_to_dossier(), 'gebruikers' => $this->gebruiker->get_by_klant($this->session->userdata( 'kid' ), true), )); } } function verwijderen( $dossier_id=null, $confirm=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.verwijderen' ) ); else { try { $this->_check_dossier_security( $dossier, true ); } catch (Exception $e) { die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.verwijderen' ) ); } if ($dossier->get_afmelden_access_to_dossier() == 'none') die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.verwijderen' ) ); if ($confirm=='confirm') { if ($dossier->verwijder()) redirect( '/dossiers' ); else echo tgng( 'php.dossiers.database.fout.bij.verwijderen' ); } else { $this->load->view( 'dossiers/verwijderen', array( 'dossier' => $dossier, ) ); } } } function terugzetten( $dossier_id=null, $confirm=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.terugzetten' ) ); else { try { $this->_check_dossier_security( $dossier, true ); } catch (Exception $e) { die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.terugzetten' ) ); } if ($dossier->get_afmelden_access_to_dossier() == 'none') die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.terugzetten' ) ); if ($confirm=='confirm') { if ($dossier->zet_terug()) redirect( '/dossiers/bekijken/' . $dossier_id ); else echo tgng( 'php.dossiers.database.fout.bij.terugzetten' ); } else { $this->load->view( 'dossiers/terugzetten', array( 'dossier' => $dossier, ) ); } } } function archiveren( $dossier_id=null, $confirm=null ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.archiveren' ) ); else { try { $this->_check_dossier_security( $dossier ); } catch (Exception $e) { die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.archiveren' ) ); } if ($dossier->get_afmelden_access_to_dossier() == 'none') die( tgng( 'php.dossiers.u.kunt.dit.dossier.niet.archiveren' ) ); if ($confirm=='confirm') { if ($dossier->archiveer()) redirect( '/dossiers' ); else echo tgng( 'php.dossiers.database.fout.bij.archiveren' ); } else { $this->load->view( 'dossiers/archiveren', array( 'dossier' => $dossier, ) ); } } } function archiveren_multi( $dossier_ids=null, $mode='mijn', $page=0, $pagesize=10, $search='' ) { $this->load->model('dossier'); foreach (explode( ',', $dossier_ids ) as $dossier_id) { $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { $this->_check_dossier_security( $dossier ); if ($dossier->get_afmelden_access_to_dossier() == 'write') $dossier->archiveer(); } } // redirect properly if (!in_array( $mode, array( 'mijn', 'alle', 'archief' ))) $mode = 'mijn'; if (!is_int( $page )) $page = intval( $page ); if (!is_int( $pagesize )) $pagesize = intval( $pagesize ); $search = html_entity_decode( rawurldecode( $search ), ENT_QUOTES, 'UTF-8' ); redirect( '/dossiers/index/' . $mode . '/' . $page . '/' . $pagesize . '/' . $search ); } function _get_bescheiden_cache_jpg_filename( $bescheiden_id ) { return $this->_cache_path . '/bescheiden/' . $bescheiden_id . '.jpg'; } public function export( $dossier_id=null, $doc_type='standaard' ) { // no time limit, export might take a while! // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit( 3600); $this->load->library('dossierexport'); $this->load->model('dossier'); $this->load->model('dossierrapport'); $this->load->helper('user_download'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) redirect(); else { // check security $this->_check_dossier_security( $dossier ); if ($dossier->get_rapportage_access_to_dossier() == 'none') redirect( '/dossiers/bekijken/' . $dossier_id ); // genereer daadwerkelijke rapport //$doc_type = ($_POST['output_format'] == 'output_format:docx') ? 'docx' : 'standaard'; switch ($_POST['output_format']) { case 'output_format:docx': $doc_type = 'docx'; break; case 'output_format:docxpdf': $doc_type = 'docxpdf'; break; case 'output_format:pdf': default: $doc_type = 'standaard'; } $format = $doc_type == "docx" ? ".docx" : ".pdf"; // If a file with full-size annotation overviews exists before creating the report, delete it first. $annotaties_filename = "annotaties_full_size_{$dossier->id}.zip"; $annotaties_filename_complete = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $annotaties_filename; if (file_exists($annotaties_filename_complete)) { unlink($annotaties_filename_complete); } // Now generate the report $docdata = $this->dossierexport->export( $dossier, $doc_type, $_POST, $deelplan_objecten ); $file_name = $_POST['file_naam'] ? $_POST['file_naam'].$format : $docdata->get_filename(); // sla gegenereerde rapport op in rapporten database if ($_POST['target'] == 'target:email-custom') $target = $_POST['custom_email']; else $target = $_POST['target']; $this->dossierrapport->add( $dossier, $file_name, $docdata->get_contents(), $_POST, $doc_type, $target, $deelplan_objecten ); // If at this point in the code a file exists with annotation overviews, we can be reasonably certain that the file was generated for this run. We // then proceed to add it to the 'dossier rapporten' table. if (file_exists($annotaties_filename_complete)) { //user_download( file_get_contents($annotaties_filename_complete), $annotaties_filename, true, 'application/zip' ); $this->dossierrapport->add( $dossier, $annotaties_filename, file_get_contents($annotaties_filename_complete), $_POST, 'zip', $target, $deelplan_objecten ); } // before we output anything, clear all output buffers, so any PHP warnings // will automatically disappear! this is ugly, I know, but it's even more ugly // when people cannot download otherwise perfect PDF files... :/ while (ob_get_level()) ob_end_clean(); // local send email function $send_email = function( $email_address ) use ($docdata, $dossier) { $CI = get_instance(); $CI->load->library( 'simplemail' ); if ($CI->simplemail->send_with_attachments( /* subject */ tgn('email.subject', $dossier->kenmerk, $dossier->get_locatie()), /* text */ tgn('email.text', $dossier->kenmerk, $dossier->get_locatie()), /* recipients */ $email_address, /* cc */ array(), /* bcc */ array(), /* sender */ $CI->gebruiker->get_logged_in_gebruiker()->email, /* attachments */ array( /* attachment 1 */ array( 'type' => 'contents', 'contents' => $docdata->get_contents(), 'filename' => $file_name ), ) )) echo json_encode(array('success'=>true)); else echo json_encode(array('success'=>false)); }; switch (@$_POST['target']) { case 'target:download': // output download user_download( $docdata->get_contents(), $file_name, true, $docdata->get_contenttype() ); exit; case 'target:email-custom': $email_addresses = array( @$_POST['custom_email'] ); if (isset( $_POST['cc_self'] )) $email_addresses[] = $this->gebruiker->get_logged_in_gebruiker()->email; $send_email( $email_addresses ); break; default: $email_addresses = array( @$_POST['target'] ); if (isset( $_POST['cc_self'] )) $email_addresses[] = $this->gebruiker->get_logged_in_gebruiker()->email; $send_email( $email_addresses ); break; } } } public function rapportage( $dossier_id ) { $this->load->model('dossier'); $this->load->model('gebruiker'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); else { $this->_check_dossier_security( $dossier ); $this->load->library('dossierexport'); $this->load->view( 'dossiers/rapportage', array( 'dossier' => $dossier, 'subjecten' => $dossier->get_subjecten(), 'download_tag' => get_export_tag( 'dossierexport' ), 'gebruiker' => $this->gebruiker->get_logged_in_gebruiker() ) ); } } public function rapportage_geschiedenis( $dossier_id ) { $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' ) ); else { $this->_check_dossier_security( $dossier ); $this->load->model( 'dossierrapport' ); $this->load->view( 'dossiers/rapportage_geschiedenis', array( 'dossier' => $dossier, 'rapporten' => $this->dossierrapport->get_for_dossier( $dossier ), ) ); } } public function rapportage_geschiedenis_download( $dossier_rapport_id ) { $this->load->model('dossier'); $this->load->model('dossierrapport'); if (!($dossierrapport = $this->dossierrapport->get( $dossier_rapport_id ))) throw new Exception( tgng( 'php.dossiers.ongeldig.dossier.rapport.id' ) ); else { $dossier = $dossierrapport->get_dossier(); $this->_check_dossier_security( $dossier ); $this->load->helper( 'user_download' ); user_download($dossierrapport->getContent(), $dossierrapport->bestandsnaam); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Organisatiekenmerken //------------------------------------------------------------------------------ public function rapportage_organisatiekenmerken( $dossierId ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierId ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('org_kenmerken'); $org_kenmerken = $this->org_kenmerken->get_by_dossier( $dossier->id ); $this->load->view( 'dossiers/rapportage_organisatiekenmerken', array( 'dossier' => $dossier ,'org_kenmerken'=> $org_kenmerken ) ); } } //------------------------------------------------------------------------------ public function save_organisatiekenmerken( $dossierId=null ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierId ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('org_kenmerken'); $return = array(); $res = $this->org_kenmerken->save( $dossier, $_POST ); if(!(bool)$res){ $return['error'] = true; $return['success'] = false; }else{ $return['error'] = false; $return['success'] = true; $return['id'] = ( is_object($res)) ? $res->id : $_POST['id']; } echo json_encode($return); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // PAGO/PMO //------------------------------------------------------------------------------ public function rapportage_pago_pmo( $dossierId ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierId ); $this->load->model('pago_pmo'); $funcs = $this->pago_pmo->get_funcs( $dossier ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->view( 'dossiers/rapportage_pago_pmo', array( 'dossier' => $dossier ,'funcs' => $funcs ) ); } } //------------------------------------------------------------------------------ public function show_pago_pmo_form($dossierId, $recId=NULL ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierId ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('pago_pmo'); $func = $recId != NULL ? $this->pago_pmo->get_func_by_id( $recId ) : NULL; $this->load->view( 'dossiers/pago_pmo_form', array( 'dossier' => $dossier ,'func' => $func ) ); } } //------------------------------------------------------------------------------ public function save_pago_pmo( $dossier_id=null ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('pago_pmo'); $return = array(); $res = $this->pago_pmo->save( $dossier, $_POST ); if(!(bool)$res){ $return['error'] = true; $return['success'] = false; }else{ $return['error'] = false; $return['success'] = true; $return['id'] = ( is_object($res)) ? $res->id : $_POST['id']; } } echo json_encode($return); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // PBM //------------------------------------------------------------------------------ public function rapportage_pbm( $dossier_id ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('pbm'); $tasks = $this->pbm->get_tasks( $dossier ); foreach( $tasks as &$task ){ $count_risks = count($task->risks); $task->real_count_risks = $count_risks; if( !$count_risks ) $task->risks[] = new PbmRiskResult(array('id'=>'','risico_blootstelling'=>'','bronmaatregelen'=>'','pbm'=>'','w'=>'','b'=>'','e'=>'','r'=>'')); } $this->load->view( 'dossiers/rapportage_pbm', array( 'dossier' => $dossier ,'tasks' => $tasks ) ); } } //------------------------------------------------------------------------------ public function show_pbm_form($dossierId, $recId=NULL ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossierId ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('pbm'); $func = $recId != NULL ? $this->pbm->get_task_by_id( $recId ) : NULL; $this->load->view( 'dossiers/pbm_form', array( 'dossier' => $dossier ,'func' => $func ) ); } } //------------------------------------------------------------------------------ public function save_pbm( $dossier_id=null ){ $this->load->model('dossier'); $dossier = $this->dossier->get( $dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); else{ $this->_check_dossier_security( $dossier ); $this->load->model('pbm'); $res = $this->pbm->save( $dossier, $_POST ); $return = array(); if(!(bool)$res){ $return['error'] = true; $return['success'] = false; }else{ $return['error'] = false; $return['success'] = true; $return['id'] = ( is_object($res)) ? $res->id : $_POST['id']; } echo json_encode($return); } } //------------------------------------------------------------------------------ public function show_pbm_risk_form($taskId, $recId=NULL ){ $this->load->model('pbm'); $task = $this->pbm->get_task_by_id( $taskId ); $this->load->model('dossier'); $dossier = $this->dossier->get( $task->dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); $this->_check_dossier_security( $dossier ); if ($task==null) die('Task Not found'); $this->load->model('pbm_risk'); $risk = $recId != NULL ? $this->pbm_risk->get_risk_by_id( $recId ) : NULL; $this->load->view( 'dossiers/pbm_risk_form', array( 'dossier' => $dossier ,'task' => $task ,'risk' => $risk ) ); } //------------------------------------------------------------------------------ public function save_pbm_risk( $taskId ){ $this->load->model('pbm'); $task = $this->pbm->get_task_by_id( $taskId ); $this->load->model('dossier'); $dossier = $this->dossier->get( $task->dossier_id ); if ($dossier==null) die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); $this->_check_dossier_security( $dossier ); if ($task==null) die('Task Not found'); unset( $_POST['wxbxe_r'] ); $_POST['wxbxe_w'] = str_replace(",",".",$_POST['wxbxe_w']); $_POST['wxbxe_b'] = str_replace(",",".",$_POST['wxbxe_b']); $_POST['wxbxe_e'] = str_replace(",",".",$_POST['wxbxe_e']); $this->load->model('pbm_risk'); $res = $this->pbm_risk->save( $task, $_POST ); $return = array(); if(!(bool)$res){ $return['error'] = true; $return['success'] = false; }else{ $return['error'] = false; $return['success'] = true; $return['id'] = 100; $return['id'] = ( is_object($res)) ? $res->id : $_POST['id']; } echo json_encode($return); } //------------------------------------------------------------------------------ // Woningborg specific controller call: Gets the first (and only) deelplan and redirects to the 'project specifieke mapping' // for that public function project_specifieke_mapping( $dossierId ) { $this->load->model('dossier'); $dossier = $this->dossier->get($dossierId); if (is_null($dossier)) { die( tgng( 'php.dossiers.geen.toegang.tot.dossier' )); } $this->_check_dossier_security( $dossier ); // Get the deelplannen, and use the first of it. $deelplannen = $dossier->get_deelplannen(); if (empty($deelplannen) || is_null($deelplannen)) { die('Het dossier heeft geen deelplan en geen project specifieke mapping.'); } else { $deelplan = reset($deelplannen); redirect( '/deelplannen/project_specifieke_mapping/' . $deelplan->id ); } } }// Class end<file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Overzicht')) ?> <div style="border: 2px solid grey; border-radius: 25px; padding: 40px; background: #dddddd"> <div> <form name="gebruiks_overzicht" method="post"> <table> <tr> <td style="width: 15px; padding: 5px">Jaar: </td> <td style="padding: 5px"> <select id="year" name="year"> <? foreach( $years as $year ) { ?> <option <?= $selected_year == $year ? 'selected':'' ?> value="<?= $year ?>"> <?= $year ?> </option> <? } ?> </select> </td> </tr> <tr> <td style="width: 15px; padding: 5px">Organisatie: </td> <td style="padding: 5px"> <select id="client_id" name="client_id"> <? foreach( $clients as $client_id => $client_name ) { ?> <option <?= $selected_client == $client_id ? 'selected':'' ?> value="<?= $client_id ?>"> <?= utf8_encode($client_name) ?> </option> <? } ?> </select> </td> </tr> <tr> <td style="padding: 5px"><input type="submit" value="show results"></td> </tr> </table> </form> </div> <? if( $_POST && !empty($info) ) { $components = array_keys($info); $max = 0; $years_available = array(); $selected_year = $_POST['year']; list($current_year, $current_month) = explode('-', date('Y-m')); ?> <div> <table width="75%" border="1" style="margin-top: 30px"> <caption><b><?= $selected_year ?></b></caption> <tr> <th></th> <? foreach($months as $month) { ?> <th><?= ucfirst($month) ?></th> <? } ?> <th>Total</th> </tr> <? $months_index = array_keys($months); foreach($components as $component) { $total = 0; ?> <tr> <td align="center"><b><?= ucfirst($component) ?></b></td> <? foreach($months_index as $i) { $total_month = isset($info[$component][$selected_year][$i]) ? $info[$component][$selected_year][$i] : 0; $total+= $total_month; ?> <td align="center"><?= $total_month ?></td> <? } ?> <td align="center"><?= $total ?></td> </tr> <? } ?> </table> </div> <div> <? foreach($components as $component) { if( isset($info[$component][$selected_year]) ) unset($info[$component][$selected_year]); if( count($info[$component]) == 0 ) unset($info[$component]); } foreach($info as $key => $years) { ?> <table border="1" width="75%" style="margin-top: 30px;"> <caption><b><?= ucfirst($key) ?></b></caption> <tr> <th></th> <? foreach($months as $month) { ?> <th><?= ucfirst($month) ?></th> <? } ?> <th>Total</th> </tr> <? foreach($years as $year => $month) { $total = 0; ?> <tr> <td align="center"><?= '<b>'.($selected_year - $year).'º Birthday('.$year.')</b>' ?></td> <? foreach(array_keys($months) as $i) { $total_month = 0; if( isset($years[$year][$i]) && (($year != ($current_year - 1)) || $i <= $current_month) ) { $total_month = $years[$year][$i]; } $total+= $total_month; ?> <td align="center"><?= $total_month ?></td> <? } ?> <td align="center"><?= $total ?></td> </tr> <? } ?> </table> <? } ?> </div> <!-- <div>--> <!-- --><?// // foreach($info as $item => $year_array) { // $years_available+= array_keys($year_array); // } // foreach( $years_available as $year ) { ?> <!-- <table width="75%" border="1" style="margin-top: 30px">--> <!-- <caption><b>--><?//= $year ?><!--</b></caption>--> <!-- <tr>--> <!-- <th></th>--> <!-- --><?// foreach($months as $month) { ?> <!-- <th>--><?//= ucfirst($month) ?><!--</th>--> <!-- --><?// } ?> <!-- <th>Total</th>--> <!-- </tr>--> <!-- --><?// foreach($info as $key => $years) { // $total = 0; ?> <!-- <tr>--> <!-- <td align="center"><b>--><?//= ucfirst($key) ?><!--</b></td>--> <!-- --><?// foreach(array_keys($months) as $i) { // $total_month = isset($years[$year][$i]) ? $years[$year][$i] : 0; // $total+= $total_month; // ?> <!-- <td align="center">--><?//= $total_month ?><!--</td>--> <!-- --><?// } ?> <!-- <td align="center">--><?//= $total ?><!--</td>--> <!-- </tr>--> <!-- --><?// } ?> <!-- </table>--> <!-- --><?// } ?> <!-- --><?// } ?> <!-- </div>--> <? } ?> </div> <? $this->load->view('elements/footer') ?><file_sep><?php require_once('dossierbase.php'); class Tablet extends DossierBase { public function index( $mode=null, $search=null ) { // get dossier list $data = $this->_dossier_list( $mode, 0, 'alle', 'herkomst', 'asc', $search ); $data['skip_regular_header'] = true; $data['include_nokia_maps'] = true; // load view $this->load->view('tablet/index', $data ); } } <file_sep><? require_once 'base.php'; class DossierResult extends BaseResult { function DossierResult( &$arr ) { parent::BaseResult( 'dossier', $arr ); } function add_create_notificatie() { // voeg notificatie toe if (!($gebruiker = $this->_CI->gebruiker->get_logged_in_gebruiker())) $gebruiker = $this->get_gebruiker(); $this->_CI->notificatie->add_dossier_notificatie( $this->id, 'Dossier "' . $this->kenmerk . '" aangemaakt door ' . $gebruiker->volledige_naam ); } function verwijder() { $this->_CI->db->query( 'UPDATE dossiers SET verwijderd = 1 WHERE id = ' . intval( $this->id ) ); $this->_CI->notificatie->add_dossier_notificatie( $this->id, 'Dossier "' . $this->kenmerk . '" verwijderd', false /* niet klikbare notificatie */ ); return true; } function zet_terug() { $this->_CI->db->query( 'UPDATE dossiers SET verwijderd = 0, gearchiveerd = 0 WHERE id = ' . intval( $this->id ) ); $this->_CI->notificatie->add_dossier_notificatie( $this->id, 'Dossier "' . $this->kenmerk . '" teruggezet' ); return true; } function archiveer() { $this->_CI->db->query( 'UPDATE dossiers SET gearchiveerd = 1 WHERE id = ' . intval( $this->id ) ); $this->_CI->notificatie->add_dossier_notificatie( $this->id, 'Dossier "' . $this->kenmerk . '" gearchiveerd' ); return true; } // Returns either 'none', 'readonly' or 'write' function get_access_to_dossier() { $logged_in_user_id = $this->_CI->login->get_user_id(); $lees_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_LEZEN ); $schrijf_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_SCHRIJVEN ); // heeft de gebruiker geen recht om dossiers te lezen? if ($lees_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen dossier te lezen? dan geen toegang // als dit dossier niet van de ingelogde gebruiker is if ($lees_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $this->gebruiker_id) return 'none'; // heeft de gebruiker geen recht om dossiers te schrijven? dan op dit moment, alleen lezen if ($schrijf_recht == RECHT_MODUS_GEEN) return 'readonly'; // heeft de gebruiker recht om z'n eigen dossier te schrijven? dan readonly toegang // als dit dossier niet van de ingelogde gebruiker is if ($schrijf_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $this->gebruiker_id) return 'readonly'; // is het dossier gearchiveerd? dan readonly access if ($this->gearchiveerd) return 'readonly'; // gebruiker heeft schrijf recht op alle dossiers, of alleen op die van zichzelf // en dit dossier is van hem, dus schrijf rechten! return 'write'; } // Returns either 'none' or 'readonly' function get_rapportage_access_to_dossier() { $logged_in_user_id = $this->_CI->login->get_user_id(); $rapportage_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DEELPLAN_AFDRUKKEN ); // geen rapportage recht? dan geen rapportages mogen maken if ($rapportage_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen dossiers af te drukken? dan geen toegang // als dit dossier niet van de ingelogde gebruiker is if ($rapportage_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $this->gebruiker_id) return 'none'; // toegang! return 'readonly'; } // Returns either 'none' or 'write' function get_afmelden_access_to_dossier() { $logged_in_user_id = $this->_CI->login->get_user_id(); $afmeld_recht = $this->_CI->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_AFMELDEN ); // geen afmeld recht? dan geen afmelds mogen maken if ($afmeld_recht == RECHT_MODUS_GEEN) return 'none'; // heeft de gebruiker alleen recht om z'n eigen dossier af te melden? dan geen toegang // als dit dossier niet van de ingelogde gebruiker is if ($afmeld_recht == RECHT_MODUS_EIGEN && $logged_in_user_id != $this->gebruiker_id) return 'none'; // toegang! return 'write'; } //------------------------------------------------------------------------- // export //------------------------------------------------------------------------- function export( $doc_type, $filter_data=array() ) { $this->_CI->load->library( 'dossierexport' ); return $this->_CI->dossierexport->export( $this, $doc_type, $filter_data ); } //------------------------------------------------------------------------- // getters //------------------------------------------------------------------------- function get_omschrijving() { $str = ''; if ($this->beschrijving) $str .= (strlen($str)>0 ? ' ' : '') . $this->beschrijving; if (strlen($str)==0) $str = tgng('php.dossier_geen_omschrijving'); return htmlentities($str); } function get_gebruiker() { $this->_CI->load->model( 'gebruiker' ); return $this->_CI->gebruiker->get( $this->gebruiker_id ); } function get_geo_locatie() { if (!$this->geo_locatie_id) return null; if (!isset( $this->_CI->geolocatie )) $this->_CI->load->model( 'geolocatie' ); return $this->_CI->geolocatie->get( $this->geo_locatie_id ); } function get_aanmaak_datum() { return date( 'd-m-Y G:i', $this->aanmaak_datum ); } function get_kenmerk() { if ($this->kenmerk) return $this->kenmerk; else return '(geen kenmerk opgegeven)'; } function get_locatie( $when_empty_output_no_locatie=true ) { $str = ''; if ($this->locatie_adres) $str = $this->locatie_adres; if ($this->locatie_postcode) $str .= (strlen($str)>0 ? ', ' : '') . $this->locatie_postcode; if ($this->locatie_woonplaats) $str .= (strlen($str)>0 ? ', ' : '') . strtoupper( $this->locatie_woonplaats ); if (strlen($str)==0 && $when_empty_output_no_locatie) $str = '(geen locatie opgegeven)'; return htmlentities($str); } function get_kadastraal() { $str = ''; if ($this->locatie_kadastraal) $str = $this->locatie_kadastraal; if ($this->locatie_sectie) $str .= (strlen($str)>0 ? ', ' : '') . $this->locatie_sectie; if ($this->locatie_nummer) $str .= (strlen($str)>0 ? ', ' : '') . $this->locatie_nummer; if (strlen($str)==0) $str = '(geen kadastrale gegevens)'; return htmlentities($str); } public function get_deelplannen() { $this->_CI->load->model( 'deelplan' ); $this->_CI->dbex->prepare( 'get_deelplannen', 'SELECT * FROM ' . get_instance()->deelplan->get_table() . ' WHERE dossier_id = ? ORDER BY sortering' ); return $this->_CI->deelplan->convert_results( $this->_CI->dbex->execute( 'get_deelplannen', array( $this->id ) ) ); } public function get_deelplannen_voor_toezichthouder( $voor_toezichthouder_id ) { $this->_CI->load->model( 'deelplan' ); $this->_CI->dbex->prepare( 'get_deelplannen_voor_toezichthouder', ' SELECT de.* FROM ' . get_instance()->deelplan->get_table() . ' de JOIN deelplan_checklist_groepen dcg ON de.id = dcg.deelplan_id WHERE de.dossier_id = ? AND dcg.toezicht_gebruiker_id = ? ORDER BY de.sortering ' ); return $this->_CI->deelplan->convert_results( $this->_CI->dbex->execute( 'get_deelplannen_voor_toezichthouder', array( $this->id, $voor_toezichthouder_id ) ) ); } public function get_subjecten() { $this->_CI->load->model( 'dossiersubject' ); return $this->_CI->dossiersubject->get_by_dossier( $this->id ); } public function get_bescheiden( $isAll=FALSE ) { $this->_CI->load->model( 'dossierbescheiden' ); return $isAll ? $this->_CI->dossierbescheiden->db ->where('dossier_id', $this->id ) ->get( $this->_CI->dossierbescheiden->get_table() ) ->result() : $this->_CI->dossierbescheiden->get_by_dossier( $this->id ); } function get_foto() { $this->_CI->load->model( 'dossierfoto' ); $dossierFoto = $this->_CI->dossierfoto->get_one_by_dossier_with_content($this->id); return $dossierFoto; } public function set_all_bescheiden_for_all_deelplannen() { $this->_CI->load->model( 'dossierbescheiden' ); $this->_CI->load->model( 'deelplanbescheiden' ); // Now get the 'dossierbescheiden' for the dossier $dossierBescheidenen = $this->_CI->dossierbescheiden->get_by_dossier($this->id, true); $dossierBescheidenenIds = array_keys($dossierBescheidenen); //echo sizeof($dossierBescheidenen) . " bescheiden "; //d($dossierBescheidenen); //$dossierDeelplannen = $gebruikerDossier->get_deelplannen(); $dossierDeelplannen = $this->get_deelplannen(); //echo sizeof($dossierDeelplannen) . " deelplannen "; //d($dossierDeelplannen); //foreach($dossierDeelplannen AS $dpIdx => $dossierDeelplan) foreach($dossierDeelplannen AS $dossierDeelplan) { //echo "Deelplan met ID: '" . $dossierDeelplan->id . "'\n"; // Get the currently assigned documents for this deelplan $currentlyAssignedDeelplanBescheidenen = $this->_CI->deelplanbescheiden->get_by_deelplan($dossierDeelplan->id); //echo sizeof($currentlyAssignedDeelplanBescheidenen) . " deelplanbescheiden "; //d($currentlyAssignedDeelplanBescheidenen); // Now use the model to assign the proper set of documents to the deelplan. $this->_CI->deelplanbescheiden->set_for_deelplan($dossierDeelplan->id, $dossierBescheidenenIds, $currentlyAssignedDeelplanBescheidenen); } } // public function set_all_bescheiden_for_all_deelplannen() public function get_plannings_datum() { $res = $this->_CI->db->query( 'SELECT gepland_datum FROM dossiers WHERE dossier_id = ' . intval($this->id) ); $datum = $res->num_rows() ? $res->row_object()->gepland_datum : NULL; if ($datum) $datum = date( 'd-m-Y', strtotime( $datum ) ); $res->free_result(); return $datum; } } class Dossier extends BaseModel { function Dossier() { parent::BaseModel( 'DossierResult', 'dossiers' ); } public function check_access( BaseResult $object ) { $this->check_relayed_access( $object, 'gebruiker', 'gebruiker_id' ); } function add( $kenmerk, $beschrijving, $aanmaak_datum /* unix timestamp */, $locatie_adres, $locatie_postcode, $locatie_woonplaats, $locatie_kadastraal, $locatie_sectie, $locatie_nummer, $opmerkingen, $photo, $herkomst, $gebruiker_id=null,$bag_identificatie_nummer=null,$xy_coordinaten=null,$correspondentie_adres=null, $correspondentie_postcode=null,$correspondentie_plaats=null) { /* $this->dbex->prepare( 'dossier_toevoegen', 'INSERT INTO '.$this->_table.' '. '(gebruiker_id, kenmerk, beschrijving, aanmaak_datum, '. 'locatie_adres, locatie_postcode, locatie_woonplaats, locatie_kadastraal, locatie_sectie, locatie_nummer, opmerkingen, herkomst) '. 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ); $args = array( $gebruiker_id ? $gebruiker_id : $this->login->get_user_id(), $kenmerk, $beschrijving, $aanmaak_datum, $locatie_adres, $locatie_postcode, $locatie_woonplaats, $locatie_kadastraal, $locatie_sectie, $locatie_nummer, $opmerkingen, $photo, $herkomst, ); $this->dbex->execute( 'dossier_toevoegen', $args ); $id = $this->db->insert_id(); return $id; * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'gebruiker_id' => $gebruiker_id ? $gebruiker_id : $this->login->get_user_id(), 'kenmerk' => $kenmerk, 'beschrijving' => $beschrijving, 'aanmaak_datum' => $aanmaak_datum, 'locatie_adres' => $locatie_adres, 'locatie_postcode' => $locatie_postcode, 'locatie_woonplaats' => $locatie_woonplaats, 'locatie_kadastraal' => $locatie_kadastraal, 'locatie_sectie' => $locatie_sectie, 'locatie_nummer' => $locatie_nummer, 'opmerkingen' => $opmerkingen, //'foto' => $photo, 'herkomst' => $herkomst, 'bag_identificatie_nummer' => $bag_identificatie_nummer, 'xy_coordinaten' => $xy_coordinaten, 'correspondentie_adres' => $correspondentie_adres, 'correspondentie_postcode' => $correspondentie_postcode, 'correspondentie_plaats' => $correspondentie_plaats, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'ississsssscs' : ''; $result = $this->insert( $data, '', $force_types ); // If a dossier was successfully created and a photo was provided, store it if (!is_null($result) && !empty($result) && !is_null($photo) && !empty($photo)) { $this->_CI->load->model( 'dossierfoto' ); $dossierFoto = $this->_CI->dossierfoto->add($this->id); $dossierFoto->bestand = $photo; $dossierFoto->bestandsnaam = ''; $dossierFoto->save(); } //return $result; return $result->id; } function get_by_kenmerk( $kenmerk, $use_klant_id = null ) { $klant_id = (is_null($use_klant_id)) ? $this->gebruiker->get_logged_in_gebruiker()->klant_id : $use_klant_id; // !!! Note: Oracle: fix the 'LIMIT' part! $query = ' SELECT r.* FROM '.$this->_table.' r JOIN gebruikers g ON r.gebruiker_id = g.id WHERE r.kenmerk = ' . $this->db->escape( $kenmerk ) . ' AND g.klant_id = ' . intval($klant_id) . ' AND r.verwijderd = 0 LIMIT 1 '; $res = $this->db->query( $query ); if ($res->num_rows() > 0) $result = $this->getr( reset( $res->result() ) ); else $result = null; $res->free_result(); return $result; } private function get_search_subquery( $search ) { $conn = get_instance()->db; // !!! Query tentatively/partially made Oracle compatible. To be fully tested... $query = ' AND (0=1 '; // zoek dossier verantwoordelijke $query .= 'OR dossiers.gebruiker_id IN (SELECT id FROM gebruikers WHERE 0=1 '; $query .= 'OR volledige_naam LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ') '; // zoek dossier velden $query .= 'OR dossiers.beschrijving LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.kenmerk LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.opmerkingen LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_adres LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_postcode LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_woonplaats LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_kadastraal LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_sectie LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR dossiers.locatie_nummer LIKE \'%'. $conn->escape_str( $search ).'%\''; // zoek deelplan velden $query .= 'OR dossiers.id IN (SELECT DISTINCT(dossier_id) FROM deelplannen WHERE 0=1 '; $query .= 'OR naam LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR olo_nummer LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ') '; // zoek subject velden $query .= 'OR dossiers.id IN (SELECT DISTINCT(dossier_id) FROM dossier_subjecten WHERE 0=1 '; $query .= 'OR rol LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR naam LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR adres LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR postcode LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR woonplaats LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR telefoon LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= 'OR email LIKE \'%'. $conn->escape_str( $search ).'%\''; $query .= ') '; $query .= ' )'; return $query; } function get_by_gebruikers( $gebruiker_id=array(), &$size=null, $search=null, $gearchiveerd=null ) { if (empty($gebruiker_id)) $gebruiker_id = $this->login->get_user_id(); $this->db->select ( 'dossiers.*, b.gepland_datum' ); $this->db->join('dossier_planning b','dossiers.id = b.dossier_id','left'); $this->db->where ( 'verwijderd',0); $this->db->where ( 'gearchiveerd',intval($gearchiveerd)); $this->db->where ( 'gebruiker_id IN ('.implode(",", $gebruiker_id).')'); if (!empty( $search )) $this->db->where (substr($this->get_search_subquery( $search ),4)); $this->db->order_by('aanmaak_datum','desc'); $result=$this->db->get ( $this->_table )->result_array(); $size = count($result); foreach ($result as $row){ $row=(object)$row; $result[] = $this->getr( $row );} return $result; } function get_by_gebruiker( $gebruiker_id=false, &$size=null, $search=null, $gearchiveerd=null ) { if ($gebruiker_id===FALSE) $gebruiker_id = $this->login->get_user_id(); $query = 'SELECT dossiers.*, b.gepland_datum FROM '.$this->_table.' LEFT JOIN dossier_planning b ON dossiers.id = b.dossier_id WHERE verwijderd = 0 AND gebruiker_id = ' . $gebruiker_id; $query .= ' AND gearchiveerd = ' . intval($gearchiveerd) . ' '; if (!empty( $search )) $query .= $this->get_search_subquery( $search ); $query .= ' ORDER BY aanmaak_datum DESC'; $res = $this->db->query( $query ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $size = $res->num_rows(); $res->free_result(); return $result; } function get_van_collegas( $gebruiker_id=false, &$size=null, $all=false, $search=null, $gearchiveerd=null ) { if ($gebruiker_id===FALSE) $gebruiker_id = $this->login->get_user_id(); else if (!is_numeric($gebruiker_id)) return array(); $query = ' SELECT dossiers.*, b.gepland_datum FROM dossiers LEFT JOIN dossier_planning b ON dossiers.id = b.dossier_id WHERE verwijderd = 0 AND (gebruiker_id IN (SELECT gebruiker2_id FROM gebruiker_collegas WHERE gebruiker1_id = %d) OR gebruiker_id IN (SELECT id FROM gebruikers WHERE klant_id = %d AND speciale_functie = \'nog niet toegekend\')) '; $query .= ' AND gearchiveerd = ' . intval($gearchiveerd) . ' '; if (!is_null( $search )) $query .= str_replace( '%', '%%', $this->get_search_subquery( $search ) ); $q = sprintf($query, $gebruiker_id, $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $q .= 'ORDER BY aanmaak_datum DESC'; $res = $this->db->query( $q ); $result = array(); foreach ($res->result() as $row) $result[ $row->id ] = $this->getr( $row ); $size = $res->num_rows(); $res->free_result(); return $result; } function get_dossiers_by_klant( $gebruiker_id=false, &$size=null, $all=false, $search=null, $gearchiveerd=null){ if ($gebruiker_id===FALSE) $gebruiker_id = $this->login->get_user_id(); $klant = $this->_CI->klant->get_logged_in_klant(); $query = 'SELECT dossiers.*, b.gepland_datum FROM '.$this->_table.' LEFT JOIN dossier_planning b ON dossiers.id = b.dossier_id LEFT JOIN gebruikers gg on dossiers.gebruiker_id=gg.id WHERE verwijderd = 0 AND gg.klant_id = ' . $klant->id; $query .= ' AND gearchiveerd = ' . intval($gearchiveerd) . ' '; if (!empty( $search )) $query .= $this->get_search_subquery( $search ); $query .= ' ORDER BY aanmaak_datum DESC'; $res = $this->db->query( $query ); $result = array(); foreach ($res->result() as $row) $result[] = $this->getr( $row ); $size = $res->num_rows(); $res->free_result(); return $result; } function get_by_herkomst( $herkomst ) { return $this->search( array( 'herkomst' => $herkomst ) ); } public function save( $object, $do_transaction=true, $alias=null, $error_on_no_changes=true ) { $gd = @$object->gepland_datum; unset( $object->gepland_datum ); $res = parent::save( $object, $do_transaction, $alias, $error_on_no_changes ); $object->gepland_datum = $gd; return $res; } public function get_dossiers_by_toezichthouder( $search=null, $archief=false, $gebruiker_id=null ) { if (!$gebruiker_id) $gebruiker_id = $this->login->get_user_id(); $klant = $this->_CI->klant->get_logged_in_klant(); $stmt_name = 'get_dossiers_by_toezichthouder'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT dossiers.*, p.gepland_datum FROM dossiers LEFT JOIN dossier_planning p ON dossiers.id = p.dossier_id WHERE dossiers.id IN ( SELECT * from ( ( SELECT dossiers.id FROM dossiers LEFT JOIN deelplannen de ON dossiers.id = de.dossier_id LEFT JOIN deelplan_checklisten dc ON de.id = dc.deelplan_id LEFT JOIN bt_checklisten bc ON dc.checklist_id = bc.id LEFT JOIN bt_checklist_groepen bcg ON bc.checklist_groep_id = bcg.id WHERE bcg.modus="niet-combineerbaar" AND (dc.toezicht_gebruiker_id=? OR dc.toezicht_gebruiker_id IS NULL) AND (SELECT `klant_id` FROM `gebruikers` WHERE `gebruikers`.`id`= `dossiers`.`gebruiker_id` LIMIT 1)=? AND dossiers.gearchiveerd = ? AND verwijderd = 0'.(is_null( $search ) ? '' : $this->get_search_subquery( $search )).' ) UNION ( SELECT dossiers.id FROM dossiers LEFT JOIN deelplannen de ON dossiers.id = de.dossier_id LEFT JOIN deelplan_checklist_groepen dcg ON de.id = dcg.deelplan_id LEFT JOIN bt_checklist_groepen bcg ON dcg.checklist_groep_id = bcg.id WHERE (bcg.modus="combineerbaar-op-checklist" OR bcg.modus="combineerbaar") AND (dcg.toezicht_gebruiker_id=? OR dcg.toezicht_gebruiker_id IS NULL) AND (SELECT `klant_id` FROM `gebruikers` WHERE `gebruikers`.`id`= `dossiers`.`gebruiker_id` LIMIT 1)=? AND dossiers.gearchiveerd = ? AND verwijderd = 0'.(is_null( $search ) ? '' : $this->get_search_subquery( $search )).' ) ) AS t )' ); $result = $this->convert_results( $this->_CI->dbex->execute( $stmt_name, array( $gebruiker_id, $klant->id, $archief ? 1 : 0, $gebruiker_id, $klant->id, $archief ? 1 : 0 ) ) ); return $result; } } <file_sep>INSERT INTO `webservice_components` (`id` ,`naam`) VALUES (NULL , 'Klanten koppeling'); <file_sep>UPDATE bt_checklist_groepen SET standaard_waardeoordeel_tekst_00 = 'Geen waardeoordeel', standaard_waardeoordeel_tekst_01 = 'Niet van toepassing', standaard_waardeoordeel_tekst_02 = 'Nader onderzoek nodig', standaard_waardeoordeel_tekst_03 = 'Niet kunnen controleren', standaard_waardeoordeel_tekst_04 = 'Niet gecontroleerd', standaard_waardeoordeel_tekst_10 = 'Voldoet', standaard_waardeoordeel_tekst_11 = 'Bouwdeel voldoet', standaard_waardeoordeel_tekst_12 = 'Gelijkwaardigheid', standaard_waardeoordeel_tekst_13 = 'Na aanwijzingen toezichthouder', standaard_waardeoordeel_tekst_20 = 'Voldoet niet', standaard_waardeoordeel_tekst_21 = 'Voldoet niet (niet zwaar)', standaard_waardeoordeel_kleur_00 = 'oranje', standaard_waardeoordeel_kleur_01 = 'groen', standaard_waardeoordeel_kleur_02 = 'oranje', standaard_waardeoordeel_kleur_03 = 'groen', standaard_waardeoordeel_kleur_04 = 'groen', standaard_waardeoordeel_kleur_10 = 'groen', standaard_waardeoordeel_kleur_11 = 'oranje', standaard_waardeoordeel_kleur_12 = 'groen', standaard_waardeoordeel_kleur_13 = 'groen', standaard_waardeoordeel_kleur_20 = 'rood', standaard_waardeoordeel_kleur_21 = 'groen', standaard_waardeoordeel_is_leeg_00 = 1, standaard_waardeoordeel_is_leeg_01 = 0, standaard_waardeoordeel_is_leeg_02 = 0, standaard_waardeoordeel_is_leeg_03 = 0, standaard_waardeoordeel_is_leeg_04 = 0, standaard_waardeoordeel_is_leeg_10 = 0, standaard_waardeoordeel_is_leeg_11 = 0, standaard_waardeoordeel_is_leeg_12 = 0, standaard_waardeoordeel_is_leeg_13 = 0, standaard_waardeoordeel_is_leeg_20 = 0, standaard_waardeoordeel_is_leeg_21 = 0, standaard_aanwezigheid = 31, standaard_waardeoordeel_standaard = '00', standaard_waardeoordeel_steekproef = '04', standaard_waardeoordeel_steekproef_tekst = 'Niet gecontroleerd ivm steekproef', standaard_toezicht_moment = 'Algemeen', standaard_fase = 'Algemeen' ; <file_sep><? $this->load->view('elements/header', array('page_header'=>'deelplannen')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'CSV bestandsinformatie', 'width' => '900px' )); ?> <ul> <li>Het te importeren CSV bestand dient <b>ELF</b> kolommen te bevatten.</li> <li>De kolom volgorde is als volgend: <ul> <li><b>A</b> Identificatienummer</li> <li><b>B</b> Opmerking code</li> <li><b>C</b> Locatie adres</li> <li><b>D</b> Locatie postcode</li> <li><b>E</b> Locatie woonplaats</li> <li><b>F</b> Dossiernaam</li> <li><b>G</b> Aanmaakdatum</li> <li><b>H</b> Geplande datum</li> <li><b>I</b> Opmerking 2e regel</li> <li><b>J</b> Dossierverantwoordelijke</li> <li><b>K</b> Stop kolom</li> </ul> </li> <li>De eerste regel is een header regel en wordt altijd overgeslagen, de kolom headers in de eerste regel worden dus nergens voor gebruikt!</li> <li>Het datum formaat is niet vastgelegd, maar het best kan worden gebruikt: dd-mm-yyyy, of yyyy/mm/dd.</li> <li>De stopkolom (K) dient enkel om het einde van de regel te markeren. Deze dient te allen tijde de tekst 'STOP' te bevatten.</li> <li>De waarde in de Opmerking code kolom (B) moet een 3-cijferige code zijn uit onderstaande tabel. De code wordt omgezet naar de bijbehorende omschrijving, die als eerste regel van de opmerkingen zal worden gebruikt. De laatste kolom (I) wordt als tweede regel in het opmerkingen veld gebruikt. <ul> <li>100: Omgevingsvergunning regulier</li> <li>110: Lichte bouwvergunning</li> <li>120: Reguliere bouwvergunning</li> <li>130: 1e fase bouwvergunning</li> <li>131: 2de fase bouwvergunning</li> <li>132: Herziening 1e fase</li> <li>200: Omgevingsvergunning uitgebreid</li> <li>300: Sloopvergunning</li> <li>400: Sloopmelding</li> <li>500: Gemeentelijk monument</li> <li>510: Rijksmonument</li> <li>600: Overige vergunningen</li> <li>900: Handhaving</li> </ul> </li> <li>Wanneer een onbekende Opmerking code wordt gebruikt, wordt niks ingevoerd op de eerste regel van de opmerkingen!</li> <li>Wanneer geen (of een onbekende) waarde wordt ingevuld als dossierverantwoordelijke, wordt het dossier toegekend aan de persoon die de import uitvoert.</li> </ul> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Nu importeren', 'width' => '900px' )); ?> <form method="POST" enctype="multipart/form-data"> <table style="width:auto"> <tr> <th style="text-align:left">CSV bestand:</th> <td><input type="file" name="csv" /></td> </tr> <tr> <th style="text-align:left"></th> <td><input type="submit" value="Importeren!" /></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep>CREATE TABLE IF NOT EXISTS `deelplan_opdrachten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deelplan_id` int(11) NOT NULL, `vraag_id` int(11) NOT NULL, `dossier_subject_id` int(11) NOT NULL, `dossier_bescheiden_id` int(11) DEFAULT NULL, `opdracht_omschrijving` text NOT NULL, `gereed_datum` date NOT NULL, `status` enum('nieuw','gereed') NOT NULL DEFAULT 'nieuw', `email_verzonden` tinyint(4) NOT NULL DEFAULT '0', `overzicht_afbeelding` longblob, `snapshot_afbeelding` longblob, `annotatie_tag` char(40) DEFAULT NULL, PRIMARY KEY (`id`), KEY `deelplan_id` (`deelplan_id`), KEY `vraag_id` (`vraag_id`), KEY `dossier_subject_id` (`dossier_subject_id`), KEY `dossier_bescheiden_id` (`dossier_bescheiden_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `deelplan_opdrachten` ADD CONSTRAINT `deelplan_opdrachten_ibfk_1` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_opdrachten_ibfk_2` FOREIGN KEY (`vraag_id`) REFERENCES `bt_vragen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_opdrachten_ibfk_3` FOREIGN KEY (`dossier_subject_id`) REFERENCES `dossier_subjecten` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `deelplan_opdrachten_ibfk_4` FOREIGN KEY (`dossier_bescheiden_id`) REFERENCES `dossier_bescheiden` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><script type="text/javascript"> function annuleren( ref ) { closePopup( ref ); } function opslaan( btn ) { var postdata = BRISToezicht.Toets.Form.getFormPostData( $(btn).parents( '.popupdata' ) ); $.ajax({ url: '/beheer/matrix_toevoegen/<?=$checklistgroep->id?>', type: 'POST', data: postdata, dataType: 'json', success: function( data, jqXHR, textStatus ) { if (data.matrix) { var select = $( 'select[name=matrix\\[<?=$checklistgroep->id?>\\]]' ); if (select.size() > 0) { // make & configure option DOM node var option = document.createElement( 'option' ); option.value = data.matrix.id; option.innerHTML = data.matrix.naam; // append it select[0].appendChild( option ); // select new matrix select[0].value = data.matrix.id; // and close popup! annuleren(); // trigger change handler, if any is set $(select).trigger('change'); } } else alert( data.errors ); }, error: function() { alert( 'Fout bij communicatie met server.' ); } }); } </script> <table width="100%" cellspacing="0" cellpadding="5" class="popupdata"> <tr> <td colspan="2"><h2><?=htmlentities( $checklistgroep->naam, ENT_COMPAT, 'UTF-8' )?> - Nieuwe matrix toevoegen</h2></td> </tr> <tr> <td>Naam:</td> <td><input type="text" name="naam" size="40" maxlength="128" value="<?=htmlentities($naam, ENT_COMPAT, 'UTF-8')?>"></td> </tr> <tr> <td>Baseer op matrix:</td> <td> <select name="matrix_id"> <? foreach ($matrices as $matrix): ?> <option <?=$matrix->id == $baseer_op ? 'selected' : ''?> value="<?=$matrix->id?>"> <?=htmlentities( $matrix->naam, ENT_COMPAT, 'UTF-8' )?> (<?=htmlentities( $matrix->get_klant()->naam, ENT_COMPAT, 'UTF-8' )?>) </option> <? endforeach; ?> </select> </td> </tr> <tr> <td id="form" colspan="2"> <input type="button" onclick="opslaan(this);" value="<?=tgng('form.opslaan')?>" /> <input type="button" onclick="annuleren();" value="<?=tgng('form.annuleren')?>" /> </td> </tr> </table> <file_sep><? require_once 'base.php'; class WebserviceApplicatieDeelplanResult extends BaseResult { function WebserviceApplicatieDeelplanResult( &$arr ) { parent::BaseResult( 'webserviceapplicatiedeelplan', $arr ); } } class WebserviceApplicatieDeelplan extends BaseModel { function WebserviceApplicatieDeelplan() { parent::BaseModel( 'WebserviceApplicatieDeelplanResult', 'webservice_applicatie_dlplnnn', true ); } function get_for_webapplicatie_id( $webapplicatie_id ) { $stmt_name = 'WebserviceApplicatieDeelplan::get_for_webapplicatie_id'; $result = array(); $CI = get_instance(); $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE webservice_applicatie_id = ?' ); foreach ($this->convert_results( $CI->dbex->execute( $stmt_name, array( $webapplicatie_id ) ) ) as $wad) $result[ $wad->deelplan_id ] = $wad; return $result; } function zet( $webservice_applicatie_id, $deelplan_id, $laatst_bijgewerk_op ) { $stmt_name = 'webserviceapplicatiedeelplan::zet'; $CI = get_instance(); //$CI->dbex->prepare( $stmt_name, $q = 'REPLACE INTO webservice_applicatie_dlplnnn (webservice_applicatie_id, deelplan_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)' ); $CI->dbex->prepare_replace_into( $stmt_name, $q = 'REPLACE INTO webservice_applicatie_dlplnnn (webservice_applicatie_id, deelplan_id, laatst_bijgewerkt_op) VALUES (?, ?, ?)', null, array('id') ); return $CI->dbex->execute( $stmt_name, array( $webservice_applicatie_id, $deelplan_id, $laatst_bijgewerk_op ) ); } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Sessie statistieken')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Sessie statistieken', 'width' => '920px' ) ); ?> <table width="900" cellpadding="0" cellspacing="0"> <tr> <th align="left">Gebruiker</th> <th align="left">Klant</th> <th align="left">Aantal</th> <th align="left">Laatste login</th> </tr> <? foreach ($data as $stat): ?> <tr> <td><?=$stat->volledige_naam?> (<?=$stat->gebruikersnaam?>)</td> <td><?=$stat->klant_naam?></td> <td><?=$stat->aantal?></td> <td><?=date("d-m-Y G:i:s", $stat->laatste_inlog)?></td> </tr> <? endforeach; ?> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>PDFAnnotator.Server.PDFAnnotatorBTZ = PDFAnnotator.Server.extend({ getBaseUrl: function() { return '/files/pdf-annotator/'; }, getLineImageUrl: function( size, up, color ) { return '/files/pdf-annotator/images/line/cache/' + parseInt(color.substr( 0, 2 ),16) + '-' + parseInt(color.substr( 2, 2 ),16) + '-' + parseInt(color.substr( 4, 2 ),16) + '-' + size + (up ? 'up' : 'down') + '.gif'; }, getDrawingOperationUrl: function( pagenr, operation ) { return '/pdfannotator/image_tools/' + pagenr + '/' + operation; }, downloadAnnotatedDocument: function( engine, layers, pageTransform, dimensions ) { if (!confirm( 'De momenteel zichtbare layers vastleggen in een nieuw bescheiden?' )) return; var vragen = []; layersData = []; for (var i=0; i<layers.length; ++i) { layersData.push( layers[i].rawExport() ); if (layers[i].getVisibility()) { var vraag_id = layers[i].getMetaData( 'referenceId' ); if (vraag_id) vragen.push( vraag_id ); } } var btz = this.getBTZ(); if (btz) { if (btz.Toets && btz.Toets.Form) { var bescheidenId = engine.getMetaData( 'document_id' ); if (bescheidenId) { var guid = engine.getMetaData( 'guid' ); if (guid) { var data = { _command: 'layertoevoegen', layers: JSON.stringify( layersData ), pagetransform: JSON.stringify( pageTransform ), dimensions: JSON.stringify( dimensions ), bescheiden_id: bescheidenId, vragen: JSON.stringify( vragen ), guid: guid }; btz.Toets.Form.addStoreOnceData( JSON.stringify( data ) ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.downloadAnnotatedDocument: geen guid in engine meta data, kan niets opslaan.' ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.downloadAnnotatedDocument: geen document id in engine meta data, kan niets opslaan.' ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.downloadAnnotatedDocument: een van de btz onderdelen is niet beschikbaar' ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.downloadAnnotatedDocument: BTZ is niet beschikbaar in parent window' ); }, loadAnnotations: function( engine, onsuccess, onerror ) { if (!(engine instanceof PDFAnnotator.Engine)) throw 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: layer is geen PDFAnnotator.Layer object'; var btz = this.getBTZ(); if (btz) { if (btz.Toets && btz.Toets.data && btz.Toets.data.layerdata) { var bescheidenId = engine.getMetaData( 'document_id' ); if (bescheidenId) { bescheidenId = parseInt( engine.getMetaData( 'document_id' ) ); if (typeof( btz.Toets.data.layerdata[bescheidenId] ) != 'undefined') { // handle layers var layerArray = btz.Toets.data.layerdata[bescheidenId].layers; if (layerArray.length) { engine.removeAllLayers(); for (var i=0; i<layerArray.length; ++i) PDFAnnotator.Layer.prototype.rawImport( engine, layerArray[i] ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: layer array leeg voor ' + bescheidenId ); // handle page transform var pageTransform = $.extend( {}, btz.Toets.data.layerdata[bescheidenId].pagetransform ); // copy! pageTransform.initial = true; // required for first call! engine.setPageTransform( pageTransform ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: geen layer data voor document ' + bescheidenId ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: geen document id in engine meta data, kan niets laden.' ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: een van de btz onderdelen is niet beschikbaar' ); } else this.log( 'PDFAnnotator.Server.PDFAnnotator.loadAnnotations: BTZ is niet beschikbaar in parent window' ); if (onsuccess) onsuccess(); }, getAvailableLayerReferenceObjects: function( onsuccess, onerror ) { var result = []; // our parent frame must be BTZ var btz = this.getBTZ(); if (btz) { var onderwerpen = btz.Toets.data.onderwerpen; for (var i in onderwerpen) { var o = onderwerpen[i]; var onderwerp = { subject: o.naam, references: [] }; for (var j in o.vragen) { var v = o.vragen[j]; var filter; var waarde = BRISToezicht.Toets.Vraag.getStatusVoorVraag( v ).waarde; switch (waarde) { case 1: filter = 'rood'; break; case 10: filter = 'geel'; break; case 1000: filter = 'groen'; break; default: filter = 'none'; break; } onderwerp.references.push( new PDFAnnotator.Server.BTZVraag( v.vraag_id, v.tekst, filter ) ); } if (onderwerp.references.length) result.push( onderwerp ); } } // send back result onsuccess( result ); }, mayAddPhoto: function( layer ) { if (!layer) return false; if (!layer.getMetaData( 'referenceId' )) { alert( 'De huidige laag is niet gekoppeld aan een vraag, u kunt daarom geen foto toevoegen.' ); return false; } return true; }, handleFormUpload: function( form, uploadinput, editable ) { var btz = this.getBTZ(); if (!btz) { this.log( 'PDFAnnotator.Server.PDFAnnotatorBTZ.handleFormUpload: geen BTZ gevonden, kan upload niet afhandelen' ); return; } // haal vraag op waar deze upload voor is var vraag_id = editable.container.layer.getMetaData( 'referenceId' ); var onderwerp_id = btz.Toets.Vraag.findOnderwerpIdByVraagId( vraag_id ); // add hidden input elements to form $('<input>').attr( 'type', 'hidden' ).appendTo( $(form) ).attr( 'name', 'filename' ).attr( 'value', editable.getPhotoFilename() ); $('<input>').attr( 'type', 'hidden' ).appendTo( $(form) ).attr( 'name', 'vraag_id' ).attr( 'value', vraag_id ); $('<input>').attr( 'type', 'hidden' ).appendTo( $(form) ).attr( 'name', 'deelplan_id' ).attr( 'value', btz.Toets.data.deelplan_id ); uploadinput.attr( 'action', '/pdfannotator/store_photo' ); /* file upload system will set this action into form */ uploadinput.attr( 'vraag_ids', vraag_id ); /* used by upload system to attach to proper vraag client-side */ uploadinput.attr( 'onderwerp_id', onderwerp_id ); /* used by upload system to attach to proper vraag client-side */ form.attr( 'name', 'form' ); /* form must have name 'form' */ // add form to BTZ to be submitted btz.Toets.Form.registerExternalUpload( uploadinput ); }, getWindowProportions: function() { var container = $('#nlaf_PDFAnnotator'); return { width: parseInt(container.width()), height: parseInt(container.height()), top: parseInt($('#nlaf_Header').height()) + parseInt($('#nlaf_GreenBar').height()), left: 0, scrollLeft: parseInt(container.scrollLeft()), scrollTop: parseInt(container.scrollTop()), scrollX: Math.max( 0, -50 + parseInt(container.scrollLeft()) ), scrollY: Math.max( 0, -50 + parseInt(container.scrollTop()) ) }; }, /* private */ getBTZ: function() { return (window && window.BRISToezicht) ? window.BRISToezicht : null; /* no longer in iframe, use window variable */ } }); <file_sep><?php class Deelplannen extends Controller { function Deelplannen() { parent::Controller(); error_reporting( E_ALL & ~(E_DEPRECATED) ); $this->load->model( 'checklist' ); $this->navigation->push( 'nav.dossierbeheer', '/dossiers' ); $this->navigation->set_active_tab( 'dossierbeheer' ); } private function _check_deelplan_security( $deelplan, $throw_exception=false ) { $dossier = $deelplan->get_dossier(); $group_users=array(); if($this->rechten->geef_recht_modus( RECHT_TYPE_DOSSIER_LEZEN )==RECHT_GROUP_ONLY){ $this->load->model( 'gebruiker' ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $my_group_users=cut_array($gebruiker->groups_users, "user_id"); $group_users=$this->dossier->get_by_gebruikers($my_group_users, $size, null ); } if ($dossier) $this->navigation->push( 'nav.dossier_bekijken', '/dossiers/bekijken/' . $dossier->id, array( $dossier->get_omschrijving() ) ); // fetch planning datum $this->load->library( 'planningdata' ); $dossier_planning = $this->planningdata->get_dossier_planning(); $dossier->gepland_datum = @$dossier_planning[$dossier->id]; // check if current dossier belongs to current user, if not, possible hack attempt if (!$this->login->logged_in() || $dossier->gebruiker_id != $this->login->get_user_id() || $dossier->verwijderd) { if (!$dossier->verwijderd) { // not owned by the user? then check if it belongs to a colleague $size = null; $dossiers = array(); foreach (array_merge( $this->dossier->get_van_collegas( false, $size, true /* all! */, null, false ), $this->dossier->get_van_collegas( false, $size, true /* all! */, null, true ), $this->dossier->get_dossiers_by_toezichthouder( null, true ), $this->dossier->get_dossiers_by_toezichthouder( null, false ), $group_users ) as $dossier){ $dossier=(object)$dossier; $dossiers[$dossier->id] = $dossier; } } if (!isset( $dossiers[$dossier->id] )) { if (!$throw_exception) redirect(''); else throw new Exception( 'Geen toegang tot opgegeven dossier.' ); } } } function index() { redirect( '/dossiers' ); } public function toezichtgegevens( $checklistgroep_id, $deelplan_id, $checklist_id=null, $bouwnummer='' ){ $bouwnummer = !$bouwnummer ? '' : $bouwnummer;//It is necessary to resolve JS conflict. $bouwnummer = urldecode( $bouwnummer ); try { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) throw new Exception( 'Geen toegang tot opgevraagde deelplan (1).' ); $this->_check_deelplan_security( $deelplan, true ); $dossier = $deelplan->get_dossier(); $this->load->model('gebruiker'); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $this->load->library( 'prioriteitstelling' ); $this->load->model('vraag'); $this->load->model('hoofdthema'); $this->load->model('thema'); $this->load->model('deelplanthema'); $this->load->model('checklist'); $this->load->model('checklistgroep'); $this->load->model('dossierbescheiden'); $this->load->model('deelplanvraagbescheiden'); $this->load->model('deelplanvraaggeschiedenis'); $this->load->model('deelplanchecklistgroep'); $this->load->model('deelplanchecklist'); $this->load->model('deelplanupload'); $this->load->model('verantwoording'); $this->load->model('matrix'); $this->load->model('deelplanlayer'); $this->load->model('deelplanvraag'); // cache all once combineerbaar-op-checklist $this->thema->all(); $checklistgroep_obj = $this->checklistgroep->get( $checklistgroep_id ); $checklistgroep_obj->modus = $deelplan->geintegreerd=='ja' ? 'combineerbaar-op-checklist' : $checklistgroep_obj->modus; $checklist_obj = $checklist_id ? $this->checklist->get( $checklist_id ) : null; $access_mode = $deelplan->get_toezicht_access_to_deelplan( $checklistgroep_obj, $checklist_obj ); $trow_message = 'Geen toegang tot opgevraagde deelplan.'. "\naccess_mode: $access_mode". "\nmodus: ".$checklistgroep_obj->modus. "\nchecklist_id: ".$checklist_id. "\ndeelplan->geintegreerd: ".$deelplan->geintegreerd ; if ($access_mode == 'none') throw new Exception( '(1) -- '.$trow_message ); if ($checklistgroep_obj->modus == 'niet-combineerbaar' && !$checklist_id && $deelplan->geintegreerd=='nee') throw new Exception( '(2) -- '.$trow_message ); else if ($checklistgroep_obj->modus != 'niet-combineerbaar' && $checklist_id) throw new Exception( '(3) -- '.$trow_message ); // haal toezicht data op $data = $deelplan->get_toezicht_data( $checklistgroep_obj, $checklist_obj, true, $bouwnummer ); // prepare data for export foreach ($dossier->get_gebruiker()->get_klant()->get_gebruikers() as $gebruiker) $gebruikers[$gebruiker->id] = $gebruiker->volledige_naam; $errors = array(); $data['success'] = true; if( $checklist_id != null ) { $deelplanchecklist = $deelplan->get_deelplanchecklist($checklist_id,$bouwnummer); }else { $null_data = array('id'=>0); $deelplanchecklist = new DeelplanChecklistResult($null_data); } $data = array_merge( $data, array( 'checklistgroep_id' => $checklistgroep_obj->id, 'checklist_id' => $checklist_obj ? $checklist_obj->id : null, 'deelplanchecklist_id' => $deelplanchecklist->id, 'access_mode' => $access_mode, 'gebruikers' => $gebruikers ) ); foreach ($data['onderwerpen'] as $onderwerp_id => &$onderwerp_data) { foreach ($onderwerp_data['vragen'] as &$vraag) { if($vraag->huidige_toelichting_id == 1000 || !(bool)$vraag->huidige_toelichting_id ){ $d_vraag = $this->deelplanvraag->get($vraag->dlpln_vrg_id); $vraag->huidige_toelichting_id = $d_vraag->huidige_toelichting_id= time(); $d_vraag->toelichting = ' '; $d_vraag->save(); } $vraag->last_updated_at = date('d-m-Y H:i:s', strtotime( $vraag->last_updated_at ) ); $datum = $vraag->hercontrole_datum ? date('d-m-Y', strtotime( $vraag->hercontrole_datum ) ) : ''; if ($datum) $datum .= '|' . $vraag->hercontrole_start_tijd . '|' . $vraag->hercontrole_eind_tijd; $vraag->hercontrole_datum = $datum; $vraag->bouwnummer_id = encode_bouwnummer($bouwnummer); } } foreach ($data['deelplanuploads'] as $vraag_id => &$deelplanuploads) foreach ($deelplanuploads as $du) { $du->url = $du->get_download_url( false ); $du->thumbnail_url = $du->get_download_url( true ); $du->delete_url = $du->get_delete_url(); $du->auteur = $du->get_auteur(); } foreach ($data['deelplanvraaggeschiedenis'] as $vraag_id => &$rvgs) foreach ($rvgs as $rvg) { $rvg->datum = date('d-m-Y H:i:s', strtotime( $rvg->datum )); $rvg->tekst = $rvg->toelichting; } $data = convert_utf8_recursive( $data ); // output! $data['sha1'] = sha1( @json_encode( $data ) ); echo @json_encode( $data ); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error_message' => $e->getMessage(), ) ); } } public function show_photo( $checklistgroep_id, $deelplan_id, $checklist_id, $photo_id_str ) { // Define the string separator value that was used for constructing the encoded part of the URL $separator = '***'; // Decode the photo ID string and check the passed hash value. Note that the '$photo_id_str' parameter is base64 encoded and should (once decoded) be of the // structure '<deelplanupload filename>***<sha1 hash value>'. The SHA1 hash value should be calculated using the following structure as seed value: // '<deelplanupload filename>***<$checklistgroep_id>***<$deelplan_id>***<$checklist_id>' $photo_id_str_decoded = base64_decode($photo_id_str); $photo_id_parts = explode($separator, $photo_id_str_decoded); $check_hash_seed = implode($separator, array($photo_id_parts[0], $checklistgroep_id, $deelplan_id, $checklist_id)); // Calculate the check for the hash value and check if it matches the passed one. $passed_hash = $photo_id_parts[1]; $check_hash = sha1($check_hash_seed); //echo "Passed hash: {$passed_hash} - calculated hash: {$check_hash}<br />"; // Only continue if the two hash values are an exact match (in which case we can still do further checking to see if the passed photo ID string // actually belong to the other passed parameters too, etc. if ($passed_hash != $check_hash) { echo "De opgegeven URL is niet geldig."; } else { // If the passed URL is valid (i.e. passes the 'sha1 test', we are not quite done yet. We then look-up the uploads that are available for the passed // deelplan and check if the requested one is amongst them, only if that is the case do we actually show the image. //echo "Geldige URL...<br />"; $this->load->model('deelplanupload'); // Get the uploads for the passed deelplan. $deelplan_uploads = $this->deelplanupload->find_by_deelplan($deelplan_id); // Now check if the requested picture indeed exists for this deelplan. If so, show the picture. $picture_found = false; foreach($deelplan_uploads as $deelplan_upload) { // Get the filename without extension $filename_parts = pathinfo($deelplan_upload->filename); //d($photo_id_parts[0]); //d($filename_parts['filename']); // If the passed photo ID matches that of one of the registered filenames (without extension!), we have found the requested picture and can show it. if ($photo_id_parts[0] == $filename_parts['filename']) { // Show the picture. Don't bother using a view for it as it's a one-liner of HTML code. $picture_found = true; echo '<img src="'.$deelplan_upload->get_download_url().'">'; } // if ($photo_id_parts[0] == $filename_parts['filename']) } // foreach($deelplan_ uploads as $deelplan_upload) // If the picture for some reason was not found show an error message. if (!$picture_found) { echo "De door u opgevraagde illustratie is niet gevonden."; } } // else of clause: if ($passed_hash != $check_hash) } // public function show_photo( $checklistgroep_id, $deelplan_id, $checklist_id, $photo_id_str ) public function checklistgroep( $checklistgroep_id, $deelplan_id, $checklist_id=null, $bouwnummer='' ){ $bouwnummer = urldecode( $bouwnummer ); $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if( $deelplan==null ) redirect(); else{ $this->_check_deelplan_security( $deelplan ); $dossier = $deelplan->get_dossier(); $dossier_access = $dossier->get_access_to_dossier(); $this->load->model('gebruiker'); $logged_in_gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $logged_in_gebruiker->get_klant(); $this->load->library( 'prioriteitstelling' ); $this->load->library( 'risicoanalyse' ); $this->load->model('vraag'); $this->load->model('hoofdthema'); $this->load->model('thema'); $this->load->model('deelplanthema'); $this->load->model('checklist'); $this->load->model('checklistgroep'); $this->load->model('dossierbescheiden'); $this->load->model('deelplanvraagbescheiden'); $this->load->model('deelplanvraaggeschiedenis'); $this->load->model('deelplanchecklistgroep'); $this->load->model('deelplanchecklist'); $this->load->model('deelplanupload'); $this->load->model('verantwoording'); $this->load->model('matrix'); $this->load->model('deelplanlayer'); $this->load->model('deelplanhoofgroepen'); $this->load->model('deelplanvraag'); $checklistgroep_obj = $this->checklistgroep->get( $checklistgroep_id ); $checklistgroep_obj->modus = $deelplan->geintegreerd=='ja' ? 'combineerbaar-op-checklist' : $checklistgroep_obj->modus; $checklist_obj = $checklist_id ? $this->checklist->get( $checklist_id ) : null; $access_mode = $deelplan->get_toezicht_access_to_deelplan( $checklistgroep_obj, $checklist_obj ); if ($access_mode == 'none') redirect( '/dossiers/bekijken/' . $dossier->id ); if ($checklistgroep_obj->modus == 'niet-combineerbaar' && !$checklist_id && $deelplan->geintegreerd=='nee') redirect( '/dossiers/bekijken/' . $dossier->id ); else if ($checklistgroep_obj->modus == 'combineerbaar' && $checklist_id) { // In case an 'integreerbaar' checklist group is called WITH a checklist ID, we do not have to return to the dossier screen // but rather we redirect to ourselved, without the checklist ID. //redirect( '/dossiers/bekijken/' . $dossier->id ); redirect( "/deelplannen/checklistgroep/{$checklistgroep_id}/{$deelplan_id}" ); } $this->navigation->push( 'nav.toezicht', $_SERVER['REQUEST_URI'], array( $checklistgroep_obj->naam ) ); if( $checklist_id != null ) { $deelplanchecklist = $deelplan->get_deelplanchecklist($checklist_id,$bouwnummer); //TODO: Don't delete until 06-04-2017 // $access_mode =(FALSE || $logged_in_gebruiker->id == $dossier->gebruiker_id // || $logged_in_gebruiker->id == $deelplanchecklist->toezicht_gebruiker_id // || $deelplanchecklist->toezicht_gebruiker_id == '' // ) // ? 'write' // : $access_mode; }else { $data = array('id'=>0); $deelplanchecklist = new DeelplanChecklistResult($data); } // _dLog(print_r( $_POST ,true)); // // Behandel POST data // NOTE: Klinkt mss gek, maar dit is afhankelijk van of we per hoofdgroep of per thema/checklist // de onderwerpen verdeeld hebben! Als een checklist "per hoofdgroep" wordt getoond, staan // alle vragen in de POST data, en is het werk vrij simpel: loop de vragen af, sla hun data // op, klaar. Maar als het per thema/checklist wordt getoond, dan worden er MINDER vragen // getoond! Namelijk, alle dubbelen zijn er niet: de thema vragen hebben ALTIJD dubbelen, // de checklist vragen NOOIT. In dit geval moeten we alle eventuele bewerkingen dus ook // voor meer dan een vraag uitvoeren! // if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){ if ($access_mode == 'write'){ $data = $deelplan->get_toezicht_data( $checklistgroep_obj, $checklist_obj, false, $bouwnummer ); $this->_checklistgroep_post( $deelplan, $data['vragen'], $data['deelplan_onderwerpen'], $checklistgroep_obj, $checklist_obj, $dossier, $bouwnummer); exit; }else{ redirect( '/deelplannen/checklistgroep/' . $checklistgroep_id . '/' . $deelplan_id ); exit; } } if (REQUEST_RESTORE_ACTIVE) { // als dit een RR is, dan gaat de js code op deze site proberen te POSTen naar /rr, wat // nooit gaat werken! en aangezien dit een GET is als we hier aankomen, moeten we simpelweg // effe redirecten naar de juiste URL, zodat alles daarna weer naar behoren werkt :) // // NOTE: dit gebeurt nu voor ELKE get automatisch, maar ik laat het hier staan "just in case" redirect( '/deelplannen/checklistgroep/' . $checklistgroep_id . '/' . $deelplan_id ); exit; } // prepare pdf annotator $this->load->library( 'pdfannotatorlib' ); $this->pdfannotatorlib->load_stempel_library(); $this->_prepare_pdf_annotator( $deelplan ); // laad bescheiden, dit moet ivm werken PDF annotator $ini_b = $deelplan->get_bescheiden(); $bescheiden = array(); foreach ($ini_b as $b) if ($b->bestandsnaam) $bescheiden[] = $b; // get risico analyse handler $risicoanalyse_handler = $checklistgroep_obj->get_risicoanalyse_handler(); // Create first superficie moments if( isset($checklist_id) ) { $voortgang = round(100 * $deelplan->get_progress_by_checklist($checklist_id,$bouwnummer)); BRIS_SupervisionCheckList::getInstance() ->setDeelplan($deelplan_id) ->setChecklistId($checklist_id) ->setBouwnummertId($bouwnummer) ->setProgress($voortgang) ->setSupervisorUserId($this->login->get_user_id()) ->saveMoment(); } else { $voortgang = round(100 * $deelplan->get_progress_by_checklistgroep($checklistgroep_id)); BRIS_SupervisionCheckListGroup::getInstance() ->setDeelplan($deelplan_id) ->setChecklistGroupId($checklistgroep_id) ->setProgress($voortgang) ->setSupervisorUserId($this->login->get_user_id()) ->saveMoment(); } $access_mode=$dossier_access=="readonly" ? "readonly" :$access_mode; // load view! $this->load->view( 'nieuwelaf/index', array( 'deelplan' => $deelplan, 'dossier' => $dossier, 'klant' => $dossier->get_gebruiker()->get_klant(), 'checklistgroep' => $checklistgroep_obj, /* never null */ 'checklist' => $checklist_obj, /* might be null */ 'bouwnummer' => $bouwnummer, 'access_mode' => $access_mode, 'extra_title' => $checklistgroep_obj->naam . ' - ' . $deelplan->naam, 'bescheiden' => $bescheiden, 'pdf_annotator_allow' => $this->pdfannotatorlib->allow(), 'lease_configuratie' => $klant->get_lease_configuratie(), 'risicoanalyse_handler' => $risicoanalyse_handler, 'deelplanchecklist_id' => $deelplanchecklist->id ) ); } } //---------------------------------------- private function _prepare_pdf_annotator( DeelplanResult $deelplan) { $this->load->library( 'imageprocessor' ); // bake data structure $documents = array(); if ($this->pdfannotatorlib->allow()) { foreach ($deelplan->get_bescheiden( false ) as $bescheiden) { $new_filename = preg_replace( '/(\.(pdf|png|jpg))*$/i', '', $bescheiden->bestandsnaam ) . '.jpg'; $document = (object)array( 'filename' => $new_filename, 'pages' => array(), 'external_data' => array( 'document_id' => $bescheiden->id, ), ); $this->imageprocessor->slice( null ); $this->imageprocessor->id( $bescheiden->id ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( 'original' ); $this->imageprocessor->page_number( 1 ); $available = sizeof( $this->imageprocessor->available() ) == 1; if ($available) { $num_pages = $this->imageprocessor->get_number_of_pages(); for ($i = 1; $i <= $num_pages; ++$i) { $this->imageprocessor->page_number( $i ); if (!$this->imageprocessor->available()) throw new Exception('Pagina (' . $i . ') niet beschikbaar'); $document->pages[] = (object)array( 'local' => $this->imageprocessor->get_image_filename(), 'overview_local' => $this->imageprocessor->get_image_filename( 'overview' ), 'filename' => $new_filename, ); } } $documents[] = $document; } } // setup POST data and load PDF annotator code $_POST['quality'] = 'high'; $_POST['documents'] = json_encode( $documents ); $_POST['no_exit'] = true; require_once( PDFANNOTATOR_CODE_PATH . 'upload-url-set.php' ); } private function _checklistgroep_post( DeelplanResult $deelplan, array $vragen, OnderwerpenSplitter $splitter, ChecklistGroepResult $checklistgroep, ChecklistResult $checklist=null, DossierResult $dossierResult, $bouwnummer='') { if (!$splitter->has_run()) throw new Exception( 'Onderwerp splitter heeft nog niet gedraaid. Interne fout!' ); try { // save any data! $this->db->_trans_status = TRUE; $this->db->trans_start(); $only_commands = @$_POST['only_commands'] == 1; if (!$only_commands) { foreach ($vragen as $vraag) { $vraag_suffix = $vraag->id.($vraag->bouwnummer!='' ? '_'.encode_bouwnummer($vraag->bouwnummer) : ''); $var = 'vraag_' . $vraag_suffix; if (isset( $_POST[$var] )) { $toelvar = 'toel_' . $vraag_suffix; $toelichting= isset( $_POST[$toelvar] ) ? $_POST[$toelvar] : null; $toel_idvar = 'toel_id_' . $vraag_suffix; $new_toelichting_id= isset( $_POST[$toel_idvar] ) ? $_POST[$toel_idvar] : null; $secvar = 'sec_' . $vraag_suffix; $sec = isset( $_POST[$secvar] ) ? $_POST[$secvar] : 0; $hcdvar = 'hcd_' . $vraag_suffix; $hcd = (isset( $_POST[$hcdvar] ) && strlen($_POST[$hcdvar])) ? $_POST[$hcdvar] : null; $flags = $vraag->flags; $ga_var = 'ga_' . $vraag_suffix; ($_POST[$ga_var]) ? $flags |= VRAAG_FLAGS_GROEPSANTWOORD : $flags &= ~VRAAG_FLAGS_GROEPSANTWOORD; $vraag_hercontrole_datum = ($vraag->hercontrole_datum) ? date( 'd-m-Y', strtotime( $vraag->hercontrole_datum )).'|'.$vraag->hercontrole_start_tijd.'|'.$vraag->hercontrole_eind_tijd : null; if( FALSE || $vraag->status != $_POST[$var] || $vraag->toelichting != $toelichting || $vraag->huidige_toelichting_id != $new_toelichting_id || $vraag->seconden != $sec || $vraag_hercontrole_datum != $hcd || $vraag->flags != $flags ){ // log! if( $vraag->status != $_POST[$var] ) $this->logger->add($deelplan, 'deelplan', 'Toetsing status van "'.$vraag->tekst.'" veranderd in <i>'.$_POST[$var].'</i>'); if (!$_POST[$var]) $_POST[$var] = null; $vrgnn = $splitter->get_gelijke_vragen( $vraag->id ); foreach ($vrgnn as $vraag_id) { $this->deelplan->update_status( $deelplan->id, $vraag_id, $_POST[$var], $toelichting, $sec, $hcd, $flags, $new_toelichting_id, $vraag->bouwnummer ); try{ Vraag::scheduleEmail( $vraag , $dossierResult , $deelplan , $_POST[$var], $toelichting /* */); }catch( Exception $e ){ $this->logger->add($deelplan, 'email_question_notice_fail', 'The email couldn\'t be sent: '.$e->getMessage()); } } } } } } $command_results = array(); if( isset( $_POST['extra_commands'] )) { $toelichting_ids=array(); foreach ($_POST['extra_commands'] as $json_command) { $data = json_decode( $json_command ); if (is_object( $data )) { switch ($data->_command){ case 'fotoupload': $contents = base64_decode( $data->foto_contents ); if ($contents === false) throw new Exception( 'Fout bij het verwerken van de foto: geen geldige base64 inhoud.' ); $du = $this->deelplanupload->add( $deelplan->id, $data->vraag_id, $data->filename, $contents, $bouwnummer ); $command_results[] = $du->id; break; case 'vraaggeschiedenis': foreach ($splitter->get_gelijke_vragen( $data->vraag_id ) as $vraag_id){ $this->deelplanvraaggeschiedenis->add( $deelplan->id, $vraag_id, $data->status, $data->toelichting, $data->gebruiker_id, date( 'Y-m-d H:i:s', strtotime( $data->datum ) ), $data->toel_id, $bouwnummer ); if(isset($_POST['hoofgroepen_level'])&&$_POST['hoofgroepen_level']==1){ $vraag_suffix = $vraag_id.($bouwnummer!='' ? '_'.encode_bouwnummer($bouwnummer) : ''); $toel_idvar = 'toel_id_' . $vraag_suffix; $toelvar = 'toel_' . $vraag_suffix; $toelichting= isset( $_POST[$toelvar] ) ? $_POST[$toelvar] : null; $toel_status_var='vraag_' . $vraag_suffix; $toel_status=isset( $_POST[$toel_status_var] ) ? $_POST[$toel_status_var] : null; $new_toelichting_id= isset( $_POST[$toel_idvar] ) ? $_POST[$toel_idvar] : null; if(count($toelichting_ids)==0){ $toelichting_ids[]=$new_toelichting_id; $hoofdgroep_id = $this->deelplanvraag->get_hoofgoep_value_by_vraag_and_deeplan($deelplan->id,$vraag_id); $this->deelplanhoofgroepen->create_new_toelichting_for_hoofgroep($deelplan->id, $hoofdgroep_id, $toelichting, $toel_status); } else if(array_search($new_toelichting_id,$toelichting_ids)!=0){ var_dump(array_search($new_toelichting_id,$toelichting_ids)) ; $toelichting_ids[]=$new_toelichting_id; $hoofdgroep_id = $this->deelplanvraag->get_hoofgoep_value_by_vraag_and_deeplan($deelplan->id,$vraag->id); $this->deelplanhoofgroepen->create_new_toelichting_for_hoofgroep($deelplan->id, $hoofdgroep_id, $toelichting, $toel_status); } } } $command_results[] = true; break; case 'verwijdervraagupload': if (isset( $data->vraagupload_data_id )){ throw new Exception('Option deprecated'); }else{ foreach ($this->deelplanupload->search( array( 'id' => $data->vraagupload_id ) ) as $du) $du->delete(); } $command_results[] = true; break; case 'maakbescheidenrelevantvoorvraag': // store! $existing = $this->deelplanvraagbescheiden->get_by_deelplan( $deelplan->id ); foreach ($splitter->get_gelijke_vragen( $data->vraag_id ) as $vraag_id) { $al_gekoppeld = false; if (isset( $existing[ $vraag_id ] )) foreach ($existing[ $vraag_id ] as $rlb) if ($rlb->dossier_bescheiden_id == $data->bescheiden_id) { $al_gekoppeld = true; break; } if (!$al_gekoppeld) $this->deelplanvraagbescheiden->add( $deelplan->id, $vraag_id, $data->bescheiden_id ); } $command_results[] = true; break; case 'maakbescheidennietlangerrelevantvoorvraag': $existing = $this->deelplanvraagbescheiden->get_by_deelplan( $deelplan->id ); foreach ($splitter->get_gelijke_vragen( $data->vraag_id ) as $vraag_id) { if (isset( $existing[ $vraag_id ] )) foreach ($existing[ $vraag_id ] as $rlb) if ($rlb->dossier_bescheiden_id == $data->bescheiden_id) { $rlb->delete(); break; } } $command_results[] = true; break; case 'verhooghoofdgroepprioriteit': $this->load->library( 'prioriteitstelling' ); $this->prioriteitstelling->store_override( $deelplan->id, $data->hoofdgroep_id, $data->nieuwe_prio ); $command_results[] = true; break; case 'layersopslaanvoordocument': // sla layers op $this->load->model( 'deelplanlayer' ); $this->deelplanlayer->replace( $deelplan->id, $data->bescheiden_id, $data->layers, $data->pagetransform ); // apply alle opdrachten opnieuw $this->load->model( 'deelplanopdracht' ); foreach ($this->deelplanopdracht->search( array('deelplan_id' => $deelplan->id ) ) as $opdracht) $opdracht->verwerk_in_layer(); $command_results[] = true; break; case 'layertoevoegen': $this->load->model( 'dossierbescheiden' ); $this->load->model( 'deelplanbescheiden' ); $this->load->model( 'deelplanvraagbescheiden' ); $this->load->library( 'pdfannotatorlib' ); // laad bron bescheiden if (!($bron_bescheiden = $this->dossierbescheiden->get( $data->bescheiden_id ))) throw new Exception( 'Kon bron bescheiden niet laden, geen rechten of niet bestaand.' ); // eerst faken we een annotations POST $_POST['layers'] = $data->layers; ob_start(); require_once( PDFANNOTATOR_CODE_PATH . 'annotations.php' ); $resultaat = ob_get_clean(); if ($resultaat != '1') throw new Exception( 'Fout bij het opslaan van het geannoteerde bescheiden.' ); // selecteer het juiste bescheiden $_POST['guid'] = $data->guid; $_POST['pagetransform'] = $data->pagetransform; $_POST['dimensions'] = $data->dimensions; $_POST['do_headers'] = false; ob_start(); require_once( PDFANNOTATOR_CODE_PATH . 'download.php' ); $png = ob_get_clean(); // see if PNG is valid! $testim = @ imagecreatefromstring( $png ); if (!is_resource( $testim )) { if (preg_match( '/<div class="error">(.*?)<\/div>/smi', $png, $matches )) $errorHack = $matches[1]; else $errorHack = ''; throw new Exception( 'Fout opgetreden bij verwerken van annotaties: ' . $errorHack ); } @ imagedestroy( $testim ); // maak bescheiden aan $dossierbescheiden = $this->dossierbescheiden->add( $deelplan->dossier_id ); $dossierbescheiden->bestandsnaam = '[ANNOTATIES] ' . $bron_bescheiden->bestandsnaam . '.png'; $dossierbescheiden->bestand = $png; $dossierbescheiden->tekening_stuk_nummer = 'annotaties'; $dossierbescheiden->auteur = $this->gebruiker->get_logged_in_gebruiker()->volledige_naam; $dossierbescheiden->omschrijving = 'Annotaties op ' . $bron_bescheiden->bestandsnaam; $dossierbescheiden->zaaknummer_registratie = ''; $dossierbescheiden->versienummer = ''; $dossierbescheiden->datum_laatste_wijziging = date('d-m-Y H:i'); if (!$dossierbescheiden->save()) throw new Exception( 'Fout bij opslaan van het bescheiden in de database.' ); // koppel aan deelplan $this->deelplanbescheiden->add( $deelplan->id, $dossierbescheiden->id ); // als er vragen zijn om aan te koppelen, doe dat nu $vragen = @json_decode( $data->vragen ); if (is_array( $vragen )) { foreach ($vragen as $vraag_id) $this->deelplanvraagbescheiden->add( $deelplan->id, $vraag_id, $dossierbescheiden->id ); } $command_results[] = true; break; case 'subjectenbijwerken': $this->load->model( 'deelplansubjectvraag' ); $this->deelplansubjectvraag->set_by_deelplan_and_vraag( $deelplan->id, $data->vraag_id, $data->subject_ids ); $command_results[] = true; break; case 'opdrachtinplannen': $this->load->model( 'deelplanopdracht' ); if (empty( $data->foto_ids )) { // geen foto opdracht $this->deelplanopdracht->add_zonder_foto( $deelplan->id, $data ); } else { // foto opdrachten foreach ($data->foto_ids as $fotodata) $this->deelplanopdracht->add_met_foto( $deelplan->id, $data, $fotodata ); } $this->load->model('notificatie'); $bericht='Opdracht "'.$data->opdracht_omschrijving.' " gegenereerde'; $this->notificatie->add_opdrachten_notificatie($deelplan->id, $bericht, true, $data->vraag_id); $command_results[] = true; break; case 'opdrachtbewerken': $this->load->model( 'deelplanopdracht' ); $opdrachten = $this->deelplanopdracht->search( array( 'vraag_id' => $data->vraag_id, 'deelplan_id' => $deelplan->id, 'tag' => $data->tag ) ); foreach ($opdrachten as $opdracht) { $opdracht->dossier_subject_id = $data->dossier_subject_id; $opdracht->opdracht_omschrijving = $data->opdracht_omschrijving; $opdracht->gereed_datum = date('Y-m-d', strtotime($data->gereed_datum)); $opdracht->save(0,0,0); $bericht='Opdracht "'.$opdracht->opdracht_omschrijving.' " bewerken'; $this->notificatie->add_opdrachten_notificatie($deelplan->id, $bericht, true, $data->vraag_id); } $command_results[] = true; break; case 'opdrachtverwijderen': $this->load->model( 'deelplanopdracht' ); $opdrachten = $this->deelplanopdracht->search( array( 'vraag_id' => $data->vraag_id, 'deelplan_id' => $deelplan->id, 'tag' => $data->tag ) ); foreach ($opdrachten as $opdracht) { $bericht='Opdracht "'.$opdracht->opdracht_omschrijving.' " verwijderde'; $this->notificatie->add_opdrachten_notificatie($deelplan->id, $bericht, false, $data->vraag_id); $opdracht->delete(); } $command_results[] = true; break; default: $command_results[] = false; break; } } } } // werkt voortgang bij if (!$checklist){ $voortgang = round( 100 * $deelplan->get_progress_by_checklistgroep( $checklistgroep->id ) ); $this->deelplanchecklistgroep->update_voortgang( $deelplan->id, $checklistgroep->id, $voortgang ); BRIS_SupervisionCheckListGroup::getInstance() ->setDeelplan($deelplan->id) ->setChecklistGroupId($checklistgroep->id) ->setProgress($voortgang) ->setSupervisorUserId($this->login->get_user_id()) ->saveMoment(); }else{ $voortgang = round( 100 * $deelplan->get_progress_by_checklist( $checklist->id, $bouwnummer ) ); $this->deelplanchecklist->update_voortgang( $deelplan->id, $checklist->id, $voortgang, $bouwnummer ); BRIS_SupervisionCheckList::getInstance() ->setDeelplan($deelplan->id) ->setChecklistId($checklist->id) ->setBouwnummertId($bouwnummer) ->setProgress($voortgang) ->setSupervisorUserId($this->login->get_user_id()) ->saveMoment(); } if (!$this->db->trans_complete()) throw new Exception( 'Fout bij opslaan in de database.' ); echo json_encode( array( 'success' => true, 'command_results' => $command_results ) ); exit; }catch (Exception $e){ echo json_encode( array( 'success' => false, 'error' => $e->getMessage() ) ); exit; } } public function deelplanupload_upload( $vraag_ids=null, $deelplan_id=null, $checklistgroep_id=null, $checklist_id=null, $bouwnummer='' ) { $this->load->model( 'deelplan' ); $this->load->model( 'deelplanupload' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->helper("transliteration"); CI_Base::get_instance()->load->library('utils'); if (!isset( $_FILES['upload'] )) die( 'Geen bestand geupload.' ); $file_count=count($_FILES['upload']['name']); if (!$vraag_ids) die( 'Interne fout, onvoldoende informatie beschikbaar: geen vraag id' ); $vraag_ids = explode( ',', $vraag_ids ); if (empty( $vraag_ids )) die( 'Interne fout, onvoldoende informatie beschikbaar: lijst van vraag ids is leeg' ); if (!$deelplan_id) die( 'Interne fout, onvoldoende informatie beschikbaar: geen deelplan id' ); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) die( 'Geen toegang tot deelplan.' ); $this->_check_deelplan_security( $deelplan ); $checklistgroep_obj = $this->checklistgroep->get( $checklistgroep_id ); $checklist_obj = $checklist_id ? $this->checklist->get( $checklist_id ) : null; $access_mode = $deelplan->get_toezicht_access_to_deelplan( $checklistgroep_obj, $checklist_obj ); if ($access_mode != 'write') die( 'Geen rechten om bestanden te uploaden.' ); for ($i=0; $i<$file_count; $i++){ if( !CI_Utils::check_extension($_FILES['upload']['name'][$i], explode(', ', IMAGE_EXTESIONS) ) ) { die('Extension not allowed'); } if ($_FILES['upload']['error'][$i]) die( 'Fout #' . $_FILES['upload']['error'][$i] . ' opgetreden bij uploaden.' ); if (!$_FILES['upload']['size'][$i]) die( 'Bestand van 0 bytes geupload.' ); $contents = file_get_contents( $_FILES['upload']['tmp_name'][$i] ); $result = null; $data_id = null; $thumbnail = null; $file_name=convert_file_name($_FILES['upload']['name'][$i]); foreach ($vraag_ids as $index => $vraag_id) { if ($index == 0) { // Try to add the upload. This can either return a 'deelplanupload' object (in case of success) or it can trigger an error. // If '$ru' is a string, we assume an error to have occurred, and simply return that error so it can be handled properly. if( $ru = ($this->deelplanupload->add( $deelplan_id, $vraag_id, $file_name, $contents, $bouwnummer )) ) { // Handle returned error messages first. Only in the case that we do not receive a string as result do we assume the upload to have // been successful. if (is_string($ru)) { die($ru); } else { $result = $ru->id . ':' . json_encode( (object) array( 'id' => $ru->id, // 'deelplan_upload_data_id' => $ru->deelplan_upload_data_id, 'filename' => htmlentities($ru->filename), 'url' => htmlentities($ru->get_download_url()), 'thumbnail_url' => htmlentities($ru->get_download_url(true)), 'delete_url' => htmlentities($ru->get_delete_url()), 'auteur' => $ru->get_auteur(), 'has_thumbnail' => 1, 'uploaded_at' => date('Y-m-d H:i:s')) ).";"; $data_id = $ru->id; } } else { //die( 'Fout bij verwerken van upload naar database (1).' ); die( 'Er is een onbekende fout opgetreden bij het verwerken van de upload.' ); } } else { if( !($this->deelplanupload->add_using_data_id( $deelplan_id, $vraag_id, $file_name, $data_id, strlen( $contents ))) ) { //die( 'Fout bij verwerken van upload naar database (2).' ); die( 'Er is een niet nader gespecificeerde fout opgetreden bij het verwerken van de upload.' ); } } } echo $result; } } public function deelplanupload_download( $deelplan_upload_id=null, $thumbnail='' ) { $this->load->model( 'deelplanupload' ); if (!($ru = $this->deelplanupload->get( $deelplan_upload_id ))) redirect(); $this->load->model( 'deelplan' ); if (!($deelplan = $this->deelplan->get( $ru->deelplan_id ))) redirect(); $this->_check_deelplan_security( $deelplan ); $this->load->helper( 'user_download' ); if ($thumbnail) user_download( $ru->preview, 'thumbnail-' . $ru->filename ); else user_download( $ru->get_data(), $ru->filename ); } function get_status_for_deelplan_vraag( $deelplan_id, $vraag_id ) { $this->db->from( 'deelplan_vragen' ); $this->db->where( 'deelplan_id', $deelplan_id ); $this->db->where( 'vraag_id', $vraag_id ); $res = $this->db->get(); if ($res->num_rows==1) return reset( $res->result() ); else return null; } function wettelijke_grondslag( $vraaggrondslag_id=null ) { $this->load->model( 'vraaggrondslag' ); $lg = $this->vraaggrondslag->get( $vraaggrondslag_id ); if (!$lg) redirect(); $lgg = $lg->get_grondslag(); $this->navigation->push( 'nav.toon_grondslag', '/deelplannen/wettelijke_grondslag/' . $vraaggrondslag_id, array( $lgg->grondslag, $lg->artikel ) ); $this->load->view( 'deelplannen/wettelijke_grondslag.php', array( 'lg' => $lg ) ); } function download_richtlijn( $richtlijn_id=null ) { $this->load->model( 'richtlijn' ); $richtlijn = $this->richtlijn->get( $richtlijn_id ); if ($richtlijn==null) redirect(); $this->load->helper( 'user_download' ); user_download( $richtlijn->data, $richtlijn->filename ); } function store_toezichthouder() { $this->load->model( 'deelplan' ); $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); try { $gebruiker_id = !isset($_POST['gebruiker_id'])||!$_POST['gebruiker_id']||$_POST['gebruiker_id']==''?null:$_POST['gebruiker_id']; $deelplan_id = $_POST['deelplan_id']; // check deelplan security $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) throw new Exception( 'Ongeldig deelplan ID.' ); $this->_check_deelplan_security( $deelplan ); $mag_gebruiker_toekennen = $deelplan->get_toezichthouder_toekennen_access_to_deelplan() == 'write'; if ($mag_gebruiker_toekennen) { // load objects (automatically checks security access) if ( $gebruiker_id != null && !($this->gebruiker->get( $gebruiker_id ))) throw new Exception( 'Ongeldige gebruiker ID.' ); if (!@$_POST['checklist_id']) { if (!($this->checklistgroep->get( $_POST['checklist_groep_id'] ))) throw new Exception( 'Ongeldige checklist groep ID.' ); $this->deelplanchecklistgroep->update_toezichthouder( $deelplan_id, $_POST['checklist_groep_id'], $gebruiker_id ); } else { if (!($this->checklist->get( $_POST['checklist_id'] ))) throw new Exception( 'Ongeldige checklist ID.' ); $bouwnummer = isset($_POST['bouwnummer'])?$_POST['bouwnummer']:''; $this->deelplanchecklist->update_toezichthouder( $deelplan_id, $_POST['checklist_id'], $gebruiker_id, $bouwnummer ); } } else throw new Exception( 'Geen rechten voor deze actie.' ); // done! echo 'OK'; } catch (Exception $e) { die( $e->getMessage() ); } } function store_matrix() { $this->load->model( 'deelplan' ); $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'matrix' ); try { // check deelplan security $deelplan = $this->deelplan->get( $_POST['deelplan_id'] ); if ($deelplan==null) throw new Exception( 'Ongeldig deelplan ID.' ); $this->_check_deelplan_security( $deelplan ); $mag_matrix_toekennen = $deelplan->get_toezichthouder_toekennen_access_to_deelplan() == 'write'; if ($mag_matrix_toekennen) { // load (automatically checks security access) if (!($this->matrix->get( $_POST['matrix_id'] ))) throw new Exception( 'Ongeldige matrix ID.' ); if (!@$_POST['checklist_id']) { if (!($this->checklistgroep->get( $_POST['checklist_groep_id'] ))) throw new Exception( 'Ongeldige checklist groep ID.' ); $this->deelplanchecklistgroep->update_matrix( $_POST['deelplan_id'], $_POST['checklist_groep_id'], $_POST['matrix_id'] ); } else { if (!($this->checklist->get( $_POST['checklist_id'] ))) throw new Exception( 'Ongeldige checklist ID.' ); $this->deelplanchecklist->update_matrix( $_POST['deelplan_id'], $_POST['checklist_id'], $_POST['matrix_id'] ); } } else throw new Exception( 'Geen rechten voor deze actie.' ); // done! echo 'OK'; } catch (Exception $e) { die( $e->getMessage() ); } } function store_planningdatum() { $this->load->model( 'deelplan' ); $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); try{ // check deelplan security $deelplan = $this->deelplan->get( $_POST['deelplan_id'] ); if ($deelplan==null) throw new Exception( 'Ongeldig deelplan ID.' ); $this->_check_deelplan_security( $deelplan ); $mag_gebruiker_toekennen = $deelplan->get_toezichthouder_toekennen_access_to_deelplan() == 'write'; if ($mag_gebruiker_toekennen) { if (!@$_POST['checklist_id']) { if (!($this->checklistgroep->get( $_POST['checklist_groep_id'] ))) throw new Exception( 'Ongeldige checklist groep ID.' ); $this->deelplanchecklistgroep->update_planningdatum( $_POST['deelplan_id'], $_POST['checklist_groep_id'], $_POST['planningdatum'], $_POST['start_tijd'], $_POST['eind_tijd'] ); } else { if (!($this->checklist->get( $_POST['checklist_id'] ))) throw new Exception( 'Ongeldige checklist ID.' ); $this->deelplanchecklist->update_planningdatum( $_POST['deelplan_id'], $_POST['checklist_id'], $_POST['planningdatum'], $_POST['start_tijd'], $_POST['eind_tijd'] ); } } else throw new Exception( 'Geen rechten voor deze actie.' ); // done! echo 'OK'; } catch (Exception $e) { die( $e->getMessage() ); } } private function _fetch_deelplan_data( $deelplan ) { $this->load->model('deelplanthema'); $this->load->model('deelplansubject'); $this->load->model('deelplanbescheiden'); $this->load->model('dossierbescheiden'); $this->load->model('dossierbescheidenmap'); $this->load->model('thema'); $this->load->model('hoofdthema'); $this->load->model('checklistgroep'); $this->load->model('checklist'); $this->load->model('hoofdgroep'); $this->load->model('deelplanchecklistgroep'); $this->load->model('matrix'); $this->load->model('sjabloon'); $klant_id = $this->session->userdata( 'kid' ); $deelplanchecklistgroep_gebruikers = $this->gebruiker->get_by_klant( $klant_id, true ); // Get the checklistgroepen. Start by getting all of the ones for the current organisation. $checklistgroepen_for_organisation = $this->checklistgroep->get_for_huidige_klant(); // Now for Riepair users only (!) filter this list, so only the ones are shown that are selected in 'gebruikersbeheer' for the currently logged in user. $this->load->model( 'gebruiker' ); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); if ($gebruiker->is_riepair_user()) { $this->load->model( 'gebruikerchecklistgroep' ); $gebruiker_checklistgroepen = $this->gebruikerchecklistgroep->get_for_user($gebruiker->id); $checklistgroepen = array(); foreach ($checklistgroepen_for_organisation as $checklistgroep_for_organisation) { if (in_array($checklistgroep_for_organisation->id, $gebruiker_checklistgroepen)) { $checklistgroepen[] = $checklistgroep_for_organisation; } } } else { $checklistgroepen = $checklistgroepen_for_organisation; } $matrices = array(); foreach ($checklistgroepen as $checklistgroep) { $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ); $matrices[$checklistgroep->id] = $this->matrix->geef_matrices_voor_checklist_groep( $checklistgroep ); } $hoofdthemas = $this->hoofdthema->get_for_huidige_klant( true ); $deelplanchecklistgroep_gebruikers = $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), true ); $current_themas = $this->deelplanthema->get_by_deelplan( $deelplan->id ); $current_subjecten = $this->deelplansubject->get_by_deelplan( $deelplan->id ); $current_bescheiden = $this->deelplanbescheiden->get_by_deelplan( $deelplan->id ); $deelplanchecklistgroepen = $this->deelplanchecklistgroep->get_by_deelplan( $deelplan->id ); $deelplan_access = $deelplan->get_access_to_deelplan(); $scope_access = array(); foreach ($deelplanchecklistgroepen as $deelplanchecklistgroep) $scope_access[$deelplanchecklistgroep->checklist_groep_id] = $deelplan->get_scope_access_to_deelplan( $deelplanchecklistgroep ); $dossier = $deelplan->get_dossier(); return array( 'deelplan' => $deelplan, 'checklistgroepen' => $checklistgroepen, 'matrices' => $matrices, 'hoofdthemas' => $hoofdthemas, 'current_themas' => $current_themas, 'current_subjecten' => $current_subjecten, 'current_bescheiden' => $current_bescheiden, 'deelplan_access' => $deelplan_access, 'scope_access' => $scope_access, 'dossier' => $dossier, 'subjecten' => $dossier->get_subjecten(), 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $dossier->id ), 'mappen' => $this->dossierbescheidenmap->get_by_dossier( $dossier->id ), 'sjabloon' => $deelplan->get_sjabloon(), 'bouwdelen' => $deelplan->get_bouwdelen(), ); } public function verwijderen( $deelplan_id=null ) { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); $dossier = $deelplan->get_dossier(); if ($deelplan->get_access_to_deelplan() != 'write') redirect( '/dossiers/bekijken/' . $dossier->id ); $deelplan->delete(); redirect( '/dossiers/bekijken/' . $dossier->id ); } } public function afmelden( $deelplan_id=null ) { $this->load->model('deelplan'); $this->load->model('btbtzdossier'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); $dossier = $deelplan->get_dossier(); // For Woningborg dossiers we use a slightly different flow than normal: their access will be set to read-only, and they // only need to be able to use the 'deelplan afmelden' functionality when the 'project status' = 'toets afgerond'. // The below code traps that situation, and prevents the redirect from taking place when it should not. $heeftBtBtzDossier = false; $btBtzDossier = $this->btbtzdossier->get_one_by_btz_dossier_id( $dossier->id ); if (!is_null($btBtzDossier) && ($btBtzDossier->project_status == 'toets afgerond')) { $heeftBtBtzDossier = true; } if ( ($deelplan->get_access_to_deelplan() != 'write') && !$heeftBtBtzDossier) { redirect( '/dossiers/bekijken/' . $dossier->id ); } $deelplan->meld_af(); // Signal that the BTZ status is now 'afgerond' (this will automatically be propogated to the project status too). if ($heeftBtBtzDossier) { $btBtzDossier->btz_status = 'afgerond'; $btBtzDossier->save(); } redirect( '/dossiers/bekijken/' . $dossier->id ); } } public function bescheiden_lijst( $deelplan_id=null, $parent_map_id=null ) { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); if ($deelplan->get_access_to_deelplan() != 'write') redirect( '/deelplannen/bekijken/' . $deelplan->id ); $dossier = $deelplan->get_dossier(); $this->load->model('dossierbescheiden'); $this->load->model('dossierbescheidenmap'); $this->load->view( 'deelplannen/_bescheiden', array( 'bescheiden' => $this->dossierbescheiden->get_by_dossier( $deelplan->dossier_id, false, $parent_map_id ), 'mappen' => $this->dossierbescheidenmap->get_by_dossier( $deelplan->dossier_id, $parent_map_id ), 'parent_map_id' => $parent_map_id, ) ); } } public function bewerken( $deelplan_id=null, $open_registratiegegevens=false ) { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); if ($deelplan->get_access_to_deelplan() != 'write') redirect( '/deelplannen/bekijken/' . $deelplan->id ); $dossier = $deelplan->get_dossier(); $viewdata = $this->_fetch_deelplan_data( $deelplan ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // hack to make all view variables available within this function foreach ($viewdata as $k => $v) $$k = $v; $redirect_to_bewerken = false; if ($deelplan_access=='write') { if ($_POST['use_sjabloon_id']) { $redirect_to_bewerken = true; if ($_POST['sjabloon_id']) { if ($sjabloon = $this->sjabloon->get( $_POST['sjabloon_id'] )) { $deelplan->sjabloon_id = $sjabloon->id; $deelplan->save(); $_POST['checklist'] = $_POST['checklistgroep'] = array(); foreach ($sjabloon->get_checklisten() as $checklist) { $_POST['checklistgroep'][$checklist->checklist_groep_id] = 'on'; $_POST['checklist'][$checklist->id] = 'on'; } } } } if ($deelplan->naam != $_POST['deelplan_naam'] || $deelplan->kenmerk != $_POST['kenmerk'] || $deelplan->olo_nummer != $_POST['olo_nummer'] || $deelplan->aanvraag_datum != date( 'Y-m-d', strtotime( $_POST['aanvraag_datum'] ) )) { $deelplan->naam = $_POST['deelplan_naam']; $deelplan->kenmerk = $_POST['kenmerk']; $deelplan->olo_nummer = $_POST['olo_nummer']; $deelplan->aanvraag_datum = date( 'Y-m-d', strtotime( $_POST['aanvraag_datum'] ) ); $deelplan->save(); } $themachanges = $this->deelplanthema->set_for_deelplan( $deelplan->id, isset( $_POST['themas'] ) ? array_keys( $_POST['themas'] ) : array(), $current_themas ); $this->deelplansubject->set_for_deelplan( $deelplan->id, isset( $_POST['subjecten'] ) ? array_keys( $_POST['subjecten'] ) : array(), $current_themas ); $this->deelplanbescheiden->set_for_deelplan( $deelplan->id, isset( $_POST['bescheiden'] ) ? array_keys( $_POST['bescheiden'] ) : array(), $current_themas ); // update checklist selectie if ($checklistchanges = $deelplan->update_checklisten( array( 'checklistgroep' => isset( $_POST['checklistgroep'] ) ? $_POST['checklistgroep'] : array(), 'checklist' => isset( $_POST['checklist'] ) ? $_POST['checklist'] : array(), 'toezichthouders' => null, 'matrices' => null, ))) $deelplan->update_content(); // nieuwe sjabloon if (@$_POST['use_sjabloon_naam']) { $naam = trim($_POST['sjabloon_naam']); if ($naam) { $sjabloon = $this->sjabloon->add( $naam ); $sjabloon->set_checklisten( $deelplan->get_checklisten( true ) ); $deelplan->sjabloon_id = $sjabloon->id; $deelplan->save(); $redirect_to_bewerken = true; } else $errors[] = 'Lege sjabloon naam niet toegestaan.'; } // werkt voortgang bij if ($checklistchanges || $themachanges) { $this->load->model( 'deelplanchecklistgroep' ); $this->load->model( 'deelplanchecklist' ); foreach ($deelplan->get_checklistgroepen() as $checklistgroep) { if ($checklistgroep->modus != 'niet-combineerbaar') { $voortgang = round( 100 * $deelplan->get_progress_by_checklistgroep( $checklistgroep->id ) ); $this->deelplanchecklistgroep->update_voortgang( $deelplan->id, $checklistgroep->id, $voortgang ); } else { foreach ($checklistgroep->get_checklisten() as $checklist) { if ($checklist->checklist_groep_id == $checklistgroep->id) { $voortgang = round( 100 * $deelplan->get_progress_by_checklist( $checklist->id ) ); $this->deelplanchecklist->update_voortgang( $deelplan->id, $checklist->id, $voortgang ); } } } } } // werk bouwdelen bij $bouwdelen = (isset( $_POST['bouwdelen'] ) && is_array( $_POST['bouwdelen'] )) ? $_POST['bouwdelen'] : array(); $this->deelplanbouwdeel->set_for_deelplan( $deelplan->id, $_POST['bouwdelen'] ); } if (empty( $errors )) { if ($redirect_to_bewerken) redirect( '/deelplannen/bewerken/' . $deelplan->id ); else redirect( '/dossiers/bekijken/' . $dossier->id . '/' . $deelplan->id ); } } $viewdata['sjablonen'] = array_merge( $this->sjabloon->get_sjablonen_voor_klant( $this->session->userdata('kid') ), $this->sjabloon->get_sjablonen_voor_klant( null ) ); $viewdata['errors'] = $errors; $viewdata['open_registratiegegevens'] = $open_registratiegegevens; $viewdata['mag_checklisten_verwijderen'] = $deelplan->mag_checklisten_verwijderen(); $this->navigation->push( 'nav.deelplan_bewerken', '/deelplannen/bewerken/' . $deelplan->id, array( $deelplan->naam ) ); $this->load->view( 'deelplannen/bewerken', $viewdata ); } } public function bekijken( $deelplan_id ) { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); $dossier = $deelplan->get_dossier(); if ($deelplan->get_access_to_deelplan() == 'none') redirect( '/dossiers/bekijken/' . $dossier->id ); $this->navigation->push( 'nav.deelplan_bekijken', '/deelplannen/bewerken/' . $deelplan->id, array( $deelplan->naam ) ); $this->load->view( 'deelplannen/bekijken', $this->_fetch_deelplan_data( $deelplan ) ); } } public function verzend_email( $checklistgroep_id, $deelplan_id, $checklist_id=null ) { $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) redirect(); else { $this->_check_deelplan_security( $deelplan ); $dossier = $deelplan->get_dossier(); $this->load->model('gebruiker'); $gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $this->load->library( 'prioriteitstelling' ); $this->load->model('vraag'); $this->load->model('hoofdthema'); $this->load->model('thema'); $this->load->model('deelplanthema'); $this->load->model('checklist'); $this->load->model('checklistgroep'); $this->load->model('dossierbescheiden'); $this->load->model('deelplanvraagbescheiden'); $this->load->model('deelplanvraaggeschiedenis'); $this->load->model('deelplanchecklistgroep'); $this->load->model('deelplanchecklist'); $this->load->model('deelplanupload'); $this->load->model('verantwoording'); $this->load->model('matrix'); $this->load->model('deelplanlayer'); $checklistgroep_obj = $this->checklistgroep->get( $checklistgroep_id ); $checklist_obj = $checklist_id ? $this->checklist->get( $checklist_id ) : null; $access_mode = $deelplan->get_toezicht_access_to_deelplan( $checklistgroep_obj, $checklist_obj ); if ($access_mode == 'none') die( tgng( 'php.geen_rechten' ) ); if ($checklistgroep_obj->modus == 'niet-combineerbaar' && !$checklist_id) die( tgng( 'php.foute_invoer' ) ); else if ($checklistgroep_obj->modus != 'niet-combineerbaar' && $checklist_id) die( tgng( 'php.foute_invoer' ) ); $klant = $gebruiker->get_klant(); $email_addresses = preg_split( '/[,;]/', $klant->contactpersoon_email, -1, PREG_SPLIT_NO_EMPTY ); if (empty( $email_addresses )) die( tgng( 'php.geen_email_adres_ingesteld' ) ); $data = $deelplan->get_toezicht_data( $checklistgroep_obj, $checklist_obj, true ); $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><checklistfragen></checklistfragen>'); $time = time(); foreach ($data['onderwerpen'] as $onderwerp_id => $onderwerp_data) { foreach ($onderwerp_data['vragen'] as $vraag) { $checklist = $this->checklist->get( $vraag->checklist_id ); $gebruiker = $this->gebruiker->get( $vraag->gebruiker_id ); if ($vraag->status && preg_match( '/w(\d{2})s?/', $vraag->status, $matches ) && ($tempVraag = $this->vraag->get( $vraag->id ))) $antwoord_tekst = $tempVraag->get_wizard_veld_recursief( 'wo_tekst_' . $matches[1] ); else $antwoord_tekst = ''; $node = $xml->addChild( 'checklistfrage' ); $node->addChild( 'maschine', $checklist->naam ); $node->addChild( 'frage', $vraag->tekst ); $node->addChild( 'status', $antwoord_tekst ); $node->addChild( 'kurzbeschreibung', $vraag->toelichting ); $fotos = $node->addChild( 'fotos' ); $bescheiden = $node->addChild( 'zeichnungen' ); $node->addChild( 'datum', date('d.m.Y', $time) ); $node->addChild( 'uhrzeit', date('H:i:s', $time ) ); $node->addChild( 'erfasser', $gebruiker->get_status() ); // koppel bescheiden if (isset( $data['vraagbescheiden'][$vraag->id] )) foreach ($data['vraagbescheiden'][$vraag->id] as $lb) { $bescheid = null; foreach ($data['bescheiden'] as $b) if ($b->id == $lb->dossier_bescheiden_id) { $bescheid = $b; break; } if ($bescheid) $bescheiden->addChild( 'zeichnung', site_url( '/dossiers/bescheiden_downloaden/' . $lb->dossier_bescheiden_id ) ); } // koppel fotos if (isset( $data['deelplanuploads'][$vraag->id] )) foreach ($data['deelplanuploads'][$vraag->id] as $upload) $fotos->addChild( 'foto', site_url( '/deelplannen/deelplanupload_download/' . $upload->id ) ); } } $tmp_file = '/tmp/meldung-' . $deelplan->id . '.xml'; if (!@file_put_contents( $tmp_file, $xml->asXML() )) die( tgng( 'php.algemene_schijf_fout' ) ); $this->load->library( 'email' ); $this->email->from( config_item( 'mail_sender' ) ); $this->email->reply_to( config_item( 'mail_sender' ) ); $this->email->to( $email_addresses ); $this->email->subject( 'M-Kart Mobil Meldung' ); $this->email->message( 'M-<NAME>' ); $this->email->attach( $tmp_file ); if (!$this->email->send()) die( tgng( 'php.algemene_fout_bij_verzenden_email' ) ); // nu alle vragen resetten! $stmt_name = 'deelplannen::verzend_email::reset_antwoord'; $this->dbex->prepare( $stmt_name, 'UPDATE deelplan_vragen SET status = ? WHERE deelplan_id = ? AND vraag_id = ?' ); foreach ($data['onderwerpen'] as $onderwerp_id => $onderwerp_data) { foreach ($onderwerp_data['vragen'] as $vraag) { $tempVraag = $this->vraag->get( $vraag->id ); $standaard = $tempVraag->get_standaard_antwoord(); if ($standaard->is_leeg) $nieuwe_waarde = null; else $nieuwe_waarde = $standaard->status; $this->dbex->execute( $stmt_name, array( $nieuwe_waarde, $vraag->deelplan_id, $vraag->id ) ); } } echo "OK"; } } public function wetteksten() { $this->load->model('grondslagtekst'); $this->load->library('quest'); $nojs = @$_POST['nojs']=='1'; $ids = @json_decode( $_POST['grondslag_tekst_ids'] ); if (!is_array( $ids ) || empty( $ids )) $grondslagteksten = array(); else $grondslagteksten = $this->grondslagtekst->search( array(), 'id IN (' . implode(',',$ids) . ')' ); if (!$nojs) { $this->load->view( 'deelplannen/wetteksten', array( 'grondslagteksten' => $grondslagteksten, ) ); } else { // build JS data $teksten = array(); foreach ($grondslagteksten as $grondslagtekst) { /** * NO LONGER FETCH REMOTELY! $tekst = $grondslagtekst->get_artikel_tekst(); */ $tekst = $grondslagtekst->tekst; if (is_null( $tekst ) || !strlen($tekst)) continue; $gs = $grondslagtekst->get_grondslag(); if ($gs && $gs->quest_document && $grondslagtekst->quest_node) $bw_url = sprintf( config_item( 'briswarenhuis_url' ), trim( $grondslagtekst->quest_node, '/' ) ); else $bw_url = ''; $teksten[] = array( 'grondslag_tekst_id' => $grondslagtekst->id, 'bw_url' => $bw_url, 'tekst' => $tekst, ); } echo json_encode(array( 'success' => true, 'teksten' => $teksten, ) ); } } public function verantwoordingen( $checklistgroep_id ) { $this->load->model( 'verantwoording' ); $json_output = isset( $_POST ) && isset( $_POST['json'] ) && $_POST['json']==1; $verantwoordingen = $this->verantwoording->get_for_checklist_groep( $checklistgroep_id ); $this->load->view( 'deelplannen/verantwoordingen', array( 'verantwoordingen' => $verantwoordingen, 'json_output' => $json_output, ) ); } public function verantwoordingen2( $checklistgroep_id, $checklist_id=null, $json=0 ) { $this->load->model( 'deelplan' ); $json_output = $json || (isset( $_POST ) && isset( $_POST['json'] ) && $_POST['json']==1); $this->load->view( 'deelplannen/verantwoordingen2', array( 'verantwoordingen' => $this->deelplan->laad_verantwoordingsteksten($checklistgroep_id, $checklist_id), 'json_output' => $json_output, ) ); } public function opdracht_afbeelding( $type, $id, $index=0, $upload_id=0 ) { $etag = sha1( 'opdracht_afbeelding-' . $type . '-' . $id . '-' . $index ); if (@$_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header("HTTP/1.1 304 Not Modified"); exit; } if (!in_array( $type, array( 'overzicht', 'snapshot', 'overzicht_preview', 'snapshot_preview', 'upload' ))) throw new Exception( 'Fout bij ophalen afbeelding: opgegeven type niet geldig' ); $this->load->model( 'deelplanopdracht' ); if (!$opdracht = $this->deelplanopdracht->get( $id )) /* handles security */ throw new Exception( 'Fout bij ophalen afbeelding: opgegeven ID niet geldig.' ); switch ($type) { case 'overzicht': $png = $opdracht->{$type . '_afbeelding_' . $index}; break; case 'snapshot': $png = $opdracht->{$type . '_afbeelding'}; break; case 'overzicht_preview': // bake super image $images = array(); $w = $h = 0; for ($i=0; $i<$opdracht->get_overzicht_afbeelding_aantal(); ++$i) { $images[] = imagecreatefromstring( $opdracht->{'overzicht_afbeelding_' . $i} ); $w = imagesx( $images[$i] ); $h += imagesy( $images[$i] ); } $im = imagecreatetruecolor( $w, $h ); $y = 0; for ($i=0; $i<$opdracht->get_overzicht_afbeelding_aantal(); ++$i) { imagecopy( $im, $images[$i], 0, $y, 0, 0, imagesx( $images[$i] ), imagesy( $images[$i] ) ); $y += imagesy( $images[$i] ); imagedestroy( $images[$i] ); } ob_start(); imagepng( $im ); $png = ob_get_clean(); imagedestroy( $im ); // resize result $im = new Imagick(); $im->readImageBlob( $png ); $im->scaleImage( $index /* is width! */, 0 ); $png = $im->getImageBlob(); $im->destroy(); break; case 'snapshot_preview': $im = new Imagick(); $im->readImageBlob( $opdracht->snapshot_afbeelding ); $im->scaleImage( $index /* is width! */, 0 ); $png = $im->getImageBlob(); $im->destroy(); break; case 'upload': $im = new Imagick(); $this->load->model('deelplanupload'); $deelplanupload = $this->deelplanupload->get( $upload_id ); $im->readImageBlob( $deelplanupload->get_data() ); if ($index > 0) { $im->scaleImage( $index /* is width! */, 0 ); } $png = $im->getImageBlob(); $im->destroy(); break; } if (!$png) throw new Exception( 'Fout bij ophalen afbeelding: geen afbeelding van type ' . $type . '/' . $index . ' in database aanwezig.' ); // output $cacheTime = 365 * 86400; $cacheExpires = strtotime( '+1 year' ); header( 'Content-Type: image/png' ); header( 'Content-Length: ' . strlen($png) ); header( 'Cache-Control: max-age=' . $cacheTime . ',public' ); header( 'Pragma: public' ); header( 'Expires: ' . date( 'D, d M Y H:i:s ', $cacheExpires ) ) . ' UTC'; header( 'Last-Modified: ' . date( 'D, d M Y H:i:s ' ) ) . ' GMT'; header( 'Etag: ' . $etag ); echo $png; } public function opdrachtenoverzicht( $deelplan_id, $bouwnummer_id = '-', $context_model=null, $context_id=null, $opdrachtgever_id='-', $opdrachtnemer_id='-', $datum='-', $locatie='-', $groen_filter=true, $oranje_filter=true, $rood_filter=true ) { // we want the base URL to always include something of a model or id // so that filtering URLs can be baked easily if (is_null( $context_model )) redirect( '/deelplannen/opdrachtenoverzicht/' . $deelplan_id . '/-/-/-' ); $this->load->model('gebruiker'); $logged_in_gebruiker = $this->gebruiker->get_logged_in_gebruiker(); $klant = $logged_in_gebruiker->get_klant(); // initialiseer op basis van input, en check security $this->load->model('deelplan'); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) throw new Exception( 'Geen toegang tot opgevraagde deelplan (1).' ); $this->_check_deelplan_security( $deelplan, true ); $dossier = $deelplan->get_dossier(); // bouw navigatie pad op $this->load->model( 'checklist' ); $this->load->model( 'hoofdgroep' ); $this->load->model( 'vraag' ); $this->load->model( 'deelplanchecklist' ); $this->load->model( 'categorie' ); $this->load->model( 'deelplanchecklisttoezichtmoment' ); $this->load->model( 'projectmap' ); $this->load->model( 'deelplanopdracht' ); $this->navigation->push( 'nav.opdrachtenoverzicht', '/deelplannen/opdrachtenoverzicht/' . $deelplan_id . '/' . $bouwnummer_id . '/-/-/' . $opdrachtgever_id . '/' . $opdrachtnemer_id . '/' . $datum . '/' . $locatie . '/' . $groen_filter . '/' . $oranje_filter . '/' . $rood_filter, array( $deelplan->naam ) ); $pad = array(); $current = ($context_model && $context_model != '-') ? $this->$context_model->get( $context_id ) : null; while ($current) { $pad[] = $current; $current = $current->get_wizard_parent(); if ($current instanceof ChecklistGroepResult) $current = null; } $pad = array_reverse( $pad ); foreach ($pad as $object) { $omodel = $object->get_model_name(); if ($omodel == 'deelplanopdracht') { $omschrijving = $object->opdracht_omschrijving; } else { $omschrijving = $object->naam; } $this->navigation->push( 'nav.opdrachtenoverzicht_pad_element', '/deelplannen/opdrachtenoverzicht/' . $deelplan_id . '/' . $bouwnummer_id . '/' . $omodel . '/' . $object->id . '/' . $opdrachtgever_id . '/' . $opdrachtnemer_id . '/' . $datum . '/' . $locatie . '/' . $groen_filter . '/' . $oranje_filter . '/' . $rood_filter, array( $omschrijving ) ); } // haal opdrachten structuur op $data = array(); $alle_data = array(); $alle_betrokkenen = array(); $alle_locaties = array(); $alle_bouwnummers = array(''); $data_debug = array(); if ($bouwnummer_id != '-') { $opdrachten = $this->deelplanopdracht->get_by_deelplan_checklistgroep_checklist( $deelplan->id, null, null, $bouwnummer_id ); } else { $opdrachten = $this->deelplanopdracht->get_by_deelplan_checklistgroep_checklist( $deelplan->id ); } $proj_vragen_ind = array(); if( $klant->heeft_toezichtmomenten_licentie=='ja' ) { $proj_vragen = $this->projectmap->get_by_deelplan( $deelplan ); foreach( $proj_vragen as $pvraag ) { $proj_vragen_ind[$pvraag->vraag_id] = $pvraag; } } $alle_opdrachtgevers = $alle_opdrachtnemers = $bw_statuses = array(); foreach ($opdrachten as $opdracht) { // get objects $vraag = $opdracht->get_vraag(); $hoofdgroep = $vraag->get_categorie()->get_hoofdgroep(); $checklist = $hoofdgroep->get_checklist(); // setup alle arrays $opdrachtDatum = $opdracht->gereed_datum; if (!in_array( $opdrachtDatum, $alle_data )) $alle_data[] = $opdrachtDatum; $opdrachtLocatie = $opdracht->annotatie_tag; $deelplanChecklist = $this->deelplanchecklist->get( $opdracht->deelplan_checklist_id ); if (!is_null($deelplanChecklist) && !is_null($deelplanChecklist->bouwnummer) & $deelplanChecklist->bouwnummer !='') { $bouwnummer = $deelplanChecklist->bouwnummer; } else { $bouwnummer = '-'; } if ($opdrachtLocatie) if (!in_array( $opdrachtLocatie, $alle_locaties )) $alle_locaties[] = $opdrachtLocatie; $opdrachtBetrokkene_id = $opdracht->get_dossier_subject()->gebruiker_id; if (!$opdrachtBetrokkene_id) { $opdrachtBetrokkene_id= $opdracht->opdrachtgever_gebruiker_id; } get_instance()->gebruiker->setSkipCheck(); if (!isset( $alle_betrokkenen[$opdrachtBetrokkene_id] )) { if ($opdracht->get_dossier_subject()->get_gebruiker()) { $alle_betrokkenen[$opdrachtBetrokkene_id] = $opdracht->get_dossier_subject()->get_gebruiker(); } else { $alle_betrokkenen[$opdrachtBetrokkene_id] = $opdracht->get_dossier_opdrachtgever(); } } $opdrachtOpdrachtgever_id = $opdracht->opdrachtgever_gebruiker_id; if (!isset( $alle_opdrachtgevers[$opdrachtOpdrachtgever_id] )) { $alle_opdrachtgevers[$opdrachtOpdrachtgever_id] = $opdracht->get_dossier_opdrachtgever()->volledige_naam; } $opdrachtOpdrachtnemer_id = $opdracht->dossier_subject_id; if (!isset( $alle_opdrachtnemers[$opdrachtOpdrachtnemer_id] )) { if ($opdracht->get_dossier_subject()->get_gebruiker()) { $alle_opdrachtnemers[$opdrachtOpdrachtnemer_id] = $opdracht->get_dossier_subject()->get_gebruiker()->volledige_naam; } else { $alle_opdrachtnemers[$opdrachtOpdrachtnemer_id] = $opdracht->get_dossier_subject()->naam .($opdracht->get_dossier_subject()->organisatie ? " (".$opdracht->get_dossier_subject()->organisatie.")" : ""); } } // apply filter to this opdracht, bail on it if filters say we shouldn't show it if (!is_null( $opdrachtgever_id ) && $opdrachtgever_id != '-' && $opdrachtOpdrachtgever_id != $opdrachtgever_id) continue; if (!is_null( $opdrachtnemer_id ) && $opdrachtnemer_id != '-' && $opdrachtOpdrachtnemer_id != $opdrachtnemer_id) continue; if (!is_null( $datum ) && $datum != '-' && $opdrachtDatum != $datum) continue; if (!is_null( $locatie ) && $locatie != '-' && $opdrachtLocatie != rawurldecode( $locatie )) continue; $vraag = $opdracht->get_vraag(); $opdrachtKleur = $vraag->get_waardeoordeel_kleur( true, $opdracht->antwoord ); if ($opdrachtKleur == 'groen' && !$groen_filter) continue; if ($opdrachtKleur == 'oranje' && !$oranje_filter) continue; if ($opdrachtKleur == 'rood' && !$rood_filter) continue; // build data structure if (!isset( $data[$bouwnummer] )) $data[$bouwnummer]= array( 'object' => '', 'status' => '', 'gereed' => null, 'datum' => '', 'children' => array(), 'bouwnummer' => $bouwnummer, 'bouwnummer_identifier' => true, ); if (!isset( $data[$bouwnummer]['children'][$checklist->id] )) $data[$bouwnummer]['children'][$checklist->id] = array( 'object' => $checklist, 'status' => '', 'gereed' => null, 'datum' => '', 'children' => array(), 'bouwnummer' => $bouwnummer, ); if (!isset( $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id] )) $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id] = array( 'object' => $hoofdgroep, 'status' => '', 'gereed' => null, 'datum' => '', 'children' => array(), 'bouwnummer' => $bouwnummer, ); if (!isset( $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id] )) $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id] = array( 'object' => $vraag, 'status' => '', 'gereed' => null, 'datum' => '', 'children' => array(), 'bouwnummer' => $bouwnummer, ); if (!isset( $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id]['children'][$opdracht->id] )) $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id]['children'][$opdracht->id] = array( 'object' => $opdracht, 'status' => '', 'gereed' => null, 'datum' => '', 'children' => array(), 'bouwnummer' => $bouwnummer, ); $data[$bouwnummer]['children'][$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id]['children'][$opdracht->id]['children'][] = $opdracht; // $data[$checklist->id]['children'][$hoofdgroep->id]['children'][$vraag->id]['children'][] = 'opdracht / '.$opdracht->id; if( $klant->heeft_toezichtmomenten_licentie=='ja' ) { $deelplanchecklist = $this->deelplanchecklist->get($opdracht->deelplan_checklist_id); if (isset($proj_vragen_ind[$vraag->id])) { $pvraag= $proj_vragen_ind[$vraag->id]; } else { $pvraag = null; } if (isset($deelplanchecklist->id) && isset ($pvraag->toezichtmoment_id)) { $dp_chklst_tmoment = $this->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist( $deelplanchecklist->id, $pvraag->toezichtmoment_id ); $bw_status = $dp_chklst_tmoment[0]->status_akkoord_woningborg; } else { $bw_status = 1; } if (isset($deelplanchecklist->bouwnummer)) { $idd = $hoofdgroep->id.$deelplanchecklist->bouwnummer; $hf_ind = sha1( $idd ); $bw_statuses["$hf_ind"] = $bw_status; } } } // haal het deel eruit wat getoond moet worden foreach ($pad as $object) { if (key_exists($bouwnummer_id, $data)) { if (!isset( $data[$bouwnummer_id]['children'][$object->id]['children'] )) { $data = array(); break; } $data = $data[$bouwnummer_id]['children'][$object->id]['children']; } else { if (!isset( $data[$object->id]['children'] )) { $data = array(); break; } $data = $data[$object->id]['children']; } } // bepaal status, gereed-zijn en eerstvolgende datum van de top data elementen hoofdgroep $data = $this->_opdrachtenoverzicht_zet_status_en_overige_data( $data ); // alle arrays sortering sort( $alle_locaties ); sort( $alle_bouwnummers ); sort( $alle_data ); // MJ 15-04-2016: changed usort to uasort in order to preserve the opdrachtgever id uasort( $alle_opdrachtgevers, function( $a, $b ){ if (isset( $a->volledige_naam ) && isset($b->volledige_naam )) { return strcasecmp( $a->volledige_naam, $b->volledige_naam ); } }); if( $klant->heeft_toezichtmomenten_licentie=='ja') { if('checklist' == $context_model) { $this->load->model( 'btbtzdossier' ); $bt_btz_dossier = $this->btbtzdossier->get_one_by_btz_dossier_id( $dossier->id ); if ($bt_btz_dossier) { $alle_bouwnummers = $bt_btz_dossier->get_bouwnummers(); } $data = $this->setHfGereedStatus( $data, $alle_bouwnummers, $opdrachten ); } } // render view $this->load->view( 'deelplannen/opdrachtenoverzicht', array( // global data 'klant' => $klant, 'deelplan' => $deelplan, 'dossier' => $dossier, 'data' => $data, 'bouwnummer_id' => $bouwnummer_id, // context we're in 'context_model' => $context_model, 'context_id' => $context_id, // list of alle <something> 'alle_data' => $alle_data, 'alle_opdrachtgevers' => $alle_opdrachtgevers, 'alle_opdrachtnemers' => $alle_opdrachtnemers, 'alle_locaties' => $alle_locaties, 'alle_bouwnummers' => $alle_bouwnummers, // filters 'opdrachtgever_id' => $opdrachtgever_id, 'opdrachtnemer_id' => $opdrachtnemer_id, 'datum' => $datum, 'locatie' => rawurldecode( $locatie ), 'groen_filter' => $groen_filter, 'oranje_filter' => $oranje_filter, 'rood_filter' => $rood_filter, 'bw_statuses' => $bw_statuses ) ); } public function change_status_akkoord( $hoofdgroepId ){ $this->load->model( 'deelplanchecklist' ); $this->load->model( 'deelplanchecklisttoezichtmoment' ); $this->load->model( 'toezichtmoment' ); $toezichtmoment = $this->toezichtmoment->get_by_hoofdgroep( $hoofdgroepId ); $deelplan_id = $_POST['deelplan_id']; $deelplanchecklisten = $this->deelplanchecklist->get_by_deelplan( $deelplan_id ); foreach( $deelplanchecklisten as $deelplanchecklist ) { if( $deelplanchecklist->bouwnummer == $_POST['bouwnummer'] ) { break; } } $dp_ch_moment = $this->deelplanchecklisttoezichtmoment->get_by_deelplanchecklist( $deelplanchecklist->id, $toezichtmoment->id ); $dp_ch_moment = $dp_ch_moment[0]; $dp_ch_moment->status_akkoord_woningborg = !$dp_ch_moment->status_akkoord_woningborg; $dp_ch_moment->save(); echo json_encode( array('success' => true ) ); } private function setHfGereedStatus( $data, $bouwnummers, $opdrachten ){ $debug_gereed = true; foreach( $data as $hoofdgroep_id => &$hfdata ){ $hfdata['bwgereed'] = array(); foreach( $bouwnummers as $bouwnummer ){ $gereed = true; foreach( $opdrachten as $opdracht ){ $odlp_chk_lst = $this->deelplanchecklist->get($opdracht->deelplan_checklist_id); if ( isset($odlp_chk_lst->bouwnummer) && ($odlp_chk_lst->bouwnummer == $bouwnummer) ){ $vraag = $this->vraag->get($opdracht->vraag_id); $category = $this->categorie->get($vraag->categorie_id); if($category->hoofdgroep_id == $hoofdgroep_id){ if($opdracht->status != 'gereed' ){ $gereed = false; break; } } } } $hfdata['bwgereed']["$bouwnummer"] = $gereed; } } return $data; } private function _opdrachtenoverzicht_zet_status_en_overige_data( array $data ) { // if 'children' is set and is_bouwnummer is not, this is an array of bouwnummers, checklists, hoofdgroepen or vragen // else it is an opdracht and needs to stay in tact. // $data[$hoofdgroep->id]['children'][$vraag->id]['children'][] = $opdracht; //ATT: Such data we have for hoofdgroepen level. $first = reset( $data ); if (is_array( $first ) && isset( $first['children'] )) { foreach ($data as $i => $entry) { // do children first $entry['children'] = $this->_opdrachtenoverzicht_zet_status_en_overige_data( $entry['children'] ); // then update object $worst_status = 'groen'; $eerste_datum = '2099-12-31'; $gereed = true; foreach ($entry['children'] as $child_id=>$child) { if (is_object( $child )) { // opdracht! $vraag = $child->get_vraag(); $nieuwe_status = $vraag->get_waardeoordeel_kleur( true, $child->antwoord ); $nieuwe_datum = $child->gereed_datum; $nieuwe_gereed = $child->status == 'gereed'; } else { // checklist, hoofdgroep of vraag! $nieuwe_status = $child['status']; $nieuwe_datum = $child['datum']; $nieuwe_gereed = $child['gereed']; } // werk onze data bij op basis van nieuwe info if (isset($nieuwe_status) && isset($nieuwe_datum) && isset($nieuwe_gereed)) { if ($nieuwe_status == 'rood' || ($nieuwe_status == 'oranje' && $worst_status == 'groen')) $worst_status = $nieuwe_status; if (strtotime($eerste_datum) > strtotime( $nieuwe_datum )) $eerste_datum = $nieuwe_datum; if (!$nieuwe_gereed) $gereed = $nieuwe_gereed; } } // set data. If we have a bouwnummer identifier, make sure the information is set to the underlying checklists if (isset($data[$i]['bouwnummer_identifier']) && $data[$i]['bouwnummer_identifier']) { $data[$i]['children'][$child_id]['status'] = $worst_status; $data[$i]['children'][$child_id]['datum'] = $eerste_datum; $data[$i]['children'][$child_id]['gereed'] = $gereed; } else { $data[$i]['status'] = $worst_status; $data[$i]['datum'] = $eerste_datum; $data[$i]['gereed'] = $gereed; } } } return $data; } public function project_specifieke_mapping( $deelplan_id ) { $this->load->model('deelplan'); $this->load->model('btbtzdossier'); $this->load->model( 'colectivematrix' ); $deelplan = $this->deelplan->get( $deelplan_id ); if ($deelplan==null) { redirect(); } // else //ATT: Don't delete for any case. // { // $this->_check_deelplan_security( $deelplan ); // if ($deelplan->get_access_to_deelplan() != 'write') // redirect( '/deelplannen/bekijken/' . $deelplan_id ); // } $this->navigation->push( 'nav.deelplan_mappingen', '/deelplannen/mappingen/' . $deelplan_id, array( $deelplan->naam ) ); $bt_btz_doss = $this->btbtzdossier->get_one_by_btz_dossier_id( $deelplan->dossier_id ); $bt_project_matrix = $this->colectivematrix->getProjectSpecifiekeMapping( $bt_btz_doss->bt_dossier_id, $bt_btz_doss->bt_dossier_hash ); $this->load->view( 'mappingen/project_specifieke_mapping', array( 'deelplan_id' => $deelplan_id ,'bt_project_matrix'=> $bt_project_matrix ,'bt_dossier_id'=> $bt_btz_doss->bt_dossier_id ) ); } public function setintegraalstatus( $deelplan_id ){ try{ $this->load->model( 'deelplan' ); $deelplan = $this->deelplan->get( $deelplan_id ); $deelplan->geintegreerd = $_POST['geintegreerd']; $deelplan->save(); }catch( Exception $e ){ echo json_encode( array('success' => false, 'message' => $e->getMessage() ) ); } echo json_encode( array('success' => true ) ); } } <file_sep>REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('dossier.bristoetsstatus', 'BRIStoets status', NOW(), 0), ('dossier.bristoezichtstatus', 'BRIStoezicht status', NOW(), 0), ('dossier.projectstatus', 'Projectstatus', NOW(), 0) ; <file_sep><? $this->load->view('extern/header'); ?> <div class='page'> <div class='logo'><img src="<?=site_url('/files/images/logo-transparent.png')?>" /></div> <div class='main'> <div class='login'> <div > <form method="post"> <input type="hidden" name="post_login_location" value="<?=$post_login_location?>"> <? if ( isset($error)): ?> <p class="error"><? echo $error; ?></p> <? endif; ?> <? if ( isset($token )): ?> <? if ( isset($token_is_valid ) && $token_is_valid == true): ?> <input type="text" name="email" placeholder="<?=tg('mail')?>:"><br> <input type="<PASSWORD>" name="password" placeholder="<?=tg('password')?>:"><br> <input type="<PASSWORD>" name="new_password" placeholder="<?=tg('<PASSWORD>')?>:"><br> <input type="hidden" name="token" value="<?=$token?>"> <button value="setpassword"><?=tg('setpassword')?></button> <? else: ?> <p class="error"><?=tg('invalid_token')?></p> <? endif; ?> <? else: ?> <input type="text" name="email" placeholder="<?=tg('mail')?>:"><br> <input type="password" name="password" placeholder="<?=tg('password')?>:"><button id="pwdreset" value="" title="Reset Password">?</button><br> <button value="login"><?=tg('login')?></button><input type="checkbox" title="<?=tg('stayloggedin')?>"> <? endif; ?> </form> </div> </div> </div> </div> <file_sep><?php function getDefChklstGrpIconUrl() { $instace = get_instance(); if( $lc = $instace->session->_loginSystem->get_lease_configuratie_id() ) { $instace->load->model( 'leaseconfiguratie' ); $lease_name = $instace->leaseconfiguratie->get($lc)->naam; return '/files/images/lease/checklistgroep-icon_' . $lease_name . '.png'; } return site_url('/files/checklistwizard/checklistgroep-icon.png'); } ?> <div class="main"> <? $this->load->view( 'checklistwizard/_checklist_status' ) ?> <? if (!@$checklistgroep || !$checklistgroep->is_wizard_readonly()): ?> <table cellspacing="0" cellpadding="0" border="0" class="list"> <tr> <td colspan="3"> <input type="text" name="naam" size="80" class="rounded5" placeholder="<?=isset($placeholder) ? $placeholder : 'Naam'?>"> <div class="button snel" style="margin-left: 10px;"> <i class="icon-plus" style="font-size: 12pt;"></i> <span>Snel</span> </div> <?=htag('snel')?> <div class="button uitgebreid" style="margin-left: 10px;"> <i class="icon-plus" style="font-size: 12pt"></i> <span>Uitgebreid</span> </div> <?=htag('uitgebreid')?> </td> </tr> </table> <? else: ?> <br/><br/> <? endif; ?> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($entries as $i => $entry): ?> <? $bottom = ($i==sizeof($entries)-1) ? 'bottom' : ''; $readonly = $entry->is_wizard_readonly(); ?> <li class="entry top left right <?=$bottom?> <?=$readonly?'readonly':''?>" entry_id="<?=$get_id($entry)?>" aantal_onderliggenden="<?=isset( $settings_url ) ? $get_aantal_onderliggenden( $entry ) : ''?>"> <img style="margin-left: 3px; padding-top: 10px; vertical-align: bottom;" src="<?=($im=$get_image($entry)) ? $im->get_url() : getDefChklstGrpIconUrl() ?>"> <div class="list-entry" style="margin-top: 3px; vertical-align: bottom;"><?=htmlentities( $get_naam($entry), ENT_COMPAT, 'UTF-8' )?></div> <? if (!$readonly): ?> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton verwijder" title="<?=tgng('checklistwizard.lijst.verwijder')?>"><i class="icon-trash" style="font-size: 12pt"></i></div> <? endif; ?> <? if (!$readonly || $entry instanceof ChecklistGroepResult): ?> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton kopieer" title="<?=tgng('checklistwizard.lijst.kopieer')?>"><i class="icon-copy" style="font-size: 12pt"></i></div> <? endif; ?> <? if (!$readonly): ?> <div style="margin-top: 5px; margin-left: 3px; float:right;" class="optiebutton settings" title="<?=tgng('checklistwizard.lijst.settings')?>"><i class="icon-cog" style="font-size: 12pt"></i></div> <? endif; ?> <? if ($readonly): ?> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.locked')?>"> <i class="icon-lock" style="font-size: 12pt; opacity: 1; color: #A00;"></i> </div> <? else: ?> <? if ($entry instanceof ChecklistResult): $in_gebruik = $entry->is_in_gebruik(); $afgerond = $entry->is_afgerond(); ?> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.' . ($in_gebruik ? 'in-gebruik' : 'niet-in-gebruik'))?>"> <i class="icon-warning-sign" style="font-size: 12pt; opacity: <?=$in_gebruik ? 1 : 0.25;?>; color: <?=$in_gebruik ? '#000' : '#777'?>;"></i> </div> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.' . ($afgerond ? 'actief' : 'niet-actief'))?>"> <i class="icon-eye-open" style="font-size: 12pt; opacity: <?=$afgerond ? 1 : 0.25;?>; color: <?=$afgerond ? '#000' : '#777'?>;"></i> </div> <? endif; ?> <? if ($entry instanceof ChecklistGroepResult): $afgerond = $entry->is_afgerond(); ?> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.checklist.' . ($afgerond ? 'actief' : 'niet-actief'))?>"> <i class="icon-eye-open" style="font-size: 12pt; opacity: <?=$afgerond ? 1 : 0.25;?>; color: <?=$afgerond ? '#000' : '#777'?>;"></i> </div> <? endif; ?> <? if ($afwijking = wizard_object_heeft_afwijkingen( $entry )): ?> <div style="float: right; margin-right: 8px; margin-top: 8px;" title="<?=tgng( 'checklistwizard.' . ($afwijking==2 ? 'default-afwijkingen' : 'zelf-default-afwijkingen') )?>"> <i class="<?=$afwijking==2 ? 'icon-flag-alt' : 'icon-flag'?>" style="font-size: 12pt; opacity: 1; color: #000;"></i> </div> <? endif; ?> <? endif; ?> </li> <? endforeach; ?> </ul> </div> <script type="text/javascript"> $(document).ready(function(){ // stop event propagation down to parents for all optie buttons $('ul.list div.optiebutton').click(function(event){ eventStopPropagation (event); }); // bij het klikken op de activiteitsknop de checklist editen om deze actief te maken! $('ul.list div.actiefbutton').click(function(event){ eventStopPropagation (event); $(this).closest('li').find('div.optiebutton.settings').trigger('click'); }); // handle uitgebreid toevoegen $('div.main div.button.uitgebreid').click(function(){ location.href = '<?=site_url($add_uitgebreid_url)?>/' + encodeURIComponent( $('div.main input[type=text]').val() ); }); // handle toevoegen $('div.main input[type=text]').keypress(function(event){ if (event.which == 13) $('div.main div.button.snel').trigger('click'); }); $('div.main div.button.snel').click(function(){ $.ajax({ url: '<?=site_url($add_url)?>', type: 'POST', data: { naam: $('div.main input[type=text]').val() }, dataType: 'json', success: function( data ) { if (data && data.success) location.href = location.href; // refresh else { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen:<br/><br/><i>' + data.error + '</i>', type: 'error', buttons: ['ok'] }); } }, error: function() { showMessageBox({ message: 'Er is iets fout gegaan bij het toevoegen.', type: 'error', buttons: ['ok'] }); } }); }); // handle verwijderen $('ul.list div.optiebutton.verwijder').click(function(event){ var thiz = this; var entry_id = $(this).closest('[entry_id]').attr('entry_id'); if (entry_id) { showMessageBox({ message: 'Wilt u <b>' + $(this).siblings('div.list-entry').html() + '</b> werkelijk verwijderen? U kunt deze actie niet ongedaan maken!', type: 'warning', buttons: ['yes', 'cancel'], onClose: function( response ) { if (response == 'yes') { showPleaseWait(); // delay slightly to prevent double-messagebox-issues setTimeout( function() { var showError = function() { hidePleaseWait(); showMessageBox({ message: 'Er is iets fout gegaan bij het verwijderen.', type: 'error', buttons: ['ok'] }); }; $.ajax({ url: '<?=site_url($delete_url)?>', type: 'POST', data: { entry_id: entry_id }, dataType: 'html', success: function( data ) { if (data != 'OK') showError(); else { hidePleaseWait(); $(thiz).closest('li').remove(); } }, error: function() { showError(); } }); }, 500 ); } } }); } }); // handle kopieren $('ul.list div.optiebutton.kopieer').click(function(event){ var thiz = this; var entry_id = $(this).closest('[entry_id]').attr('entry_id'); if (entry_id) { showMessageBox({ message: 'Wilt u echt <b>' + $(this).siblings('div.list-entry').html() + '</b> dupliceren?', type: 'notice', buttons: ['yes', 'cancel'], onClose: function( response ) { if (response == 'yes') { showPleaseWait(); // delay slightly to prevent double-messagebox-issues setTimeout( function() { var showError = function() { hidePleaseWait(); showMessageBox({ message: 'Er is iets fout gegaan bij het dupliceren.', type: 'error', buttons: ['ok'] }); }; $.ajax({ url: '<?=site_url($copy_url)?>', type: 'POST', data: { entry_id: entry_id }, dataType: 'html', success: function( data ) { if (data != 'OK') showError(); else location.href = location.href; // refresh }, error: function() { showError(); } }); }, 500 ); } } }); } }); // handle settings $('ul.list div.optiebutton.settings').click(function(event){ var entry_id = $(this).closest('[entry_id]').attr('entry_id'); location.href = '<?=$defaults_url?>/' + entry_id; }); }); </script><file_sep>ALTER TABLE `klanten` ADD `kan_dossieroverzichten_genereren` ENUM( 'nee', 'ja' ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'nee' AFTER `heeft_toezichtmomenten_licentie`; <file_sep><?php class Lease extends Controller { public function do_lease( $lease, $not_redirect = false) { $this->load->model( 'leaseconfiguratie' ); $lease_configuratie_id = $this->session->_loginSystem->get_lease_configuratie_id(); // Try to login as lease config. $lc = $this->leaseconfiguratie->search( array( 'naam' => $lease ) ); if( $lease_configuratie_id && $lease_configuratie_id != $lc[0]->id ){ // $this->session->_loginSystem->forget_lease_configuratie_id(); // $this->login->logout(); // $_SESSION = array(); $this->reset(false); } if (empty( $lc )) redirect(); // zet nieuwe lease config in login systeem $this->session->_loginSystem->set_lease_configuratie_id( $lc[0]->id ); if(!$not_redirect) { // redirect naar root URL, zodat het login systeem kan afhandelen of je moet inloggen of niet redirect(); } } //public function do_telefoon($naam, $not_redirect = false) public function do_telefoon($dummy, $deelplan_parameters) { // Explode the second parameter on the commas. The last part of this string SHOULD be the lease name. If it is not, error out! $deelplan_parameter_parts = explode(",", $deelplan_parameters); // Check the validity of the various parts of information that were passed. if (sizeof($deelplan_parameter_parts) != 3) { throw new Exception('De URL om opdrachten op te vragen is ongeldig'); } else { // If we have exactly three parts, the last one SHOULD be the lease configuration name. For now, assume it really is, and // in case nothing is found, the normal error handling takes care of it. $naam = $deelplan_parameter_parts[2]; } // Try to get the lease configuration for the name that was passed. $this->load->model( 'leaseconfiguratie' ); $lc = $this->leaseconfiguratie->search( array( 'naam' => $naam ) ); //d($lc); // If nothing was found, we error out. if (empty( $lc )) { throw new Exception("De lease configuratie met de naam '{$naam}' bestaat niet"); //redirect(); } // zet nieuwe lease config in login systeem $this->session->_loginSystem->set_lease_configuratie_id( $lc[0]->id ); // Work out a post-login URL, being the one that points to the telephone interface. $post_login_location = 'telefoon/index/' . $deelplan_parameter_parts[0] . ',' . $deelplan_parameter_parts[1]; $post_login_location_encoded = base64_encode($post_login_location); redirect('gebruikers/inloggen/'.$post_login_location_encoded); //redirect(); /* if(!$not_redirect) { // redirect naar root URL, zodat het login systeem kan afhandelen of je moet inloggen of niet redirect(); } * */ } public function reset( $is_redirect=true ) { // verwijder lease config in login systeem $this->session->_loginSystem->forget_lease_configuratie_id(); // laat login systeem zichzelf netjes uitloggen $this->login->logout(); // maar verwijder echt alle sessie data daarna, dus ook de unsafe data $_SESSION = array(); if($is_redirect){ // redirect naar root URL zodat we defaults krijgen redirect(); } } } <file_sep>CREATE TABLE IF NOT EXISTS `dossier_bescheiden_mappen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_dossier_bescheiden_map_id` int(11) DEFAULT NULL, `dossier_id` int(11) NOT NULL, `naam` varchar(256) NOT NULL, PRIMARY KEY (`id`), KEY `parent_dossier_bescheiden_map_id` (`parent_dossier_bescheiden_map_id`), KEY `dossier_id` (`dossier_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ALTER TABLE `dossier_bescheiden_mappen` ADD CONSTRAINT `dossier_bescheiden_mappen_ibfk_2` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `dossier_bescheiden_mappen_ibfk_1` FOREIGN KEY (`parent_dossier_bescheiden_map_id`) REFERENCES `dossier_bescheiden_mappen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `dossier_bescheiden` ADD `dossier_bescheiden_map_id` INT NULL DEFAULT NULL, ADD INDEX ( `dossier_bescheiden_map_id` ) ; ALTER TABLE `dossier_bescheiden` ADD FOREIGN KEY ( `dossier_bescheiden_map_id` ) REFERENCES `dossier_bescheiden_mappen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ; <file_sep><? $tab = 200;?> <form name="risk_form" id="risk_form" method="post" action="/dossiers/save_pbm_risk/<?=$task->id?>"> <input type="hidden" name="id" id="id" value="<?=isset($risk->id)?$risk->id:''?>" /> <table class="rapportage-filter pago_pmo_form_tbl"> <tr><td class="column"><?=tg('risico_blootstelling')?></td><td class="input"><input type="text" name="risico_blootstelling" id="risico_blootstelling" value="<?=isset($risk->risico_blootstelling)?$risk->risico_blootstelling:''?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('wxbxe_w')?></td><td class="input"><input onblur="calculate_r();" type="text" name="wxbxe_w" id="wxbxe_w" value="<?=isset($risk->w)?$risk->w:0?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('wxbxe_b')?></td><td class="input"><input onblur="calculate_r();" type="text" name="wxbxe_b" id="wxbxe_b" value="<?=isset($risk->b)?$risk->b:0?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('wxbxe_e')?></td><td class="input"><input onblur="calculate_r();" type="text" name="wxbxe_e" id="wxbxe_e" value="<?=isset($risk->e)?$risk->e:0?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('wxbxe_r')?></td><td class="input"><input type="text" name="wxbxe_r" id="wxbxe_r" readonly="readonly" value="<?=isset($risk->r)?$risk->r:0?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('bronmaatregelen')?></td><td class="input"><input type="text" name="bronmaatregelen" id="bronmaatregelen" value="<?=isset($risk->bronmaatregelen)?$risk->bronmaatregelen:''?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td class="column"><?=tg('pbm')?></td><td class="input"><input type="text" name="pbm" id="pbm" value="<?=isset($risk->pbm)?$risk->pbm:''?>" tabindex="<?=$tab++?>" /></td></tr> <tr><td><button type="submit" tabindex="<?=$tab++?>">Opslaan</button></td><td><button type="button" onclick="cancel_pago_pmo_form();" tabindex="<?=$tab++?>">Annuleren</button></td></tr> </table> </form> <script> $('#risk_form').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), dataType: 'json', success: function (data) { alert( '<?=tg('successfully_saved')?>' ); var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pbm/' . $dossier->id)?>' ); }, error: function() { alert( '<?=tg('error_not_saved')?>' ); } }); }); function cancel_pago_pmo_form(){ var target = $("#pbm_tab").next().children(':first'); target.load( '<?=site_url('/dossiers/rapportage_pbm/' . $dossier->id)?>' ); } function calculate_r(){ var r=0. ,w,b,e ; w = $("#wxbxe_w").val().replace(",", "."); b = $("#wxbxe_b").val().replace(",", "."); e = $("#wxbxe_e").val().replace(",", "."); r = Math.round(w*b*e*100)/100; r = r.toString(); w = w.replace(".", ","); b = b.replace(".", ","); e = e.replace(".", ","); r = r.replace(".", ","); $("#wxbxe_w").val(w); $("#wxbxe_b").val(b); $("#wxbxe_e").val(e); $("#wxbxe_r").val(r); } </script> <file_sep><? $this->load->view('elements/header', array('page_header'=>'managementinfo') ); ?> <form method="POST"> <input type="hidden" name="tag" value="<?=$tag?>" /> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Periode', 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table> <tr> <td style="width: 100px">Vanaf:</td> <td><input type="text" value="<?=isset( $settings['van'] ) ? $settings['van'] : date('01-01-Y')?>" name="van" /></td> </tr> <tr> <td style="width: 100px">Tot:</td> <td><input type="text" value="<?=isset( $settings['tot'] ) ? $settings['tot'] : date('01-01-Y', strtotime('+1 year'))?>" name="tot" /></td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <!-- POSTCODE TAB START --> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Postcodegebied', 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <input type="button" value="Selecteer niks" mode="none" style="float: right"> <input type="button" value="Selecteer alles" mode="all" style="float: right"> <? foreach ($dossiers as $dossier):?> <? if(isset($dossier->locatie_postcode)):?> <? $checked = !is_array( $settings ) || isset( $settings['postcode'][$dossier->locatie_postcode] );?> <label> <input type="checkbox" name="postcode[<?=$dossier->locatie_postcode;?>]" <?=$checked?'checked':''?> value="<?=$dossier->locatie_postcode;?>"/> <?=htmlentities( $dossier->locatie_postcode, ENT_COMPAT, 'UTF-8' );?> </label><br/> <?endif;?> <? endforeach; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <!-- POSTCODE TAB END--> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Grafieken', 'expanded' => true, 'width' => '100%', 'height' => 'auto' ) ); ?> <input type="button" value="Selecteer niks" mode="none" style="float: right"> <input type="button" value="Selecteer alles" mode="all" style="float: right"> <? $fake_periode = new GrafiekPeriode( '01-01-2010', '01-01-2011' ); $fake_afmeting = new GrafiekAfmeting( 100, 100 ); $cur_categorie = null; ?> <table> <tr> <td style="vertical-align: top"> <? foreach ($grafiek_types as $grafiek_type): ?> <? $grafiek = $this->grafiek->maak( $fake_periode, $fake_afmeting, $grafiek_type ); $categorie = $grafiek->get_categorie(); if ($cur_categorie != $categorie) { if ($cur_categorie) echo '</td><td style="vertical-align: top">'; $cur_categorie = $categorie; echo '<h2>' . $cur_categorie . '</h2>'; } $checked = !is_array( $settings ) || isset( $settings['grafiek_types'][$grafiek_type] ); ?> <label> <input type="checkbox" name="grafiek_types[<?=$grafiek_type?>]" <?=$checked?'checked':''?> value=: /> <? if ($grafiek instanceof GrafiekSimpelPie3D): ?> <img src="<?=site_url('/files/images/chart_pie.png')?>" style="vertical-align: top" /> <? elseif (($grafiek instanceof GrafiekSimpelBar) || ($grafiek instanceof GrafiekSimpelBar2)): ?> <img src="<?=site_url('/files/images/chart_bar.png')?>" style="vertical-align: top" /> <? elseif ($grafiek instanceof GrafiekMultiBar): ?> <img src="<?=site_url('/files/images/chart_multibar.png')?>" style="vertical-align: top" /> <? else: ?> <img src="<?=site_url('/files/images/chart_curve.png')?>" style="vertical-align: top" /> <? endif; ?> <?=htmlentities( $grafiek->get_groeptitle(), ENT_COMPAT, 'UTF-8' );?> </label> <br/> <? endforeach; ?> </td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Scopes', 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Sjablonen', 'width' => '100%' ) ); ?> Gebruik een scope sjabloon: <select name="sjabloon_id"> <option value="" disabled selected>-- selecteer een sjabloon --</option> <? foreach ($sjablonen as $s): ?> <option value="<?=$s->id?>"><?=htmlentities( $s->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <br/> <input type="button" value="Selecteer niks" mode="none" style="float: right"> <input type="button" value="Selecteer alles" mode="all" style="float: right"> <br/><br/> <? foreach ($checklistgroepen as $checklistgroep): ?> <? $checked = !is_array( $settings ) || isset( $settings['checklistgroep'][$checklistgroep->id] ); ?> <div style="background-color:transparent;margin:0 0 10px 0;padding:10px;height:auto;border: 1px solid #ccc;background-color:#eee;"> <label> <input type="checkbox" name="checklistgroep[<?=$checklistgroep->id?>]" <?=$checked?'checked':''?> checklistgroep_id="<?=$checklistgroep->id?>" /> <? if ($checklistgroep->image_id): ?> <img src="<?=site_url('/content/images/' . $checklistgroep->image_id)?>" style="vertical-align: top" /> <? endif; ?> <span style="font-weight:bold; font-size:120%;"><?=$checklistgroep->naam?></span> </label> <br/> <ul style="list-style-type: none; padding-bottom: 5px; margin:0px; padding:0px; <?=$checked?'':'display:none;'?>"> <? foreach ($checklistgroep->get_checklisten() as $checklist): ?> <? $checked_checklist = !is_array( $settings ) || isset( $settings['checklist'][$checklist->id] ); ?> <li style="display: inline-block; width: 27em; padding: 5px; white-space: nowrap; overflow: hidden" title="<?=$checklist->naam?>"> <label for="sfg_<?=$checklist->id?>" style="cursor:pointer"> <input type="checkbox" name="checklist[<?=$checklist->id?>]" <?=$checked_checklist?'checked':''?> style="vertical-align: bottom" /> <?=$checklist->naam?> </label> </li> <? endforeach; ?> </ul> <input type="button" value="Selecteer niks" mode="none" style="<?=$checked?'':'display:none;'?>" geen_checklist_groepen="1"> <input type="button" value="Selecteer alles" mode="all" style="<?=$checked?'':'display:none;'?>" geen_checklist_groepen="1"> </div> <? endforeach; ?> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <? $this->load->view( 'elements/laf-blocks/generic-group-begin', array( 'header' => 'Uitvoer', 'expanded' => false, 'width' => '100%', 'height' => 'auto' ) ); ?> <table> <tr> <td style="width: 100px">Kleurstijl:</td> <td> <select name="theme"> <? foreach ($themes as $value => $desc): ?> <? $selected = (is_array( $settings ) && (@$settings['theme'] == $value)) || (!is_array( $settings ) && $value == 'pastel'); ?> <option value="<?=$value?>" <?=$selected ? 'selected' : ''?>><?=$desc?></option> <? endforeach; ?> </select> </td> </tr> <tr> <td style="width: 100px">Uitvoeren naar:</td> <td> <select name="uitvoer"> <? foreach (array( 'scherm' => 'Scherm', 'pdf' => 'PDF bestand' ) as $value => $desc): ?> <? $selected = is_array( $settings ) && (@$settings['uitvoer'] == $value); ?> <option value="<?=$value?>" <?=$selected ? 'selected' : ''?>><?=$desc?></option> <? endforeach; ?> </select> </td> </tr> </table> <? $this->load->view( 'elements/laf-blocks/generic-group-end' ); ?> <p> <input type="button" value="Aanmaken" class="aanmaken" /><?=htag('aanmaken')?> <div class="rapportage-progress" style="display: none; height:auto; border:0; background-color:transparent;"> <? $this->load->view( 'elements/laf-blocks/generic-progress-bar', array( 'extra_class' => 'rapportage', 'width' => '560px', 'proc' => 0, ) ); ?> <span class="rapportage-progress-text">0%</span> <br/> <span class="rapportage-progress-action"></span> </div> </p> </form> <script type="text/javascript"> $(document).ready(function(){ $('[name=van]').datepicker({ dateFormat: "dd-mm-yy" }); $('[name=tot]').datepicker({ dateFormat: "dd-mm-yy" }); $('input[checklistgroep_id]').click(function(){ $(this).parent().siblings('ul')[ this.checked ? 'slideDown' : 'slideUp' ](); $(this).parent().siblings( 'input' )[ this.checked ? 'slideDown' : 'slideUp' ](); }); $('input[mode]').click(function(){ var all = $(this).attr('mode') == 'all'; var noCGs = $(this).attr('geen_checklist_groepen') ? true : false; $(this).parent().find('input[type=checkbox]').each(function(){ if (noCGs && $(this).is('[checklistgroep_id]')) return; this.checked = all; if ($(this).is('[checklistgroep_id]')) { $(this).parent().siblings('ul')[ all ? 'slideDown' : 'slideUp' ](); $(this).parent().next().siblings('input')[ all ? 'slideDown' : 'slideUp' ](); } }); }); $('input.aanmaken').click(function(){ // init progress BRISToezicht.Progress.initialize( this, 'marap', '<?=$tag?>' ); // commit var data = {}; $(this).parents('form').find( 'input,select' ).each(function(){ var n = this.name; if (!n) return; if ($(this).attr('type') == 'checkbox') { if (this.checked) data[n] = 'on'; } else data[n] = $(this).val(); }); $.ajax({ url: '/instellingen/managementinfo', type: 'POST', data: data, dataType: 'json', success: function( data ) { if (!data.success) alert( 'Fout bij genereren van management rapportage:\n\n' + data.error ) else if(data.error_redirect) location.href = '/instellingen/managementinfo/error'; else if (data.tag) location.href = '/instellingen/managementinfo_download/' + data.tag; else location.href = '/instellingen/managementinfo_resultaat'; }, error: function() { alert( 'Communicatie- of serverfout.' ); } }); return true; }); $('select[name=sjabloon_id]').change(function(){ // deselect and hide all (both checklisten and checklistgroepen) $('input[name^=checklist]').each(function(){ this.checked = false; }); $('input[name^=checklistgroep]').parent().siblings('ul').slideUp(); // create helper functions var selectChecklistGroep = function( id ) { $('input[name=checklistgroep\\[' + id + '\\]]').each(function(){ if (!this.checked) { this.checked = true; $(this).parent().siblings('ul').slideDown(); } }); }; var selectChecklist = function( id ) { $('input[name=checklist\\[' + id + '\\]]').each(function(){ this.checked = true; }); }; switch (this.value) { <? foreach ($sjablonen as $sjabloon): ?> case '<?=$sjabloon->id?>': <? foreach ($sjabloon->get_checklisten() as $checklist): ?> selectChecklistGroep( <?=$checklist->checklist_groep_id?> ); selectChecklist( <?=$checklist->id?> ); <? endforeach; ?> break; <? endforeach; ?> } }); }); </script> <? $this->load->view('elements/footer'); ?><file_sep>ALTER TABLE `klanten` ADD `heeft_fine_kinney_licentie` ENUM('nee','ja') NOT NULL DEFAULT 'nee' AFTER `heeft_bel_import_licentie`; ALTER TABLE `bt_checklist_groepen` ADD `risico_model` ENUM( 'generiek', 'fine_kinney' ) NOT NULL DEFAULT 'generiek' AFTER `naam` ; ALTER TABLE `bt_risicoanalyse_kansen` ADD `fine_kinney_waarschijnlijkheid` FLOAT NOT NULL , ADD `fine_kinney_blootstelling` FLOAT NOT NULL ; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`, `lease_configuratie_id`) VALUES ('prioriteitstelling.beschrijving.zeer_hoog.generiek', 'Algehele controle van alle onderdelen ', '2014-06-28 19:37:16', 0), ('beheer.prioriteitstelling_matrix::prioriteitstelling.beschrijving.hoog.generiek', 'Beoordeling hoofdlijnen en kenmerkende details ', '2014-06-28 19:37:11', 0), ('prioriteitstelling.beschrijving.gemiddeld.generiek', 'Beoordeling van hoofdlijnen ', '2014-06-28 19:37:07', 0), ('beheer.prioriteitstelling_matrix::prioriteitstelling.beschrijving.laag.generiek', 'Visuele Controle ', '2014-06-28 19:37:02', 0), ('prioriteitstelling.beschrijving.zeer_laag.generiek', 'Steekproef ', '2014-06-28 19:36:58', 0), ('prioriteitstelling.beschrijving.zeer_hoog.fine_kinney', 'Zeer hoog ', '2014-06-28 19:36:29', 0), ('beheer.prioriteitstelling_matrix::prioriteitstelling.beschrijving.hoog.fine_kinney', 'Hoog ', '2014-06-28 19:36:26', 0), ('prioriteitstelling.beschrijving.gemiddeld.fine_kinney', 'Belangrijk ', '2014-06-28 19:36:24', 0), ('beheer.prioriteitstelling_matrix::prioriteitstelling.beschrijving.laag.fine_kinney', 'Mogelijk ', '2014-06-28 19:36:19', 0), ('prioriteitstelling.beschrijving.zeer_laag.fine_kinney', ' Aanvaardbaar', '2014-06-28 19:36:15', 0), ('beheer.risicoanalyse_invullen::kanswaarde.blootstelling', 'Blootstelling', '2014-06-28 17:54:17', 0), ('beheer.risicoanalyse_invullen::kanswaarde.waarschijnlijkheid', 'Waarschijnlijkheid', '2014-06-28 17:54:17', 0), ('beheer.risicoanalyse_invullen::effectwaarde.ramp', 'Ramp', '2014-06-28 17:40:05', 0), ('beheer.risicoanalyse_invullen::effectwaarde.belangrijk', 'Belangrijk', '2014-06-28 17:40:05', 0), ('beheer.risicoanalyse_invullen::effectwaarde.aanzienlijk', 'Aanzienlijk', '2014-06-28 17:40:05', 0), ('beheer.risicoanalyse_invullen::effectwaarde.catastrofaal', 'Catastrofaal', '2014-06-28 17:40:05', 0), ('beheer.risicoanalyse_invullen::effectwaarde.zeer ernstig', 'Zeer ernstig', '2014-06-28 17:40:05', 0), ('beheer.risicoanalyse_invullen::effectwaarde.gering_hinder', 'Gering/hinder', '2014-06-28 17:40:05', 0), ('checklistwizard.risico_model', 'Risico model ', '2014-06-28 13:04:07', 0), ('nav.account_bewerken', 'Klant configurator', '2014-06-28 12:56:09', 0), ('klant.heeft_fine_kinney_licentie', 'Klant heeft Fine & Kinney licentie? ', '2014-06-28 12:55:15', 0); <file_sep>UPDATE `bt_grondslag_teksten` SET `display_artikel` = `artikel`; <file_sep><? $this->load->view('elements/header', array('page_header'=>'deelplannen')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Importeren afgerond', 'width' => '900px' )); ?> <p> Er zijn <b><?=$num?></b> dossiers ge&iuml;mporteerd! Ga naar het dossierbeheer om de nieuw ge&iuml;mporteerde dossiers te openen of te bewerken. </p> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?> <file_sep><?php /* |--------------------------------------------------------------- | FODDEX: Force outputbuffering |--------------------------------------------------------------- | Must be here, otherwise large pages crash on the Byte server... ?!?!?! */ ob_start(); /* |--------------------------------------------------------------- | FODDEX: Performance logging, comment to disable |--------------------------------------------------------------- */ // require_once( 'performance.php' ); /* |--------------------------------------------------------------- | FODDEX: CLI support |--------------------------------------------------------------- | | So that CI can be used from the commandline: | php index.php /cli/somemethod | */ if( isset( $argv ) ) { $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/'.$argv[1]; $_SERVER['HTTP_USER_AGENT'] = 'Firefox'; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; $_SERVER['SERVER_NAME'] = 'localhost'; define( 'IS_CLI', true ); } else define( 'IS_CLI', false ); /* |--------------------------------------------------------------- | FODDEX: P3P header |--------------------------------------------------------------- | Gekopieerd van: | | http://www.softwareprojects.com/resources/programming/t-how-to-get-internet-explorer-to-use-cookies-inside-1612.html | | Toegevoegd omdat IE anders weigert cookies te accepteren in lease-frameset-setups. | | Zie ook: http://www.w3.org/P3P/implementations.html */ header('P3P: CP="CAO COR CURa ADMa DEVa OUR IND ONL COM DEM PRE"'); /* |--------------------------------------------------------------- | FODDEX: Maintenance mode |--------------------------------------------------------------- | | Set the if to true in stead of false, to show a maintenance | message, with the exception for certain IP's. | */ // // XXX TEST DEBUG if (false || (@$_SERVER['HTTP_HOST'] == 'dev.bristoezicht.imotepbv.nlllllllllllllll')) { define( 'IP_LIMIT_ENABLED', true ); $ip = isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : @$_SERVER['REMOTE_ADDR']; $is_developer_device = preg_match( '/HTC Desire X/', $_SERVER['HTTP_USER_AGENT'] ); if (!IS_CLI && !$is_developer_device) { $allowed = false; foreach (array( '192.168.240.\d+', /* foddex local */ '192.168.127.12', /* foddex buiten ip */ '192.168.127.12', /* raoul kantoor */ '172.16.17.32', /* raoul kantoor bij hans */ '172.16.17.32', /* raoul thuis */ '172.16.31.10', /* raoul werk */ '192.168.127.12', /* olaf thuis */ ) as $regexp) if (preg_match( '#' . $regexp . '#', $ip )) $allowed = true; if (!$allowed) { echo file_get_contents( 'maintenance.html' ) . '<br/>' . $ip; exit; } } } else define( 'IP_LIMIT_ENABLED', false ); /* |--------------------------------------------------------------- | FODDEX: Request restore |--------------------------------------------------------------- | | See if there's a request to restore. | */ require_once( dirname(__FILE__) . '/application/helpers/requestrestore_helper.php' ); $is_rr = 0; if (isset( $_SERVER['REQUEST_URI'] )) { //if (preg_match( '#' . REQUEST_RESTORE_REDIRECT . '#', $_SERVER['REQUEST_URI'] )) if (preg_match( '#' . REQUEST_RESTORE_REDIRECT . '#', $_SERVER['REQUEST_URI'] ) && ($_SERVER['REQUEST_URI'] != '/root/online_check')) { $rr = new RequestRestore(); if (!$rr->restore_request()) // reload on /rr? { header( 'Location: /', true, 302 ); exit; } else { $is_rr = 1; } } } define( 'REQUEST_RESTORE_ACTIVE', $is_rr ); /* |--------------------------------------------------------------- | FODDEX: Force memory limit on LIVE servers |--------------------------------------------------------------- */ ini_set( 'memory_limit', '2G' ); /* |--------------------------------------------------------------- | FODDEX: Global error handling |--------------------------------------------------------------- | */ set_exception_handler( function( $exception ) { if (function_exists( 'show_error' )) { $trace = preg_replace( '#\s+[/a-z0-9\-_\.]+((index|system|application))#ms', ' /$1', $exception->getTraceAsString() ); show_error( $exception->getMessage() . '<br/><!-- ' . "\n\n\n" . $trace . "\n\n\n" . ' -->' ); } else die( 'Startup exception: ' . $exception->getMessage() ); }); /* |--------------------------------------------------------------- | PHP ERROR REPORTING LEVEL |--------------------------------------------------------------- | | By default CI runs with error reporting set to ALL. For security | reasons you are encouraged to change this when your site goes live. | For more info visit: http://www.php.net/error_reporting | */ error_reporting(E_ALL); /* |--------------------------------------------------------------- | SYSTEM FOLDER NAME |--------------------------------------------------------------- | | This variable must contain the name of your "system" folder. | Include the path if the folder is not in the same directory | as this file. | | NO TRAILING SLASH! | */ $system_folder = "system"; /* |--------------------------------------------------------------- | APPLICATION FOLDER NAME |--------------------------------------------------------------- | | If you want this front controller to use a different "application" | folder then the default one you can set its name here. The folder | can also be renamed or relocated anywhere on your server. | For more info please see the user guide: | http://codeigniter.com/user_guide/general/managing_apps.html | | | NO TRAILING SLASH! | */ $application_folder = "application"; /* |=============================================================== | END OF USER CONFIGURABLE SETTINGS |=============================================================== */ /* |--------------------------------------------------------------- | SET THE SERVER PATH |--------------------------------------------------------------- | | Let's attempt to determine the full-server path to the "system" | folder in order to reduce the possibility of path problems. | Note: We only attempt this if the user hasn't specified a | full server path. | */ if (strpos($system_folder, '/') === FALSE) { if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE) { $system_folder = realpath(dirname(__FILE__)).'/'.$system_folder; } } else { // Swap directory separators to Unix style for consistency $system_folder = str_replace("\\", "/", $system_folder); } /* |--------------------------------------------------------------- | DEFINE APPLICATION CONSTANTS |--------------------------------------------------------------- | | EXT - The file extension. Typically ".php" | FCPATH - The full server path to THIS file | SELF - The name of THIS file (typically "index.php) | BASEPATH - The full server path to the "system" folder | APPPATH - The full server path to the "application" folder | */ define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION)); define('FCPATH', __FILE__); define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); define('BASEPATH', $system_folder.'/'); if (is_dir($application_folder)) { define('APPPATH', $application_folder.'/'); } else { if ($application_folder == '') { $application_folder = 'application'; } define('APPPATH', BASEPATH.$application_folder.'/'); } /* |--------------------------------------------------------------- | LOAD THE FRONT CONTROLLER |--------------------------------------------------------------- | | And away we go... | */ require_once BASEPATH.'codeigniter/CodeIgniter'.EXT; /* End of file index.php */ /* Location: ./index.php */ <file_sep>-- draai: php index.php /cli/fix_checklist_sortering/133 -- draai daarna: php index.php /cli/fix_checklist_sortering/133/1 <file_sep>PDFAnnotator.Tool.CameraAssignment = PDFAnnotator.Tool.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'cameraassignment' ); /* initialize runtime data */ this.currentEditable = null; /* handle mouse clicks to start new forms */ this.on( 'mouseclick', function( tool, data ){ if (!tool.currentEditable) tool.locationSelected( data ); else tool.finishDirectionArrow(); }); /* handle drag move */ this.on( 'mousemove', function( tool, data ){ if (tool.currentEditable) tool.updateDirectionArrow( data ); }); this.on( 'dragmove', function( tool, data ){ if (tool.currentEditable) tool.updateDirectionArrow( data ); }); this.on( 'dragend', function( tool, data ){ if (tool.currentEditable) tool.finishDirectionArrow(); }); /* handle situation when tool is deselected */ this.on( 'deselect', function( tool, data ){ // remove old editable if still set (means unfinished) if (tool.currentEditable) { tool.currentEditable.container.removeObject( tool.currentEditable ); tool.currentEditable = null; } }); }, locationSelected: function( data ) { if (this.currentEditable) throw 'PDFAnnotator.Tool.CameraAssignment.locationSelected: this.currentEditable is not null, it should be!'; var cameraConfig = this.engine.gui.tools.toolsconfig.camera; var thiz = this; showMessageBox({ message: 'Vul de naam voor deze fotolocatie in:<br/><br/><input type="text" name="photoid" size="50" />', width: 500, onClose: function( res ) { if (res == 'ok') { config = { position: data.position.subtracted( cameraConfig.imageSize.divided( 2 ) ), imageSrc: cameraConfig.imageSrc, imageOpdrachtSrc: cameraConfig.imageOpdrachtSrc, imageSize: cameraConfig.imageSize }; var photoId = getPopup().find( '[name=photoid]' ).val(); if (photoId.length) config.photoId = photoId; thiz.currentEditable = new PDFAnnotator.Editable.PhotoAssignment(config); if (!data.container.addObject( thiz.currentEditable )) { thiz.currentEditable = null; } } } }); }, finishDirectionArrow: function() { /* reset state */ this.currentEditable = null; }, updateDirectionArrow: function( data ) { if (!this.currentEditable) throw 'PDFAnnotator.Tool.CameraAssignment.locationSelected: this.currentEditable is null, it shouldn\'t be!'; var centerPos = this.currentEditable.data.position.added( this.currentEditable.data.imageSize.divided( 2 ) ); var newPos = data.position; var vec1 = new PDFAnnotator.Math.IntVector2( 1, 0 ); var vec2 = newPos.subtracted( centerPos ); var angle = vec1.angle( vec2 ); if (centerPos.y < newPos.y) angle = 2*Math.PI - angle; this.currentEditable.setDirection( angle ); } }); <file_sep><?php class SSOSynchronizer { const HOST = 'https://sanctiestrategie.nl'; const USE_VERBOSE_CURL = false; private $CI; private $_ssowebapp = null; private $_ssobagwebapp = null; private $_dossier_informatie = array(); private $_bescheiden_informatie = array(); public function __construct() { $this->CI = get_instance(); } public function log( $msg ) { $time = microtime(true); echo sprintf( "[%s.%03d] %s\n", date('Y-m-d H:i:s'), round( 1000 * ($time - floor($time)) ), $msg ); } public function run() { // startup $this->log( 'SSOSynchronizer running' ); // initialize $this->CI->load->model( 'webserviceapplicatie' ); $this->CI->load->model( 'webserviceapplicatiedossier' ); $this->CI->load->model( 'webserviceapplicatiedeelplan' ); $this->CI->load->model( 'webserviceapplicatiebescheiden' ); // find webapp object if (!($this->_ssowebapp = $this->CI->webserviceapplicatie->get_by_name( 'SSO' ))) throw new Exception( 'Kon SSO webapplicatie niet ophalen uit database.' ); if (!($this->_ssobagwebapp = $this->CI->webserviceapplicatie->get_by_name( 'SSOBAG' ))) throw new Exception( 'Kon SSO BAG webapplicatie niet ophalen uit database.' ); // find current sync information $this->_dossier_informatie = $this->_ssowebapp->get_dossier_informatie(); $this->_bescheiden_informatie = $this->_ssowebapp->get_bescheiden_informatie(); $this->_bag_deelplan_informatie = $this->_ssobagwebapp->get_deelplan_informatie(); // init done, now start syncing! $this->log( 'initialisatie voltooid' ); // do sync! $this->_sync_bag_koppeling(); // gebruikt _ssobagwebapp $this->_sync_dossiers(); // gebruikt _ssowebapp $this->_sync_bescheiden(); // gebruikt _ssowebapp } private function _sync_bag_koppeling() { // see what needs to be updated $this->CI->load->library( 'prioriteitstelling' ); $this->CI->load->model( 'bagkoppelinginstelling' ); $this->CI->load->model( 'dossier' ); $this->CI->load->model( 'deelplan' ); $this->CI->load->model( 'checklist' ); $this->CI->load->model( 'vraag' ); $this->CI->load->model( 'matrix' ); // get koppeling settings $checklist_id = $this->CI->bagkoppelinginstelling->get( 'CHECKLIST_ID' ); $klanten = array(); foreach ($this->CI->klant->all() as $klant) if (intval( $this->CI->bagkoppelinginstelling->get( 'KLANT' . $klant->id, 0 ) )) $klanten[] = $klant; // get dossiers for klanten $this->log( 'BAG checklist id: ' . $checklist_id ); $this->log( sizeof($klanten) . ' klant(en) te synchroniseren voor BAG koppeling.' ); foreach ($klanten as $klant) { // inloggen $gebruikers = $klant->get_gebruikers(true); $gebruiker = reset( $gebruikers ); $this->log( 'Inloggen als kid=' . $klant->id . ', uid=' . $gebruiker->id ); $this->CI->login( $klant->id, $gebruiker->id, false ); /* functie in cli controller! */ $this->log( 'Ingelogd' ); // itereer over dossiers $dossiers = $klant->get_dossiers(); $this->log( 'Klant ' . $klant->naam . ' heeft ' . sizeof($dossiers) . ' dossiers.' ); foreach ($dossiers as $dossier) { foreach ($dossier->get_deelplannen() as $deelplan) { foreach ($deelplan->get_checklisten() as $checklist) { $checklist = $this->CI->checklist->get( $checklist->checklist_id ); if ($checklist->id == $checklist_id) { // Fork for each deelplan, so that the deelplan/vraag data state does not get messed up. // This happens because we set non-unique data in unique objects here and there. Normally // this isn't really an issue as we deal with just one deelplan per request, but here // we deal with many. // NOTE: since all file descriptors are copied (also sockets!) we close the DB connection // here, otherwise two processes will try to use the same TCP connection! $this->CI->db->close(); $this->CI->dbex->unprepare_all(); switch ($pid = pcntl_fork()) { case -1: throw new Exception( 'Failed to fork' ); case 0: // // child code // // reinitialize DB connection $this->CI->db->initialize(); // werk automatische velden bij $deelplan->werk_automatische_antwoorden_bij( 'bij synchroniseren' ); // zie wanneer dit deelplan voor het laatst gesynchroniseerd was $laatst_gesynchroniseerd = isset( $this->_bag_deelplan_informatie[$deelplan->id] ) ? $this->_bag_deelplan_informatie[$deelplan->id]->laatst_bijgewerkt_op : '0000-00-00 00:00:00'; // haal vragen op, bekijk of er geupdate moet worden $this->log( '... deelplan_id=' . $deelplan->id . ', haal vragen op...' ); $vragen = $deelplan->get_toezicht_data( $checklist->get_checklistgroep(), $checklist, false /* beperkte data, eigenlijk alleen vragen */ ); $synchronize = false; foreach ($vragen['vragen'] as $vraag) { if ($vraag->last_updated_at > $laatst_gesynchroniseerd) { $synchronize = true; break; } } if (!$synchronize) $this->log( '... deelplan_id=' . $deelplan->id . ' is up-to-date sinds ' . $laatst_gesynchroniseerd . ', niks te doen' ); else { $this->log( '... deelplan_id=' . $deelplan->id . ' is out-of-date (laatst gesynchroniseerd op ' . $laatst_gesynchroniseerd . ')' ); if (!$deelplan->alle_automatische_antwoord_gezet_voor_moment( 'bij synchroniseren' )) { $this->log( '... deelplan_id=' . $deelplan->id . ' wordt nog niet gesynchroniseerd, nog niet alle "bij synchroniseren" velden kunnen worden gezet!' ); } else { // bouw data structuur op $data = (object)array( 'KlantId' => intval( $klant->id ), 'DossierId' => intval( $dossier->id ), 'DeelplanId' => intval( $deelplan->id ), 'ChecklistId' => intval( $checklist->id ), 'Vragen' => array(), ); foreach ($vragen['vragen'] as $vraag) { $data->Vragen[] = (object)array( 'VraagId' => intval( $vraag->id ), 'Tekst' => strval( $vraag->tekst ), 'Antwoord' => strval( $vraag->status ), 'Toelichting' => strval( $vraag->toelichting ), ); } if ($this->_post( 'BAG', $data )) { $tijd = date( 'Y-m-d H:i:s' ); $res = $this->CI->webserviceapplicatiedeelplan->zet( $this->_ssobagwebapp->id, $deelplan->id, $tijd ); if ($res) $this->log( 'laatste SSOBAG synchronisatie tijdstip bijgewerkt naar ' . $tijd ); else $this->log( 'FOUT BIJ UITVOEREN: kon synchronisatie tijdstip niet bijwerken in database!' ); } else { $this->log( '_post gaf FALSE terug!' ); } } } exit(0); default: // // parent code // pcntl_waitpid($pid, $status); if ($status != 0) throw new Exception( 'Child failed, stopping' ); // reinitialize DB connection $this->CI->db->initialize(); } } } } } } } private function _sync_dossiers() { // see what needs to be updated $this->CI->load->model( 'dossier' ); $dossiers = $this->CI->dossier->get_by_herkomst( 'koppeling' ); $this->log( sizeof($dossiers) . ' dossiers gevonden vanuit koppeling.' ); // loop over dossiers foreach ($dossiers as $index => $dossier) { // als dit dossier verwijderd is, niks doen met dit dossier! if ($dossier->verwijderd || $dossier->gearchiveerd) continue; // !!! Quick dirty solution as SSO is currently being phased out anyway: restrict the dossier to those of Berkelland alone // These are the ones belonging to the 'klant' with DB ID = 86. if ($dossier->get_gebruiker()->klant_id != 86) continue; // als we dit dossier al eens eerder gesynchroniseerd hebben, en later dan de laatste wijziging op dit dossier, // dan niets doen met dit dossier! if (isset( $this->_dossier_informatie[$dossier->id] )) { if ($this->_dossier_informatie[$dossier->id]->laatst_bijgewerkt_op >= $dossier->laatst_bijgewerkt_op) { $this->log( 'dossier ' . $dossier->kenmerk . ' is up-to-date, bekijk subjecten.' ); // om het dossier hoeven we het niet te doen, bekijk of alle subjecten ook al gesynced zijn $verouderd = false; foreach ($dossier->get_subjecten() as $subject) { if ($this->_dossier_informatie[$dossier->id]->laatst_bijgewerkt_op < $subject->laatst_bijgewerkt_op) { $verouderd = true; break; } } // zowel dossier als subjecten zijn gesynced if (!$verouderd) { $this->log( 'dossier ' . $dossier->kenmerk . ' heeft geen out-of-date subjecten. ' ); continue; } else $this->log( 'dossier ' . $dossier->kenmerk . ' heeft subjecten. ' ); } else $this->log( 'dossier ' . $dossier->kenmerk . ' is out-of-date.' ); } else $this->log( 'dossier ' . $dossier->kenmerk . ' is nog nooit gesynchroniseerd' ); // probeer bij te werken bij de SSO $this->log( 'synchroniseer ' . ($index+1) . '/' . sizeof($dossiers) . ': kenmerk ' . $dossier->kenmerk . '.' ); $data = $this->_dossier_to_sso_data( $dossier ); if ($this->_post( 'UpdateZaak', $data )) { $tijd = date( 'Y-m-d H:i:s' ); $res = $this->CI->webserviceapplicatiedossier->zet( $this->_ssowebapp->id, $dossier->id, $tijd ); if ($res) $this->log( 'laatste SSO synchronisatie tijdstip bijgewerkt naar ' . $tijd ); else $this->log( 'FOUT BIJ UITVOEREN: kon synchronisatie tijdstip niet bijwerken in database!' ); } } } private function _sync_bescheiden() { // see what needs to be updated $this->CI->load->model( 'dossierbescheiden' ); $bescheiden = $this->CI->dossierbescheiden->get_by_herkomst( 'koppeling' ); $this->log( sizeof($bescheiden) . ' bescheiden gevonden vanuit koppeling.' ); // loop over dossiers foreach ($bescheiden as $index => $b) { // !!! Quick dirty solution as SSO is currently being phased out anyway: restrict the bescheiden to those of Berkelland alone // These are the ones belonging to the 'klant' with DB ID = 86. $dossier = $b->get_dossier(); if ($dossier->get_gebruiker()->klant_id != 86) continue; // als we dit bescheiden al eens eerder gesynchroniseerd hebben, en later dan de laatste wijziging op dit bescheiden, // dan niets doen met dit bescheiden! if (isset( $this->_bescheiden_informatie[$b->id] )) { if ($this->_bescheiden_informatie[$b->id]->laatst_bijgewerkt_op >= $b->laatste_bestands_wijziging_op) { $this->log( 'bescheiden ' . $b->id . ' is up-to-date. ' ); continue; } else $this->log( 'bescheiden ' . $b->id . ' is out-of-date.' ); } else $this->log( 'bescheiden ' . $b->id . ' is nog nooit gesynchroniseerd' ); // probeer bij te werken bij de SSO $this->log( 'synchroniseer ' . ($index+1) . '/' . sizeof($bescheiden) . ': id ' . $b->id . '.' ); $b->laad_inhoud(); $data = $this->_bescheiden_to_sso_data( $b ); $b->geef_inhoud_vrij(); if ($this->_post( 'PostDocument', $data )) { $tijd = date( 'Y-m-d H:i:s' ); $res = $this->CI->webserviceapplicatiebescheiden->zet( $this->_ssowebapp->id, $b->id, $tijd ); if ($res) $this->log( 'laatste SSO synchronisatie tijdstip bijgewerkt naar ' . $tijd ); else $this->log( 'FOUT BIJ UITVOEREN: kon synchronisatie tijdstip niet bijwerken in database!' ); } // release memory unset( $data ); } } private function _dossier_to_sso_data( DossierResult $dossier ) { $subjecten = array( 'ContentType' => 'json', 'Subjecten' => array(), ); foreach ($dossier->get_subjecten() as $subject) { $subjecten['Subjecten'][] = array( 'ContentType' => 'json', 'Foreign_id' => $subject->id, 'Nummer' => $subject->id, 'Zaaknr' => $dossier->id, 'Naam' => $subject->naam, 'Rol' => $subject->rol, 'Adres' => $subject->adres, 'Plaats' => $subject->woonplaats, 'Postcode' => $subject->postcode, 'Telefoon' => $subject->telefoon, 'Email' => $subject->email, ); } return array( 'ContentType' => 'json', 'Foreign_id' => $dossier->id, 'Zaaknummer' => $dossier->id, 'Gebruiker_id' => $dossier->gebruiker_id, 'Adres' => json_encode( array( 'ContentType' => 'json', 'Land' => 'Nederland', 'Plaats' => $dossier->locatie_woonplaats, 'Postcode' => $dossier->locatie_postcode, 'Straat' => trim( preg_replace( '/\s+[0-9]+[a-z0-9\-]+$/i', '', $dossier->locatie_adres ) ), 'Huisnr' => trim( preg_replace( '/^.*?\s+([0-9]+[a-z0-9\-])+$/i', '$1', $dossier->locatie_adres ) ), ) ), 'Omschrijving' => $dossier->beschrijving, 'Toelichting' => $dossier->opmerkingen, 'Subjecten' => json_encode( $subjecten ), ); } private function _bescheiden_to_sso_data( DossierBescheidenResult $bescheiden ) { return array( 'ContentType' => 'json', 'Foreign_id' => $bescheiden->id, 'ZaakForeign_id' => $bescheiden->dossier_id, 'Zaaknummer' => $bescheiden->dossier_id, 'Gebruiker_id' => $bescheiden->get_dossier()->gebruiker_id, 'Type' => 'bescheiden', 'Filename' => $bescheiden->bestandsnaam, 'Data' => base64_encode( gzcompress( $bescheiden->bestand ) ), ); } private function _post( $functie, $data ) { $url = self::HOST . '/synchronizer/bristoezicht/' . $functie . '/'; $this->CI->load->library( 'curl' ); $curl = $this->CI->curl->create( $url ); $curl->set_postfields( json_encode( $data ) ); $curl->set_post( true ); if (self::USE_VERBOSE_CURL) $curl->set_verbose( true ); try { $this->log( 'uitvoeren ' . $functie . ' functie.' ); $result = $curl->execute(); $this->log( 'resultaat: ' . $result ); $res = @json_decode( $result ); if (!$res || !is_object( $res )) { $this->log( 'Geen geldig json object als resultaat ontvangen.' ); return false; } else if (isset( $res->ErrorMessage )) { $this->log( 'Foutmelding van server: ' . $res->ErrorMessage ); return false; } else if (!isset( $res->result )) { $this->log( 'Geen foutmelding ontvangen, maar ook geen result veld ontvangen.' ); return false; } else return $res->result; } catch (Exception $e) { $this->log( 'FOUT BIJ UITVOEREN: ' . $e->getMessage() ); return false; } } } <file_sep><? $this->load->view('elements/header', array('page_header'=>'beheer') ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Rol ' . htmlentities( $rol->naam, ENT_QUOTES, 'UTF-8' ) . ' bewerken', 'width' => '920px' )); ?> <form method="post" enctype="multipart/form-data"> <table class="rollenbeheer"> <? if ($allow_klanten_edit): ?> <tr> <td>Klant</td> <td> <select name="klant_id" <?=$rol_editbaar?'':'disabled'?>> <option value="">- alle -</option> <? foreach ($klanten as $klant): ?> <option <?=$klant->id==$rol->klant_id?'selected':''?> value="<?=$klant->id?>"><?=$klant->naam?></option> <? endforeach; ?> </select> </td> </tr> <? endif; ?> <tr> <td>Naam</td> <td> <input name="naam" type="text" value="<?=htmlentities( $rol->naam, ENT_QUOTES, 'UTF-8' )?>" size="80" maxlength="256" <?=$rol_editbaar?'':'disabled'?> /> </td> </tr> <tr> <td>Rechten</td> <td> <table style="width:auto"> <? $rolrechten = $rol->get_rol_rechten(); ?> <? foreach ($this->rechten->geef_groepen() as $groep): ?> <tr><td colspan="3" style="padding: 3px"><span style="font-size:120%;font-weight:bold"><?=$groep?></td></tr> <? foreach ($this->rechten->geef_groep_recht_definities( $groep ) as $rechtdef): $rech_id = $rechtdef->get_id(); $rech_modus = $rechtdef->get_modi(); $rolmodus = @ $rolrechten[$rechtdef->get_id()]; $rolmodus = (!$rolmodus) ? RECHT_MODUS_GEEN:$rolmodus->get_modus(); if ((($rech_modus & RECHT_MODUS_SYSAD_ONLY) && !$allow_klanten_edit) // || ($rech_id == RECHT_TYPE_PARENT_KLANT_ADMIN && !$leaseconfiguratie->has_children_organisations) ) continue; $display = ($rech_id == RECHT_TYPE_PARENT_KLANT_ADMIN && !$leaseconfiguratie->has_children_organisations)?'style="display:none;"':''; ?> <tr <?=$display ?>> <td style="padding: 3px"><?=$rechtdef->get_beschrijving()?></td> <? foreach (array( RECHT_MODUS_GEEN => 'Geen', RECHT_MODUS_ALLE => 'Alle', RECHT_MODUS_EIGEN => 'Eigen',RECHT_GROUP_ONLY=>'Groups' ) as $modus => $modus_desc): ?> <td style="padding: 3px" > <? if( ($rech_modus & $modus) ): ?> <input type="radio" name="rechtdef[<?=$rechtdef->get_id()?>]" value="<?=$modus?>" <?=$rolmodus == $modus ? 'checked' : '' ?> <?=$rol_editbaar?'':'disabled'?>> <?=$modus_desc ?> <? else: ?> &nbsp; <? endif; ?> <? endforeach; ?> <td width="50" style="text-align:right"> <?=htag( $rechtdef->get_id() )?> </td> </tr> <? endforeach; ?> <? endforeach; ?> </table> </td> </tr> <tr> <td colspan="2"> <? if ($rol_editbaar): ?> <input type="submit" value="Opslaan" /> <input type="button" value="Verwijderen" onclick="if (confirm('Rol werkelijk verwijderen? Deze actie kan niet ongedaan gemaakt worden!\nEventuele gebruikers met deze rol zullen geen rol en daarmee geen rechten meer hebben!')) location.href='/instellingen/rol_verwijderen/<?=$rol->id?>';" /> <input type="button" value="Terug" onclick="if (confirm('Wijzigingen annuleren?')) location.href='/instellingen/rollenbeheer/';" /> <? else: ?> <input type="button" value="Terug" onclick="location.href='/instellingen/rollenbeheer/';" /> <? endif; ?> </td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end'); ?> <? $this->load->view('elements/footer'); ?><file_sep><form name="form1" id="form1" method="post" action="/dossiers/save_organisatiekenmerken/<?=$dossier->id?>"> <input type="hidden" name="id" id="id" value="<?=($org_kenmerken ? $org_kenmerken->id : '')?>" /> <table class="rapportage-filter Organisatiekenmerken"> <tr><td class="column"><?=tg('bedrijf')?></td><td class="input"><input type="text" name="bedrijf" id="bedrijf" value="<?=($org_kenmerken ? $org_kenmerken->bedrijf : '')?>" /></td></tr> <tr><td class="column"><?=tg('bezoekadres')?></td><td><input type="text" name="bezoekadres" id="bezoekadres" value="<?=($org_kenmerken ? $org_kenmerken->bezoekadres : '')?>" /></td></tr> <tr><td class="column"><?=tg('postadres')?></td><td><input type="text" name="postadres" id="postadres" value="<?=($org_kenmerken ? $org_kenmerken->postadres : '')?>" /></td></tr> <tr><td class="column"><?=tg('telefoon')?></td><td><input type="text" name="telefoon" id="telefoon" value="<?=($org_kenmerken ? $org_kenmerken->telefoon : '')?>" /></td></tr> <tr><td class="column"><?=tg('contactpersoon')?></td><td><input type="text" name="contactpersoon" id="contactpersoon" value="<?=($org_kenmerken ? $org_kenmerken->contactpersoon : '')?>" /></td></tr> <tr><td class="column"><?=tg('preventiemedewerker')?></td><td><input type="text" name="preventiemedewerker" id="preventiemedewerker" value="<?=($org_kenmerken ? $org_kenmerken->preventiemedewerker : '')?>" /></td></tr> <tr><td class="column"><?=tg('branche')?></td><td><input type="text" name="branche" id="branche" value="<?=($org_kenmerken ? $org_kenmerken->branche : '')?>" /></td></tr> <tr><td class="column"><?=tg('bedrijfsactiviteiten')?></td><td><input type="text" name="bedrijfsactiviteiten" id="bedrijfsactiviteiten" value="<?=($org_kenmerken ? $org_kenmerken->bedrijfsactiviteiten : '')?>" /></td></tr> <tr><td class="column"><?=tg('productieproces')?></td><td><input type="text" name="productieproces" id="productieproces" value="<?=($org_kenmerken ? $org_kenmerken->productieproces : '')?>" /></td></tr> <tr><td class="column"><?=tg('bedrijfslocatie')?></td><td><input type="text" name="bedrijfslocatie" id="bedrijfslocatie" value="<?=($org_kenmerken ? $org_kenmerken->bedrijfslocatie : '')?>" /></td></tr> <tr><td class="column"><?=tg('projectlocatie')?></td><td><input type="text" name="projectlocatie" id="projectlocatie" value="<?=($org_kenmerken ? $org_kenmerken->projectlocatie : '')?>" /></td></tr> <tr><td class="column"><?=tg('productie_en')?></td><td><input type="text" name="productie_en" id="productie_en" value="<?=($org_kenmerken ? $org_kenmerken->productie_en : '')?>" /></td></tr> <tr><td class="column"><?=tg('personen_werkzaam')?></td><td><input type="text" name="personen_werkzaam" id="personen_werkzaam" value="<?=($org_kenmerken ? $org_kenmerken->personen_werkzaam : '')?>" /></td></tr> <tr><td class="column" colspan="2"><h2><?=tg('leeftijd')?></h2></td></tr> <tr><td class="column"><?=tg('less_18_jaar')?></td><td><input type="text" name="jaar_less_18" id="jaar_less_18" value="<?=($org_kenmerken ? $org_kenmerken->jaar_less_18 : '')?>" /></td></tr> <tr><td class="column"><?=tg('18_20_jaar')?></td><td><input type="text" name="jaar_18_20" id="jaar_18_20" value="<?=($org_kenmerken ? $org_kenmerken->jaar_18_20 : '')?>" /></td></tr> <tr><td class="column"><?=tg('21_30_jaar')?></td><td><input type="text" name="jaar_21_30" id="jaar_21_30" value="<?=($org_kenmerken ? $org_kenmerken->jaar_21_30 : '')?>" /></td></tr> <tr><td class="column"><?=tg('31_40_jaar')?></td><td><input type="text" name="jaar_31_40" id="jaar_31_40" value="<?=($org_kenmerken ? $org_kenmerken->jaar_31_40 : '')?>" /></td></tr> <tr><td class="column"><?=tg('41_50_jaar')?></td><td><input type="text" name="jaar_41_50" id="jaar_41_50" value="<?=($org_kenmerken ? $org_kenmerken->jaar_41_50 : '')?>" /></td></tr> <tr><td class="column"><?=tg('51_60_jaar')?></td><td><input type="text" name="jaar_51_60" id="jaar_51_60" value="<?=($org_kenmerken ? $org_kenmerken->jaar_51_60 : '')?>" /></td></tr> <tr><td class="column"><?=tg('61_65_jaar')?></td><td><input type="text" name="jaar_61_65" id="jaar_61_65" value="<?=($org_kenmerken ? $org_kenmerken->jaar_61_65 : '')?>" /></td></tr> <tr><td class="column"><?=tg('aantal_fte')?></td><td><input type="text" name="aantal_fte" id="aantal_fte" value="<?=($org_kenmerken ? $org_kenmerken->aantal_fte : '')?>" /></td></tr> <tr><td class="column" colspan="2"><h2><?=tg('bijzondere_groepen')?></h2></td></tr> <tr><td class="column"><?=tg('minder_validen')?></td><td><input type="text" name="minder_validen" id="minder_validen" value="<?=($org_kenmerken ? $org_kenmerken->minder_validen : '')?>" /></td></tr> <tr><td class="column"><?=tg('zwangeren')?></td><td><input type="text" name="zwangeren" id="zwangeren" value="<?=($org_kenmerken ? $org_kenmerken->zwangeren : '')?>" /></td></tr> <tr><td class="column"><?=tg('jeugdigen')?></td><td><input type="text" name="jeugdigen" id="jeugdigen" value="<?=($org_kenmerken ? $org_kenmerken->jeugdigen : '')?>" /></td></tr> <tr><td class="column"><?=tg('allochtonen')?></td><td><input type="text" name="allochtonen" id="allochtonen" value="<?=($org_kenmerken ? $org_kenmerken->allochtonen : '')?>" /></td></tr> <tr><td class="column"><?=tg('thuiswerkers')?></td><td><input type="text" name="thuiswerkers" id="thuiswerkers" value="<?=($org_kenmerken ? $org_kenmerken->thuiswerkers : '')?>" /></td></tr> <tr><td class="column"><?=tg('inleenkrachten')?></td><td><input type="text" name="inleenkrachten" id="inleenkrachten" value="<?=($org_kenmerken ? $org_kenmerken->inleenkrachten : '')?>" /></td></tr> <tr><td class="column"><?=tg('oproepkrachten')?></td><td><input type="text" name="oproepkrachten" id="oproepkrachten" value="<?=($org_kenmerken ? $org_kenmerken->oproepkrachten : '')?>" /></td></tr> <tr><td class="column"><?=tg('wwb_ers')?></td><td><input type="text" name="wwb_ers" id="wwb_ers" value="<?=($org_kenmerken ? $org_kenmerken->wwb_ers : '')?>" /></td></tr> <tr><td class="column"><?=tg('werktijden_en_overwerk')?></td><td><input type="text" name="werktijden_en_overwerk" id="werktijden_en_overwerk" value="<?=($org_kenmerken ? $org_kenmerken->werktijden_en_overwerk : '')?>" /></td></tr> <tr><td><?=tg('functies_voor')?></td><td><input type="text" name="functies_voor" id="functies_voor" value="<?=($org_kenmerken ? $org_kenmerken->functies_voor : '')?>" /></td></tr> <tr> <td><?=tg('ziekteverzuimcijfers')?></td> <td> <table> <tr><td><?=tg('verzuimpercentage')?> </td><td><input type="text" name="verzuimpercentage" id="verzuimpercentage" value="<?=($org_kenmerken ? $org_kenmerken->verzuimpercentage : '')?>" /></td></tr> <tr><td><?=tg('meldingsfrequentie')?> </td><td><input type="text" name="meldingsfrequentie" id="meldingsfrequentie" value="<?=($org_kenmerken ? $org_kenmerken->meldingsfrequentie : '')?>" /></td></tr> <tr><td><?=tg('verzuimduur')?> </td><td><input type="text" name="verzuimduur" id="verzuimduur" value="<?=($org_kenmerken ? $org_kenmerken->verzuimduur : '')?>" /></td></tr> </table> </td> </tr> <tr> <td class="column"><?=tg('wao_wia_toetreding_1')?></td> <td> <?=tg('wao_wia_toetreding_2')?> <input type="text" name="wao_wia_toetreding" id="wao_wia_toetreding" value="<?=($org_kenmerken ? $org_kenmerken->wao_wia_toetreding : '')?>" /> <?=tg('wao_wia_toetreding_3')?> </td> </tr> <tr> <td class="column"><?=tg('ongevallencijfers_1')?></td> <td> <?=tg('ongevallencijfers_2')?> <input type="text" name="ongevallencijfers" id="ongevallencijfers" value="<?=($org_kenmerken ? $org_kenmerken->ongevallencijfers : '')?>" /> <?=tg('ongevallencijfers_3')?> </td> </tr> <tr><td class="column"><?=tg('geconstateerde_beroepsziekten')?></td><td><input type="text" name="geconstateerde_beroepsziekten" id="geconstateerde_beroepsziekten" value="<?=($org_kenmerken ? $org_kenmerken->geconstateerde_beroepsziekten : '')?>" /></td></tr> <tr> <td class="column"><?=tg('ziekteverzuimbegeleiding_1')?></td> <td> <?=tg('ziekteverzuimbegeleiding_1')?> <input type="text" name="ziekteverzuimbegeleiding" id="ziekteverzuimbegeleiding" value="<?=($org_kenmerken ? $org_kenmerken->ziekteverzuimbegeleiding : '')?>" /> </td> </tr> <tr> <td class="column"><?=tg('gezondheidskundig_onderzoek_1')?></td> <td> <?=tg('gezondheidskundig_onderzoek_2')?> <input type="text" name="gezondheidskundig_onderzoek" id="gezondheidskundig_onderzoek" value="<?=($org_kenmerken ? $org_kenmerken->gezondheidskundig_onderzoek : '')?>" /> <?=tg('gezondheidskundig_onderzoek_3')?> </td> </tr> <tr><td></td><td><input type="submit" value="Opslaan" /></td></tr> </table> </form> <script type="text/javascript"> $('#form1').submit(function(event) { event.preventDefault(); $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), dataType: 'json', success: function (data) { $('#id').val(data.id); alert( '<?=tg('successfully_saved')?>' ); }, error: function() { alert( '<?=tg('error_not_saved')?>' ); } }); }); </script><file_sep>PDFAnnotator.Math.IntVector2 = Class.extend({ init: function( x, y ) { if (x instanceof PDFAnnotator.Math.IntVector2) { this.x = x.x; this.y = x.y; } else if (x instanceof PDFAnnotator.Math.Vector2) { this.x = Math.round( x.x ); this.y = Math.round( x.y ); } else { this.x = 1 * parseInt( x ); this.y = 1 * parseInt( y ); } }, length: function() { return Math.sqrt( this.x*this.x + this.y*this.y ); }, added: function( vec ) { if (vec instanceof PDFAnnotator.Math.IntVector2) return new PDFAnnotator.Math.IntVector2( this.x + vec.x, this.y + vec.y ); else return new PDFAnnotator.Math.IntVector2( this.x + vec, this.y + vec ); }, subtracted: function( vec ) { if (vec instanceof PDFAnnotator.Math.IntVector2) return new PDFAnnotator.Math.IntVector2( this.x - vec.x, this.y - vec.y ); else return new PDFAnnotator.Math.IntVector2( this.x - vec, this.y - vec ); }, multiplied: function( vec ) { if (vec instanceof PDFAnnotator.Math.IntVector2) return new PDFAnnotator.Math.IntVector2( this.x * vec.x, this.y * vec.y ); else return new PDFAnnotator.Math.IntVector2( this.x * vec, this.y * vec ); }, divided: function( vec ) { if (vec instanceof PDFAnnotator.Math.IntVector2) return new PDFAnnotator.Math.IntVector2( Math.round( this.x / vec.x ), Math.round( this.y / vec.y ) ); else return new PDFAnnotator.Math.IntVector2( Math.round( this.x / vec ), Math.round( this.y / vec ) ); }, dot: function( vec ) { return this.x*vec.x + this.y*vec.y; }, angle: function( vec ) { return Math.acos( this.dot( vec ) / (this.length() * vec.length()) ); } }); <file_sep>CREATE TABLE IF NOT EXISTS `dossier_rapporten` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dossier_id` int(11) NOT NULL, `bestandsnaam` varchar(256) NOT NULL, `bestand` longblob NOT NULL, `aangemaakt_op` datetime NOT NULL, `gebruiker_id` int(11) DEFAULT NULL, `instellingen` text NOT NULL, `doc_type` varchar(40) NOT NULL, `target` varchar(128) NOT NULL, `omschrijving` varchar(512) NOT NULL, PRIMARY KEY (`id`), KEY `dossier_id` (`dossier_id`), KEY `gebruiker_id` (`gebruiker_id`) ) ENGINE=InnoDB; ALTER TABLE `dossier_rapporten` ADD CONSTRAINT `dossier_rapporten_ibfk_1` FOREIGN KEY (`dossier_id`) REFERENCES `dossiers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `dossier_rapporten_ibfk_2` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; ALTER TABLE `dossier_rapporten` ADD `bestandsgrootte` INT NOT NULL AFTER `bestand` ; <file_sep>BRISToezicht.Toets = { readonlyMode: false, // can be overriden from HTML script blocks to make system run in disabled/readonly mode data: null, // value is generated in PHP is_automatic_accountability_text:false, initialize: function() { // have data? if (!this.data) return; // initialize componenten var components = ['ButtonConfig','SpecialImage','Planning','Bescheiden','VraagUpload','Form','Vraag','Subject','Verantwoording','Opdracht']; for (var i=0; i<components.length; ++i) if (this[components[i]]) this[components[i]].initialize(); // set onbeforeunload handler $(window).bind( 'beforeunload', function(){ if (BRISToezicht.Toets.haveReasonToStayOnPage()) return 'Deze pagina werkelijk sluiten? U zal hiermee niet opgeslagen gegevens kwijtraken!'; }); // set vorige vraag knop handler $('#nlaf_VorigeVraag div').click(function(){ BRISToezicht.Toets.Vraag.gotoPrevious(); }); // set volgende vraag knop handler $('#nlaf_VolgendeVraag div').click(function(){ BRISToezicht.Toets.Vraag.gotoNext(); }); // make plus button work $('#nlaf_PrioPanel .button').click(function(e){ if (!$(this).is( ':not(.disabled):not(.selected)' )) return; // de volgorde van checks is bewust 'apart', eerst de zeer_ variant, voordat je de korte variant doet! if (this.className.match( /zeer_hoog/ )) BRISToezicht.Toets.Vraag.verhoogHoofdgroepPrioriteit( 'zeer_hoog' ); else if (this.className.match( /hoog/ )) BRISToezicht.Toets.Vraag.verhoogHoofdgroepPrioriteit( 'hoog' ); else if (this.className.match( /gemiddeld/ )) BRISToezicht.Toets.Vraag.verhoogHoofdgroepPrioriteit( 'gemiddeld' ); else if (this.className.match( /zeer_laag/ )) BRISToezicht.Toets.Vraag.verhoogHoofdgroepPrioriteit( 'zeer_laag' ); else if (this.className.match( /laag/ )) BRISToezicht.Toets.Vraag.verhoogHoofdgroepPrioriteit( 'laag' ); }); }, haveReasonToStayOnPage: function() { return BRISToezicht.DirtyStatus.getState(); // dirty data? then warn! } }; <file_sep>function showPopup( title, url, width, height, html, extraOpts ) { // wrapper om nieuwe popup var props = { width: width, height: height, loadingImage: '/files/images/ajax-loader.gif', url: url ? url : null, html: html ? html : null }; for (var i in extraOpts) props[i] = extraOpts[i]; modalPopup(props); } function show_logo( groot, klein, sel ) { var kid = sel.options[sel.selectedIndex].value; var urlBase = '/content/logo/' + kid; var g = document.getElementById(groot); if (g!=null) g.src = urlBase + '/0'; var k = document.getElementById(klein); if (k!=null) k.src = urlBase; } function verwijder_dossier( rapport_id ) { showPopup( "Dossier verwijderen", "/dossiers/verwijderen/"+rapport_id, 400, 150 ); } function terugzetten_dossier( rapport_id ) { showPopup( "Dossier verwijderen", "/dossiers/terugzetten/"+rapport_id, 400, 150 ); } function archiveer_dossier( rapport_id ) { showPopup( "Dossier archiveren", "/dossiers/archiveren/"+rapport_id, 400, 150 ); } <file_sep>BRISToezicht.Group = { groups: {}, // "map" object, key is group tag, value is array of div's visibleGroup: {}, // "map" object, key is group tag, value jQuery collection with 1 object alwaysOpenGroup: {}, // "map" object, key is group tag, value is a bool, default true, determines if one group per tag should always be open onlyOneOpenGroup: {}, // "map" object, key is group tag, value is a bool, default true, determines if opening one group, closes the current one initialize: function() { // find all groups, if no groups, stop instantly $('.group:not(.defunct)').each(function(){ var groupTag = $(this).attr('group_tag'); // register group in correct DIV if (typeof( BRISToezicht.Group.groups[groupTag] ) == 'undefined') { BRISToezicht.Group.groups[groupTag] = []; BRISToezicht.Group.visibleGroup[groupTag] = null; BRISToezicht.Group.alwaysOpenGroup[groupTag] = false; BRISToezicht.Group.onlyOneOpenGroup[groupTag] = true; } BRISToezicht.Group.groups[groupTag].push( this ); // show/hide initially if (!BRISToezicht.Group.visibleGroup[groupTag] && $(this).hasClass( 'expanded' ) && (!$(this).hasClass( 'hdd' ) || $('.group.hdd').length<=1)) { BRISToezicht.Group.visibleGroup[groupTag] = $(this); $(this).next().removeClass( 'hidden' ); } else{ $(this).next().addClass( 'hidden' ); if($(this).hasClass( 'hdd' )) BRISToezicht.Group.visibleGroup[groupTag] = $(this); } }); // install click handler $('.group:not(.defunct)').live( 'click', function(){ var content = $(this).next(); var groupTag = $(this).attr('group_tag'); if($(".open_close_alle_deelplannen").attr("status")=="open"){ $(".open_close_alle_deelplannen").attr("status","close"); $(".groupcontent .groupcontent").hide(); } if (BRISToezicht.Group.onlyOneOpenGroup[groupTag]) { if (!BRISToezicht.Group.visibleGroup[groupTag].size() || BRISToezicht.Group.visibleGroup[groupTag][0] != this) { // hide current if (BRISToezicht.Group.visibleGroup[groupTag]) BRISToezicht.Group.visibleGroup[groupTag].next().slideUp( 'fast' ); // show new, and set as current if (BRISToezicht.Group.onlyOneOpenGroup[groupTag] || !BRISToezicht.Group.visibleGroup[groupTag] || BRISToezicht.Group.visibleGroup[groupTag][0] != this) { BRISToezicht.Group.visibleGroup[groupTag] = $(this); BRISToezicht.Group.visibleGroup[groupTag].next().slideDown( 'fast' ); } else BRISToezicht.Group.visibleGroup[groupTag] = null; } } else { if (content.css( 'display' ) == 'none') content.slideDown( 'fast' ); else content.slideUp( 'fast' ); } }); } }; <file_sep>-- php index.php /cli/opdrachtprocessor -- crontab dit! <file_sep><? require_once 'base.php'; class BtBtzDossierResult extends BaseResult { function BtBtzDossierResult( &$arr ) { parent::BaseResult( 'btbtzdossier', $arr ); } // Works out the correct 'project_status' value, based on the BT and BTZ status. public function determineAndSetProjectStatus($saveNewStatus = true) { // Initialise the new value with the existing value and then determine if a new value needs to be set. // Note that the below logic only traps EXACTLY the BT + BTZ statuses that were determined as those that should // result in a project status transition. The other combinations for now shall not result in a project_status change. $projectStatus = $previousProjectStatus = $this->project_status; if ($this->bt_status == 'open' && $this->btz_status == 'open') { $projectStatus = 'open'; } else if ($this->bt_status == 'gestart' && $this->btz_status == 'open') { $projectStatus = 'toets gestart'; } else if ($this->bt_status == 'bouwfase' && $this->btz_status == 'open') { $projectStatus = 'toets bouwfase'; } else if ($this->bt_status == 'afgerond' && $this->btz_status == 'open') { $projectStatus = 'toezicht open'; } else if ($this->bt_status == 'bouwfase' && $this->btz_status == 'bouwfase') { $projectStatus = 'bouwfase'; } else if ($this->bt_status == 'afgerond' && $this->btz_status == 'bouwfase') { $projectStatus = 'toets afgerond'; } else if ($this->bt_status == 'bouwfase' && $this->btz_status == 'afgerond') // This situation should not occur, but handle it nonetheless { $projectStatus = 'toezicht afgerond'; } else if ($this->bt_status == 'afgerond' && $this->btz_status == 'afgerond') { $projectStatus = 'afgerond'; } else if ($this->bt_status == 'afgesloten' && $this->btz_status == 'afgesloten') { $projectStatus = 'afgesloten'; } // Update the project status (if it was changed) and save the new value if we were requested to do so. if ($projectStatus != $previousProjectStatus) { $this->project_status = $projectStatus; $this->bijgewerkt_op = date("Y-m-d H:i:s"); if ($saveNewStatus) { $this->save(); } } } // public function determineAndSetProjectStatus($saveNewStatus = true) public function get_bouwnummers(){ $bouwnummers = explode( ',', $this->bouwnummers); return $bouwnummers; } } class BtBtzDossier extends BaseModel { function BtBtzDossier() { parent::BaseModel( 'BtBtzDossierResult', 'bt_btz_dossiers' ); } public function check_access( BaseResult $object ) { return; } public function get_one_by_btz_dossier_id_and_hash( $btzDossierId, $btzDossierHash ) { $parameters = array($btzDossierId, $btzDossierHash); $stmt_name = 'get_one_by_btz_dossier_id_and_hash'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT bbd.* FROM bt_btz_dossiers bbd WHERE (bbd.btz_dossier_id = ?) AND (bbd.btz_dossier_hash = ?)'); $btBtzDossiers = $this->convert_results( $this->_CI->dbex->execute($stmt_name, $parameters) ); return (empty($btBtzDossiers)) ? null : $btBtzDossiers[0]; } // public function get_one_by_btz_dossier_id_and_hash( $btzDossierId, $btzDossierHash ) public function get_one_by_btz_dossier_id( $btzDossierId ) { $parameters = array($btzDossierId); $stmt_name = 'get_one_by_btz_dossier_id'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT bbd.* FROM bt_btz_dossiers bbd WHERE (bbd.btz_dossier_id = ?)'); $btBtzDossiers = $this->convert_results( $this->_CI->dbex->execute($stmt_name, $parameters) ); return (empty($btBtzDossiers)) ? null : $btBtzDossiers[0]; } // public function get_one_by_btz_dossier_id( $btzDossierId ) public function get_active_by_klant( $klant_id, $dossier_id = null ) { // Specify a dossier ID filter if necessary if (is_null($dossier_id) || !is_int($dossier_id)) { $dossier_clause = ''; $parameters = array($klant_id); } else { $dossier_clause = 'AND (d.id = ?)'; $parameters = array($klant_id, $dossier_id); } $stmt_name = 'get_active_btbtzdossiers_by_klant'; $this->_CI->dbex->prepare( $stmt_name, ' SELECT bbd.* FROM bt_btz_dossiers bbd INNER JOIN dossiers d ON (d.id = bbd.btz_dossier_id) INNER JOIN gebruikers g ON (g.id = d.gebruiker_id) WHERE (g.klant_id = ?) AND (d.gearchiveerd = 0) AND (d.gearchiveerd = 0) ' . $dossier_clause); return $this->convert_results( $this->_CI->dbex->execute($stmt_name, $parameters) ); } public function get_all_non_closed( $klant_id = null ) { // Specify a dossier ID filter if necessary if (is_null($klant_id) || !is_int($klant_id)) { $klant_clause = ''; $parameters = array(); } else { $klant_clause = 'AND (g.klant_id = ?)'; $parameters = array($klant_id); } $stmt_name = 'get_all_non_closed_btbtzdossiers'; $this->_CI->dbex->prepare( $stmt_name, " SELECT bbd.* FROM bt_btz_dossiers bbd INNER JOIN dossiers d ON (d.id = bbd.btz_dossier_id) INNER JOIN gebruikers g ON (g.id = d.gebruiker_id) WHERE (bbd.project_status NOT IN ('afgesloten')) " . $klant_clause); return $this->convert_results( $this->_CI->dbex->execute($stmt_name, $parameters) ); } } <file_sep>SELECT @gem_bilt_id:=id FROM klanten WHERE naam = '<NAME>'; INSERT INTO gebruikers SET klant_id = @gem_bilt_id, rol_id = null, speciale_functie = 'geen', gebruikersnaam = 'nog_niet_toegewezen', wachtwoord = SHA1('<PASSWORD>'), volledige_naam = '<NAME>', status = 'geblokkeerd', intern = 'ja'; <file_sep><?php class DatabaseIdCleanup { private $CI; public function __construct() { $this->CI = get_instance(); } public function run() { // get tables $tables = $this->_get_tables_with_ids(); // start transaction foreach ($tables as $table) { $this->_cleanup_ids_in_table( $table ); } } public function _cleanup_ids_in_table( $table ) { // get all current ids $ids = array(); $res = $this->_query( 'SELECT id FROM ' . $table . ' ORDER BY id' ); foreach ($res->result() as $row) $ids[] = $row->id; $res->free_result(); // get info $before_id_count = sizeof($ids); // update IDs $next_id = 1; foreach ($ids as $id) { if ($id <= 0) throw new Exception( 'Error in table ' . $table . ', id ' . $id . ' is <= 0' ); $new_id = $next_id++; if ($new_id != $id) { $query = 'UPDATE ' . $table . ' SET id = ' . $new_id . ' WHERE id = ' . $id; $this->_query( $query ); echo "$id -> $next_id\r"; } } // check counts $res = $this->_query( 'SELECT COUNT(*) AS count FROM ' . $table ); $after_id_count = $res->row_object()->count; $res->free_result(); if ($before_id_count != $after_id_count) throw new Exception( 'Error in table: before count=' . $before_id_count . ', after count=' . $after_id_count ); // echo result echo sprintf("TABLE: %35s ID count %5d, new auto increment is %5d\n", $table, $before_id_count, $next_id ); // update auto increment echo "Updating AUTOINCREMENT on table " . $table . "\r"; $this->_query( 'ALTER TABLE ' . $table . ' AUTO_INCREMENT = ' . $next_id ); } public function _get_tables_with_ids() { // get table names $res = $this->_query( 'SHOW TABLES' ); $table_rows = $res->result(); $res->free_result(); // find ones with id fields $tables = array(); foreach ($table_rows as $row) { $table = reset( $row ); $res = $this->_query( 'SHOW FIELDS FROM ' . $table ); foreach ($res->result() as $row) { $field = reset( $row ); if ($field == 'id') { $tables[] = $table; break; } } $res->free_result(); } return $tables; } private function _query( $query ) { $res = $this->CI->db->query( $query ); if (!$res) throw new Exception( 'Query error: ' . $query ); return $res; } } <file_sep>PDFAnnotator.GUI.Menu.Text = PDFAnnotator.GUI.Menu.Panel.extend({ init: function( menu, config ) { this._super( menu ); this.bold = config.bold; this.italic = config.italic; this.underline = config.underline; this.sizes = config.sizes; this.fonts = config.fonts; this.selectedClass = config.selectedClass; this.currentFont = config.currentFont; var thiz = this; this.fonts.click(function(){ thiz.fonts.removeClass( thiz.selectedClass ); $(this).addClass( thiz.selectedClass ); thiz.currentFont.text( $(this).css( 'font-family' ).replace( /'/g, '' ) ); }); }, getBold: function() { return !!this.bold.attr( 'checked' ); }, getItalic: function() { return !!this.italic.attr( 'checked' ); }, getUnderline: function() { return !!this.underline.attr( 'checked' ); }, getFontSize: function() { return this.sizes.filter( ':checked' ).val(); }, getFontFamily: function() { return this.fonts.filter( '.' + this.selectedClass ).css( 'font-family' ); } }); <file_sep><?php function logger($str, $filepath = null) { if($filepath) { $fp = fopen($filepath, 'a+'); fwrite($fp, $str."\n"); fclose($fp); } else { echo "$str\n"; } } define('BASEPATH', __DIR__ . '/../system/'); require_once __DIR__ . '/../application/config/database.php'; require_once __DIR__ . '/../application/config/constants.php'; $db = (object) $db['default']; switch($db->dbdriver) { case 'mysql': case 'mysqli': $pdo_driver = 'mysql'; } global $dbh; $dbh = new PDO($pdo_driver . ':dbname=' . $db->database . ';host=' . $db->hostname, $db->username, $db->password); $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $dbh->exec('SET CHARACTER SET '.$db->char_set);<file_sep><div class="nlaf_TabContent"> <table class="aandachtspunten" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="tekst" rowspan="4" style="border-right: 1px solid #ccc;"> <div class="subtabcontents" tab-name="grondslagen"> <img src="<?=site_url('/files/images/nlaf/aandachtspunten-background.png')?>" > </div> <div class="subtabcontents hidden" tab-name="richtlijnen"></div> <div class="subtabcontents hidden" tab-name="aandachtspunten"></div> </td> <td class="subtab selected" tab-name="grondslagen"> <div id="nlaf_AantalGrondslagen" class="notificaties" />0</div> <?=tg('wettelijke_grondslagen')?> </td> </tr> <tr> <td class="subtab" tab-name="richtlijnen"> <div id="nlaf_AantalRichtlijnen" class="notificaties" />0</div> <?=tg('richtlijnen')?> </td> </tr> <tr> <td class="subtab" tab-name="aandachtspunten"> <div id="nlaf_AantalAandachtspunten" class="notificaties" />0</div> <?=tg('aandachtspunten')?> </td> </tr> <tr> <td class="filler">&nbsp;</td> </tr> </table> </div> <script type="text/javascript"> $(document).ready(function(){ // handle switching tabs $('.aandachtspunten td.subtab').click(function(){ // handle selected class on tabs $('.aandachtspunten td.subtab.selected').removeClass('selected'); $(this).addClass('selected'); // handle display correct tab contents $('.aandachtspunten div.subtabcontents').hide(); $('.aandachtspunten div.subtabcontents[tab-name=' + $(this).attr('tab-name') + ']').show(); }); }); </script> <file_sep><? require_once 'base.php'; class RichtlijnResult extends BaseResult { function RichtlijnResult( &$arr ) { parent::BaseResult( 'richtlijn', $arr ); } function get_download_url() { if ($this->url) return $this->url; else return '/deelplannen/download_richtlijn/' . $this->id; } function get_checklistgroepen() /* geef lijst van alle checklistgroepen waarin deze richtlijn gebruikt wordt */ { $CI = get_instance(); $CI->load->model( 'checklistgroep' ); // !!! Query tentatively/partially made Oracle compatible. To be fully tested... /* $query = ' SELECT cg.* FROM bt_vraag_rchtlnn vrl JOIN bt_vragen v ON vrl.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE vrl.richtlijn_id = ' . $this->id . ' GROUP BY cg.id '; */ $query = ' SELECT cg.* FROM bt_checklist_groepen cg WHERE cg.id IN ( SELECT cg.id FROM bt_vraag_rchtlnn vrl JOIN bt_vragen v ON vrl.vraag_id = v.id JOIN bt_categorieen c ON v.categorie_id = c.id JOIN bt_hoofdgroepen h ON c.hoofdgroep_id = h.id JOIN bt_checklisten cl ON h.checklist_id = cl.id JOIN bt_checklist_groepen cg ON cl.checklist_groep_id = cg.id WHERE vrl.richtlijn_id = ' . $this->id . ' ) '; return $CI->checklistgroep->convert_results( $CI->db->query($query) ); } } class Richtlijn extends BaseModel { function Richtlijn() { parent::BaseModel( 'RichtlijnResult', 'bt_richtlijnen' ); } public function check_access( BaseResult $object ) { // we kunnen niet alleen maar naar de klant_id kijken, in plaats daarvan // kijken we in welke checklistgroepen deze richtlijn voorkomt, en als de // gebruiker EEN van die checklistgroepen mag gebruiken, dan mag hij deze // richtlijn gebruiken $CI = get_instance(); foreach ($object->get_checklistgroepen() as $cg) { try { $CI->checklistgroep->check_access( $cg ); // we have access! return; } catch (Exception $e) { // no access! } } // als geen van de checklisten toegang geeft, of als er geen checklisten // zijn (ook goed mogelijk), dan gewoon de normale klant_id methode // uitvoeren return parent::check_access( $object ); } function add( $filename, $data, $multi_upload_richtlijnen=0 ) { /* $db = $this->get_db(); $this->dbex->prepare( 'Richtlijn::add', 'INSERT INTO bt_richtlijnen (filename, data, klant_id) VALUES (?, ?, ?)', $db ); $args = array( 'filename' => $filename, 'data' => $data, 'klant_id' => get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, ); $this->dbex->execute( 'Richtlijn::add', $args, false, $db ); $id = $db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'filename' => $filename, 'data' => $data, 'klant_id' => get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, 'multi_upload_richtlijnen' => $multi_upload_richtlijnen, ); // Call the normal 'insert' method of the base record. // For Oracle force the types of the parameters, as at least one LOB column needs to be written to. $force_types = (get_db_type() == 'oracle') ? 'sbi' : ''; $result = $this->insert( $data, '_file', $force_types ); return $result; } function add_url( $url, $beschrijving ) { /* $db = $this->get_db(); $this->dbex->prepare( 'Richtlijn::add', 'INSERT INTO bt_richtlijnen (url, url_beschrijving, klant_id) VALUES (?, ?, ?)', $db ); $args = array( 'url' => $url, 'url_beschrijving' => $beschrijving, 'klant_id' => get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, ); $this->dbex->execute( 'Richtlijn::add', $args, false, $db ); $id = $db->insert_id(); if (!is_numeric($id)) return null; return new $this->_model_class( array_merge( array('id'=>$id), $args ) ); * */ // !!! Rewritten to use the base model's insert functionality - remove the commented out code when it has been verified to work correctly. // Use the base model's 'insert' method. $data = array( 'url' => $url, 'url_beschrijving' => $beschrijving, 'klant_id' => get_instance()->gebruiker->get_logged_in_gebruiker()->klant_id, ); // Call the normal 'insert' method of the base record. $result = $this->insert( $data, '_url' ); return $result; } public function find( $richtlijn ) { $db = $this->get_db(); $this->dbex->prepare( 'Richtlijn::find', 'SELECT * FROM bt_richtlijnen WHERE filename = ? AND klant_id = ?', $db ); $args = array( $richtlijn, $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $res = $this->dbex->execute( 'Richtlijn::find', $args, false, $db ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function find_url( $url, $beschrijving ) { $db = $this->get_db(); $this->dbex->prepare( 'Richtlijn::find', 'SELECT * FROM bt_richtlijnen WHERE url = ? AND url_beschrijving = ? AND klant_id = ?', $db ); $args = array( $url, $beschrijving, $this->gebruiker->get_logged_in_gebruiker()->klant_id ); $res = $this->dbex->execute( 'Richtlijn::find', $args, false, $db ); $result = $res->result(); $result = empty( $result ) ? null : $this->getr( reset( $result ) ); $res->free_result(); return $result; } public function get_for_huidige_klant( $assoc=false ) { $CI = get_instance(); $stmt_name = get_class($this) . '::get_for_huidige_klant'; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE klant_id = ? ORDER BY filename' ); $res = $CI->dbex->execute( $stmt_name, array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); $result = array(); foreach ($res->result() as $row) if (!$assoc) $result[] = $this->getr( $row, false ); else $result[$row->id] = $this->getr( $row, false ); return $result; } public function get_multi_documents($document_id=null){ $CI = get_instance(); $stmt_name = get_class($this) . '::get_multi_documents'; $sub_query = $document_id ? " and id=".$document_id :""; $CI->dbex->prepare( $stmt_name, 'SELECT * FROM ' . $this->get_table() . ' WHERE klant_id = ? and multi_upload_richtlijnen=1'.$sub_query ); $res = $CI->dbex->execute( $stmt_name, array( $this->gebruiker->get_logged_in_gebruiker()->klant_id ) ); return $res->result(); } public function delete_richtlijn_documents($document_id){ $this->db->delete('bt_richtlijnen', array('id' => $document_id)); } } <file_sep>PDFAnnotator.Handle.MeasureFinish = PDFAnnotator.Handle.extend({ /* constructor */ init: function( editable ) { /* initialize base class */ this._super( editable ); this.addNodes(); }, /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 0, 1, baseurl + 'images/nlaf/edit-handle-measure-finish.png', 32, 32, 'click', this.execute, null, 1 /*inside*/, -1 /*outside*/ ); }, execute: function() { /* this.editable is eigenlijk de measure tool helper window! */ /* this.editable.owner is de measure tool! */ var measureTool = this.editable.owner; if (!measureTool.finish()) alert( 'Calibratie nog niet voltooid. Plaats eerst een meetlijn en vul de lengte in.' ); } }); <file_sep>ALTER TABLE klanten ADD letter TINYINT(1) UNSIGNED NOT NULL DEFAULT '0'; REPLACE INTO teksten(string, tekst , timestamp , lease_configuratie_id) VALUES ('klant.letter', 'Standaardbrief', '2014-12-18 20:51:21', '0'), ('klant.letter', 'Standaardbrief', '2014-12-18 20:51:21', '1'), ('checklistwizard.section.email.letter', 'Standaardbrief', '2014-12-18 20:51:21', '0'), ('checklistwizard.section.email.letter', 'Standaardbrief', '2014-12-18 20:51:21', '1'); <file_sep>ALTER TABLE `bt_checklist_groepen` ADD `standaard_waardeoordeel_in_gebruik_00` TINYINT NULL DEFAULT '1' AFTER `standaard_waardeoordeel_kleur_00` , ADD `standaard_waardeoordeel_in_gebruik_01` TINYINT NULL DEFAULT '1' AFTER `standaard_waardeoordeel_kleur_01` , ADD `standaard_waardeoordeel_in_gebruik_02` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_02` , ADD `standaard_waardeoordeel_in_gebruik_03` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_03` , ADD `standaard_waardeoordeel_in_gebruik_04` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_04` , ADD `standaard_waardeoordeel_in_gebruik_10` TINYINT NULL DEFAULT '1' AFTER `standaard_waardeoordeel_kleur_10` , ADD `standaard_waardeoordeel_in_gebruik_11` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_11` , ADD `standaard_waardeoordeel_in_gebruik_12` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_12` , ADD `standaard_waardeoordeel_in_gebruik_13` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_13` , ADD `standaard_waardeoordeel_in_gebruik_20` TINYINT NULL DEFAULT '1' AFTER `standaard_waardeoordeel_kleur_20` , ADD `standaard_waardeoordeel_in_gebruik_21` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_21` , ADD `standaard_waardeoordeel_in_gebruik_22` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_22` , ADD `standaard_waardeoordeel_in_gebruik_23` TINYINT NULL DEFAULT '0' AFTER `standaard_waardeoordeel_kleur_23` ; ALTER TABLE `bt_checklisten` ADD `standaard_waardeoordeel_in_gebruik_00` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_00` , ADD `standaard_waardeoordeel_in_gebruik_01` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_01` , ADD `standaard_waardeoordeel_in_gebruik_02` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_02` , ADD `standaard_waardeoordeel_in_gebruik_03` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_03` , ADD `standaard_waardeoordeel_in_gebruik_04` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_04` , ADD `standaard_waardeoordeel_in_gebruik_10` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_10` , ADD `standaard_waardeoordeel_in_gebruik_11` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_11` , ADD `standaard_waardeoordeel_in_gebruik_12` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_12` , ADD `standaard_waardeoordeel_in_gebruik_13` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_13` , ADD `standaard_waardeoordeel_in_gebruik_20` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_20` , ADD `standaard_waardeoordeel_in_gebruik_21` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_21` , ADD `standaard_waardeoordeel_in_gebruik_22` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_22` , ADD `standaard_waardeoordeel_in_gebruik_23` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_23` ; ALTER TABLE `bt_hoofdgroepen` ADD `standaard_waardeoordeel_in_gebruik_00` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_00` , ADD `standaard_waardeoordeel_in_gebruik_01` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_01` , ADD `standaard_waardeoordeel_in_gebruik_02` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_02` , ADD `standaard_waardeoordeel_in_gebruik_03` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_03` , ADD `standaard_waardeoordeel_in_gebruik_04` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_04` , ADD `standaard_waardeoordeel_in_gebruik_10` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_10` , ADD `standaard_waardeoordeel_in_gebruik_11` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_11` , ADD `standaard_waardeoordeel_in_gebruik_12` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_12` , ADD `standaard_waardeoordeel_in_gebruik_13` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_13` , ADD `standaard_waardeoordeel_in_gebruik_20` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_20` , ADD `standaard_waardeoordeel_in_gebruik_21` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_21` , ADD `standaard_waardeoordeel_in_gebruik_22` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_22` , ADD `standaard_waardeoordeel_in_gebruik_23` TINYINT NULL DEFAULT NULL AFTER `standaard_waardeoordeel_kleur_23` ; ALTER TABLE `bt_vragen` ADD `waardeoordeel_in_gebruik_00` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_00` , ADD `waardeoordeel_in_gebruik_01` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_01` , ADD `waardeoordeel_in_gebruik_02` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_02` , ADD `waardeoordeel_in_gebruik_03` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_03` , ADD `waardeoordeel_in_gebruik_04` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_04` , ADD `waardeoordeel_in_gebruik_10` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_10` , ADD `waardeoordeel_in_gebruik_11` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_11` , ADD `waardeoordeel_in_gebruik_12` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_12` , ADD `waardeoordeel_in_gebruik_13` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_13` , ADD `waardeoordeel_in_gebruik_20` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_20` , ADD `waardeoordeel_in_gebruik_21` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_21` , ADD `waardeoordeel_in_gebruik_22` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_22` , ADD `waardeoordeel_in_gebruik_23` TINYINT NULL DEFAULT NULL AFTER `waardeoordeel_kleur_23` ; UPDATE `bt_checklist_groepen` SET `standaard_waardeoordeel_in_gebruik_00` = 1, `standaard_waardeoordeel_in_gebruik_01` = 1, `standaard_waardeoordeel_in_gebruik_02` = 1, `standaard_waardeoordeel_in_gebruik_03` = 1, `standaard_waardeoordeel_in_gebruik_04` = 1, `standaard_waardeoordeel_in_gebruik_10` = 1, `standaard_waardeoordeel_in_gebruik_11` = 1, `standaard_waardeoordeel_in_gebruik_12` = 1, `standaard_waardeoordeel_in_gebruik_13` = 1, `standaard_waardeoordeel_in_gebruik_20` = 1, `standaard_waardeoordeel_in_gebruik_21` = 1; <file_sep>-- run php index.php /cli/vraagupload2bescheidenconverter <file_sep>PDFAnnotator.Editable.MeasureLine = PDFAnnotator.Editable.Line.extend({ init: function( config ) { this._super( config, PDFAnnotator.Tool.prototype.getByName( 'measure' ) ); this.setData( config, {}, [ 'mm', 'pixels' ] ); this.data.mm = parseInt( this.data.mm ); this.data.pixels = parseInt( this.data.pixels ); this.lengthDiv = null; }, /** override! */ render: function() { // let line render itself this._super(); // add text this.lengthDiv = $('<div>') .css( 'position', 'absolute' ) .css( 'font-family', 'Arial' ) .css( 'font-size', '14pt' ) .css( 'color', '#ed1c24' ) .appendTo( $(this.visuals) ); this.updateVisualLength(); // create arrow heads // // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE // these attached rotated lines are OUTSIDE this line's div!! // this is not by design, but I don't have time to this differently now // for this reason, we have a preremove implementation to remove the lines // when the editable is removed // when the editable is MOVED (not REmoved), then the line is updated, which // automatically triggers the attached rotated lines to update, so no need to // fiddle there // // var angle = 30; this.arrows = [ new PDFAnnotator.AttachedRotatedLine( this.line, ((180 - angle)/180.0)*Math.PI, 25, false ), new PDFAnnotator.AttachedRotatedLine( this.line, ((180 + angle)/180.0)*Math.PI, 25, false ), new PDFAnnotator.AttachedRotatedLine( this.line, ((- angle)/180.0)*Math.PI, 25, true ), new PDFAnnotator.AttachedRotatedLine( this.line, (( angle)/180.0)*Math.PI, 25, true ) ]; for (var i=0; i<this.arrows.length; ++i) this.container.dom.append( this.arrows[i].myline.dom ); }, updateCalibration: function( mm, pixels ) { this.data.mm = mm; this.data.pixels = pixels; this.updateVisualLength(); }, /** override! */ updateInternal: function() { this._super(); this.updateVisualLength(); }, getMeasureLength: function() { var zoomLevel = this.container ? this.container.engine.getZoomLevel() : 1; var linepixels = this.line.length() / zoomLevel; var mymm = (linepixels / this.data.pixels) * this.data.mm; return Math.round( mymm ); }, updateVisualLength: function() { if (this.lengthDiv) { var x = Math.round((this.line.from.x + this.line.to.x)/2) - Math.min(this.line.from.x, this.line.to.x), y = Math.round((this.line.from.y + this.line.to.y)/2) - Math.min(this.line.from.y, this.line.to.y); this.lengthDiv .css( 'left', x + 'px' ) .css( 'top', y + 'px' ) .text( this.getMeasureLength() + 'mm' ); } }, /* !!overide!! */ rawExport: function() { return { type: 'measureline', x1: this.data.from.x, y1: this.data.from.y, x2: this.data.to.x, y2: this.data.to.y, color: this.data.color, mm: this.data.mm, pixels: this.data.pixels }; }, /* static */ rawImport: function( data ) { return new PDFAnnotator.Editable.MeasureLine({ color: data.color, from: new PDFAnnotator.Math.IntVector2( data.x1, data.y1 ), to: new PDFAnnotator.Math.IntVector2( data.x2, data.y2 ), mm: data.mm, pixels: data.pixels }); }, /** override! */ preremove: function() { for (var i=0; i<this.arrows.length; ++i) { this.arrows[i].remove(); } this.arrows = []; } }); <file_sep>-- run: -- php index.php /cli/checkutf8/1<file_sep>PDFAnnotator.Server = PDFAnnotator.Base.extend({ instance: null, /* returns base url for images, js files, css files, etc. */ getBaseUrl: function() { return '/'; }, /* returns the image url for an image with the given specification */ getLineImageUrl: function( size, up, color ) { }, /* returns the url for performing a specific drawing operation */ getDrawingOperationUrl: function( pagenr, operation ) { }, /* starts download for an annotated document. */ downloadAnnotatedDocument: function( engine, layers, pageTransform, dimensions ) { }, /* loads layer annotations for the current document */ loadAnnotations: function( layer, onsuccess, onerror ) { }, /* starts loading available reference objects for layers (in BTZ: vraag objecten) */ getAvailableLayerReferenceObjects: function( onsuccess, onerror ) { }, /* determines whether or not a photo (with file upload) may be added to the given layer. */ mayAddPhoto: function( layer ) { return true; }, /* registers the given form as a photo upload (camera tool) that still needs to be performed */ handleFormUpload: function( form, uploadinput, editable ) { }, /* returns window size, may be overridden to return size from something else than the main window (if embedded) */ getWindowProportions: function() { var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; } return { width: myWidth, height: myHeight, top: 0, left: 0 }; } }); <file_sep>INSERT INTO `teksten` ( `string` , `tekst` , `timestamp` , `lease_configuratie_id` ) VALUES ( 'klant.kan_dossieroverzichten_genereren', 'Kan dossieroverzichten genereren', '2015-09-20 15:07:20', '0' ); INSERT INTO `teksten` ( `string`, `tekst`, `timestamp`, `lease_configuratie_id` ) VALUES ( 'form.dossieroverzicht_genereren', 'Dossier overzicht genereren', '2015-09-20 22:32:00', '0' ); INSERT INTO `help_buttons` ( `tag`, `taal`, `tekst`, `laast_bijgewerkt_op` ) VALUES ( 'dossiers.index.dossieroverzicht_genereren', 'nl', 'Dossier overzicht genereren naar Excel.', '2015-09-20 22:37:00' );<file_sep><? $operatoren = array( 'bevat' => 'bevat', 'bevat niet' => 'bevat niet', 'bevat iets anders dan' => 'bevat iets anders dan', '==' => 'is', '!=' => 'is niet', '>' => 'groter dan', '<' => 'kleiner dan', '>=' => 'groter dan of gelijk aan', '<=' => 'kleiner dan of gelijk aan', ); ?> <? $this->load->view('elements/header', array('page_header'=>'BRIStoets-koppeling checklistbeheer') ); ?> <h2>Checklist</h2> <select name="checklist_id"> <option value="" disabled <?=$checklist ? '' : 'selected'?>>- selecteer een checklist -</option> <? foreach ($checklisten as $cl): ?> <? if ($alleen_met_regels && !in_array( $cl->id, $list_of_checklist_ids_with_voorwaarden )) continue; ?> <option <?=($checklist && $checklist->id==$cl->id)?'selected':''?> && value="<?=$cl->id?>"> <?=htmlentities( $checklistgroepen[$cl->checklist_groep_id]->naam, ENT_COMPAT, 'UTF-8' )?> - <?=htmlentities( $cl->naam, ENT_COMPAT, 'UTF-8' )?> </option> <? endforeach; ?> </select> <br/> <label> <input type="checkbox" name="alleen_met_regels" <?=$alleen_met_regels ? 'checked' : ''?> /> Toon alleen checklisten waar al voorwaarden voor gedefinieerd zijn. </label> <br/><br/> <? if ($checklist): ?> <form method="POST"> <h2>Voorwaarde toevoegen</h2> <table> <tr> <td width="150px"><b>Veld:</b></td> <td> <select name="veld"> <? foreach (array( 'aanvraagdatum','gebruiksfunctie','bouwsom','is integraal','is eenvoudig','is dakkapel','is bestaand' ) as $veld): ?> <option value="<?=$veld?>"><?=$veld?></option> <? endforeach; ?> </select> <select name="operator"> <? foreach ($operatoren as $operator => $desc): ?> <option value="<?=$operator?>"><?=htmlentities( $desc )?></option> <? endforeach; ?> </select> <input class="waarde aanvraagdatum" type="text" name="aanvraagdatum" size="20" maxlength="20" /> <select class="waarde gebruiksfunctie" name="gebruiksfunctie"> <? foreach (array( 'woonfunctie', 'bijeenkomstfunctie', 'celfunctie', 'gezondheidszorgfunctie', 'industriefunctie', 'kantoorfunctie', 'logiesfunctie', 'onderwijsfunctie', 'sportfunctie', 'winkelfunctie', 'overige gebruiksfunctie', 'bouwwerk geen gebouw zijnde' ) as $functie): ?> <option value="<?=$functie?>"><?=$functie?></option> <? endforeach; ?> </select> <input class="waarde bouwsom" type="text" name="bouwsom" size="10" maxlength="10" /> <select class="waarde is_integraal is_eenvoudig is_dakkapel is_bestaand" name="is"> <option value="ja">ja</option> <option value="nee">nee</option> </select> </td> </tr> <tr> <td></td> <td><input type="submit" value="Toevoegen" /></td> </tr> </table> <br/><br/> <h2>Voorwaarden waarbij deze checklist wordt gebruikt</h2> <i><?=sizeof($voorwaarden)?> voorwaarde(n) gedefinieerd</i> <table width="500px" style="border-spacing:0"> <? foreach ($voorwaarden as $i => $voorwaarde): ?> <tr style="background-color: <?=($i % 2) ? '#fff' : '#eee'?>"> <td style="background-color: transparent; padding: 5px"> <b><?=$voorwaarde->veld?></b> <?=$operatoren[ $voorwaarde->operator ]?> <b><?=htmlentities( $voorwaarde->waarde )?></b> </td> <td style="text-align:right; padding: 5px"> <a href="javascript:void(0);" onclick="if (confirm('Voorwaarde werkelijk verwijderen?')) location.href='<?=site_url('/admin/koppelvoorwaarde_verwijderen/' . $checklist->id . '/' . $voorwaarde->id)?>';"><img src="<?=site_url('/files/images/delete.png')?>"></a> </td> </tr> <? endforeach; ?> </table> </form> <? endif; ?> <script type="text/javascript"> // als dit verandert, ook de code in het checklistkoppelwaarde model aanpassen! var veldOps = { aanvraagdatum: ['==', '!=', '>', '>=', '<', '<='], gebruiksfunctie: ['bevat', 'bevat niet', 'bevat iets anders dan'], bouwsom: ['==', '!=', '>', '>=', '<', '<='], is_integraal: ['==', '!='], is_eenvoudig: ['==', '!='], is_dakkapel: ['==', '!='], is_bestaand: ['==', '!='] }; $(document).ready(function(){ $('[name=checklist_id]').change(function(){ location.href = '<?=site_url('/admin/koppelvoorwaarden_beheer')?>/' + this.value; }); $('[name=alleen_met_regels]').click(function(){ location.href = '<?=site_url('/admin/koppelvoorwaarden_set_alleen_met_regels')?>/' + (this.checked ? '1' : '0') + '/' + $('[name=checklist_id]').val() ; }); $('[name=aanvraagdatum]').datepicker({ dateFormat: "dd-mm-yy" }); $('[name=veld]').change(function(){ var veldnaam = this.value.replace(/ /, '_'); $('.waarde').hide(); $('.waarde.' + veldnaam).show(); $('[name=operator] option').each(function(){ if (indexOfArray( veldOps[veldnaam], this.value ) != -1) $(this).show(); else $(this).hide(); }); var opSel = $('[name=operator]')[0]; opSel.value = veldOps[veldnaam][0]; }); // init $('[name=veld]').change(); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Account beheer')); ?> <form method="POST"> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Checklistgroepbeheer', 'width' => '920px' ) ); ?> <p> Via deze pagina kan worden ingesteld welke klanten checklistgroepen en checklisten mogen publiceren voor gebruik door andere klanten. Klanten mogen niet zelf bepalen of hun checklistgroep zichtbaar is voor anderen, dit gebeurt door de systeembeheerders van BRIStoezicht. Wel mogen klanten zelf bepalen welke checklisten binnen de door BRIStoezicht aangewezen checklistgroepen prive, publiek voor iedereen, of beperkt publiek zijn. </p> <p> Om afbeeldingen te uploaden die kunnen worden gekoppeld aan deze checklistgroepen, klik <a href="<?=site_url('/admin/image_beheer')?>">hier</a>. </p> <table class="admintable" width="100%" cellpadding="3" cellspacing="0"> <tr> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 120px;">Klant naam</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 250px;">Checklistgroep</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 100px;">Afbeelding</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777; width: 100px;">Beschikbaarheid</th> <th style="text-align:left; padding-left: 0px; border-bottom:2px solid #777;">Voor klanten</th> </tr> <tr> <td style="vertical-align:top" valign="top"><b><?=$klanten->naam?$klanten->naam:'(naamloze klant)'?></b></td> <? $j = 0; foreach ($checklistgroepen[$klanten->id] as $i => $cg): ?> <? if ($j): ?> </tr> <tr> <td></td> <? endif; ?> <td> <? if ($cg->image_id): ?> <img src="<?=$images[$cg->image_id]->get_url()?>" /> <? else: ?> <img src="<?=site_url( '/files/images/geen-logo.png' )?>" /> <? endif; ?> <?=htmlentities( $cg->naam, ENT_COMPAT, 'UTF-8' )?> </td> <td> <select name="images[<?=$cg->id?>]"> <option value="">-- geen --</option> <? foreach ($images as $image): ?> <option value="<?=$image->id?>" <?=$image->id==$cg->image_id?'selected':''?>><?=$image->filename?> (<?=$image->width?>x<?=$image->height?>)</option> <? endforeach; ?> </select> </td> <td> <select name="checklistgroepen[<?=$cg->id?>]" cg_id="<?=$cg->id?>"> <option <?='prive' == $cg->beschikbaarheid ? 'selected' : '' ?> value="prive">Priv&eacute;</option> <option <?='publiek-voor-iedereen' == $cg->beschikbaarheid ? 'selected' : ''?> value="publiek-voor-iedereen">Publiek voor iedereen</option> <option <?='publiek-voor-beperkt' == $cg->beschikbaarheid ? 'selected' : '' ?> value="publiek-voor-beperkt">Beperkt publiek</option> </select> </td> <td> <div class="<?=$cg->beschikbaarheid!='publiek-voor-iedereen'?'hidden':''?> publiek-voor-iedereen cg<?=$cg->id?>"> <b>Beschikbaar voor alle klanten.</b> </div> <div class="<?=$cg->beschikbaarheid!='publiek-voor-beperkt'?'hidden':''?> publiek-voor-beperkt cg<?=$cg->id?>"> <b>Alleen voor <a href="javascript:void(0);" onclick="$('.lijst-cg<?=$cg->id?>').slideToggle();">geselecteerde klanten</a></b> </div> </td> </tr> <tr class="hidden lijst-cg<?=$cg->id?>"> <td colspan="2"></td> <td colspan="3"> <ul class="checklist-ul"> <? foreach ($all_klanten as $k2): ?> <? $checked = (isset( $checklistgroep_klanten[$cg->id] ) && in_array( $k2->id, $checklistgroep_klanten[$cg->id] )); $color = $checked ? 'black' : 'red'; $unavailable = in_array( $k2, $unavailable_klanten ); ?> <li style="<?=$unavailable ? 'display:none;' : ''?>"> <input type="checkbox" name="checklistgroepklant[<?=$cg->id?>][<?=$k2->id?>]" <?=$checked?'checked':''?>> <span style="color: <?=$color?>"><?=htmlentities( $k2->naam, ENT_COMPAT, 'UTF-8' )?></span> </li> <? endforeach; ?> </ul> </td> <? ++$j; endforeach; ?> </tr> </table> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <br/> <p> <input type="submit" value="Opslaan" /> </p> </form> <script type="text/javascript"> $('select[name^=checklistgroepen]').change(function(){ var cg_id = $(this).attr('cg_id'); var value = this.value; $('div.cg' + cg_id + ', tr.cg' + cg_id).hide(); $('div.cg' + cg_id + '.' + value + ', tr.cg' + cg_id + '.' + value).show(); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep>PDFAnnotator.Handle.OverviewMove = PDFAnnotator.Handle.Move.extend({ /* overrideable function that adds the nodes */ addNodes: function() { var baseurl = PDFAnnotator.Server.prototype.instance.getBaseUrl(); this.addNodeRelative( 1, 0, baseurl + 'images/nlaf/overview-move.png', 23, 23, 'drag', this.execute, null, 1, 1, -10, 14 ); } }); <file_sep>var NokiaMapsHelper = { initialize: function( insertAfter, adressen, onCreateElement, onInstallMap, onDoneSearching ) { // creeer kaart element dynamisch var kaartElement = $('<div>') .css( 'width', 'auto' ) .css( 'height', '500px' ) .css( 'border', '1px solid #888' ) .css( 'padding', '0px' ) .css( 'margin', '0px' ) .insertAfter( insertAfter ); if (typeof( onCreateElement ) == 'function') onCreateElement( kaartElement ); // init nokia maps ding nokia.Settings.set("appId", "McvEOKhagR0v_FwbZixf"); nokia.Settings.set("authenticationToken", "<KEY>"); // init map var infoBubbles = new nokia.maps.map.component.InfoBubbles(); var nokiaMap = new nokia.maps.map.Display( kaartElement[0], { 'zoomLevel': 7, // pretty zoomed out 'center': [52.160455,5.524292], // centered on The Netherlands components: [ new nokia.maps.map.component.Behavior(), // allow panning/zooming new nokia.maps.map.component.ZoomBar(), // have zoom bar new nokia.maps.map.component.ScaleBar(), // have scale bar new nokia.maps.map.component.TypeSelector(), // have switch map types infoBubbles // info bubbles ] }); if (typeof(onInstallMap) == 'function') onInstallMap( kaartElement ); // voeg markers toe voor de adressen markerContainer = new nokia.maps.map.Container(); var count = 0; for (var i=0; i<adressen.length; ++i) { var adres = adressen[i]; nokia.places.search.manager.findPlaces({ adres: adres, searchTerm: adres.volledig_adres, onComplete: function( responseData, status ) { if (status == 'OK' && responseData.results.items.length > 0) { var position = responseData.results.items[0].position; var center = [position.latitude, position.longitude]; // maak html var html = ''; if (this.adres.deelplannen) { html += '<div style="width: 500px; height: 250px; background-color: #f8f8f8; color: #333; padding: 20px; overflow-y: auto; ">' + '<span style="font-size: 16pt; font-weight: bold;">' + this.adres.kenmerk + '</span><br/>' + '<br/>' + '<p><b>' + this.adres.volledig_adres + '</b></p>'; for (var j=0; j<this.adres.deelplannen.length; ++j) { var deelplan = this.adres.deelplannen[j]; if (!deelplan.scopes.length) continue; html += '<h4 style="margin-top:15px;">' + deelplan.naam + '</h4>'; for (var k=0; k<deelplan.scopes.length; ++k) { html += '<p style="padding-left:20px">' + '<a target="_blank" style="color:inherit" href="' + deelplan.scopes[k].url + '">' + deelplan.scopes[k].naam + '</a>' + '</p>'; } } html += '</div>'; } else { html += '<div style="width: 350px; height: 150px; background-color: #f8f8f8; color: #333; padding: 20px; ">' + '<span style="font-size: 16pt; font-weight: bold;">' + this.adres.kenmerk + '</span><br/>' + '<br/>' + '<p><b>' + this.adres.volledig_adres + '</b></p>' + '<a style="color: #333;" href="' + this.adres.url + '">Naar dossier</a>' + '</div>'; } // maak marker var marker = new nokia.maps.map.StandardMarker(center, { $html: html }); // als je er op klikt moet er een HTML popupje verschijnen var TOUCH = nokia.maps.dom.Page.browser.touch, CLICK = TOUCH ? "tap" : "click"; marker.addListener(CLICK, function(evt) { infoBubbles.addBubble(evt.target.$html, evt.target.coordinate); }, false); // voeg toe aan container markerContainer.objects.add(marker); } // zijn we klaar? ++count; if (count == adressen.length) { nokiaMap.objects.add( markerContainer ); // nokiaMap.zoomTo( markerContainer.getBoundingBox(), false, true ); if (typeof( onDoneSearching ) == 'function') onDoneSearching( kaartElement ); } } }); } return kaartElement; } }; <file_sep>PDFAnnotator.Editable.PhotoAssignment = PDFAnnotator.Editable.Photo.extend({ init: function( config ) { this._super( config, PDFAnnotator.Tool.prototype.getByName( 'cameraassignment' ) ); this.setData( config, {}, [ 'imageOpdrachtSrc' ] ); }, render: function() { this._super(); var base = this.visuals; $('<img>') .attr( 'src', this.data.imageOpdrachtSrc ) .css({ position: 'absolute', left: (this.data.imageSize.x + 5) + 'px' }) .appendTo( base ); }, /* !!overide!! */ rawExport: function() { var val = this._super(); val.type = 'photoassignment'; val.imageopdrachtsrc = this.data.imageOpdrachtSrc; return val; }, rawImport: function( data ) { return new PDFAnnotator.Editable.PhotoAssignment({ position: new PDFAnnotator.Math.IntVector2( data.x, data.y ), direction: data.direction, lineColor: data.dircolor, lineLength: data.dirlength, imageSrc: data.imagesrc, imageSize: new PDFAnnotator.Math.IntVector2( data.imagesizew, data.imagesizeh ), imageOpdrachtSrc: data.imageopdrachtsrc, photoId: data.photoid }); } }); <file_sep><? load_view( 'header.php' ); ?> <h2>PDF annotatie afgerond.</h2> Uw annotaties zijn succesvol opgeslagen. U kunt dit scherm nu sluiten. <? load_view( 'footer.php' ); ?><file_sep>PDFAnnotator.Tool.DownloadAlles = PDFAnnotator.Tool.Download.extend({ /* constructor */ init: function( engine ) { /* initialize base class */ this._super( engine, 'downloadalles' ); }, /* !!overide!! */ getDimensions: function() { return null; /* indicates "alles" */ } }); <file_sep><?php class Beheer extends Controller { var $errors = array(); function Beheer() { parent::Controller(); global $method; if (substr( $method, 0, 4 ) != 'prio' && substr( $method, 0, 6 ) != 'risico' && substr( $method, 0, 6 ) != 'matrix' && substr( $method, 0, 10 ) != 'management' && substr( $method, 0, 9 ) != 'gebruiker' && substr( $method, 0, 3 ) != 'rol' && 1) { $this->navigation->push( 'nav.instellingen', '/instellingen' ); } } function _get_gebruikers( $search=null, $gebruikers_id=null ) { return $this->gebruiker->get_by_klant( $this->session->userdata( 'kid' ), false, $search, $gebruikers_id ); } function _get_gebruiker_rollen() { return $this->rol->get_toekenbare_rollen_for_huidige_klant(); } function index() { $this->navigation->set_active_tab( 'beheer' ); $this->load->view( 'beheer/index', array( 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), ), ) ); } function log() { $this->navigation->push( 'nav.log_informatie', '/instellingen/log' ); $this->navigation->set_active_tab( 'beheer' ); // basic info $soorten = $this->log->get_soorten(); $gebruikers = $this->_get_gebruikers(); // zoeken! $data = array(); $selected_soorten = array(); $selected_gebruikers = array(); $count = 0; $start_datum = sprintf( '01-%d-%d', intval( date( 'm', time() ) ), intval( date( 'Y', time() ) ) ); $eind_datum = date( 'd-m-Y', strtotime( $start_datum . '+1 month' ) ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { foreach ($soorten as $soort) { $varname = 'soort_'.$soort; if (isset($_POST[$varname]) && $_POST[$varname]=='on') $selected_soorten[] = $soort; } foreach ($gebruikers as $gebruiker) { $varname = 'gebruiker_'.$gebruiker->id; if (isset($_POST[$varname]) && $_POST[$varname]=='on') $selected_gebruikers[] = $gebruiker->id; } if (isset($_POST['start_datum'])) $start_datum = $_POST['start_datum']; if (isset($_POST['eind_datum'])) $eind_datum = $_POST['eind_datum']; $data = $this->log->search_log( $selected_soorten, $selected_gebruikers, $start_datum, $eind_datum ); $count = sizeof($data); } $this->load->view( 'beheer/log', array( 'soorten' => $soorten, 'gebruikers' => $gebruikers, 'data' => $data, 'count' => $count, 'selected_soorten' => $selected_soorten, 'selected_gebruikers' => $selected_gebruikers, 'start_datum' => $start_datum, 'eind_datum' => $eind_datum, 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), array( 'url'=>'/instellingen/log', 'text'=>'Log informatie' ), ), ) ); } function gebruikers( $mode=null, $sortfield=null, $sortorder=null, $search=null ) { $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'gebruikers' ); if (!is_array( $viewdata )) $viewdata = array( 'mode' => 'actief', 'search' => '', 'sortfield' => 'volledige_naam', 'sortorder' => 'asc', ); if (!is_null( $mode )) $viewdata['mode'] = $mode; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; // check input $realsortfields = array( 'volledige_naam' => 'volledige_naam', 'gebruikersnaam' => 'gebruikersnaam', 'rol' => 'rol_id', 'status' => 'status', ); if (!isset( $realsortfields[$viewdata['sortfield']] )) $viewdata['sortfield'] = 'volledige_naam'; $viewdata['sortorder'] = strtolower($viewdata['sortorder']); if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!in_array( $viewdata['mode'], array( 'actief', 'alle' ) )) $viewdata['mode'] = 'actief'; // get data $rollen = $this->_get_gebruiker_rollen(); if($this->rechten->geef_recht_modus( RECHT_TYPE_GEBRUIKERS_BEHEREN ) == RECHT_GROUP_ONLY){ $gebruikers_id=cut_array($this->gebruiker->get_logged_in_gebruiker()->groups_users, "user_id"); $gebruikers = $this->_get_gebruikers( $viewdata['search'], $gebruikers_id); } else { $gebruikers = $this->_get_gebruikers( $viewdata['search']); } /*if ($viewdata['mode']=='actief') { foreach ($gebruikers as $i => $gebruiker) if ($gebruiker->status != 'actief') unset( $gebruikers[$i] ); $gebruikers = array_values( $gebruikers ); }*/ // sort! $factor = $viewdata['sortorder']=='asc' ? 1 : -1; switch ($actualsortfield = @ $realsortfields[$viewdata['sortfield']]) { case 'rol_id': usort($gebruikers, function( $a, $b ) use ($rollen, $factor){ if (!$a->rol_id || !isset( $rollen[$a->rol_id] )) return $factor * -1; if (!$b->rol_id || !isset( $rollen[$b->rol_id] )) return $factor * 1; return $factor * strcasecmp( $rollen[$a->rol_id]->naam, $rollen[$b->rol_id]->naam ); }); break; case 'volledige_naam': case 'gebruikersnaam': case 'status': usort($gebruikers, function( $a, $b ) use ($actualsortfield, $factor){ return $factor * strcasecmp( $a->$actualsortfield, $b->$actualsortfield ); }); break; } // sla zoekinstellingen op $this->zoekinstelling->set( 'gebruikers', $viewdata ); // view! $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $this->load->model( 'checklistgroep' ); $this->load->model( 'gebruikerchecklistgroep' ); $this->load->view( 'beheer/gebruikers', array( 'errors' => $this->errors, 'data' => $gebruikers, 'volledige_naam' => isset($_POST['volledige_naam']) ? $_POST['volledige_naam'] : '', 'gebruikersnaam' => isset($_POST['gebruikersnaam']) ? $_POST['gebruikersnaam'] : '', 'volledige_naam' => isset($_POST['volledige_naam']) ? $_POST['volledige_naam'] : '', 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), array( 'url'=>'/instellingen/gebruikers', 'text'=>'Gebruiker beheer' ), ), 'rollen' => $rollen, 'viewdata' => $viewdata, 'checklistgroepen' => $this->checklistgroep->get_for_huidige_klant(), 'gebruiker_checklistgroepen' => $this->gebruikerchecklistgroep->all(), ) ); } function gebruiker_checklist_groep_rechten() { try { if (!($gebruiker = $this->gebruiker->get( $_POST['gebruiker_id'] ))) throw new Exception( 'Invalid gebruiker id' ); } catch (Exception $e) { die( 'Gebruiker ongeldig' ); } if (!$_POST['checklist_groep_ids']) $checklist_groep_ids = array(); else $checklist_groep_ids = explode( ',', $_POST['checklist_groep_ids'] ); $data = array( $gebruiker->id => $checklist_groep_ids ); $this->load->model( 'gebruikerchecklistgroep' ); $this->gebruikerchecklistgroep->replace( $data ); die('OK'); } function gebruiker_delete( $id=null ) { if (APPLICATION_LOGIN_SYSTEM != 'LocalDB') throw new Exception( 'Gebruikers niet-actief zetten niet mogelijk.' ); $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->push( 'nav.gebruiker_verwijderen', '/instellingen/gebruiker_delete/'.$id ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $gebruikers = $this->_get_gebruikers(); if (!isset( $gebruikers[$id] )) redirect( '/instellingen' ); $gebruiker = $gebruikers[$id]; if ($gebruiker->status == 'geblokkeerd') { $this->errors[] = 'view.errors.gebruikers.reeds_geblokkeerd'; $this->gebruikers(); return; } if ($gebruiker->id == $this->login->get_user_id()) { $this->errors[] = 'view.errors.gebruikers.niet_blokkeren_eigen_account'; $this->gebruikers(); return; } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (isset($_POST['blokkeer'])) { $this->logger->add( null, 'blokkeren', 'Gebruiker '. $gebruiker->volledige_naam.' geblokkeerd' ); $gebruiker->status = 'geblokkeerd'; $gebruiker->save(); } if (isset( $_POST['referer'] )) redirect( $_POST['referer'] ); else redirect( '/instellingen/gebruikers' ); } $this->load->view( 'beheer/gebruiker_delete', array( 'gebruiker' => $gebruiker, 'referer' => isset($_POST['referer']) ? $_POST['referer'] : $_SERVER['HTTP_REFERER'], 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), array( 'url'=>'/instellingen/gebruikers', 'text'=>'Gebruiker beheer' ), array( 'url'=>'/instellingen/gebruiker_delete/'.$id, 'text'=>'Gebruiker blokkeren' ), ), ) ); } function gebruiker_edit( $id=null ) { $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->push( 'nav.gebruiker_bewerken', '/instellingen/gebruiker_edit/'.$id ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $gebruikers = $this->_get_gebruikers(); if (!isset( $gebruikers[$id] )) redirect( '/instellingen' ); $gebruiker = $gebruikers[$id]; if ($gebruiker->status == 'geblokkeerd') { $this->errors[] = 'view.errors.gebruikers.gebruiker_geblokkeerd'; $this->gebruikers(); return; } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->load->model( 'rol' ); if ($rol = $this->rol->get( $_POST['rol_id'] )) { $rol->dump(); $gebruiker->dump(); $gebruiker->factuur_flags |= $rol->factuur_flags; $gebruiker->save(0,0,0); } } $this->load->helper('editor'); editor( $gebruiker, 'Gebruikersbeheer - Gebruiker bewerken', array() ); } function gebruiker_toevoegen() { $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->push( 'nav.gebruiker_toevoegen', '/instellingen/gebruiker_toevoegen' ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $this->load->model( 'rol' ); $wachtwoord = strval( @$_POST['wachtwoord'] ); $gebruikersnaam = strval( @$_POST['gebruikersnaam'] ); $volledige_naam = strval( @$_POST['volledige_naam'] ); $email = (!empty($_POST['email'])) ? strval( @$_POST['email'] ) : null; $rol_id = intval( @$_POST['rol_id'] ); $rollen = $this->rol->get_toekenbare_rollen_for_huidige_klant(); if (!strlen($wachtwoord)) $errors[] = 'leeg.wachtwoord.niet.toegestaan'; else if (strlen($wachtwoord)<5) $errors[] = 'wachtwoord.moet.minstens.5.karakters.bevatten'; else if (!strlen($gebruikersnaam)) $errors[] = 'lege.gebruikersnaam.niet.toegestaan'; else if (!strlen($volledige_naam)) $errors[] = 'lege.volledige_naam.niet.toegestaan'; else if (!isset( $rollen[$rol_id] )) $errors[] = 'ongeldige.rol.opgegeven'; else { $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; if (sizeof( $this->gebruiker->search( array( 'klant_id' => $klant_id, 'gebruikersnaam' => $gebruikersnaam ) ) )) $errors[] = 'opgegeven.gebruikersnaam.reeds.in.gebruik'; else { if (!$this->gebruiker->add_localdb( $klant_id, $gebruikersnaam, $wachtwoord, $volledige_naam, $rol_id, $email )) $errors[] = 'database.fout.bij.toevoegen.nieuwe.gebruiker'; else redirect( '/instellingen/gebruikers' ); } } } $_SERVER['REQUEST_METHOD'] = 'GET'; $this->load->helper('editor'); editor( $this->gebruiker, tgn('gebruiker.toevoegen'), array(), array('errors' => $errors) ); } function gebruiker_collegas( $id=null ) { $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->push( 'nav.collegas_instellen', '/instellingen/gebruiker_collegas/'.$id ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); // get gebruiker $gebruikers = $this->_get_gebruikers(); if (!isset( $gebruikers[$id] )) redirect( '/instellingen' ); $gebruiker = $gebruikers[$id]; // get alle gebruikers $alle_gebruikers = $this->gebruiker->get_by_klant( $this->session->userdata('kid') ); // handle post if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $gebruiker->update_collegas( $alle_gebruikers ); redirect( '/instellingen/gebruikers' ); } // get reeds gelinkte collega's $collegas = $gebruiker->get_collegas(); $_gebruikers = $alle_gebruikers; foreach($_gebruikers as $ind=>$_gebruiker ){ if( $_gebruiker->id == $id ){ unset($_gebruikers[$ind]); break; } } $count_all = count($_gebruikers); $count_coll = count($collegas); // view $this->load->view( 'beheer/gebruiker_collegas', array( 'gebruiker' => $gebruiker, 'alle_gebruikers' => $alle_gebruikers, 'collegas' => $collegas, 'is_all_checked' => ($count_all == $count_coll), 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), array( 'url'=>'/instellingen/gebruikers', 'text'=>'Gebruiker beheer' ), array( 'url'=>'/instellingen/gebruiker_collegas/'.$id, 'text'=>'Collega\'s beheren' ), ), ) ); } function instellingen() { $this->navigation->push( 'nav.instellingen', '/instellingen/instellingen' ); $this->navigation->set_active_tab( 'beheer' ); $kid = $this->session->userdata( 'kid' ); $klant = $this->klant->get( $kid ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // update klant data $klant->steekproef_interval = max( 1, intval( $_POST['steekproef_interval'] ) ); $klant->outlook_synchronisatie = isset( $_POST['outlook_synchronisatie'] ) ? 1 : 0; $klant->standaard_netwerk_modus = $_POST['standaard_netwerk_modus']; $klant->dossierregels_rood_kleuren = $_POST['dossierregels_rood_kleuren']; $klant->dossiers_als_startpagina_openen = $_POST['dossiers_als_startpagina_openen']; $klant->not_automaticly_select_betrokkenen = $_POST['not_automaticly_select_betrokkenen']; $klant->alleen_deelplannen_betrokkene = $_POST['alleen_deelplannen_betrokkene']; $klant->vragen_alleen_voor_betrokkenen_tonen = $_POST['vragen_alleen_voor_betrokkenen_tonen']; // save to db $klant->save(); redirect( '/instellingen' ); } $this->load->view( 'beheer/instellingen', array ( 'nav' => array( array( 'url'=>'/instellingen', 'text'=>'Instellingen' ), array( 'url'=>'/instellingen/instellingen', 'text'=>'Instellingen' ), ), 'klant' => $klant, )); } function _get_hoofdstukken() { if (!isset( $this->hoofdstuk )) $this->load->model( 'hoofdstuk' ); return $this->hoofdstuk->all( 'id', true ); } function managementinfo( $error=null ) { $this->navigation->push( 'nav.management_rapportage', '/instellingen/managementinfo' ); $this->navigation->set_active_tab( 'management' ); $this->load->library( 'grafiek' ); $this->load->helper( 'export' ); $this->load->model( 'sjabloon' ); $this->load->model('dossier'); // laad alle checklistgroepen $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $checklistgroepen = $this->checklistgroep->get_for_huidige_klant(); usort( $checklistgroepen, function( $a, $b ) { return strcasecmp( $a->naam, $b->naam ); }); // grafiek types $grafiek_types = $this->grafiek->get_alle_grafiek_types(); $dossiers=$this->dossier->get_dossiers_by_klant(); $errors = array(); if ($error) $errors[] = 'Uw grafiek en scope selectie is leeg.'; if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // store POST, so we can restore it next time around $this->session->set_userdata( 'managementinfo-settings', serialize( $_POST ) ); // filter grafiek types foreach ($grafiek_types as $i => $grafiek_type) if (!isset( $_POST['grafiek_types'][$grafiek_type] )) unset( $grafiek_types[$i] ); // filter checklistgroepen foreach ($checklistgroepen as $i => $checklistgroep) if (!isset( $_POST['checklistgroep'][$checklistgroep->id] )) unset( $checklistgroepen[$i] ); $checklistgroepen = array_values( $checklistgroepen ); $checklistgroepen_assoc = array(); foreach ($checklistgroepen as $checklistgroep) $checklistgroepen_assoc[ $checklistgroep->id ] = $checklistgroep; // laad alle checklisten $this->load->model( 'checklist' ); $checklisten = array(); foreach ($checklistgroepen as $checklistgroep) $checklisten = array_merge( $checklisten, $checklistgroep->get_checklisten() ); usort( $checklisten, function( $a, $b ) use ($checklistgroepen_assoc) { $gnaama = $checklistgroepen_assoc[ $a->checklist_groep_id ]->naam; $gnaamb = $checklistgroepen_assoc[ $b->checklist_groep_id ]->naam; if ($gnaama != $gnaamb) return strcasecmp( $gnaama, $gnaamb ); return strcasecmp( $a->naam, $b->naam ); }); $checklisten = array_values( $checklisten ); // filter checklisten foreach ($checklisten as $i => $checklist) if (!isset( $_POST['checklist'][$checklist->id] )) unset( $checklisten[$i] ); // if we have data left, go! if (!empty( $checklistgroepen ) && !empty( $checklisten ) && !empty( $grafiek_types )) { $periode = new GrafiekPeriode( $_POST['van'], $_POST['tot'] ); // set time limit to nothing! // Changed, after consulting Olaf, on 12-10 to 1 hour set_time_limit( 3600 ); try { $result = array( 'success' => true, ); if(isset($_POST['postcode'])){ $postcode =array_keys ($_POST['postcode']); for($i=0;$i<count($postcode);$i++){ $postcode[$i]="'".$postcode[$i]."'"; } $postcode = "(".implode(",", $postcode).")"; } else $postcode=""; switch ($_POST['uitvoer']) { case 'pdf': $this->load->library( 'marap' ); $marap = $this->marap->export( 'standaard', $_POST['tag'], $periode, $checklistgroepen, $checklisten, $grafiek_types, $_POST['theme'], $postcode ); $result['tag'] = $marap->store(); break; case 'scherm': // determine size $is_Mobile = preg_match( '/(Mobile|Android)/', @$_SERVER['HTTP_USER_AGENT'] ); if ($is_Mobile) { $afmeting = new GrafiekAfmeting( 620, 350 ); } else { //$afmeting = new GrafiekAfmeting( 800, 350 ); $afmeting = new GrafiekAfmeting( 800, 800 ); } // build grafieken $progress = new ExportProgress( 'marap' ); $grafieken = $this->grafiek->maak_grafieken( $periode, $afmeting, $checklistgroepen, $checklisten, $grafiek_types, $_POST['theme'], function( $grafiek, $i, $total ) use ($progress) { $progress->set_progress( $_POST['tag'], $i / $total, 'Grafiek: ' . $grafiek->get_groeptitle() ); }, $postcode ); // build & store data in session $data = array( 'grafieken' => $grafieken, 'periode' => $periode, ); $this->session->set_userdata( 'managementinfo', serialize( $data ) ); // redirect to result page $progress->set_progress( $_POST['tag'], 1, 'Marap klaar' ); break; default: throw new Exception( 'Ongeldige waarde voor uitvoer veld: ' . @$_POST['uitvoer'] . '.' ); } } catch (Exception $e) { $result['success'] = false; $result['error'] = $e->getMessage(); } die(json_encode($result)); } else { $result['success'] = true; $result['error_redirect']=true; die(json_encode($result)); $result['error'] = $e->getMessage(); redirect( '/beheer/managementinfo/error' ); } } // show view $this->load->view( 'beheer/managementinfo', array( 'checklistgroepen' => $checklistgroepen, 'grafiek_types' => $grafiek_types, 'settings' => @unserialize( $this->session->userdata( 'managementinfo-settings' ) ), 'errors' => $errors, 'tag' => get_export_tag( 'marap' ), 'themes' => array( 'universal' => 'Universeel', 'aqua' => 'Aqua', 'green' => 'Groen', 'ocean' => 'Oceaan', 'orange' => 'Oranje', 'pastel' => 'Pastel', 'rose' => 'Roos', 'softy' => 'Zacht', 'vivid' => 'Levendig', ), 'sjablonen' => array_merge( $this->sjabloon->get_sjablonen_voor_klant( $this->session->userdata('kid') ), $this->sjabloon->get_sjablonen_voor_klant( null ) ), 'dossiers' => isset($dossiers) ? $dossiers : array(), ) ); } function managementinfo_resultaat() { $this->load->library( 'grafiek' ); $data = unserialize( $this->session->userdata( 'managementinfo' ) ); if (!is_array( $data )) redirect( '/beheer/managementinfo' ); $this->navigation->push( 'nav.management_rapportage', '/instellingen/managementinfo' ); $this->navigation->push( 'nav.management_info_resultaat', '/instellingen/managementinfo_resultaat', array( $data['periode']->get_human_description() ) ); $this->navigation->set_active_tab( 'management' ); $this->load->view( 'beheer/managementinfo_resultaat', array ( 'grafieken' => $data['grafieken'], 'periode' => $data['periode']->get_human_description(), ) ); } function managementinfo_download( $tag ) { $this->load->helper( 'export' ); ExportResult::download( rawurldecode( $tag ) ); } public function matrixbeheer() { $this->navigation->push( 'nav.matrixbeheer', '/instellingen/matrixbeheer' ); $this->navigation->set_active_tab( 'matrixbeheer' ); // get all checklist(group)s $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); // load view $this->load->view( 'beheer/matrixbeheer', array( 'checklistgroepen' => $this->checklistgroep->get_for_huidige_klant(), ) ); } private function _get_risicoanalyse( $checklist_id, $matrix_id ) { $ra = $this->risicoanalyse->lookup_or_create( $matrix_id, $checklist_id ); if (!$ra) throw new Exception( 'Kon risicoanalyse niet ophalen voor checklist ' . $checklist_id . ' en matrix ' . $matrix_id ); return $ra; } public function risicoanalyse_effecten( $checklist_id, $matrix_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $this->navigation->push( 'nav.matrixbeheer', '/instellingen/matrixbeheer' ); $this->navigation->push( 'nav.prioriteitstellingsmatrix_invullen', '/instellingen/prioriteitstelling_matrix/' . $ra->get_checklist()->checklist_groep_id ); $this->navigation->push( 'nav.risicoanalyse_effecten', '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); $this->navigation->set_active_tab( 'matrixbeheer' ); $clean_float = function( $waarde ) { $waarde = str_replace( ',', '.', $waarde ); $waarde = floatval( $waarde ); return $waarde; }; $effecten = $ra->get_effecten(); $checklist = $ra->get_checklist(); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $save_only = isset( $_POST['action'] ) && $_POST['action'] == 'Opslaan'; // sla wijzigingen aan bestaande effecten op foreach ($effecten as $k => $effect) { $effect->update_db( $this->risicoanalyse->get_db(), $_POST['effect'][$k], $clean_float( $_POST['waarde'][$k] ) ); } // sla nieuwe op als gezet if (trim( $_POST['effect_nieuw'] )) { $effect = trim( $_POST['effect_nieuw'] ); $waarde = $clean_float( $_POST['waarde_nieuw'] ); $ra->add_effect( $effect, $waarde ); } if ($save_only) redirect( '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); else if (empty( $effecten )) $errors[] = 'U heeft geen enkel effect gedefinieerd. U kunt de risico analyse nog niet invullen.'; else redirect( '/instellingen/risicoanalyse_invullen/' . $checklist_id . '/' . $matrix_id ); } // load view $this->load->model( 'matrix' ); $this->load->view( 'beheer/risicoanalyse_effecten', array( 'errors' => $errors, 'ra' => $ra, 'effecten' => $effecten, 'checklist' => $checklist, 'matrix' => $this->matrix->get( $matrix_id ), ) ); } public function risicoanalyse_effect_verwijderen( $checklist_id, $matrix_id, $effect_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $ra->delete_effect( $effect_id ); redirect( '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); } private function _ra_swap_effecten( $effecten, $a, $b ) { $db = get_instance()->risicoanalyse->get_db(); $swap = $effecten[$a]->get_sortering(); $effecten[$a]->update_db( $db, null, null, $effecten[$b]->get_sortering() ); $effecten[$b]->update_db( $db, null, null, $swap ); } public function risicoanalyse_effect_omhoog( $checklist_id, $matrix_id, $effect_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $effecten = $ra->get_effecten(); if (!isset( $effecten[$effect_id] )) throw new Exception( 'Fout bij omhoog verplaatsen van onbestaande risico analyse effect.' ); $prev = null; foreach ($effecten as $k => $v) if ($k != $effect_id) $prev = $k; else break; if (!is_null( $prev )) $this->_ra_swap_effecten( $effecten, $prev, $effect_id ); redirect( '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); } public function risicoanalyse_effect_omlaag( $checklist_id, $matrix_id, $effect_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $effecten = $ra->get_effecten(); if (!isset( $effecten[$effect_id] )) throw new Exception( 'Fout bij omlaag verplaatsen van onbestaande risico analyse effect.' ); $next = null; $take_next = false; foreach ($effecten as $k => $v) if ($k == $effect_id) $take_next = true; else if ($take_next) { $next = $k; break; } if (!is_null( $next )) $this->_ra_swap_effecten( $effecten, $next, $effect_id ); redirect( '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); } public function risicoanalyse_invullen( $checklist_id, $matrix_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $this->navigation->push( 'nav.matrixbeheer', '/instellingen/matrixbeheer' ); $this->navigation->push( 'nav.prioriteitstellingsmatrix_invullen', '/instellingen/prioriteitstelling_matrix/' . $ra->get_checklist()->checklist_groep_id ); $this->navigation->push( 'nav.risicoanalyse_effecten', '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); $this->navigation->push( 'nav.risicoanalyse_invullen', '/instellingen/risicoanalyse_invullen/' . $checklist_id . '/' . $matrix_id ); $this->navigation->set_active_tab( 'matrixbeheer' ); $effecten = $ra->get_effecten(); $checklist = $ra->get_checklist(); $hoofdgroepen = $checklist->get_hoofdgroepen(); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $db = get_instance()->risicoanalyse->get_db(); $save_only = isset( $_POST['action'] ) && $_POST['action'] == 'Opslaan'; // // store waarden // $ra->get_waarde( -1, -1 ); // make sure data is loaded, so dirty flag is appropriately set foreach ($hoofdgroepen as $hoofdgroep) { foreach ($effecten as $effect) { $waarde = @$_POST['waarde'][$hoofdgroep->id][$effect->get_id()]; if (trim( $waarde )) { $ra->set_waarde( $hoofdgroep->id, $effect->get_id(), intval( $waarde ) ); } else { $ra->delete_waarde( $hoofdgroep->id, $effect->get_id() ); } } } $ra->update_db_waarden( $db ); // // store kansen // $ra->get_kans( -1 ); // make sure data is loaded, so dirty flag is appropriately set foreach ($hoofdgroepen as $hoofdgroep) { $kans = @$_POST['kans'][$hoofdgroep->id]; if (!empty( $kans )) $ra->set_kans( $hoofdgroep->id, $kans ); } $ra->update_db_kansen( $db ); // redirect for POST reload issues if ($save_only) redirect( '/instellingen/risicoanalyse_invullen/' . $checklist_id . '/' . $matrix_id ); else { // we get here because user clicked "Volgende" // so check if complete if (!$ra->is_complete( $hoofdgroepen )) { $errors[] = 'De risicoanalyse is nog niet compleet, u kunt nog niet verder gaan naar het aanmaken van de prioriteitstelling.'; } else { redirect( '/instellingen/risicoanalyse_prioriteitstelling/' . $checklist_id . '/' . $matrix_id ); } } } // bepaal kans uit naleefgedrag $this->load->library( 'grafiek' ); $kans_uit_naleefgedrag = array(); $basequery = get_naleefgedrag_base_query( array( $checklist->get_checklistgroep() ), new GrafiekPeriode( '01-01-1980', '01-01-2034' ), 'h.id', '<EMAIL>' ); // query 1 $fout_query = sprintf( $basequery, 'cl.id = ' . $checklist->id . ' AND ' . get_expression_for_vragen_with_kleur( 'rood' ) ); if (!($res = $this->db->query( $fout_query ))) throw new Exception( 'Query fout bij bepalen naleefgedrag. (1)' ); foreach ($res->result() as $row) $kans_uit_naleefgedrag[$row->id] = intval( $row->count ); $res->free_result(); // query 2 $alles_query = sprintf( $basequery, 'cl.id = ' . $checklist->id ); if (!($res = $this->db->query( $alles_query ))) throw new Exception( 'Query fout bij bepalen naleefgedrag. (2)' ); foreach ($res->result() as $row) $kans_uit_naleefgedrag[$row->id] = $row->count ? intval( @$kans_uit_naleefgedrag[$row->id] ) / $row->count : 0; // load view $this->load->model( 'matrix' ); $this->load->view( 'beheer/risicoanalyse_invullen', array( 'errors' => $errors, 'ra' => $ra, 'effecten' => $effecten, 'checklist' => $checklist, 'hoofdgroepen' => $hoofdgroepen, 'matrix' => $this->matrix->get( $matrix_id ), 'kans_uit_naleefgedrag' => $kans_uit_naleefgedrag, ) ); } public function risicoanalyse_prioriteitstelling( $checklist_id, $matrix_id ) { $this->load->library( 'prioriteitstelling' ); $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $this->navigation->push( 'nav.matrixbeheer', '/instellingen/matrixbeheer' ); $this->navigation->push( 'nav.prioriteitstellingsmatrix_invullen', '/instellingen/prioriteitstelling_matrix/' . $ra->get_checklist()->checklist_groep_id ); $this->navigation->push( 'nav.risicoanalyse_effecten', '/instellingen/risicoanalyse_effecten/' . $checklist_id . '/' . $matrix_id ); $this->navigation->push( 'nav.risicoanalyse_invullen', '/instellingen/risicoanalyse_invullen/' . $checklist_id . '/' . $matrix_id ); $this->navigation->push( 'nav.prioriteitstelling_genereren', '/instellingen/risicoanalyse_prioriteitstelling' . $checklist_id . '/' . $matrix_id ); $this->navigation->set_active_tab( 'matrixbeheer' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { // get db connection $db = get_instance()->risicoanalyse->get_db(); // set prio stelling! $ra->create_prioriteitstelling( $matrix_id, $db ); // redirect redirect( '/instellingen/prioriteitstelling_matrix/' . $ra->get_checklist()->checklist_groep_id . '/' . $matrix_id ); } $this->load->view( 'beheer/risicoanalyse_prioriteitstelling', array( 'errors' => $errors, 'ra' => $ra, ) ); } public function risicoanalyse_verwijderen( $checklist_id, $matrix_id ) { $this->load->library( 'risicoanalyse' ); $ra = $this->_get_risicoanalyse( $checklist_id, $matrix_id ); $checklist_groep_id = $ra->get_checklist()->checklist_groep_id; $this->risicoanalyse->delete( $matrix_id, $checklist_id ); redirect( '/instellingen/prioriteitstelling_matrix/' . $checklist_groep_id . '/' . $matrix_id ); } public function prioriteitstelling_matrix( $checklist_groep_id, $matrix_id=null, $weergave='' ) { $klant = $this->gebruiker->get_logged_in_gebruiker()->get_klant(); $this->navigation->push( 'nav.matrixbeheer', '/instellingen/matrixbeheer' ); $this->navigation->push( 'nav.prioriteitstellingsmatrix_invullen', '/instellingen/prioriteitstelling_matrix/' . $checklist_groep_id . '/' . $weergave ); $this->navigation->set_active_tab( 'matrixbeheer' ); $errors = array(); $this->load->library( 'prioriteitstelling' ); $this->load->library( 'risicoanalyse' ); $this->load->library( 'risicografiek' ); // get all checklist(group)s $this->load->model( 'checklistgroep' ); $this->load->model( 'checklist' ); $this->load->model( 'hoofdthema' ); $this->load->model( 'matrix' ); if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) throw new Exception( 'Ongeldig checklistgroep id ' . $checklist_groep_id ); $matrix = $this->matrix->get( $matrix_id ); if (!$matrix || $matrix->checklist_groep_id != $checklist_groep_id) if (!($matrix = $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ))) throw new Exception( 'Kon standaard matrix niet ophalen voor checklistgroep id ' . $checklist_groep_id ); $this->risicoanalyse->lookup_all($matrix->id); $this->prioriteitstelling->lookup_all($matrix->id); $readonly = $matrix->klant_id != $this->session->userdata( 'kid' ); if ($weergave != 'eenvoudig' && $weergave != 'bestuurlijk') $weergave = $checklistgroep->modus == 'niet-combineerbaar' ? 'eenvoudig' : 'bestuurlijk'; $checklisten = $checklistgroep->get_checklisten(); $editbaar = array(); $een_checklist_niet_editbaar = false; foreach ($checklisten as $i => $checklist) if (!$checklist->is_afgerond()) unset( $checklisten[$i] ); else { $editbaar[ $checklist->id ] = $this->risicoanalyse->lookup( $matrix->id, $checklist->id ) ? false : true; if (!$editbaar[ $checklist->id ]) $een_checklist_niet_editbaar = true; } $unieke_hoofdgroepen = $prioriteitstellingen = array(); foreach ($checklisten as $checklist) { $hoofdgroepen = $checklist->get_hoofdgroepen(); foreach ($hoofdgroepen as $hoofdgroep) { $hoofdgroep_naam = $hoofdgroep->naam; if (!isset( $unieke_hoofdgroepen[ $hoofdgroep_naam ] )) $unieke_hoofdgroepen[ $hoofdgroep_naam ] = array( 'naam' => $hoofdgroep_naam, 'checklist_map' => array(), ); $unieke_hoofdgroepen[ $hoofdgroep_naam ]['checklist_map'][ $checklist->id ] = $hoofdgroep; } $prioriteitstellingen[ $checklist->id ] = $this->prioriteitstelling->lookup_or_create( $matrix->id, $checklist->id ); $prioriteitstellingen[ $checklist->id ]->get_waarde( null, null ); // makes PS load its data! } // is this a POST? then store! if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { foreach ($checklisten as $checklist) { $ps = $prioriteitstellingen[ $checklist->id ]; $hoofdgroepen = $checklist->get_hoofdgroepen(); foreach ($hoofdgroepen as $hoofdgroep) foreach ($hoofdgroep->get_hoofdthemas() as $hoofdthema) switch ($weergave) { case 'eenvoudig': if ($waarde = (@ $_POST['checklist1'][$checklist->id][$hoofdgroep->id] )) $ps->set_waarde( $hoofdgroep->id, $hoofdthema['hoofdthema']->id, $waarde ); /* YES! geen break! */ case 'bestuurlijk': if ($waarde = (@ $_POST['checklist'][$checklist->id][$hoofdgroep->id][$hoofdthema['hoofdthema']->id] )) $ps->set_waarde( $hoofdgroep->id, $hoofdthema['hoofdthema']->id, $waarde ); } $ps->update_db( $this->prioriteitstelling->get_db() ); } redirect( '/instellingen/prioriteitstelling_matrix/' . $checklistgroep->id . '/' . $matrix->id . '/' . $weergave ); } switch ($weergave) { case 'eenvoudig': $view = 'beheer/prioriteitstelling_matrix_eenvoudig'; break; case 'bestuurlijk': $view = 'beheer/prioriteitstelling_matrix_per_thema'; break; } // make sure at least one is available (this function will create one if it's not available) $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ); $matrices = $this->matrix->geef_matrices_voor_checklist_groep( $checklistgroep, false ); $risico_handler = RisicoAnalyseHandlerFactory::create($checklistgroep->risico_model); // Add the risk graphs for the users that belong to a client that is allowed to see them. $risico_grafieken = array(); if ($klant->risico_grafieken) { foreach ($checklisten as $checklist) { $ra = $this->_get_risicoanalyse( $checklist->id, $matrix->id ); $handler = $ra->get_handler(); $hoofdgroepen = $checklist->get_hoofdgroepen(); $checklist_naam = $checklist->naam; $graph_title = "Risicoprofiel voor checklist '{$checklist_naam}'"; $data_kans = array(); $data_effect = array(); $data_legenda = array(); foreach ($hoofdgroepen as $hoofdgroep) { // First get the 'kans' for this 'hoofdgroep' $origval = $ra->get_kans( $hoofdgroep->id ); $val = $handler->kans_data_to_kans_value($origval); $data_kans[] = $val; $data_effect[] = $ra->get_gemiddelde( $hoofdgroep->id ); $data_legenda[] = $hoofdgroep->naam; } $filename = $this->risicografiek->generate_risico_grafiek($graph_title, $data_kans, $data_effect, $data_legenda); if (!empty($filename)) { $risico_grafieken["$checklist_naam"] = $filename; } } // foreach ($checklisten as $checklist) } // if ($klant->risico_grafieken) // load view $this->load->view( $view, array( 'errors' => $errors, 'checklistgroep' => $checklistgroep, 'checklisten' => $checklisten, 'unieke_hoofdgroepen' => $unieke_hoofdgroepen, 'prioriteitstellingen' => $prioriteitstellingen, 'editbaar' => $editbaar, 'een_checklist_niet_editbaar' => $een_checklist_niet_editbaar, 'hoofdthemas' => $this->hoofdthema->get_by_checklistgroep( $checklistgroep->id ), 'matrix' => $matrix, 'matrices' => $matrices, 'readonly' => $readonly, 'weergave' => $weergave, 'risico_handler' => $risico_handler, 'risico_grafieken' => $risico_grafieken, ) ); } public function themabeheer( $bewerk=null ) { $this->load->model( 'hoofdthema' ); $this->load->model( 'thema' ); $this->navigation->push( 'nav.themabeheer', '/instellingen/themabeheer' ); $this->navigation->set_active_tab( 'beheer' ); $themas = $this->thema->get_for_huidige_klant( true, true ); $hoofdthemas = $this->hoofdthema->get_for_huidige_klant( true, true ); usort( $themas, function( $a, $b ) use ($hoofdthemas) { $ah = @$hoofdthemas[$a->hoofdthema_id]; if (!$ah) return true; $bh = @$hoofdthemas[$b->hoofdthema_id]; if (!$bh) return false; if ($ah->nummer - $bh->nummer) return $ah->nummer - $bh->nummer; return strcmp( $a->thema, $b->thema ); }); $next_hoofdthema_nummer = 1; foreach ($hoofdthemas as $hoofdthema) $next_hoofdthema_nummer = max( $next_hoofdthema_nummer, $hoofdthema->nummer+1 ); $errors = array(); if ($bewerk) if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { foreach ($themas as $thema) { if (isset( $_POST['hoofdthema'][$thema->id] )) { if ($_POST['hoofdthema'][$thema->id] != $thema->hoofdthema_id) { $thema->hoofdthema_id = $_POST['hoofdthema'][$thema->id]; $thema->save(); } } } redirect( '/instellingen/themabeheer' ); } // load view $this->load->view( 'beheer/themabeheer', array( 'errors' => $errors, 'themas' => $themas, 'hoofdthemas' => $hoofdthemas, 'bewerk' => $bewerk, 'next_hoofdthema_nummer' => $next_hoofdthema_nummer, ) ); } public function hoofdthema_toevoegen() { $this->load->model( 'hoofdthema' ); $this->hoofdthema->add( $_POST['naam'], $_POST['nummer'], $_POST['bron'] ); redirect( '/instellingen/themabeheer/bewerken' ); } public function thema_toevoegen() { $this->load->model( 'thema' ); $this->thema->add( $_POST['naam'], $_POST['nummer'], $_POST['hoofdthema_id'] ); redirect( '/instellingen/themabeheer/bewerken' ); } private function _get_checklistgroepen() { $this->load->model( 'checklistgroep' ); return $this->checklistgroep->get_for_huidige_klant( true ); } private function _get_checklisten( array $checklistgroepen ) { $this->load->model( 'checklist' ); return $this->checklist->get_for_huidige_klant( true ); } private function _allow_klanten_edit() { return $this->rechten->geef_recht_modus( RECHT_TYPE_SITEBEHEER ) != RECHT_MODUS_GEEN; } public function verantwoordingsteksten( $pagenum=null, $pagesize=null, $sortfield=null, $sortorder=null, $search=null ) { $this->load->model( 'verantwoording' ); $this->load->model( 'hoofdthema' ); $this->load->model( 'thema' ); $this->navigation->push( 'nav.verantwoordingsteksten', '/instellingen/verantwoordingsteksten' ); $this->navigation->set_active_tab( 'beheer' ); // beheer zoekinstellingen $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'verantwoordingsteksten' ); if (!is_array( $viewdata )) $viewdata = array( 'pagenum' => 0, 'pagesize' => 25, 'search' => '', 'sortfield' => 'gepland_datum', 'sortorder' => 'asc', ); if (!is_null( $pagenum )) $viewdata['pagenum'] = $pagenum; if (!is_null( $pagesize )) $viewdata['pagesize'] = $pagesize; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; // check input $realsortfields = array( 'checklistgroep' => 'checklist_groep_id', 'checklist' => 'checklist_id', 'hoofdthema' => 'hoofdthema_id', 'thema' => 'thema_id', 'beoordeling' => 'status', 'tekst' => 'tekst', 'klant' => 'klant_id', ); if (!isset( $realsortfields[$viewdata['sortfield']] )) $viewdata['sortfield'] = 'checklistgroep'; $viewdata['sortorder'] = strtolower($viewdata['sortorder']); if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!is_int( $viewdata['pagenum'] )) $viewdata['pagenum'] = intval( $viewdata['pagenum'] ); if (!is_int( $viewdata['pagesize'] )) $viewdata['pagesize'] = intval( $viewdata['pagesize'] ); // fetch data $allow_klanten_edit = $this->_allow_klanten_edit(); $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $checklistgroepen = $this->_get_checklistgroepen(); $checklisten = $this->_get_checklisten( $checklistgroepen ); $verantwoordingsteksten = $this->verantwoording->get_for_klant( $klant_id, $viewdata['search'] ); if ($allow_klanten_edit) { $verantwoordingsteksten = array_merge( $verantwoordingsteksten, $this->verantwoording->get_for_klant( null, $viewdata['search'] ) ); if (!$this->klant->allow_lease_administratie()) { foreach ($verantwoordingsteksten as $i => $vt) if ($vt->klant_id && $this->klant->get( $vt->klant_id )->lease_configuratie_id) unset( $verantwoordingsteksten[$i] ); $verantwoordingsteksten = array_values( $verantwoordingsteksten ); } } $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); $klanten = $this->_filter_klanten( $klanten ); // load thema's en hoofdthemas $thema_ids = array(-1); $hoofdthema_ids = array(-1); foreach ($verantwoordingsteksten as $v) { if ($v->thema_id) $thema_ids[] = $v->thema_id; if ($v->hoofdthema_id) $hoofdthema_ids[] = $v->hoofdthema_id; } $hoofdthemas = $this->hoofdthema->search( array(), 'id IN (' . implode(',', $hoofdthema_ids) . ')', true ); $themas = $this->thema->search( array(), 'id IN (' . implode(',', $thema_ids) . ')', true ); // sort $factor = $viewdata['sortorder']=='asc' ? 1 : -1; switch ($actualsortfield = @ $realsortfields[$viewdata['sortfield']]) { case 'checklist_groep_id': usort($verantwoordingsteksten, function( $a, $b ) use ($checklistgroepen, $factor){ if (!$a->checklist_groep_id || !isset( $checklistgroepen[$a->checklist_groep_id] )) return $factor * -1; if (!$b->checklist_groep_id || !isset( $checklistgroepen[$b->checklist_groep_id] )) return $factor * 1; return $factor * strcasecmp( $checklistgroepen[$a->checklist_groep_id]->naam, $checklistgroepen[$b->checklist_groep_id]->naam ); }); break; case 'checklist_id': usort($verantwoordingsteksten, function( $a, $b ) use ($checklisten, $factor){ if (!$a->checklist_id || !isset( $checklisten[$a->checklist_id] )) return $factor * -1; if (!$b->checklist_id || !isset( $checklisten[$b->checklist_id] )) return $factor * 1; return $factor * strcasecmp( $checklisten[$a->checklist_id]->naam, $checklisten[$b->checklist_id]->naam ); }); break; case 'thema_id': usort($verantwoordingsteksten, function( $a, $b ) use ($themas, $factor){ if (!$a->thema_id || !isset( $themas[$a->thema_id] )) return $factor * -1; if (!$b->thema_id || !isset( $themas[$b->thema_id] )) return $factor * 1; return $factor * strcasecmp( $themas[$a->thema_id]->thema, $themas[$b->thema_id]->thema ); }); break; case 'hoofdthema_id': usort($verantwoordingsteksten, function( $a, $b ) use ($hoofdthemas, $factor){ if (!$a->hoofdthema_id || !isset( $hoofdthemas[$a->hoofdthema_id] )) return $factor * -1; if (!$b->hoofdthema_id || !isset( $hoofdthemas[$b->hoofdthema_id] )) return $factor * 1; return $factor * strcasecmp( $hoofdthemas[$a->hoofdthema_id]->naam, $hoofdthemas[$b->hoofdthema_id]->naam ); }); break; case 'klant_id': usort($verantwoordingsteksten, function( $a, $b ) use ($klanten, $factor){ if (!$a->klant_id || !isset( $klanten[$a->klant_id] )) return $factor * -1; if (!$b->klant_id || !isset( $klanten[$b->klant_id] )) return $factor * 1; return $factor * strcasecmp( $klanten[$a->klant_id]->naam, $klanten[$b->klant_id]->naam ); }); break; case 'status': case 'tekst': usort($verantwoordingsteksten, function( $a, $b ) use ($actualsortfield, $factor){ return $factor * strcasecmp( trim( $a->$actualsortfield ), trim( $b->$actualsortfield ) ); }); break; } // take requested page if ($viewdata['pagesize'] != 'alle') { $total = sizeof($verantwoordingsteksten); $pages = ceil( $total / $viewdata['pagesize'] ); if ($viewdata['pagenum'] >= $pages) $viewdata['pagenum'] = $pages - 1; if ($viewdata['pagenum'] < 0) $viewdata['pagenum'] = 0; $verantwoordingsteksten = array_slice( $verantwoordingsteksten, $viewdata['pagesize'] * $viewdata['pagenum'], $viewdata['pagesize'] ); } else $pages = $total = 0; // sla zoekinstellingen op $this->zoekinstelling->set( 'verantwoordingsteksten', $viewdata ); // view! $this->load->view( 'beheer/verantwoordingsteksten', array( 'verantwoordingsteksten' => $verantwoordingsteksten, 'checklistgroepen' => $checklistgroepen, 'checklisten' => $checklisten, 'hoofdthemas' => $hoofdthemas, 'themas' => $themas, 'viewdata' => array_merge( $viewdata, array( 'total' => $total, 'pages' => $pages, ) ), 'allow_klanten_edit' => $allow_klanten_edit, 'klanten' => $klanten, ) ); } private function _get_alle_grondslagen() { $this->load->model( 'grondslag' ); return $this->grondslag->all( 'grondslag' ); } public function verantwoordingstekst_bewerken( $verantwoording_id=null ) { $this->load->model( 'verantwoording' ); if (!($verantwoording = $this->verantwoording->get( $verantwoording_id ))) redirect( '/instellingen/verantwoordingsteksten' ); $this->navigation->push( 'nav.verantwoordingsteksten', '/instellingen/verantwoordingsteksten' ); $this->navigation->push( 'nav.verantwoordingstekst_bewerken', '/instellingen/verantwoordingstekst_bewerken/' . $verantwoording_id ); $this->navigation->set_active_tab( 'beheer' ); $allow_klanten_edit = $this->_allow_klanten_edit(); if (!$allow_klanten_edit && !$verantwoording->klant_id) redirect( '/instellingen/verantwoordingsteksten' ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if ($allow_klanten_edit) $verantwoording->klant_id = $_POST['klant_id'] ? $_POST['klant_id'] : null; $verantwoording->checklist_groep_id = $_POST['checklist_groep_id'] ? $_POST['checklist_groep_id'] : null; $verantwoording->checklist_id = @$_POST['checklist_id'] ? $_POST['checklist_id'] : null; $verantwoording->hoofdthema_id = @$_POST['hoofdthema_id'] ? $_POST['hoofdthema_id'] : null; $verantwoording->thema_id = @$_POST['thema_id'] ? $_POST['thema_id'] : null; $verantwoording->status = $_POST['status'] ? $_POST['status'] : null; $verantwoording->grondslag = $_POST['grondslag'] ? $_POST['grondslag'] : null; $verantwoording->artikel = $_POST['artikel'] ? preg_replace( '/artie?kk?el(en)?\s+/', '', $_POST['artikel'] ) : null; $verantwoording->tekst = $_POST['tekst']; if (!$verantwoording->save( false, null, false )) throw new Exception( 'Fout bij opslaan verantwoording in database.' ); redirect( '/instellingen/verantwoordingsteksten' ); } $checklistgroepen = $this->_get_checklistgroepen(); $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); $klanten = $this->_filter_klanten( $klanten ); $this->load->view( 'beheer/verantwoordingstekst_bewerken', array( 'verantwoording' => $verantwoording, 'checklistgroepen' => $checklistgroepen, 'statussen' => array( 'onbeoordeeld', 'voldoet', 'voldoet_niet', 'gelijkwaardig', 'nvt', 'bouwdeel_voldoet', 'voldoet_na_aanwijzingen', 'voldoet_niet_niet_zwaar', 'nader_onderzoek_nodig', 'niet_gecontroleerd', 'niet_gecontroleerd_ivm_steekproef', 'niet_kunnen_controleren' ), 'allow_klanten_edit' => $allow_klanten_edit, 'klanten' => $klanten, 'grondslagen' => $this->_get_alle_grondslagen(), ) ); } public function verantwoordingstekst_verwijderen( $verantwoording_id=null ) { $this->load->model( 'verantwoording' ); if (($verantwoording = $this->verantwoording->get( $verantwoording_id ))) $verantwoording->delete(); // if we get here, the current user has access to this object redirect( '/instellingen/verantwoordingsteksten' ); } public function verantwoordingstekst_nieuw() { $this->load->model( 'verantwoording' ); $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $verantwoording = $this->verantwoording->add( $klant_id, '' ); redirect( '/instellingen/verantwoordingstekst_bewerken/' . $verantwoording->id ); } public function verantwoordingstekst_context() { $model = $_POST['model']; $value = $model != 'grondslagtekst' ? intval( $_POST['value'] ) : $_POST['value']; $results = array(); switch ($model) { case 'checklist': $this->load->model( 'checklist' ); if ($value) $checklisten = $this->checklist->search( array( 'checklist_groep_id' => $value ) ); else { $this->load->model( 'checklistgroep' ); $checklisten = array(); foreach ($this->checklistgroep->get_for_huidige_klant() as $checklistgroep) $checklisten = array_merge( $checklisten, $checklistgroep->get_checklisten() ); } foreach ($checklisten as $row) $results[] = array( 'id' => $row->id, 'omschrijving' => $row->get_checklistgroep()->naam . ' - ' . $row->naam, ); break; case 'hoofdthema': $this->load->model( 'hoofdthema' ); if ($value) $hoofdthemas = $this->hoofdthema->get_by_checklistgroep( $value ); else $hoofdthemas = $this->hoofdthema->get_for_huidige_klant(); foreach ($hoofdthemas as $row) $results[] = array( 'id' => $row->id, 'omschrijving' => $row->naam, ); break; case 'thema': $this->load->model( 'thema' ); if ($value) $themas = $this->thema->get_by_hoofdthema_id( $value ); else $themas = $this->thema->get_for_huidige_klant(); foreach ($themas as $row) $results[] = array( 'id' => $row->id, 'omschrijving' => $row->thema ); break; case 'grondslagtekst': $this->load->model( 'grondslagtekst' ); $artikelen = $this->grondslagtekst->get_by_grondslag_naam( $value ); foreach ($artikelen as $row) $results[] = array( 'id' => $row->artikel, 'omschrijving' => $row->artikel, 'quest' => $row->quest_node ? true : false, ); break; } usort( $results, function( $a, $b ){ return strcasecmp( $a['omschrijving'], $b['omschrijving'] ); }); die(json_encode(array('options' => $results))); } public function rollenbeheer( $sortfield=null, $sortorder=null, $search=null ) { $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); // beheer zoekinstellingen $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'rollen' ); if (!is_array( $viewdata )) $viewdata = array( 'search' => '', 'sortfield' => 'gepland_datum', 'sortorder' => 'asc', ); if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; // check input $realsortfields = array( 'naam' => 'naam', 'klant' => 'klant_id', 'gemaakt_op' => 'gemaakt_op', 'gebruiker' => 'gemaakt_door_gebruiker_id', 'aanpasbaar' => 'aanpasbaar', 'counts' => 'counts', ); if (!isset( $realsortfields[$viewdata['sortfield']] )) $viewdata['sortfield'] = 'naam'; $viewdata['sortorder'] = strtolower($viewdata['sortorder']); if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; // fetch data $allow_klanten_edit = $this->_allow_klanten_edit(); $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $rollen = $this->rol->get_for_klant( $klant_id, $viewdata['search'] ); $rollen = array_merge( $rollen, $this->rol->get_for_klant( null, $viewdata['search'] ) ); $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); $klanten = $this->_filter_klanten( $klanten ); $gebruikers = $this->gebruiker->get_by_klant( $klant_id, true ); $counts = $this->rol->get_gebruik_tellers(); // filter if (!$this->klant->allow_lease_administratie()) { foreach ($rollen as $i => $rol) if ($rol->is_lease) unset( $rollen[$i] ); $rollen = array_values( $rollen ); } // sort $factor = $viewdata['sortorder']=='asc' ? 1 : -1; switch ($actualsortfield = @ $realsortfields[$viewdata['sortfield']]) { case 'klant_id': usort($rollen, function( $a, $b ) use ($klanten, $factor){ if (!$a->klant_id || !isset( $klanten[$a->klant_id] )) return $factor * -1; if (!$b->klant_id || !isset( $klanten[$b->klant_id] )) return $factor * 1; return $factor * strcasecmp( $klanten[$a->klant_id]->naam, $klanten[$b->klant_id]->naam ); }); break; case 'gemaakt_door_gebruiker_id': usort($rollen, function( $a, $b ) use ($gebruikers, $factor){ if (!$a->gemaakt_door_gebruiker_id || !isset( $gebruikers[$a->gemaakt_door_gebruiker_id] )) return $factor * -1; if (!$b->gemaakt_door_gebruiker_id || !isset( $gebruikers[$b->gemaakt_door_gebruiker_id] )) return $factor * 1; return $factor * strcasecmp( $gebruikers[$a->gemaakt_door_gebruiker_id]->volledige_naam, $gebruikers[$b->gemaakt_door_gebruiker_id]->volledige_naam ); }); break; case 'aanpasbaar': usort($rollen, function( $a, $b ) use ($factor, $allow_klanten_edit){ $a_editbaar = ($a->klant_id || $allow_klanten_edit); $b_editbaar = ($b->klant_id || $allow_klanten_edit); return $factor * (intval($a_editbaar) - intval($b_editbaar)); }); break; case 'counts': usort($rollen, function( $a, $b ) use ($factor, $counts){ return $factor * (@$counts[$a->id] - @$counts[$b->id]); }); break; case 'naam': case 'gemaakt_op': $x=usort($rollen, function( $a, $b ) use ($actualsortfield, $factor){ return $factor * strcasecmp( $a->$actualsortfield, $b->$actualsortfield ); }); break; } // sla zoekinstellingen op $this->zoekinstelling->set( 'rollen', $viewdata ); // view! $this->load->view( 'beheer/rollenbeheer', array( 'rollen' => $rollen, 'klanten' => $klanten, 'gebruikers' => $gebruikers, 'viewdata' => $viewdata, 'allow_klanten_edit' => $allow_klanten_edit, 'counts' => $counts, ) ); } public function rol_bewerken( $rol_id=null ) { $this->load->model( 'rol' ); if (!($rol = $this->rol->get( $rol_id ))) redirect( '/instellingen/rollenbeheer' ); $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/rollenbeheer' ); $this->navigation->push( 'nav.rol_bewerken', '/instellingen/rol_bewerken/' . $rol_id ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $allow_klanten_edit = $this->_allow_klanten_edit(); $rol_editbaar = ($rol->klant_id || $allow_klanten_edit); // fetch data $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if ($rol_editbaar) { $this->db->_trans_status = TRUE; $this->db->trans_start(); // first store rol data $changes = false; if ($allow_klanten_edit) { $new_klant_id = $_POST['klant_id'] ? $_POST['klant_id'] : null; if ($new_klant_id != $rol->klant_id) { $rol->klant_id = $new_klant_id; $changes = true; } } if ($rol->naam != $_POST['naam']) { $rol->naam = $_POST['naam']; $changes = true; } if ($changes) if (!$rol->save()) die( 'Fout bij opslaan rol in database.' ); // now store rol rechten foreach ($this->rechten->get_recht_definities() as $rechtdef) { if (($rechtdef->get_modi() & RECHT_MODUS_SYSAD_ONLY) && !$allow_klanten_edit) { continue; } $this->rolrecht->replace( $rol->id, $rechtdef->get_id(), $_POST['rechtdef'][$rechtdef->get_id()] ); sql_dump_rules($rol->id, $rechtdef->get_id(), $_POST['rechtdef'][$rechtdef->get_id()]); } if (!$this->db->trans_complete()) die( 'Fout bij opslaan van data in de database (transactie fout.)' ); } redirect( '/instellingen/rollenbeheer' ); } $CI = get_instance(); $lease_configuratie_id = $CI->session->_loginSystem->get_lease_configuratie_id(); $null_data = array( 'id'=>null, 'has_children_organisations'=>null, 'naam' => '', 'voorgrondkleur' => 'ff0000', 'achtergrondkleur' => '2eb099' ); $leaseconfiguratie = $lease_configuratie_id ? $CI->leaseconfiguratie->get( $lease_configuratie_id ) : new LeaseConfiguratieResult($null_data); // view! $this->load->view( 'beheer/rol_bewerken', array( 'klanten' => $klanten, 'rol' => $rol, 'allow_klanten_edit' => $allow_klanten_edit, 'rol_editbaar' => $rol_editbaar, 'leaseconfiguratie' => $leaseconfiguratie ) ); } public function rol_nieuw() { $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $rol = $this->rol->add( $klant_id, 'Nieuwe rol' ); redirect( '/instellingen/rol_bewerken/' . $rol->id ); } public function rol_verwijderen( $rol_id=null ) { $this->load->model( 'rol' ); if (!($rol = $this->rol->get( $rol_id ))) redirect( '/instellingen/rollenbeheer' ); $allow_klanten_edit = $this->_allow_klanten_edit(); $rol_editbaar = ($rol->klant_id || $allow_klanten_edit); if ($rol_editbaar) $rol->delete(); redirect( '/instellingen/rollenbeheer' ); } public function matrix_toevoegen( $checklist_groep_id=null ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'matrix' ); // check input if (!($checklistgroep = $this->checklistgroep->get( $checklist_groep_id ))) die( 'Ongeldige checklist groep' ); // make sure at least once is available (this function will create one if it's not available) $this->matrix->geef_standaard_matrix_voor_checklist_groep( $checklistgroep ); // load all for this checklistgroep $matrices = $this->matrix->geef_matrices_voor_checklist_groep( $checklistgroep, false /* also other people's matrices! */ ); // handle POST $errors = array(); $matrix = null; if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $_POST['naam'] = trim($_POST['naam']); if (!trim($_POST['naam'])) $errors[] = 'Lege naam opgegeven.'; else { foreach ($matrices as $matrix) if ($matrix->naam == $_POST['naam']) { $errors[] = 'Matrix genaamd "' . htmlentities( $_POST['naam'], ENT_COMPAT, 'UTF-8' ) . '" bestaat reeds.'; break; } $baseer_op = $this->matrix->get( $_POST['matrix_id'] ); if (!$baseer_op) $errors[] = 'Ongeldige "baseer op" matrix ID'; if (empty($errors)) { $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $matrix = $this->matrix->add( $klant_id, $checklistgroep->id, $_POST['naam'], 0 ); $matrix->copy_from( $baseer_op ); } else $matrix = null; } // output results die(json_encode(array( 'matrix' => $matrix ? array( 'id' => $matrix->id, 'naam' => $matrix->naam ) : null, 'errors' => empty( $errors ) ? null : implode( "\n", $errors ), ))); } // view! $this->load->view( 'beheer/matrix_toevoegen', array( 'checklistgroep' => $checklistgroep, 'matrices' => $matrices, 'errors' => $errors, 'naam' => @$_POST['naam'], 'baseer_op' => @$_POST['matrix_id'], ) ); } public function matrix_verwijderen( $matrix_id=null ) { $this->load->model( 'checklistgroep' ); $this->load->model( 'matrix' ); $errors = array(); $close = false; if (!($matrix = $this->matrix->get( $matrix_id ))) $errors[] = 'Ongeldig matrix id.'; else if ($matrix->is_standaard) $errors[] = 'U kunt een standaard matrix niet verwijderen.'; else if ($matrix->klant_id != $this->session->userdata( 'kid' )) $errors[] = 'U kunt deze matrix niet verwijderen.'; else { if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if (!$matrix->delete()) $errors[] = 'Er is een fout opgetreden bij het verwijderen van deze matrix.'; else $close = true; // output results die(json_encode(array( 'errors' => empty( $errors ) ? null : implode( "\n", $errors ), ))); } } // view! $this->load->view( 'beheer/matrix_verwijderen', array( 'matrix' => $matrix, 'close' => $close, 'errors' => $errors, ) ); } public function scopesjablonen( $pagenum=null, $pagesize=null, $sortfield=null, $sortorder=null, $search=null ) { $this->load->model( 'sjabloon' ); $this->navigation->push( 'nav.scope_sjablonen', '/instellingen/scopesjablonen' ); $this->navigation->set_active_tab( 'beheer' ); // beheer zoekinstellingen $this->load->model( 'zoekinstelling' ); $viewdata = $this->zoekinstelling->get( 'scopesjablonen' ); if (!is_array( $viewdata )) $viewdata = array( 'pagenum' => 0, 'pagesize' => 25, 'search' => '', 'sortfield' => 'gepland_datum', 'sortorder' => 'asc', ); if (!is_null( $pagenum )) $viewdata['pagenum'] = $pagenum; if (!is_null( $pagesize )) $viewdata['pagesize'] = $pagesize; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; // check input $realsortfields = array( 'naam' => 'naam', 'klant' => 'klant_id', 'gebruik' => 'gebruik', ); if (!isset( $realsortfields[$viewdata['sortfield']] )) $viewdata['sortfield'] = 'naam'; $viewdata['sortorder'] = strtolower($viewdata['sortorder']); if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!is_int( $viewdata['pagenum'] )) $viewdata['pagenum'] = intval( $viewdata['pagenum'] ); if (!is_int( $viewdata['pagesize'] )) $viewdata['pagesize'] = intval( $viewdata['pagesize'] ); // fetch data $allow_klanten_edit = $this->_allow_klanten_edit(); $klant_id = $this->gebruiker->get_logged_in_gebruiker()->klant_id; $sjablonen = $this->sjabloon->get_sjablonen_voor_klant( $klant_id, $viewdata['search'] ); if ($allow_klanten_edit) $sjablonen = array_merge( $sjablonen, $this->sjabloon->get_sjablonen_voor_klant( null, $viewdata['search'] ) ); $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); $gebruik = $this->sjabloon->get_sjabloon_gebruik(); // sort $factor = $viewdata['sortorder']=='asc' ? 1 : -1; switch ($actualsortfield = @ $realsortfields[$viewdata['sortfield']]) { case 'klant_id': usort($sjablonen, function( $a, $b ) use ($klanten, $factor){ if (!$a->klant_id || !isset( $klanten[$a->klant_id] )) return $factor * -1; if (!$b->klant_id || !isset( $klanten[$b->klant_id] )) return $factor * 1; return $factor * strcasecmp( $klanten[$a->klant_id]->naam, $klanten[$b->klant_id]->naam ); }); break; case 'gebruik': usort($sjablonen, function( $a, $b ) use ($gebruik, $factor){ $a_gebruik = intval(@$gebruik[$a->id]); $b_gebruik = intval(@$gebruik[$b->id]); return $factor * ($a_gebruik - $b_gebruik); }); break; case 'naam': usort($sjablonen, function( $a, $b ) use ($actualsortfield, $factor){ return $factor * strcasecmp( trim( $a->$actualsortfield ), trim( $b->$actualsortfield ) ); }); break; } // take requested page if ($viewdata['pagesize'] != 'alle') { $total = sizeof($sjablonen); $pages = ceil( $total / $viewdata['pagesize'] ); if ($viewdata['pagenum'] >= $pages) $viewdata['pagenum'] = $pages - 1; if ($viewdata['pagenum'] < 0) $viewdata['pagenum'] = 0; $sjablonen = array_slice( $sjablonen, $viewdata['pagesize'] * $viewdata['pagenum'], $viewdata['pagesize'] ); } else $pages = 0; // sla zoekinstellingen op $this->zoekinstelling->set( 'scopesjablonen', $viewdata ); // view! $this->load->view( 'beheer/sjablonen', array( 'sjablonen' => $sjablonen, 'gebruik' => $gebruik, 'viewdata' => array_merge( $viewdata, array( 'total' => $total, 'pages' => $pages, ) ), 'allow_klanten_edit' => $allow_klanten_edit, 'klanten' => $klanten, ) ); } public function scopesjabloon_verwijderen( $sjabloon_id ) { $this->load->model( 'sjabloon' ); if ($sjabloon = $this->sjabloon->get( $sjabloon_id )) { $allow_klanten_edit = $this->_allow_klanten_edit(); if (!$allow_klanten_edit || $sjabloon->klant_id == $this->session->userdata( 'kid' )) $sjabloon->delete(); } redirect( '/instellingen/scopesjablonen' ); } public function scopesjabloon_bewerken( $sjabloon_id ) { $this->navigation->push( 'nav.scope_sjablonen', '/instellingen/scopesjablonen' ); $this->navigation->push( 'nav.scopesjabloon_bewerken', '/instellingen/scopesjablonen' ); $this->load->model( 'sjabloon' ); if (!$sjabloon = $this->sjabloon->get( $sjabloon_id )) redirect( '/instellingen/scopesjablonen' ); $allow_klanten_edit = $this->_allow_klanten_edit(); $klanten = $this->klant->all( array( 'naam' => 'asc' ), true ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { if ($allow_klanten_edit) $sjabloon->klant_id = $_POST['klant_id'] ? $_POST['klant_id'] : null; $sjabloon->naam = trim( $_POST['naam'] ); if ($sjabloon->naam) { $sjabloon->save(); redirect( '/instellingen/scopesjablonen' ); } else $errors[] = 'Lege naam niet toegestaan.'; } $this->load->view( 'beheer/sjabloon_bewerken', array( 'errors' => $errors, 'sjabloon' => $sjabloon, 'klanten' => $klanten, 'allow_klanten_edit' => $allow_klanten_edit, ) ); } private function _filter_klanten( array $klanten ) { if (!$this->klant->allow_lease_administratie()) { foreach ($klanten as $i => $klant) if ($klant->lease_configuratie_id) unset($klanten[$i]); $klanten = array_values( $klanten ); } return $klanten; } public function speciaalveld() { $this->navigation->push( 'nav.speciaalveld', '/instellingen/speciaalveld' ); $leaseconfiguratie = $this->gebruiker->get_logged_in_gebruiker()->get_klant()->get_lease_configuratie(); if (!$leaseconfiguratie || !$leaseconfiguratie->speciaal_veld_gebruiken) redirect( '/instellingen' ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { $leaseconfiguratie->speciaal_veld_waarden = $_POST['waarden']; $leaseconfiguratie->save(0,0,0); redirect( '/instellingen' ); } $this->load->view( 'beheer/speciaalveld', array( 'waarden' => $leaseconfiguratie->get_speciaal_veld_waarden(), ) ); } public function pdf_converter() { $this->load->helper( 'pdf' ); $this->navigation->push( 'nav.pdf-converter', '/instellingen/pdf-converter' ); $errors = array(); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { ob_start(); $this->load->helper( 'user_download' ); if (!isset( $_FILES['pdf_file'] ) || $_FILES['pdf_file']['error']) $errors[] = tgng('php.fout.bij.uploaden.bestand'); else { $original_filename = $_FILES['pdf_file']['name']; if (preg_match( '/\.pdf$/i', $original_filename )) { try { $new_pdf_contents = converteer_pdf_file_naar_pdf15( $_FILES['pdf_file']['tmp_name'] ); user_download( $new_pdf_contents, $original_filename ); } catch (Exception $e) { $errors[] = $e->getMessage(); } } } } $this->load->view( 'beheer/pdf_converter', array( 'errors' => $errors, ) ); } public function users_groups($pagenum=null, $pagesize=null, $sortfield=null, $sortorder=null, $search=null ) { $this->navigation->push( 'nav.gebruikersbeheer', '/instellingen/gebruikers' ); $this->navigation->set_active_tab( 'gebruikersbeheer' ); $this->load->model('zoekinstelling'); $mode=""; $viewdata = $this->zoekinstelling->get('users_groups'); if (!is_array( $viewdata )) $viewdata = array( 'pagenum' => 0, 'pagesize' => 10, 'sortfield' => 'garage_naam', 'search' => '', 'sortorder' => 'asc', ); if (!is_null( $pagenum )) $viewdata['pagenum'] = $pagenum; if (!is_null( $pagesize )) $viewdata['pagesize'] = $pagesize; if (!is_null( $sortfield )) $viewdata['sortfield'] = $sortfield; if (!is_null( $sortorder )) $viewdata['sortorder'] = $sortorder; if (!is_null( $search )) $viewdata['search'] = $search; if (!is_int( $viewdata['pagenum'] )) $viewdata['pagenum'] = intval( $viewdata['pagenum'] ); if (!is_int( $viewdata['pagesize'] )) $viewdata['pagesize'] = intval( $viewdata['pagesize'] ); $viewdata['search'] = html_entity_decode( rawurldecode( $viewdata['search'] ), ENT_QUOTES, 'UTF-8' ); if ($viewdata['search'] == '~') $viewdata['search'] = ''; if (!in_array( $viewdata['sortorder'], array( 'asc', 'desc' ))) $viewdata['sortorder'] = 'asc'; $sortfactor = $viewdata['sortorder']=='asc' ? 1 : -1; $real_sort_field = array( 'garage_naam' => 'garage_naam', 'straat' => 'straat', 'huisnummer' => 'huisnummer', 'toevoeging' => 'toevoeging', ); $this->load->model('usergroup'); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; if ($this->rechten->geef_recht_modus( RECHT_TYPE_GRP_ADMINISTRATOR) == RECHT_MODUS_EIGEN){ $groups_id=cut_array($this->gebruiker->get_logged_in_gebruiker()->groups, "users_group_id"); $data=$this->usergroup->get_list($viewdata['search'],$klant_id,$groups_id); } else { $data=$this->usergroup->get_list($viewdata['search'],$klant_id); } $actualsortfield = @ $real_sort_field[$viewdata['sortfield']]; switch ($viewdata['sortfield']) { case 'garage_naam': usort( $data, function( $a, $b ) use ($actualsortfield, $sortfactor) { return strcasecmp( $a->$actualsortfield, $b->$actualsortfield ) * $sortfactor; }); break; default: break; } $total = sizeof($data); $pages = $viewdata['pagesize'] != 'alle' ? ceil( $total / $viewdata['pagesize'] ) : 0; if ($viewdata['pagesize']!='alle') { if ($viewdata['pagenum'] >= $pages) $viewdata['pagenum'] = $pages - 1; if ($viewdata['pagenum'] < 0) $viewdata['pagenum'] = 0; $startindex = $viewdata['pagesize'] * $viewdata['pagenum']; $data = array_slice( $data, $startindex, $viewdata['pagesize'] ); } $this->zoekinstelling->set('users_groups', $viewdata ); $this->load->view( 'beheer/users_groups', array('data' => $data, 'viewdata'=> array_merge( $viewdata, array( 'total' => $total, 'pages' => $pages, ) ),)); } public function user_group_edit() { $this->load->model('usergroup'); $_POST['klant_id']= $this->gebruiker->get_logged_in_gebruiker()->klant_id; $this->usergroup->save($_POST ); if(!empty($_POST['id'])){$res=$_POST['id'];}else{$res=$this->db->insert_id();} $this->usergroup->upload($res); redirect('/instellingen/show_user_group_form/'.$res); } public function show_user_group_form($id=null){ $this->load->model('usergroup'); $data=$this->usergroup->get_user_group_by_id($id); $this->load->view( 'beheer/user_group_form', array('data'=>$data)); } public function user_group_upload( $id ) { header('Content-Type: image/jpeg'); if(file_exists(DIR_DISTRIBUTEUR_UPLOAD.'/'.DIR_THUMBNAIL.'/'.$id)){ echo file_get_contents(DIR_DISTRIBUTEUR_UPLOAD.'/'.DIR_THUMBNAIL.'/'.$id);}else{ echo file_get_contents(PATH_TO_IMAGE); } } public function delete_user_group( $dist_id=null ) { $this->load->model( 'usergroup' ); if (!($distributeur = $this->usergroup->get($dist_id))) redirect( '/instellingen/users_groups' ); $allow_klanten_edit = $this->_allow_klanten_edit(); if ($allow_klanten_edit) $distributeur->delete(); if(file_exists(DIR_DISTRIBUTEUR_UPLOAD."/".$dist_id))unlink(DIR_DISTRIBUTEUR_UPLOAD."/".$dist_id); if(file_exists(DIR_DISTRIBUTEUR_UPLOAD.'/'.DIR_THUMBNAIL."/".$dist_id))unlink(DIR_DISTRIBUTEUR_UPLOAD.'/'.DIR_THUMBNAIL."/".$dist_id); redirect( '/instellingen/users_groups' ); } public function standard_documents(){ $this->navigation->push( 'nav.standaard_documenten', '/instellingen' ); $this->load->model("standarddocument"); $data=$this->standarddocument->get_by_klant($this->gebruiker->get_logged_in_gebruiker()->klant_id); $this->load->view("beheer/standard_documents",array("bescheiden"=>$data)); } function standart_document_popup($document_id=null ) { $this->load->model("standarddocument"); $document=$this->standarddocument->get($document_id); if ($document) { $this->load->library('imageprocessor'); $this->imageprocessor->id( $document_id ); $this->imageprocessor->type( 'bescheiden' ); $this->imageprocessor->mode( 'original' ); $num_slices = $this->imageprocessor->count_slices(); } else $num_slices = null; $this->load->view( 'beheer/standart_documents_popup', array( 'document' => $document, 'num_slices' => $num_slices, ) ); } function create_document() { $this->load->model("standarddocument"); $_POST['klant_id']= $this->gebruiker->get_logged_in_gebruiker()->klant_id; $amount_of_uploaded_files = sizeof($_FILES['document']['name']); CI_Base::get_instance()->load->library('utils'); $this->load->helper("transliteration"); for ($file_idx = 0 ; $file_idx < $amount_of_uploaded_files ; $file_idx++) { if( isset( $_FILES['document'] ) && !CI_Utils::check_extension($_FILES['document']['name'][$file_idx], explode(', ', ALLOWED_EXTENSIONS)) ) { die(tgng('php.dossiers.fout.ext.not.allowed')); } elseif( isset( $_FILES['document'] ) && !$_FILES['document']['error'][$file_idx] && $_FILES['document']['size'][$file_idx]) { $_POST['bestandsnaam']=convert_file_name($_FILES['document']['name'][$file_idx]); if(!$_POST['omschrijving']) $_POST['omschrijving']=$_POST['bestandsnaam']; $this->standarddocument->insert($_POST); $file_id=$this->db->insert_id(); $this->standarddocument->upload($file_idx,$this->gebruiker->get_logged_in_gebruiker()->klant_id, $file_id); } } } function document_downloaden($document_id=null ) { $document = null; $this->load->helper( 'pdf' ); $this->load->model("standarddocument"); if (is_null( $document_id )) redirect( '/beheer/standard_documents'); else { $document=$this->standarddocument->get($document_id); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; $file=$this->standarddocument->laad_inhoud($klant_id,$document_id); if (is_null( $file )) redirect( '/beheer/standard_documents'); else { $this->load->helper( 'user_download' ); user_download( $file, $document->bestandsnaam ); } } } //Delete only standart document public function document_delete($id) { if($id){ $this->load->model('standarddocument'); $document = $this->standarddocument->get($id); $document->delete(); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; if(file_exists(DIR_STANDAARTEN_DOCUMENTEN."/".$klant_id."/".$id)) unlink(DIR_STANDAARTEN_DOCUMENTEN."/".$klant_id."/".$id); } else redirect( '/beheer/standard_documents'); } //Delete all child documents and standart document public function documents_all_delete($id) { if($id){ $this->load->model('standarddocument'); $this->load->model('dossierbescheiden'); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; $document = $this->standarddocument->get_document_by_id_and_klant_id($id,$klant_id); foreach ($document as $doc) $file_id=$this->dossierbescheiden->get_bescheiden_id_by_file_name($doc->bestandsnaam); foreach ($file_id as $f_id) $f_id->delete($doc); $this->document_delete($id); } else redirect( '/beheer/standard_documents'); } public function standard_deelplannen (){ if ($this->gebruiker->get_logged_in_gebruiker()->get_klant()->standaard_deelplannen){ $this->navigation->push( 'nav.standard_deelplannen', '/instellingen' ); $this->load->model("standarddeelplan"); $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; if($klant_id){ $data=$this->standarddeelplan->get_by_klant($klant_id); $this->load->view( 'standard_deelplannen/standard_deelplannen',array("data"=>$data)); } } else redirect(); } private function delete_deeplannen(array $delete_id){ foreach ($delete_id as $id) { if (!($object = $this->standarddeelplan->get( $id ))) throw new Exception( 'Ongeldig ID ' . $id ); $object->delete(); } } public function find_deelplannen(){ $naam=$_POST['naam']; $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; $this->load->model("standarddeelplan"); try { if (!strlen( $naam )) throw new Exception( 'Lege naam niet toegestaan.' ); if ($this->standarddeelplan->find_standard_deelplan( $naam, $klant_id )) throw new Exception( 'Er bestaat reeds een standaard deelplan met de opgegeven naam.' ); echo json_encode(array( 'success' => TRUE, )); } catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } public function save_standard_deelplan(){ $klant_id=$this->gebruiker->get_logged_in_gebruiker()->klant_id; $existing_deelplannen_id=array(); $post_deelplannen_id=array(); $this->load->model('standarddeelplan' ); $existing_deelplannen=$this->standarddeelplan->get_by_klant($klant_id); foreach ($existing_deelplannen as $object) $existing_deelplannen_id[]=$object->id; if($_POST['deelplannen']){ foreach ($_POST['deelplannen'] as $data){ if(!$data["id"]){ try { $obj = $this->standarddeelplan->insert(array("naam"=>$data["name"],"klant_id"=>$klant_id)); // voeg toe met default settings } catch (Exception $e) { $e->getMessage(); } } else { $post_deelplannen_id[]=$data["id"]; try{ $obj = $this->standarddeelplan->update(array("id"=>$data["id"], "naam"=>$data["name"])); } catch (Exception $e){ $e->getMessage(); } } } try { $delete_id=array_diff($existing_deelplannen_id,$post_deelplannen_id); $this->delete_deeplannen($delete_id); redirect("beheer/standard_deelplannen"); } catch (Exception $e) { $e->getMessage(); } } else { $delete_id=array_diff($existing_deelplannen_id,$post_deelplannen_id); $this->delete_deeplannen($delete_id); redirect("beheer/standard_deelplannen"); } } public function show_richtlijn_multi_upload_popup(){ $this->load->view('beheer/richtlijn_multi_upload_popup'); } public function richtlijn_multi_upload() { $this->load->model( 'richtlijn' ); if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST') { try { $this->load->helper("transliteration"); if (isset( $_FILES['document'])){ $filename = $_FILES['document']['name']; $file_count=count($filename); for ($i=0; $i<$file_count;$i++){ if (false === ($contents = @file_get_contents( $_FILES['document']['tmp_name'][$i]))) throw new Exception( 'Interne fout bij verwerken van upload, kon bestandsinformatien niet lezen.' ); if (!($rl = $this->richtlijn->add( convert_file_name($filename[$i]), $contents,1))) throw new Exception( 'Fout bij opslaan van upload in de database.' ); } } }catch (Exception $e) { echo json_encode(array( 'success' => false, 'error' => $e->getMessage() )); } } $this->load->view( 'beheer/richtlijn_multi_upload', array( 'documents' => $this->richtlijn->get_multi_documents(), ) ); } public function delete_richtlijn_documents(){ if (isset($_POST['ids'])){ $this->load->model( 'richtlijn' ); $document_ids=json_decode($_POST['ids']); foreach ($document_ids as $document_id){ $this->richtlijn->delete_richtlijn_documents($document_id); } $this->load->view( 'beheer/richtlijn_multi_upload', array( 'documents' => $this->richtlijn->get_multi_documents(), ) ); } } }<file_sep>-- -- -- -- LET OP, deze migratie is wellicht al toegepast op LIVE ivm een live hackfix! -- -- -- CREATE TABLE IF NOT EXISTS `back_log_uploads` ( `id` int(11) NOT NULL AUTO_INCREMENT, `back_log_id` int(11) NOT NULL, `bestandsnaam` varchar(128) NOT NULL, `bestand` longblob NOT NULL, `content_type` varchar(64) NOT NULL, `grootte` int(11) NOT NULL, `aangemaakt_op` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `back_log_id` (`back_log_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; ALTER TABLE `back_log_uploads` ADD CONSTRAINT `back_log_uploads_ibfk_1` FOREIGN KEY (`back_log_id`) REFERENCES `back_log` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; REPLACE INTO `teksten` (`string`, `tekst`, `timestamp`) VALUES ('admin.backlog_uploads::backlog-upload-new', 'Nieuw bestand uploaden', '2013-06-13 13:03:02'), ('admin.backlog_uploads::backlog-uploads', 'Backlog uploads', '2013-06-13 12:45:18'), ('nav.backlog_uploads', 'Uploads', '2013-06-13 12:44:50'), ('backlog.uploads', 'Uploads', '2013-06-13 12:42:25'); <file_sep> DROP TABLE IF EXISTS `rol_rechten_buffer`; CREATE TABLE `rol_rechten_buffer` ( id int(11) NOT NULL AUTO_INCREMENT, `rol_id` int(11) NOT NULL, `recht` int(11) NOT NULL, `modus` int(11) NOT NULL, PRIMARY KEY (id), INDEX rol_rh_bf_id (rol_id), UNIQUE INDEX UK_rol_rechten_buffer (rol_id, recht), CONSTRAINT rol_recht_buff_ibfk_1 FOREIGN KEY (rol_id) REFERENCES rollen (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; REPLACE INTO `rol_rechten_buffer` (`rol_id`,`recht`,`modus`) SELECT `rol_id`,`recht`,`modus` FROM `rol_rechten`; DROP TABLE IF EXISTS `rol_rechten`; RENAME TABLE `rol_rechten_buffer` TO `rol_rechten`; <file_sep><? $this->load->view('elements/header', array('page_header'=>'wizard.main')); ?> <h1><?=tgg('checklistwizard.headers.checklistgroep_volgorde')?></h1> <? $this->load->view( 'checklistwizard/_volgorde', array( 'entries' => $checklistgroepen, 'get_id' => function( $cg ) { return $cg->id; }, 'get_image' => function( $cg ) { return $cg->get_image(); }, 'get_naam' => function( $cg ) { return $cg->naam; }, 'store_url' => '/checklistwizard/checklistgroep_volgorde', 'return_url' => '/checklistwizard/checklistgroepen', ) ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>ALTER TABLE `bt_grondslag_teksten` ADD `next_update_timestamp` DATETIME NOT NULL DEFAULT '2014-01-01 00:00:00'; ALTER TABLE `bt_grondslag_teksten` ADD `last_fetch_time` FLOAT NULL DEFAULT NULL; <file_sep><? $this->load->view('elements/header', array('page_header'=>'toezichtmomenten.checklisten','map_view'=>true)); ?> <h1><?=tgg('toezichtmomenten.headers.checklisten')?></h1> <div class="main"> <?if(count($list) > 0):?> <ul id="sortable" class="list" style="margin-top: 10px;"> <? foreach ($list as $i => $entry): $bottom = ($i==sizeof($list)-1) ? 'bottom' : ''; ?> <li class="entry top left right <?=$bottom?>" entry_id="<?=$entry->id ?>"> <img style="margin-left: 3px; padding-top: 10px; vertical-align: bottom;" src="<?=$image_url ?>"> <div class="list-entry" style="margin-top: 3px; vertical-align: bottom;"><?=htmlentities( $entry->naam, ENT_COMPAT, 'UTF-8' )?></div> </li> <? endforeach; ?> </ul> <?else:?> <div style=""><?=tgg('toezichtmomenten.noitems') ?></div> <?endif ?> </div> <script type="text/javascript"> $(document).ready(function(){ $('li[entry_id]').click(function(){ location.href = '<?=site_url('/toezichtmomenten/momenten/').'/'.$checklistgroep_id.'/'?>'+$(this).attr('entry_id'); }); }); </script> <? $this->load->view('elements/footer'); ?> <file_sep><?php class DownloadedGenericImporter { protected $_db; protected $_CI; public function __construct( $db ) { $this->_db = $db; $this->_CI = get_instance(); } protected function _log( $log ) { // for debugging purposes, enable this // echo "<" . date('H:i:s') . "> " . $log . "\n"; } } class DownloadedChecklistImporter extends DownloadedGenericImporter { private $_thema_cache = array(); private $_richtlijn_cache = array(); public function import( array $rawdata, $checklistgroep_id ) { if (@$rawdata['type'] != 'checklist') throw new Exception( 'Het geuploade bestand bevat geen checklist informatie.' ); if (!isset( $rawdata['checklist'] ) || !is_array( $rawdata['checklist'] )) throw new Exception( 'Missend data element "checklist"' ); // maak nieuwe checklist $this->_import_checklist( $checklistgroep_id, $rawdata['checklist'], $rawdata['hoofdgroepen'] ); } private function _import_checklist( $checklistgroep_id, array $checklistdata, array $hoofdgroepen ) { // maak checklist $this->_log( 'Maak checklist "' . $checklistdata['naam'] . '"' ); $checklist = $this->_CI->checklist->add( $checklistgroep_id, $checklistdata['naam'] ); if (!$checklist) throw new Exception( 'Fout bij aanmaken van nieuwe checklist.' ); // maak hoofdgroepen foreach ($hoofdgroepen as $hoofdgroep) $this->_import_hoofdgroep( $checklist, $hoofdgroep['hoofdgroep'], $hoofdgroep['categorieen'] ); } private function _import_hoofdgroep( ChecklistResult $checklist, array $hoofdgroepdata, array $categorieen ) { // maak hoofdgroep $this->_log( '.. maak hoofdgroep "' . $hoofdgroepdata['naam'] . '"' ); $hoofdgroep = $this->_CI->hoofdgroep->add( $checklist->id, $hoofdgroepdata['naam'] ); if (!$hoofdgroep) throw new Exception( 'Fout bij aanmaken van nieuwe hoofdgroep.' ); // maak categorieen foreach ($categorieen as $categorie) $this->_import_categorie( $hoofdgroep, $categorie['categorie'], $categorie['vragen'] ); } private function _import_categorie( HoofdgroepResult $hoofdgroep, array $categoriedata, array $vragen ) { // maak categorie $this->_log( '.... maak categorie "' . $categoriedata['naam'] . '"' ); $categorie = $this->_CI->categorie->add( $hoofdgroep->id, $categoriedata['naam'] ); if (!$categorie) throw new Exception( 'Fout bij aanmaken van nieuwe categorie.' ); // maak vragen foreach ($vragen as $vraag) $this->_import_vraag( $categorie, $vraag['vraag'], $vraag['grondslagen'], $vraag['richtlijnen'] ); } private function _import_vraag( CategorieResult $categorie, array $vraagdata, array $grondslagen, array $richtlijnen ) { // maak vraag $this->_log( '...... maak vraag "' . $vraagdata['tekst'] . '"' ); $vraag = $this->_CI->vraag->add( $categorie->id, $vraagdata['tekst'], $vraagdata['thema'] ? resolve_thema( 'new', $vraagdata['thema'] )->id : NULL, $vraagdata['aanwezigheid'], $vraagdata['aandachtspunt']=='ja' ); if (!$vraag) throw new Exception( 'Fout bij aanmaken van nieuwe vraag.' ); // maak richtlijnen foreach ($richtlijnen as $richtlijn) $this->_import_richtlijn( $vraag, $richtlijn ); // maak grondslagen foreach ($grondslagen as $grondslag) $this->_import_grondslag( $vraag, $grondslag ); } private function _import_richtlijn( VraagResult $vraag, array $richtlijndata ) { $this->_log( '...... vind richtlijn "' . $richtlijndata['richtlijn'] . '"' ); if (!isset( $this->_thema_cache[ $richtlijndata['richtlijn'] ] )) { $richtlijn = $this->_CI->richtlijn->find( $richtlijndata['richtlijn'] ); if (!$richtlijn) die( 'Kan richtlijn "' . $richtlijndata['richtlijn'] . '" niet vinden.' ); $this->_thema_cache[ $richtlijndata['richtlijn'] ] = $richtlijn; } else $richtlijn = $this->_thema_cache[ $richtlijndata['richtlijn'] ]; $this->_CI->vraagrichtlijn->add( $vraag->id, $richtlijn->id ); } private function _import_grondslag( VraagResult $vraag, array $grondslagdata ) { $this->_log( '...... vind/maak grondslag "' . $grondslagdata['grondslag'] . '"' ); $grondslag = resolve_grondslag( 'new', $grondslagdata['grondslag'] ); $this->_CI->vraaggrondslag->add( $vraag->id, $grondslag->id, $grondslagdata['artikel'], $grondslagdata['tekst'] ); } } class DownloadedChecklistgroepImporter extends DownloadedGenericImporter { public function import( array $rawdata ) { if (@$rawdata['type'] != 'checklistgroep') throw new Exception( 'Het geuploade bestand bevat geen checklistgroep informatie.' ); if (!isset( $rawdata['checklistgroep'] ) || !is_array( $rawdata['checklistgroep'] )) throw new Exception( 'Missend data element "checklistgroep"' ); // maak nieuwe checklist $this->_import_checklistgroep( $rawdata['checklistgroep'], $rawdata['checklisten'] ); } private function _import_checklistgroep( array $checklistgroepdata, array $checklisten ) { // maak checklist $this->_log( 'Maak checklistgroep "' . $checklistgroepdata['naam'] . '"' ); $checklistgroep = $this->_CI->checklistgroep->add( $checklistgroepdata['naam'] ); if (!$checklistgroep) throw new Exception( 'Fout bij aanmaken van nieuwe checklistgroep.' ); // maak hoofdgroepen foreach ($checklisten as $checklist) { import_checklist_from_php( $checklist, $checklistgroep->id, true ); } } } function import_convert( $string, $sub=false ) { foreach (explode( "\n", $string ) as $line) { if ($line[0] == '#') continue; break; } // decode base64 $line = @base64_decode( $line ); if ($line===FALSE) die( sprintf( 'Fout bij importeren, %sbestand lijkt beschadigd (error: base64_decode).', $sub?'(sub)':'hoofd' ) ); // unserialize PHP string $data = @unserialize( $line ); if (!is_array( $data )) die( sprintf( 'Fout bij importeren, %sbestand lijkt beschadigd (error: unserialize).', $sub?'(sub)':'hoofd' ) ); return $data; } function init_models() { // init models $CI = get_instance(); $CI->load->model( 'checklist' ); $CI->load->model( 'checklistgroep' ); $CI->load->model( 'hoofdgroep' ); $CI->load->model( 'categorie' ); $CI->load->model( 'vraag' ); $CI->load->model( 'thema' ); $CI->load->model( 'grondslag' ); $CI->load->model( 'vraaggrondslag' ); $CI->load->model( 'richtlijn' ); $CI->load->model( 'vraagrichtlijn' ); } function import_checklist_from_php( $string, $checklistgroep_id, $sub=false ) { // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit(3600); $data = import_convert( $string, $sub ); init_models(); // get db conn $CI = get_instance(); $db = $CI->checklist->get_db(); // NOTE: // transactions are no use, since table locks are used, which means that any transaction will be auto-committed :/ try { // build importer $importer = new DownloadedChecklistImporter( $db ); $importer->import( $data, $checklistgroep_id ); } catch (Exception $e) { die( $e->getMessage() ); } } function import_checklistgroep_from_php( $string ) { // Changed the time limit, after consulting Olaf, on 12-10 to 1 hour set_time_limit(3600); $data = import_convert( $string ); init_models(); // get db conn $CI = get_instance(); $db = $CI->checklist->get_db(); // NOTE: // transactions are no use, since table locks are used, which means that any transaction will be auto-committed :/ try { // build importer $importer = new DownloadedChecklistgroepImporter( $db ); $importer->import( $data ); } catch (Exception $e) { die( $e->getMessage() ); } }<file_sep>CREATE TABLE IF NOT EXISTS `zoek_instellingen` ( `gebruiker_id` int(11) NOT NULL, `pagina` varchar(32) NOT NULL, `instellingen` text NOT NULL, PRIMARY KEY (`gebruiker_id`,`pagina`) ) ENGINE=InnoDB; ALTER TABLE `zoek_instellingen` ADD CONSTRAINT `zoek_instellingen_ibfk_1` FOREIGN KEY (`gebruiker_id`) REFERENCES `gebruikers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; <file_sep><? require_once 'base.php'; class SupervisionMomentsClResult extends BaseResult { public function __construct($arr) { parent::BaseResult('supervisionmomentscl', $arr); } } class SupervisionMomentsCl extends BaseModel { public function __construct() { parent::BaseModel('SupervisionMomentsClResult', 'supervision_moments_cl'); } // silly method only for overwrite their parent public function check_access(BaseResult $object) { if( isset($object->klant_id) ) { parent::check_access($object); } } }<file_sep><? $this->load->view('elements/header', array('page_header'=>'Site beheer - Logo\'s')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Logo beheer', 'width' => '920px' ) ); ?> <ul> <li><a href="<?=site_url('/admin/account_logo_nieuw')?>">Nieuw logo toevoegen</a></li> <li><a href="<?=site_url('/admin/account_logo_delete')?>">Bestaand logo verwijderen</a></li> <li><a href="<?=site_url('/admin/account_logo_bekijken')?>">Logo's bekijken</a></li> </ul> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?><file_sep>CREATE TABLE IF NOT EXISTS `geo_locaties` ( `id` int(11) NOT NULL AUTO_INCREMENT, `adres` varchar(512) NOT NULL, `latitude` double NOT NULL, `longitude` double NOT NULL, PRIMARY KEY (`id`), KEY `adres` (`adres`) ) ENGINE=InnoDB; ALTER TABLE `dossiers` ADD `geo_locatie_id` INT NULL DEFAULT NULL, ADD `geo_locatie_opgehaald` TINYINT NOT NULL DEFAULT '0', ADD `geo_locatie_volgende_poging` DATETIME NULL DEFAULT NULL, ADD `geo_locatie_foutmelding` VARCHAR( 64 ) NULL DEFAULT NULL, ADD INDEX ( `geo_locatie_id` ), ADD INDEX ( `geo_locatie_volgende_poging` ) ; ALTER TABLE `dossiers` ADD FOREIGN KEY ( `geo_locatie_id` ) REFERENCES `geo_locaties` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE ; <file_sep><? load_view( 'header.php' ); ?> <img src="<?=PDFANNOTATOR_FILES_BASEURL?>images/logo.png" height="21" /> <p style="width: 400px; text-align: justify;"> Er is iets fout gegaan bij het opstarten van de sessie. Dit komt hoogstwaarschijnlijk doordat de cookie instellingen op uw iPad verkeerd staan. Neem de volgende stappen om het probleem op te lossen: <ul> <li>Verlaat Safari en open uw iPad <i>Instellingen</i>.</li> <li>Klik links in het menu op <i>Safari</i>.</li> <li>Onder de header <i>Privacy</i> ziet u de optie <i>Accepteer cookies</i>.</li> <li>Klik hierop en selecteer vervolgens de optie <i>Altijd</i>.</li> <li>Ga terug naar Safari en probeer opnieuw een bestand te annoteren.</li> </ul> </p> <? load_view( 'footer.php' ); ?> <file_sep><? $this->load->view('elements/header', array('page_header'=>'Lease beheer')); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Lease bewerken voor ' . $configuratie->naam, 'width' => '920px' ) ); ?> <form method="POST"> <table class="admintable lease" width="100%" cellpadding="0" cellspacing="0"> <tr> <th style="width:300px">Naam:</th> <td><?=$configuratie->naam?></td> </tr> <tr> <th>Site titel:</th> <td><input type="text" name="pagina_titel" value="<?=$configuratie->pagina_titel?>" size="40" maxlength="128"> <i>Pagina titel in browser</i></td> </tr> <tr> <th>Login systeem:</th> <td> <select name="login_systeem"> <option <?=$configuratie->login_systeem == 'kennisid' ? 'selected' : ''?> value="kennisid">Via KennisID</option> <option <?=$configuratie->login_systeem == 'normaal' ? 'selected' : ''?> value="normaal">Via normale organisatie/gebruikersnaam/wachtwoord login</option> <option <?=$configuratie->login_systeem == 'hybride' ? 'selected' : ''?> value="hybride">Hybride</option> </select> </td> </tr> <tr> <th>Login label:</th> <td><input type="text" name="login_label" value="<?=$configuratie->login_label?>" size="40" maxlength="128"> <i>Dit is de header op de inlogpagina</i></td> </tr> <tr> <th>Achtergrondkleur:</th> <td><input type="text" name="achtergrondkleur" value="<?=$configuratie->achtergrondkleur?>" size="10" maxlength="6"> <i>HTML kleur code zonder #</i></td> </tr> <tr> <th>Voorgrondkleur:</th> <td><input type="text" name="voorgrondkleur" value="<?=$configuratie->voorgrondkleur?>" size="10" maxlength="6"></td> </tr> <tr> <th>Url:</th> <td><input type="text" name="url" value="<?=$configuratie->url ?>" size="10" maxlength="80"></td> </tr> <tr> <th>E-mail afzender:</th> <td><input type="text" name="email_sender" value="<?=$configuratie->email_sender ?>" size="10" maxlength="80"></td> </tr> <tr> <th>Beheert eigen nieuwsberichten:</th> <td><input type="checkbox" name="eigen_nieuws_berichten" <?=$configuratie->eigen_nieuws_berichten=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Nieuwe gebruikers zijn automatisch collega's:</th> <td><input type="checkbox" name="automatisch_collega_zijn" <?=$configuratie->automatisch_collega_zijn=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Toon gebruikersforum knop:</th> <td><input type="checkbox" name="toon_gebruikersforum_knop" <?=$configuratie->toon_gebruikersforum_knop=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon matrixbeheer:</th> <td><input type="checkbox" name="gebruik_matrixbeheer" <?=$configuratie->gebruik_matrixbeheer=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon management rapportage:</th> <td><input type="checkbox" name="gebruik_management_rapportage" <?=$configuratie->gebruik_management_rapportage=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon instellingen:</th> <td><input type="checkbox" name="gebruik_instellingen" <?=$configuratie->gebruik_instellingen=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon rollenbeheer:</th> <td><input type="checkbox" name="gebruik_rollenbeheer" <?=$configuratie->gebruik_rollenbeheer=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon dossier rapportage:</th> <td><input type="checkbox" name="gebruik_dossier_rapportage" <?=$configuratie->gebruik_dossier_rapportage=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Gebruik/toon deelplan email:</th> <td><input type="checkbox" name="gebruik_deelplan_email" <?=$configuratie->gebruik_deelplan_email=='ja' ? 'checked' : ''?> ></td> </tr> <tr> <th>Deelplan/OLO-nummer veranderen in speciaal selectie veld:</th> <td><input type="checkbox" name="speciaal_veld_gebruiken" <?=$configuratie->speciaal_veld_gebruiken ? 'checked' : ''?> ></td> </tr> <tr> <th>Mag kinderorganisaties hebben:</th> <td><input type="checkbox" name="has_children_organisations" <?=$configuratie->has_children_organisations ? 'checked' : ''?> ></td> </tr> <tr> <th>Klanten:</th> <td> <select multiple name="klanten[]" size="10" style="min-width: 400px"> <? foreach ($klanten as $klant): ?> <option value="<?=$klant->id?>" <?=isset( $geselecteerd[$klant->id] ) ? 'selected' : ''?>><?=htmlentities( $klant->naam, ENT_COMPAT, 'UTF-8' )?></option> <? endforeach; ?> </select> <br/> <i>Houd SHIFT ingedrukt om meerdere klanten tegelijk te selecteren.</i> </td> </tr> <tr> <th></th> <td><input type="submit" value="Opslaan"/></td> </tr> </table> </form> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-begin', array( 'header' => 'Afbeeldingen lijst', 'width' => '920px' ) ); ?> <div style="padding: 5px 5px 5px 26px; background: white url('/files/images/letop.png') no-repeat 5px 5px; font-style: italic; font-size: 90%; "> Let op! De ingevulde achtergrondkleur verandert niet op alle plekken automatisch de kleur. Dit komt omdat er aparte afbeeldingen voor moeten worden gemaakt, die hieronder worden weergegeven. Dit zal door een programmeur moeten gebeuren! </div> <? foreach ($configuratie->get_image_files() as $file): ?> <img src="<?=$file?>" /> <? endforeach; ?> <? $this->load->view('elements/laf-blocks/generic-rounded-block-end' ); ?> <? $this->load->view('elements/footer'); ?> <file_sep>CREATE TABLE IF NOT EXISTS `bag_koppeling_instellingen` ( `sleutel` varchar(64) NOT NULL, `waarde` varchar(128) NOT NULL, PRIMARY KEY (`sleutel`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `webservice_applicaties` (`id` ,`naam` ,`actief` ) VALUES (NULL , 'SSOBAG', '1'); CREATE TABLE IF NOT EXISTS `webservice_applicatie_deelplannen` ( `id` int(11) NOT NULL AUTO_INCREMENT, `webservice_applicatie_id` int(11) NOT NULL, `deelplan_id` int(11) NOT NULL, `laatst_bijgewerkt_op` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `webservice_applicatie_id` (`webservice_applicatie_id`), KEY `deelplan_id` (`deelplan_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=24 ; ALTER TABLE `webservice_applicatie_deelplannen` ADD CONSTRAINT `webservice_applicatie_deelplannen_ibfk_1` FOREIGN KEY (`webservice_applicatie_id`) REFERENCES `webservice_applicaties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `webservice_applicatie_deelplannen_ibfk_2` FOREIGN KEY (`deelplan_id`) REFERENCES `deelplannen` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
82a8da4c9d7862601a7b7ecdadff62a073824a21
[ "JavaScript", "SQL", "PHP" ]
774
PHP
nawataster/gh_btz
768de7410f0192519fd1fc7db98191b76e5b77ef
1cd064a57566f212530a6b420e2dd3b12e568c77
refs/heads/master
<file_sep>import moment from "moment"; const objPromotion = (allPromotion, generalInfo, subidaImagenInfo) => ({ id: ( allPromotion !== null && Array.isArray(allPromotion.value) && parseInt(allPromotion.value[allPromotion.value.length - 1].id) + 1 ).toString(), Name: generalInfo.Name, Negocio: generalInfo.Negocio.toUpperCase(), Description: generalInfo.Description, CreationDate: moment(new Date()).format(), DateFrom: generalInfo.fechaIF.inicio, ExpirationDate: generalInfo.fechaIF.expiracion, Legal: generalInfo.Legal, Visible: generalInfo.Visible, Order: 3, HotSale: { Title: generalInfo.Name, Text: generalInfo.Description, Align: "Bottom", Priority: 3, Image: { MimeType: subidaImagenInfo.type, Embedded: true, Payload: subidaImagenInfo.imgData, }, }, Benefits: { Title: generalInfo.Name, Text: generalInfo.Description, Align: "Bottom", Image: { MimeType: subidaImagenInfo.type, Embedded: true, Payload: subidaImagenInfo.imgData, }, }, Details: { BackColor: null, ForeColor: null, Title: generalInfo.Name, Text: generalInfo.Description, Align: "Bottom", Image: { MimeType: subidaImagenInfo.type, Embedded: true, Payload: subidaImagenInfo.imgData, }, Actions: [], }, ProductCodes: null, Schedules: [ { ScheduleType: "W", Enabled: false, TimeFrom: "00:00", DurationMins: 0, Days: generalInfo.Days, }, ], }); export { objPromotion }; <file_sep>const getIdFromTable = (e, allPromotion) => { let visible = false; let dataResult = null; if (allPromotion !== null && allPromotion.value.length > 0) { allPromotion.value.map((data) => { if (data.id === e.currentTarget.value) { visible = data.Visible; dataResult = data; return; } }); } return { visible, dataResult }; }; const handleEditPromotion = (e, allPromotion) => { let dataResult = null; if (allPromotion !== null && allPromotion.value.length > 0) { allPromotion.value.map((data) => { if (data.id === e.currentTarget.value) { dataResult = data; return; } }); } return dataResult; }; const handleDeletePromotion = (e, allPromotion) => { let id = null; let promotionData = null; if (allPromotion !== null && allPromotion.value.length > 0) { allPromotion.value.map((data) => { if (data.id === e.currentTarget.value) { id = data.id; if (data.Benefits !== null && data.Benefits.Image !== null) { promotionData = data; } promotionData = data; return; } }); } return { id, promotionData }; }; const findHotSale = (data, allPromotion) => { let hotSaleDisable = null; let hotSaleEnable = null; if ( data !== null && allPromotion !== null && allPromotion.value.length > 0 && data.Visible ) { allPromotion.value.map((item) => { if ( item.Visible && Date.parse(item.ExpirationDate) > new Date().getTime() && item.Schedules != null && item.Schedules[0].Enabled && item.Negocio === data.Negocio ) { hotSaleDisable = item; } if (item.id === data.id) { hotSaleEnable = item; } }); } return { hotSaleDisable, hotSaleEnable }; }; const EditType = (inputType) => { var type = null; switch (inputType) { case "Name": type = "text"; break; case "DateFrom": type = "date"; break; case "ExpirationDate": type = "date"; break; default: type = "text"; break; } return type; }; export { getIdFromTable, handleEditPromotion, handleDeletePromotion, findHotSale, EditType, }; <file_sep>const treeData = [ { title: "Domingo", value: 0, key: "0", }, { title: "Lunes", value: 1, key: "1", }, { title: "Martes", value: 2, key: "2", }, { title: "Mi\u00E9rcoles", value: 3, key: "3", }, { title: "Jueves", value: 4, key: "4", }, { title: "Viernes", value: 5, key: "5", }, { title: "S\u00E1bado", value: 6, key: "6", }, ]; export { treeData }; <file_sep>import React, { useState, useEffect } from "react"; import { useDispatch } from "react-redux"; import { Form, Button, Col, Row, Upload, Modal, Spin, Alert } from "antd"; import { PlusOutlined } from "@ant-design/icons"; import { save_subida_imagen_info } from "../../../actions/promotion"; export function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); } const SubidaImagenForm = ({ onFinish, dataUpdate, loading, imgPromoIsUpload, }) => { const dispatch = useDispatch(); const { Item } = Form; const [isRequired, setIsRequired] = useState(imgPromoIsUpload); const [loadingBtn, setLoadingBtn] = useState(false); const [imgPromoPreview, setImgPromoPreview] = useState({ imgData: dataUpdate !== null ? dataUpdate.Details.Image.Payload : null, type: dataUpdate !== null ? dataUpdate.Details.Image.MimeType : null, }); const [file, setFile] = useState({ previewVisible: false, previewImage: "", previewTitle: "", fileList: dataUpdate !== null && dataUpdate.Details !== null && dataUpdate.Details.Image.Payload !== "" ? [ { uid: "-1", name: "Promoci\u00F3n", status: "done", url: `data:${dataUpdate.Details.Image.MimeType};base64,${dataUpdate.Details.Image.Payload}`, }, ] : [], }); useEffect(() => { if ( (imgPromoPreview.imgData !== null && imgPromoPreview.type !== null) || file !== null ) { setIsRequired(false); } }, [file, imgPromoPreview]); const dummyRequest = ({ onSuccess }) => { setTimeout(() => { onSuccess("ok"); }, 0); }; const onClickLoading = () => { setLoadingBtn(true); }; const handleCancel = () => setFile({ previewVisible: false }); const handleChange = async ({ fileList }) => { let imgBase64 = null; let imgType = null; let imgData = null; if (fileList.length > 0) { if (fileList[0].originFileObj !== undefined) { imgBase64 = await getBase64(fileList[0].originFileObj); imgType = fileList[0].originFileObj.type; imgData = imgBase64.replace( `data:${fileList[0].originFileObj.type};base64,`, "" ); } else { imgType = imgPromoPreview.type; imgData = imgPromoPreview.imgData; } dispatch( save_subida_imagen_info({ type: imgType, imgData: imgData, }) ); } else { dispatch(save_subida_imagen_info(null)); } setFile({ fileList }); }; const uploadButton = ( <div> <PlusOutlined /> <div style={{ marginTop: 8 }}>Upload</div> </div> ); const handlePreview = async (file) => { file.preview = file.originFileObj !== undefined ? await getBase64(file.originFileObj) : file.url; let typeImg = file.originFileObj !== undefined ? file.originFileObj.type : dataUpdate.Details.Image.MimeType; setImgPromoPreview({ type: typeImg, imgData: file.preview.replace(`data:${typeImg};base64,`, ""), }); setFile({ previewImage: file.url || file.preview, previewVisible: true, previewTitle: file.name || file.url.substring(file.url.lastIndexOf("/") + 1), }); }; return ( <Form layout="vertical" hideRequiredMark className="pt-3" onFinish={(e) => onFinish(e, file, imgPromoPreview)} > {loading ? ( <Spin tip="Enviando" style={{ height: "100vh" }}> <Alert type="info" className="py-5 bg-transparent border-0" /> </Spin> ) : ( <> <Row gutter={16}> <Col span={12}> <Item name="fileImg" rules={[ { required: isRequired, message: "Por favor, suba una imagen", }, ]} > <Upload customRequest={dummyRequest} listType="picture-card" fileList={file.fileList} onPreview={handlePreview} onChange={handleChange} accept=".jpg, .svg, .png, .jpeg" > {file.fileList != null && file.fileList.length > 0 ? null : uploadButton} </Upload> <Modal visible={file.previewVisible} title={file.previewTitle} onCancel={handleCancel} footer={null} > <img className="shadow rounded" alt="example" style={{ width: "100%" }} src={`data:${imgPromoPreview.type};base64,${imgPromoPreview.imgData}`} /> </Modal> </Item> </Col> </Row> <Row className="float-right"> <Button type="primary" htmlType="submit" loading={loadingBtn} onClick={onClickLoading}> Confirmar </Button> </Row> </> )} </Form> ); }; export default SubidaImagenForm; <file_sep>const CosmosClient = require("@azure/cosmos").CosmosClient; const { endpoint, key, databaseId, containerId, query } = require("../config").configAzureCosmosDb; const client = new CosmosClient({ endpoint, key }); const database = client.database(databaseId); const container = database.container(containerId); const getAllPromotion = async (req, res) => { try { const queryString = { query, }; const { resources: items } = await container.items .query(queryString) .fetchAll(); res.json({ value: items.sort((a, b) => a.id - b.id), success: true, error: null, }); } catch (error) { res.send({ value: null, success: false, error: error.message }); } }; const createPromotion = async (req, res) => { try { const { resource: createdItem } = await container.items.create(req.body); res.send({ value: createdItem, success: true, error: null }); } catch (error) { res.send({ value: null, success: false, error: error.message }); } }; const editPromotion = async (req, res) => { try { delete req.body["_rid"]; delete req.body["_self"]; delete req.body["_etag"]; delete req.body["_attachments"]; delete req.body["_ts"]; delete req.body["key"]; delete req.body["partition"]; const { resource: updatedItem } = await container .item(req.body.id) .replace(req.body); res.send({ value: updatedItem, success: true, error: null }); } catch (error) { res.send({ value: null, success: false, error: error.message }); } }; const deletePromotion = async (req, res) => { try { const { resource: result } = await container.item(req.params.id).delete(); res.send({ value: result, success: true, error: null }); } catch (error) { res.send({ value: null, success: false, error: error.message }); } }; module.exports = { getAllPromotion, createPromotion, editPromotion, deletePromotion, };<file_sep>const expressjwt = require("express-jwt"); const { secret } = require("../config"); module.exports = jwt = () => expressjwt({ secret, algorithms: ["HS256"] }).unless({ path: [ "/api/autenticar", //ruta que debe ignorar JWT. ], }); <file_sep>import { SEND_CREDENTIALS, ACTION_AUTH_SUCCESS, MESSAGE_AUTH, SAVE_AUTH_DATA_SUCCESS, } from "../constants/ActionTypes"; export const send_credentials = (data) => { return { type: SEND_CREDENTIALS, payload: data, }; }; export const save_auth_success = (isSuccess) => { return { type: ACTION_AUTH_SUCCESS, payload: isSuccess, }; }; export const message_auth = (data) => { return { type: MESSAGE_AUTH, payload: data, }; }; export const save_auth_data_success = (data) => { return { type: SAVE_AUTH_DATA_SUCCESS, payload: data, }; }; <file_sep>const EditValuesForm = (dataUpdate, generalInfo, imgData) => { dataUpdate["DateFrom"] = generalInfo.fechaIF.inicio; dataUpdate["ExpirationDate"] = generalInfo.fechaIF.expiracion; dataUpdate["Legal"] = generalInfo.Legal; dataUpdate["Negocio"] = generalInfo.Negocio; dataUpdate["Visible"] = generalInfo.Visible; dataUpdate["Name"] = generalInfo.Name; dataUpdate["Description"] = generalInfo.Description; dataUpdate.Benefits !== null && (dataUpdate.Benefits = { Title: generalInfo.Name, Text: generalInfo.Description, Actions: dataUpdate.Benefits.Actions, Align: dataUpdate.Benefits.Align, BackColor: dataUpdate.Benefits.BackColor, ForeColor: dataUpdate.Benefits.ForeColor, Image: { Embedded: dataUpdate.Benefits.Image.Embedded, MimeType: imgData.type, Payload: imgData.imgData, }, }); dataUpdate.Details !== null && (dataUpdate.Details = { Title: generalInfo.Name, Text: generalInfo.Description, Actions: dataUpdate.Details.Actions, Align: dataUpdate.Details.Align, BackColor: dataUpdate.Details.BackColor, ForeColor: dataUpdate.Details.ForeColor, Image: { Embedded: dataUpdate.Details.Image.Embedded, MimeType: imgData.type, Payload: imgData.imgData, }, }); dataUpdate.HotSale !== null && (dataUpdate.HotSale = { Title: generalInfo.Name, Text: generalInfo.Description, Actions: dataUpdate.HotSale.Actions, Align: dataUpdate.HotSale.Align, BackColor: dataUpdate.HotSale.BackColor, ForeColor: dataUpdate.HotSale.ForeColor, Image: { Embedded: dataUpdate.HotSale.Image.Embedded, MimeType: imgData.type, Payload: imgData.imgData, }, }); dataUpdate.Schedules !== null && dataUpdate.Schedules.length > 0 && (dataUpdate.Schedules = [ { Days: generalInfo.Days, DurationMins: dataUpdate.Schedules[0].DurationMins, Enabled: dataUpdate.Schedules[0].Enabled, ScheduleType: dataUpdate.Schedules[0].ScheduleType, TimeFrom: dataUpdate.Schedules[0].TimeFrom, }, ]); return dataUpdate; }; export { EditValuesForm }; <file_sep>import React, { useEffect, useState } from "react"; import moment from "moment"; import { Tag } from "antd"; const VisibilidadDias = ({ record }) => { const [days, setDays] = useState([]); useEffect(() => { if ( record !== null && record.Schedules !== null && !moment(new Date()).isAfter(record.ExpirationDate) && Array.isArray(record.Schedules) && record.Schedules.length > 0 && Array.isArray(record.Schedules[0].Days) && record.Schedules[0].Days.length > 0 && record.Schedules[0].Enabled ) { setDays(record.Schedules[0].Days); } }, [record]); const showDays = (day) => { let shortNameDay = null; switch (day) { case 0: shortNameDay = "D"; break; case 1: shortNameDay = "L"; break; case 2: shortNameDay = "M"; break; case 3: shortNameDay = "M"; break; case 4: shortNameDay = "J"; break; case 5: shortNameDay = "V"; break; case 6: shortNameDay = "S"; break; default: shortNameDay = null; break; } return shortNameDay; }; return days.map((day, i) => { let dayEnabledHotSale = day === new Date().getDay() && record.Schedules[0].Enabled; return ( <span className="small" key={i}> <Tag color={dayEnabledHotSale ? "gold" : "default"} className={dayEnabledHotSale ? "mr-0 font-weight-bold" : "mr-0"} key={day} > {showDays(day)} </Tag> </span> ); }); }; export default VisibilidadDias; <file_sep>const express = require("express"); const app = express(); const morgan = require("morgan"); const promotionRoutes = require("./routes/api/promotion"); const auth = require("./routes/api/auth"); const errorHandler = require("./helpers/error-handler"); const jwt = require("./helpers/jwt"); //settings app.set("json spaces", 2); //JWT auth to secure the api app.use(jwt()); //middlewares app.use(morgan("dev")); app.use(express.urlencoded({ extended: true })); app.use(express.json({ limit: "100mb", parameterLimit: 500000 })); //routes app.use("/api", promotionRoutes); app.use("/api", auth); //global error handler app.use(errorHandler); module.exports = app; <file_sep>import { all } from "redux-saga/effects"; import config from "./config"; import promotion from "./promotion"; import auth from "./auth"; export default function* rootSaga(getState) { yield all([config(), promotion(), auth()]); } <file_sep>import { all, call, fork, put, takeEvery } from "redux-saga/effects"; import { CONFIG_INITIAL } from "../constants/ActionTypes"; const configInitialRequest = async () => await undefined; function* config() { try { const signOutUser = yield call(configInitialRequest); if (signOutUser === undefined) { yield put(null); } else { yield put(null); } } catch (error) { yield put(null); } } export function* configInitial() { yield takeEvery(CONFIG_INITIAL, config); } export default function* rootSaga() { yield all([fork(configInitial)]); } <file_sep>This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `Instalar dependencias npm` 1. Instalar Node Js (Version LTS) URL: <a href="https://nodejs.org/es/" target="_blank"> https://nodejs.org/es/<a/> 2. Ir al archivo "package.json" y con visual studio code, ejecutar los scripts en este orden. <br /> a). "server-dependencies" (npm install) <br /> b). "client-dependencies" (npm install) <br /> c). "start" (inicia el proyecto) ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `yarn build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify <file_sep>export const CONFIG_INITIAL = "CONFIG_INITIAL"; //auth AD export const SEND_CREDENTIALS = "SEND_CREDENTIALS"; export const SAVE_AUTH_DATA_SUCCESS = "SAVE_AUTH_DATA_SUCCESS"; export const ACTION_AUTH_SUCCESS = "ACTION_AUTH_SUCCESS"; export const MESSAGE_AUTH = "MESSAGE_AUTH"; //promociones export const GET_ALL_PROMOTIONS = "GET_ALL_PROMOTIONS"; export const SAVE_ALL_PROMOTIONS = "SAVE_ALL_PROMOTIONS"; export const DELETE_PROMOTION_BY_ID = "DELETE_PRMOTION_BY_ID"; export const CREATE_A_NEW_PROMOTION = "CREATE_A_NEW_PROMOTION"; export const SAVE_GENERAL_INFO = "SAVE_GENERAL_INFO"; export const SAVE_HOT_SALE_INFO = "SAVE_HOT_SALE_INFO"; export const SAVE_BENEFICIOS_INFO = "SAVE_BENEFICIOS_INFO"; export const SAVE_DETALLES_INFO = "SAVE_DETALLES_INFO"; export const SAVE_HORARIOS_INFO = "SAVE_HORARIOS_INFO"; export const SAVE_SUBIDA_IMAGEN_INFO = "SAVE_SUBIDA_IMAGEN_INFO"; export const SAVE_CONFIRMACION_INFO = "SAVE_CONFIRMACION_INFO"; export const CHANGE_HOTSALE_BANNER = "CHANGE_HOTSALE_BANNER"; export const ASSIGN_A_NEW_HOT_SALE = "ASSIGN_A_NEW_HOT_SALE"; export const PUT_PROMOTION_DATA = "PUT_PROMOTION_DATA"; export const ACTION_SUCCESS = "ACTION_SUCCESS"; export const TAB_INDEX = "TAB_INDEX";<file_sep>const ldap = require("ldapjs"); const config = require("../config"); const jwt = require("jsonwebtoken"); const { Base64 } = require("js-base64"); const { url, port, domain } = config.configLDAP; const { secret, expirationDateJwt } = config; const authenticacion = (req, res) => { try { const { sso, password } = req.body; var ssoDecode = Base64.decode(sso), passwordDecode = Base64.decode(password), responseAd = null; const clientLdap = ldap.createClient({ url: `${url}:${port}`, }); //conexión AD clientLdap.bind( `${domain[0]}${ssoDecode}`, passwordDecode, (error, result) => { if (result !== null && error === null) { const token = jwt.sign( { check: true, }, secret, { expiresIn: "12h", } ); res.send({ value: { message: "Usuario Autenticado", token: token, expiration: expirationDateJwt, }, success: true, error: null, }); } else if (error) { //desconexión AD clientLdap.unbind(() => { if (error.code === "ENOTFOUND") { res.send({ value: null, success: false, error: { error: error, message: "VPN: No se ha podido establecer conexi\u00F3n.", }, }); } else { res.send({ value: null, success: false, error: { error: error, message: "Credenciales incorrectas", }, }); } }); } } ); } catch (error) { res.send({ value: null, success: false, error: { error: error, message: "No se ha podido establecer la conexion al Active Directory", }, }); } }; module.exports = { authenticacion }; <file_sep>import React, { useEffect, useState } from "react"; import { Table, Drawer, Form, Input, DatePicker, Select, message, Empty, } from "antd"; import moment from "moment"; import { useSelector, useDispatch } from "react-redux"; import { assign_a_new_hotsale_banner, change_hotsale_banner, delete_promotion_by_id, get_all_promotions, put_promotion_data, save_action_success, save_all_promotions, save_beneficios_info, save_confirmacion_info, save_detalles_info, save_general_info, save_hot_sale_info, save_subida_imagen_info, } from "../../../actions/promotion"; import { getIdFromTable, handleDeletePromotion, findHotSale, EditType, } from "../../../helpers/Estados"; import { assignSameHotSaleAlert } from "../../../helpers/Estados/assignHotSaleEdit"; import FormularioEdicion from "../../../components/Promociones/Edit"; import ModalVisible from "../../../components/Estados/ModalVisible"; import ModalDelete from "../../../components/Estados/ModalDelete"; import ModalHotSale from "../../../components/Estados/ModalHotSale"; import Acciones from "../../../components/Estados/Acciones"; import VisibilidadDias from "../../../components/Estados/VisibilidadDias"; import DiasExpiracion from "../../../components/Estados/Expiracion"; import Negocio from "../../../components/Estados/Negocio"; const Estados = () => { let nameEdit = null; let dateFromEdit = null; let expirationDateEdit = null; let negocioEdit = null; const dispatch = useDispatch(); const [form] = Form.useForm(); const { Item } = Form; const { Option } = Select; const [editingKey, setEditingKey] = useState(null); const { allPromotion, actionSuccess } = useSelector( ({ promotions }) => promotions ); const daySchedules = new Date().getDay(); const [promotionData, setPromotionData] = useState(null); const [loading, setLoading] = useState(false); const [showModal, setShowModal] = useState(false); const [showModalDelete, setShowModalDelete] = useState(false); const [showModalHotSale, setShowModalHotSale] = useState(false); const [showDrawer, setShowDrawer] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); const [confirmLoadingDelete, setConfirmLoadingDelete] = useState(false); const [confirmLoadingHotSale, setConfirmLoadingHotSale] = useState(false); const [dataPut, setDataPut] = useState(null); const [dataUpdate, setDataUpdate] = useState(null); const [textActionModal, setTextActionModal] = useState(false); const [deleteId, setDeleteId] = useState(null); const [recordTableEdit, setRecordTableEdit] = useState(null); const [isAssignANewHotSale, setIsAssignANewHotSale] = useState(false); const [assignANewHotSaleData, setAssignANewHotSaleData] = useState(null); const [hideColumnsEditPartial, setHideColumnsEditPartial] = useState(false); const [imgHotSaleChange, setImgHotSaleChange] = useState({ imgDisable: null, imgEnable: null, }); useEffect(() => { //#region Titulo document.title = "Estados - IUD\u00DA"; //#endregion setLoading(true); if (allPromotion !== null && Array.isArray(allPromotion.value)) { allPromotion.value.map((item) => { item["key"] = item.id; }); setPromotionData(allPromotion.value); dispatch(save_action_success(false)); setLoading(false); } if (actionSuccess) { dispatch(save_all_promotions(null)); dispatch(get_all_promotions()); dispatch(save_subida_imagen_info(null)); setLoading(true); setConfirmLoading(false); setShowModal(false); setConfirmLoadingDelete(false); setShowModalDelete(false); setShowModalHotSale(false); setConfirmLoadingHotSale(false); setShowDrawer(false); message.success("Se realizo exitosamente la acci\u00F3n"); } }, [allPromotion, actionSuccess, daySchedules]); const getIdFromTableHelper = (e) => { setShowModal(true); var result = getIdFromTable(e, allPromotion); if (result !== null) { setTextActionModal(result.visible); setDataPut(result.dataResult); } }; const handleOkModal = () => { setConfirmLoading(true); if (dataPut !== null) { if (dataPut.Visible) { dataPut["Visible"] = false; } else { dataPut["Visible"] = true; } dispatch(put_promotion_data(dataPut)); } }; const handleOkModalDelete = () => { setConfirmLoadingDelete(true); dispatch(delete_promotion_by_id(deleteId)); }; const handleOkModalHotSale = () => { setConfirmLoadingHotSale(true); if (isAssignANewHotSale && assignANewHotSaleData !== null) { dispatch(assign_a_new_hotsale_banner(assignANewHotSaleData)); } else { dispatch(change_hotsale_banner(imgHotSaleChange)); } }; const handleCloseModal = () => { setShowModal(false); setConfirmLoading(false); }; const handleCloseModalDelete = () => { setShowModalDelete(false); }; const handleCloseModalHotSale = () => { setShowModalHotSale(false); }; const handleEditPromotionHelper = (_, record) => { setShowDrawer(true); setDataUpdate(record); }; const handleDeletePromotionHelper = (e) => { setShowModalDelete(true); var result = handleDeletePromotion(e, allPromotion); setDeleteId(result.id); setDataPut(result.promotionData); }; const handleOnCloseDrawer = () => { setShowDrawer(false); dispatch(save_general_info(null)); dispatch(save_hot_sale_info(null)); dispatch(save_beneficios_info(null)); dispatch(save_detalles_info(null)); dispatch(save_subida_imagen_info(null)); dispatch(save_confirmacion_info(null)); }; const changeHotSaleModal = (e, data) => { let result = findHotSale(data, allPromotion); try { if (result.hotSaleDisable === null && result.hotSaleEnable === null) { message.warning( `La promoci\u00F3n debe estar visible para poder mostrar dentro del "HOT SALE"` ); return; } if ( result !== null && result.hotSaleDisable !== null && result.hotSaleEnable !== null && result.hotSaleDisable.id !== result.hotSaleEnable.id ) { if ( result.hotSaleDisable.HotSale !== "" && result.hotSaleDisable.HotSale !== null && result.hotSaleEnable.HotSale !== "" && result.hotSaleEnable.HotSale !== null ) { setShowModalHotSale(true); setImgHotSaleChange({ imgDisable: result.hotSaleDisable, imgEnable: result.hotSaleEnable, }); setIsAssignANewHotSale(false); //vuelve a los valores iniciales de la "AssignANewHotSale" de hotsale. setIsAssignANewHotSale(false); setAssignANewHotSaleData(null); } else { message.info( `Actualmente la promoci\u00F3n, con el ID ${result.hotSaleDisable.id} no tiene habilitado el "HOT SALE"` ); } } else { if ( result.hotSaleDisable !== null && result.hotSaleDisable.Schedules[0].Enabled ) { message.info( `El banner con el ID ${result.hotSaleDisable.id} ya se encuentra visible en "HOT SALE"` ); } else { if ( result.hotSaleDisable === null && result.hotSaleEnable !== null && result.hotSaleEnable.Schedules[0].Enabled === false ) { setShowModalHotSale(true); setIsAssignANewHotSale(true); setAssignANewHotSaleData(result.hotSaleEnable); } } } } catch (error) { message.error("No se pudo realizar la seguiente acci\u00F3n"); } }; const cancel = () => { setEditingKey(null); setHideColumnsEditPartial(false); }; const save = async (id) => { try { const newData = [...promotionData]; const index = newData.findIndex((item) => id === item.id); if (index > -1) { const item = newData[index]; item.Negocio = negocioEdit !== null ? negocioEdit : item.Negocio; item.ExpirationDate = expirationDateEdit !== null ? expirationDateEdit : item.ExpirationDate; item.DateFrom = dateFromEdit !== null ? dateFromEdit : item.DateFrom; item.Name = nameEdit !== null ? nameEdit : item.Name; item.HotSale.Title = nameEdit !== null ? nameEdit : item.Name; item.Benefits.Title = nameEdit !== null ? nameEdit : item.Name; item.Details.Title = nameEdit !== null ? nameEdit : item.Name; setLoading(true); dispatch(put_promotion_data(item)); setEditingKey(null); setHideColumnsEditPartial(false); } else { setEditingKey(null); } } catch (errInfo) { message.error("No se pudo completar la acci\u00F3n correctamente"); } }; const isEditing = (record) => record.id === editingKey; const edit = (e, record) => { form.setFieldsValue({ Name: "", Negocio: "", DateFrom: "", ExpirationDate: "", ...record, }); setEditingKey(record.id); setRecordTableEdit(record); setHideColumnsEditPartial(true); }; const NegocioName = (negocio) => { let negocioSelectText = null; if (negocio !== null) { switch (negocio.Negocio.toUpperCase()) { case "WM": negocioSelectText = "Walmart"; break; default: negocioSelectText = "IUD\u00DA"; break; } } return negocioSelectText; }; const changeNewValueEditItem = (e, newDate, dataIndex, record) => { let isEqualsNegocio = false; let negocio = null; if (e.currentTarget !== undefined) { if (e.currentTarget.id === "Name") { nameEdit = e.target.value; } } else if (e === "IU" || e === "WM") { const { isEqualsNegocio, negocioResult } = assignSameHotSaleAlert( allPromotion, record, e ); if (isEqualsNegocio) { message.warning( `No se puede asignar mas de un "HOT SALE" para el negocio ${negocioResult}` ); return; } else { negocioEdit = e; } } else if (newDate !== undefined && dataIndex === "DateFrom") { dateFromEdit = moment(newDate).format(); } else if (newDate !== undefined && dataIndex === "ExpirationDate") { expirationDateEdit = moment(newDate).format(); } return; }; const inputNodeView = (dataIndex) => { switch (dataIndex) { case "Name": return ( <Input defaultValue={ recordTableEdit !== null ? recordTableEdit.Name : null } /> ); case "DateFrom": return ( <DatePicker showTime defaultValue={moment( recordTableEdit !== null ? recordTableEdit.DateFrom : new Date(), "YYYY-MM-DD hh:mm:ss" )} /> ); case "ExpirationDate": return ( <DatePicker showTime defaultValue={moment( recordTableEdit !== null ? recordTableEdit.ExpirationDate : new Date(), "YYYY-MM-DD hh:mm:ss" )} /> ); case "Negocio": return ( <Select placeholder="Seleccione" defaultValue={NegocioName(recordTableEdit)} > <Option value="WM">Walmart</Option> <Option value="IU">IUD&Uacute;</Option> </Select> ); } }; const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { return ( <td {...restProps}> {editing ? ( <Item name={dataIndex} getValueFromEvent={(e, newDate) => changeNewValueEditItem(e, newDate, dataIndex, record) } style={{ margin: 0, }} rules={[ { required: true, message: `Please Input ${title}!`, }, ]} > {inputNodeView(dataIndex)} </Item> ) : ( children )} </td> ); }; const columns = [ { title: "Id", dataIndex: "id", key: "1", className: "text-center", render: (text) => <a>{text}</a>, }, { title: "T\u00EDtulo", dataIndex: "Name", key: "2", className: "text-center", editable: true, }, { title: "Negocio", dataIndex: "Negocio", key: "4", className: "text-center", render: (text) => <Negocio text={text} />, editable: true, }, { title: "Inicio", dataIndex: "DateFrom", inputType: "date", key: "5", className: "text-center", render: (date) => { return ( <span>{moment(new Date(date)).format("YYYY/MM/DD HH:mm:ss")}</span> ); }, editable: true, }, { title: "Expiraci\u00F3n", dataIndex: "ExpirationDate", inputType: "date", key: "6", className: "text-center", render: (date) => { return ( <span>{moment(new Date(date)).format("YYYY/MM/DD HH:mm:ss")}</span> ); }, editable: true, }, { title: "Estado", key: "7", dataIndex: "ExpirationDate", className: "text-center", render: (date) => <DiasExpiracion date={date} />, }, { title: "HOT SALE (D\u00EDas)", dataIndex: [], key: "8", className: `${ hideColumnsEditPartial ? "invisible collapse" : "text-center" }`, width: 230, render: (_, record) => <VisibilidadDias record={record} />, }, { title: "Acciones", dataIndex: [], key: "9", className: "text-center", render: (_, record) => { const editable = isEditing(record); return ( <Acciones record={record} getIdFromTableHelper={getIdFromTableHelper} changeHotSaleModal={changeHotSaleModal} save={save} cancel={cancel} edit={edit} editable={editable} handleEditPromotionHelper={handleEditPromotionHelper} handleDeletePromotionHelper={handleDeletePromotionHelper} /> ); }, }, ]; const mergedColumns = columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, inputType: EditType(col.dataIndex), dataIndex: col.dataIndex, title: col.title, editing: isEditing(record), }), }; }); return ( <div className="ant-form ant-form-vertical ant-form-hide-required-mark bg-white m-4 shadow"> <Table locale={{ emptyText: ( <Empty description={<div className="font-weight-bold">SIN DATOS</div>} /> ), }} form={form} components={{ body: { cell: EditableCell, }, }} expandable={{ expandedRowRender: (record, col, row, isExpand) => ( <div>{record.Legal}</div> ), }} rowClassName="editable-row" loading={loading} columns={mergedColumns} pagination={{ pageSize: 10, className: "p-4 float-right" }} dataSource={promotionData} /> <ModalVisible dataPut={dataPut} showModal={showModal} handleOkModal={handleOkModal} confirmLoading={confirmLoading} handleCloseModal={handleCloseModal} textActionModal={textActionModal} /> <ModalDelete dataPut={dataPut} showModalDelete={showModalDelete} handleOkModalDelete={handleOkModalDelete} confirmLoadingDelete={confirmLoadingDelete} handleCloseModalDelete={handleCloseModalDelete} /> <ModalHotSale showModalHotSale={showModalHotSale} handleOkModalHotSale={handleOkModalHotSale} confirmLoadingHotSale={confirmLoadingHotSale} handleCloseModalHotSale={handleCloseModalHotSale} imgHotSaleChange={imgHotSaleChange} isAssignANewHotSale={isAssignANewHotSale} assignANewHotSaleData={assignANewHotSaleData} /> <Drawer title="Edici&oacute;n" width={"70%"} onClose={handleOnCloseDrawer} visible={showDrawer} > {showDrawer && ( <FormularioEdicion dataUpdate={dataUpdate} handleOnCloseDrawer={handleOnCloseDrawer} /> )} </Drawer> </div> ); }; export default Estados; <file_sep>const moment = require("moment"); const configAzureCosmosDb = { endpoint: "", key: "==", databaseId: "", containerId: "", query: "SELECT * from c", }; const configLDAP = { url: "", port: 000, options: { filter: `(&(objectClass=user)(sAMAccountName={{0}}))`, scope: "sub", attributes: ["memberOf", "displayName", "name"], }, domain: ["\\"], }; const expirateJwt = new Date(); const expirationDateJwt = moment( expirateJwt.setHours(expirateJwt.getHours() + 12 /* expire in (hours)*/) ).format(); const secret = ""; module.exports = { configAzureCosmosDb, configLDAP, secret, expirationDateJwt, };<file_sep>import { all, call, fork, put, takeEvery } from "redux-saga/effects"; import { SEND_CREDENTIALS } from "../constants/ActionTypes"; import { controllerAutenticar } from "../services/service"; import { save_auth_success, message_auth, save_auth_data_success, } from "../actions/auth"; const signInRequest = async (data) => await controllerAutenticar(data) .then((response) => response) .catch((error) => error); function* signInData({ payload }) { let signInResposne = null; try { signInResposne = yield call(signInRequest, payload); if (signInResposne != null && signInResposne.success) { localStorage.setItem("user", signInResposne.success); localStorage.setItem("token", signInResposne.value.token); localStorage.setItem("tokenExpiration", signInResposne.value.expiration); yield put(save_auth_success(true)); yield put(save_auth_data_success(signInResposne.value.message)); } else { yield put(message_auth(signInResposne.error.message)); } } catch (error) { yield put(message_auth(signInResposne.error.message)); } } export function* signIn() { yield takeEvery(SEND_CREDENTIALS, signInData); } export default function* rootSaga() { yield all([fork(signIn)]); } <file_sep>import { GET_ALL_PROMOTIONS, SAVE_ALL_PROMOTIONS, DELETE_PROMOTION_BY_ID, SAVE_GENERAL_INFO, SAVE_HOT_SALE_INFO, SAVE_BENEFICIOS_INFO, SAVE_DETALLES_INFO, SAVE_SUBIDA_IMAGEN_INFO, SAVE_CONFIRMACION_INFO, PUT_PROMOTION_DATA, ACTION_SUCCESS, TAB_INDEX, CHANGE_HOTSALE_BANNER, ASSIGN_A_NEW_HOT_SALE, CREATE_A_NEW_PROMOTION, } from "../constants/ActionTypes"; export const get_all_promotions = () => { return { type: GET_ALL_PROMOTIONS, payload: null, }; }; export const create_a_new_promotion = (data) => { return { type: CREATE_A_NEW_PROMOTION, payload: data, }; }; export const save_all_promotions = (data) => { return { type: SAVE_ALL_PROMOTIONS, payload: data, }; }; export const delete_promotion_by_id = (id) => { return { type: DELETE_PROMOTION_BY_ID, payload: id, }; }; export const save_general_info = (payload) => { return { type: SAVE_GENERAL_INFO, payload: payload, }; }; export const save_hot_sale_info = (payload) => { return { type: SAVE_HOT_SALE_INFO, payload: payload, }; }; export const save_beneficios_info = (payload) => { return { type: SAVE_BENEFICIOS_INFO, payload: payload, }; }; export const save_detalles_info = (payload) => { return { type: SAVE_DETALLES_INFO, payload: payload, }; }; export const save_subida_imagen_info = (payload) => { return { type: SAVE_SUBIDA_IMAGEN_INFO, payload: payload, }; }; export const save_confirmacion_info = (payload) => { return { type: SAVE_CONFIRMACION_INFO, payload: payload, }; }; export const put_promotion_data = (data) => { return { type: PUT_PROMOTION_DATA, payload: data, }; }; export const save_action_success = (info) => { return { type: ACTION_SUCCESS, payload: info, }; }; export const tab_index = (index) => { return { type: TAB_INDEX, payload: index, }; }; export const change_hotsale_banner = (payload) => { payload.imgDisable.Schedules[0].Enabled = false; payload.imgEnable.Schedules[0].Enabled = true; payload.imgDisable.Order = 2; payload.imgEnable.Order = 1; return { type: CHANGE_HOTSALE_BANNER, payload: payload, }; }; export const assign_a_new_hotsale_banner = (payload) => { payload.Schedules[0].Enabled = true; payload.Order = 1; return { type: ASSIGN_A_NEW_HOT_SALE, payload: payload, }; };<file_sep>import React, { useEffect, useState } from "react"; import moment from "moment"; import { Tag } from "antd"; const Expiracion = ({ date }) => { const [color, setColor] = useState("success"); const [name, setName] = useState("Habilitado"); const DIASDEVENCIMIENTO = 8; useEffect(() => { if (Date.parse(date) > new Date().getTime()) { if (new Date().getDate() - DIASDEVENCIMIENTO > Math.abs(moment(new Date()).diff(new Date(date), "days"))) { setColor("gold"); setName("Por Expirar"); } else { setColor("success"); setName("Habilitado"); } } else { setColor("error"); setName("No Habilitado"); } }, [date]); return ( <span> <Tag color={color} key={date}> {name} </Tag> </span> ); }; export default Expiracion; <file_sep>import React from "react"; import { Space, Button, Tooltip, Popconfirm } from "antd"; import { EyeOutlined, EditOutlined, DeleteOutlined, EyeInvisibleOutlined, FireOutlined, } from "@ant-design/icons"; const Acciones = ({ record, getIdFromTableHelper, changeHotSaleModal, save, cancel, edit, editable, handleEditPromotionHelper, handleDeletePromotionHelper, }) => { return ( <Space size="middle"> <Tooltip title={ Date.parse(record.ExpirationDate) > new Date().getTime() && record.Visible ? "Visible" : "No Visible" } > <Button value={record.id} onClick={(e) => getIdFromTableHelper(e)} disabled={ Date.parse(record.ExpirationDate) > new Date().getTime() ? false : true } type="dashed" shape="circle" size="small" icon={ Date.parse(record.ExpirationDate) > new Date().getTime() && record.Visible ? ( <EyeOutlined /> ) : ( <EyeInvisibleOutlined /> ) } /> </Tooltip> {record.Schedules != null ? ( <Tooltip title={ record.Schedules[0].Enabled ? "Visible (HOT SALE)" : "No Visible (HOT SALE)" } > <Button onClick={(e) => changeHotSaleModal(e, record)} disabled={ record.Schedules != null && Date.parse(record.ExpirationDate) > new Date().getTime() ? false : true } type="dashed" shape="circle" size="small" icon={ <FireOutlined className={ record.Visible && Date.parse(record.ExpirationDate) > new Date().getTime() && record.Schedules != null && record.Schedules[0].Enabled ? "text-warning" : "text-muted" } /> } /> </Tooltip> ) : null} {editable ? ( <span> <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8, }} > Guardar </a> <Popconfirm title="Desea cancelar la edici&oacute;n?" onConfirm={cancel} okText="Confirmar" cancelText="Cancelar" > <a>Cancelar</a> </Popconfirm> </span> ) : ( <Tooltip title="Editar"> <Popconfirm value={record.id} title="Tipo de edici&oacute;n" onConfirm={(e) => edit(e, record)} onCancel={(e) => handleEditPromotionHelper(e, record)} okText={`Parcial`} cancelText={`Completa`} > <Button type="dashed" shape="circle" size="small" icon={<EditOutlined />} /> </Popconfirm> </Tooltip> )} <Tooltip title="Eliminar"> <Button value={record.id} disabled={false} danger type="dashed" shape="circle" size="small" icon={<DeleteOutlined />} onClick={handleDeletePromotionHelper} /> </Tooltip> </Space> ); }; export default Acciones; <file_sep>const assignSameHotSaleAlert = (allPromotion, record, negocioParam) => { let isEqualsNegocio = false; let negocioResult = null; Array.isArray(allPromotion.value) && allPromotion.value.map((data) => { if ( record.id === data.id && record.Negocio !== negocioParam && data.Schedules[0].Enabled && Date.parse(data.ExpirationDate) > Date.parse(new Date()) && Date.parse(data.DateFrom) < Date.parse(new Date()) ) { isEqualsNegocio = true; switch (negocioParam) { case "IU": negocioResult = "IUD\u00DA"; break; case "WM": negocioResult = "Walmart"; break; default: negocioResult = "IUD\u00DA"; break; } } }); return { isEqualsNegocio, negocioResult }; }; export { assignSameHotSaleAlert }; <file_sep>import React, { useEffect } from "react"; import { Route, Switch } from "react-router-dom"; import Promociones from "./dashboard/Promociones"; import Estados from "./dashboard/Estados"; import NotFound from "../components/404"; import { withRouter } from "react-router"; const Routes = () => ( <Switch> <Route exact path={"/listado-promociones"} component={Estados} /> <Route exact path={"/nueva-promocion"} component={Promociones} /> <Route path="*" component={NotFound} /> </Switch> ); export default withRouter(Routes); <file_sep>import { combineReducers } from "redux"; import { connectRouter } from "connected-react-router"; import Config from "./Config"; import promotion from "./promotion"; import auth from "./auth"; export default (history) => combineReducers({ router: connectRouter(history), config: Config, auth: auth, promotions: promotion, }); <file_sep>import { axiosAPI } from "../helpers/axiosAPI"; const controllerAutenticar = async (data) => { try { const response = await axiosAPI.post("/api/autenticar", data); if (response.data !== null) { return response.data; } } catch (error) { return { success: false, message: "No se ha podido establecer la conexion", }; } }; const controllerGetAllPromotions = async () => { try { const response = await axiosAPI.get("/api/allPromotion"); if (response.data != null) { return response.data; } } catch (error) { return { success: false, message: "No se ha podido establecer la conexion", }; } }; const controllerUpdatePromotion = async (data) => { try { const response = await axiosAPI.put("/api/updatePromotion", data); if (response.data != null) { return response.data; } } catch (error) { return { success: false, message: "No se ha podido establecer la conexion", }; } }; const controllerDeletePromotion = async (id) => { try { const response = await axiosAPI.delete(`/api/DeletePromotion/${id}`); if (response.data != null) { return response.data; } } catch (error) { return { success: false, message: "No se ha podido establecer la conexion", }; } }; const controllerCreatePromotion = async (data) => { try { const response = await axiosAPI.post("/api/createPromotion", data); if (response.data != null) { return response.data; } } catch (error) { return { success: false, message: "No se ha podido establecer la conexion", }; } }; export { controllerAutenticar, controllerGetAllPromotions, controllerUpdatePromotion, controllerDeletePromotion, controllerCreatePromotion, }; <file_sep>import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Layout, Menu } from "antd"; import { Link } from "react-router-dom"; import { get_all_promotions } from "../../actions/promotion"; import { PicCenterOutlined, GiftOutlined, LoginOutlined, ShoppingCartOutlined, } from "@ant-design/icons"; const IndexPage = ({ children }) => { const { Item } = Menu; const { allPromotion } = useSelector(({ promotions }) => promotions); const dispatch = useDispatch(); const { Header, Content, Footer } = Layout; const deleteLocalStorageInfo = () => { localStorage.removeItem("tokenExpiration"); localStorage.removeItem("token"); localStorage.removeItem("user"); }; useEffect(() => { allPromotion === null && dispatch(get_all_promotions()); }, [allPromotion]); return ( <Layout style={{ minHeight: "100vh", background: "linear-gradient(to right,#3c71b5,#753c90)!important" }}> <Header className="ant-layout" > <Menu theme="dark" defaultSelectedKeys={["1"]} mode="horizontal" > <Item key="1" icon={<PicCenterOutlined style={{ fontSize: 22 }} />}> <Link style={{ textDecoration: "none" }} to="/listado-promociones"> Estados </Link> </Item> <Item key="2" icon={<GiftOutlined style={{ fontSize: 22 }} />}> <Link style={{ textDecoration: "none" }} to="/nueva-promocion"> Nueva Promoci&oacute;n </Link> </Item> <Item key="4" icon={<LoginOutlined style={{ fontSize: 22 }} />} className="d-flex align-items-center float-right"> <Link style={{ textDecoration: "none" }} to="/login" onClick={deleteLocalStorageInfo} > Salir </Link> </Item> </Menu> </Header> <Content style={{ margin: "0 16px" }}>{children}</Content> <Footer style={{ textAlign: "center" }} className="bg-white py-3"> {`IUD\u00DA © ${new Date().getFullYear()}`} </Footer> </Layout> ); }; export default IndexPage; <file_sep>import React, { useEffect, useState, Fragment } from "react"; import { Link } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import TextField from "@material-ui/core/TextField"; import Alert from "@material-ui/lab/Alert"; import Nprogress from "nprogress"; import IconButton from "@material-ui/core/IconButton"; import Button from "@material-ui/core/Button"; import { loginImageBase64 } from "../helpers/SignIn/signInImageBase64"; import Avatar from "@material-ui/core/Avatar"; import CssBaseline from "@material-ui/core/CssBaseline"; import Input from "@material-ui/core/Input"; import InputLabel from "@material-ui/core/InputLabel"; import Visibility from "@material-ui/icons/Visibility"; import FormControl from "@material-ui/core/FormControl"; import InputAdornment from "@material-ui/core/InputAdornment"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; import Paper from "@material-ui/core/Paper"; import Box from "@material-ui/core/Box"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import LinearProgress from "@material-ui/core/LinearProgress"; import { makeStyles } from "@material-ui/core/styles"; import moment from "moment"; import { Base64 } from "js-base64"; import { save_auth_success, send_credentials } from "../actions/auth"; const useStyles = makeStyles((theme) => ({ image: { backgroundImage: "Url(./Web-Exportada-04.svg)", backgroundColor: theme.palette.type === "light" ? theme.palette.grey[50] : theme.palette.grey[900], backgroundSize: "cover", backgroundPosition: "center", }, paper: { display: "flex", flexDirection: "column", alignItems: "center", height: "100vh", }, avatar: { margin: theme.spacing(1), backgroundColor: "#fff0", width: "auto", height: "auto", marginBottom: "0px", borderRadius: "0%", }, form: { width: "90%", // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), backgroundColor: "rgb(82, 71, 162)", }, load: { width: "100%", "& > * + *": { marginTop: theme.spacing(2), }, }, backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, })); const Login = () => { //styles const classes = useStyles(); //hooks, var & handles const CHARACTER_MIN = 5; var endpoint_save = null; var getInfoUser = null; const TOKEN_KEY = "tr"; //tokenRequest const ENDPOINT = "ep"; //endPoint const SSO_SV = "sk"; //ssoKey const EXPIRES = "ex"; //expires const USER = "us"; //user const CODE = "cd"; //code const NAME_URL = "nu"; //NameUrl const USER_DISPLAY = "ud"; //user display const BASE64_DISPLAY = Base64.encode(USER_DISPLAY); const BASE64_SSO_SV = Base64.encode(SSO_SV); const BASE64_ENDPOINT = Base64.encode(ENDPOINT); const BASE64_TOKEN_KEY = Base64.encode(TOKEN_KEY); const BASE64_EXPIRES = Base64.encode(EXPIRES); const BASE64_USER = Base64.encode(USER); const BASE64_CODE = Base64.encode(CODE); const localCheck = localStorage.getItem(BASE64_SSO_SV); const localUser = localStorage.getItem(BASE64_USER); const localURLSave = localStorage.getItem(BASE64_ENDPOINT); const display_name = localStorage.getItem(BASE64_DISPLAY); const BASE64_NAME_URL = Base64.encode(NAME_URL); const [checked, setChecked] = useState(false); const [btnEnter, setBtnEnable] = useState(true); const [btnEnterSSO, setEnterSSO] = useState(true); const [clickLoading, setClickLoading] = useState(false); const [errorLogin, setErrorLogin] = useState(false); const [changeUser, setChangeUser] = useState(true); const [userPassword, setUserPassword] = useState(""); const [infoUserLocal, setInfoLocal] = useState(""); const [userSSO, setUserSSO] = useState(""); const [values, setValues] = React.useState({ password: "", showPassword: false, }); const [messageAuth, setMessageAuth] = useState(null); const dispatch = useDispatch(); const { success, message, data } = useSelector(({ auth }) => auth); useEffect(() => { //#region document.title = "Login Promociones - IUD\u00DA"; //#endregion if (message !== null && !success) { setMessageAuth(message); setErrorLogin(true); } else { setClickLoading(false); } //inicializa como url "/listado-promociones" siempre que el usuario este logueado correctamente. if ( localStorage.getItem("user") === "true" && !moment(new Date()).isAfter(localStorage.getItem("tokenExpiration")) && window.location.pathname === "/login" ) { window.location.href = "/listado-promociones"; }else{ localStorage.removeItem("token"); localStorage.removeItem("tokenExpiration"); localStorage.removeItem("user"); } }, [success, message, data]); const handleChangeCheck = (event) => { setChecked(event.target.checked); if (!event.target.checked) { localStorage.removeItem(BASE64_SSO_SV); } }; const handleChange = (prop) => (event) => { setValues({ ...values, [prop]: event.target.value }); hanleInput(event); }; const handleClickShowPassword = () => { setValues({ ...values, showPassword: !values.showPassword }); }; const hanleInput = (e) => { setUserPassword(e.target.value); if (e.target.value.length > CHARACTER_MIN && btnEnterSSO != true) { setBtnEnable(false); } else if (e.target.value.length > CHARACTER_MIN && infoUserLocal != "") { setBtnEnable(false); } else { setBtnEnable(true); } }; const hanleKeyEnter = (event) => { if (event.key === "Enter") { callApi(); } }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; const hanleInputSSO = (e) => { setUserSSO(e.target.value); if (e.target.value.length > CHARACTER_MIN) { setEnterSSO(false); } else { setEnterSSO(true); } }; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {"Copyright "} &copy;&nbsp;&nbsp; <a target="_blank" href="https://iudu.com.ar"> IUD&Uacute; </a>{" "} {new Date().getFullYear()} {"."} </Typography> ); } //**Call controller function callApi() { dispatch(save_auth_success(false)); setClickLoading(true); dispatch( send_credentials({ sso: Base64.encode(userSSO), password: <PASSWORD>(<PASSWORD>), }) ); } const hanleChangeUser = () => { localStorage.removeItem(BASE64_SSO_SV); localStorage.removeItem(BASE64_ENDPOINT); localStorage.removeItem(BASE64_CODE); localStorage.removeItem(BASE64_NAME_URL); localStorage.removeItem(BASE64_TOKEN_KEY); localStorage.removeItem(BASE64_EXPIRES); localStorage.removeItem(BASE64_USER); }; return ( <Fragment> {clickLoading && <LinearProgress />} <Grid container component="main"> <CssBaseline /> <Grid item xs={false} sm={4} md={7} className={classes.image} /> <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> <div className={`${classes.paper}`}> <div className="animated fast fadeIn"> <Avatar className={classes.avatar}> <img className="m-4" src="https://www.iudu.com.ar/wp-content/uploads/2020/11/iudu_logo_solo.svg" style={{ width: 200 }} /> </Avatar> </div> <div className="text-center"> <div style={{ fontSize: "25px" }}>IUD&Uacute;</div> <div style={{ fontSize: "13px" }} className="text-muted"> Promociones </div> </div> <div className={classes.form} noValidate> {infoUserLocal == "" && ( <TextField margin="normal" required fullWidth label="SSO" autoFocus autoComplete="off" onKeyPress={hanleKeyEnter} onChange={hanleInputSSO} /> )} <FormControl fullWidth> <InputLabel autoComplete={"off"} required htmlFor="standard-adornment-password" > Contrase&ntilde;a </InputLabel> <Input id="standard-adornment-password" margin="normal" autoComplete="off" label="Contrase&ntilde;a" type={values.showPassword ? "text" : "password"} value={values.password} onKeyPress={hanleKeyEnter} onChange={handleChange("password")} endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} > {values.showPassword ? ( <Visibility /> ) : ( <VisibilityOff /> )} </IconButton> </InputAdornment> } /> </FormControl> {errorLogin && <Alert severity="error">{messageAuth}</Alert>} <Button fullWidth variant="contained" color="primary" size="small" disabled={btnEnter} className={classes.submit} onClick={() => { callApi(); }} > Iniciar Sesion </Button> <Box mt={5}> <Copyright /> </Box> </div> </div> </Grid> </Grid> </Fragment> ); }; export default Login; <file_sep>import React, { useEffect } from "react"; import moment from "moment"; import { createBrowserHistory } from "history"; import { Redirect, Route, Switch } from "react-router-dom"; import AppLayout from "../containers/AppLayout"; import "bootstrap/dist/css/bootstrap.min.css"; import Login from "../containers/Login"; const RestrictedRoute = ({ component: Component, authUser, expiresJWT, ...rest }) => ( <Route {...rest} render={(props) => authUser && expiresJWT ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location }, }} /> ) } /> ); const App = () => { const history = createBrowserHistory(); const isAuth = localStorage.getItem("user") !== null; const expires = localStorage.getItem("tokenExpiration") !== null && !moment(new Date()).isAfter(localStorage.getItem("tokenExpiration")); return ( <div className="app-main"> <Switch> <Route exact path="/login" component={Login} /> <RestrictedRoute path="/" authUser={isAuth} expiresJWT={expires} component={AppLayout} /> </Switch> </div> ); }; export default App; <file_sep>const { Router } = require("express"); const router = Router(); const UserController = require("../../controllers/auth"); router.post("/autenticar", UserController.authenticacion); module.exports = router;<file_sep>import React, { useEffect, useState } from "react"; import { Modal, Col, message } from "antd"; import { ExclamationCircleOutlined } from "@ant-design/icons"; const ModalVisible = ({ dataPut, showModal, handleOkModal, confirmLoading, handleCloseModal, textActionModal, }) => { const [imgPutVisible, setImgPutVisible] = useState(null); const [imgTypePutVisible, setTypeImgPutVisible] = useState(null); useEffect(() => { try { if ( dataPut !== null && dataPut.Benefits !== null && dataPut.Benefits.Image !== null ) { setImgPutVisible(dataPut.Benefits.Image.Payload); setTypeImgPutVisible(dataPut.Benefits.Image.MimeType); } } catch (error) { message.error("No se pudo cargar la imagen correctamente"); } }, [dataPut]); return ( <Modal title={ <span className="row"> <ExclamationCircleOutlined style={{ fontSize: 23 }} className="text-warning pr-3 pl-3" />{" "} Desea realizar esta acci&oacute;n? </span> } visible={showModal} onOk={handleOkModal} confirmLoading={confirmLoading} onCancel={handleCloseModal} okText="Confirmar" cancelText="Cancelar" > <div className="text-center pb-2"> {`Una vez confirmado, se ${ textActionModal ? `ocultar\u00E1` : `har\u00E1 visible` } la promoci\u00F3n.`} </div> <Col className="col-12"> <img className="shadow rounded" alt="example" style={{ width: "100%" }} src={`data:${imgTypePutVisible};base64,${imgPutVisible}`} /> </Col> </Modal> ); }; export default ModalVisible; <file_sep>import { CONFIG_INITIAL } from "../constants/ActionTypes"; const initialConfig = { id: null, }; export default (state = initialConfig, action) => { switch (action.type) { case CONFIG_INITIAL: { return { ...state, id: action.payload, }; } default: return state; } };
e3dd4f70f9b14459fcd55f0251eb963119b7db8c
[ "JavaScript", "Markdown" ]
31
JavaScript
baucl/Promotions
449fef772928ac12fa2a844e9ee840e8c733369f
ba1da2cbc3bd72612c2464190425bede92761589
refs/heads/master
<repo_name>hexnova/JBlockly<file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/input/Inputer.java package com.github.mousesrc.jblockly.fx.input; public interface Inputer<T> { String getName(); void setName(String name); T getValue(); void setValue(T value); @SuppressWarnings("unchecked") default void set(Object value) throws ClassCastException { setValue((T)value); } default boolean hasValue() { return getValue() != null; } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/extra/FXBlockEditor.java package com.github.mousesrc.jblockly.fx.extra; import com.github.mousesrc.jblockly.fx.FXBlockWorkspace; import com.github.mousesrc.jblockly.fx.extra.skin.FXBlockEditorSkin; import javafx.scene.control.Control; import javafx.scene.control.Skin; public class FXBlockEditor extends Control { private FXBlockWorkspace workspace; public final FXBlockWorkspace getWorkspace() { return workspace; } public FXBlockEditor() { getStyleClass().setAll("block-editor"); } @Override protected Skin<?> createDefaultSkin() { return new FXBlockEditorSkin(this); } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/model/BlockParser.java package com.github.mousesrc.jblockly.model; import java.io.Reader; import java.lang.reflect.Type; import java.util.Map; import java.util.Map.Entry; import com.github.mousesrc.jblockly.util.DataContainer; import com.github.mousesrc.jblockly.util.DataContainer.DataContainerSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class BlockParser { public static final Gson GSON = new GsonBuilder() .registerTypeAdapter(Block.class, new BlockSerializer()) .registerTypeAdapter(BlockRow.class, new BlockRowSerializer()) .registerTypeAdapter(DataContainer.class, new DataContainerSerializer()) .create(); public static Block fromJson(String json) { return GSON.fromJson(json, Block.class); } public static Block fromJson(Reader reader) { return GSON.fromJson(reader, Block.class); } public static String toJson(Block block) { return GSON.toJson(block); } public static void toJson(Block block, Appendable writer) { GSON.toJson(block, writer); } public static JsonElement toJsonTree(Block block) { return GSON.toJsonTree(block); } public static class BlockSerializer implements JsonSerializer<Block>, JsonDeserializer<Block> { @Override public Block deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); Block block = new Block(); if(object.has("name")) block.setName(object.get("name").getAsString()); if(object.has("properties")) block.getProperties().putAll(context.deserialize(object.get("properties"), Map.class)); JsonObject rows = object.get("rows").getAsJsonObject(); for(Entry<String, JsonElement> entry : rows.entrySet()) block.getRowToNames().put(context.deserialize(entry.getValue(), BlockRow.class), entry.getKey()); return block; } @Override public JsonElement serialize(Block src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.addProperty("name", src.getName().orElse(null)); if(src.hasProperties()) object.add("properties", context.serialize(src.getProperties())); object.add("rows", context.serialize(src.getRowToNames().inverse())); return object; } } public static class BlockRowSerializer implements JsonSerializer<BlockRow>, JsonDeserializer<BlockRow> { @Override public BlockRow deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); BlockRow row = new BlockRow(); if(object.has("block")) row.setBlock(context.deserialize(object.get("block"), Block.class)); if(object.has("data")) row.getData().getDatas().putAll(context.<DataContainer>deserialize(object.get("data"), DataContainer.class).getDatas()); return row; } @Override public JsonElement serialize(BlockRow src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if(src.hasBlock()) object.add("block", context.serialize(src.getBlock().get())); if(!src.getData().isEmpty()) object.add("data", context.serialize(src.getData())); return object; } } } <file_sep>/src/test/java/com/github/mousesrc/jblockly/BlockParserTest.java package com.github.mousesrc.jblockly; import static org.junit.Assert.*; import org.junit.Test; import com.github.mousesrc.jblockly.model.Block; import com.github.mousesrc.jblockly.model.BlockParser; import com.github.mousesrc.jblockly.model.BlockRow; public class BlockParserTest { @Test public void test() { Block root = new Block(); root.setName("root"); BlockRow row1 = new BlockRow(); root.addRow(row1, "row1"); Block child = new Block(); row1.setBlock(child); row1.getData().add("data1", 1); String json = BlockParser.toJson(root); System.out.println(json); Block deserialized = BlockParser.fromJson(json); int data1 = (int)deserialized.getRow("row1").get().getData().get("data1").get(); System.out.println(BlockParser.toJson(deserialized)); } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/tool/BlockCreator.java package com.github.mousesrc.jblockly.fx.tool; public class BlockCreator { } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/extra/FXBlockSettingEditor.java package com.github.mousesrc.jblockly.fx.extra; public class FXBlockSettingEditor { } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/input/TextFieldInputer.java package com.github.mousesrc.jblockly.fx.input; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.TextField; public class TextFieldInputer extends TextField implements Inputer<String>{ public final StringProperty nameProperty(){ if(name == null) name = new SimpleStringProperty(this, "name"); return name; } private StringProperty name; public final String getName() {return name == null ? null : nameProperty().get();} public final void setName(String name) {nameProperty().set(name);} @Override public String getValue() { return getText(); } @Override public void setValue(String value) { setText(value); } public TextFieldInputer() { } public TextFieldInputer(String text) { super(text); } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/util/FXHelper.java package com.github.mousesrc.jblockly.fx.util; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; public interface FXHelper { static Bounds addBounds2D(Bounds bounds, double x, double y) { return new BoundingBox(bounds.getMinX() + x, bounds.getMinY() + y, bounds.getWidth(), bounds.getHeight()); } static Bounds subtractBounds2D(Bounds bounds, double x, double y) { return new BoundingBox(bounds.getMinX() - x, bounds.getMinY() - y, bounds.getWidth(), bounds.getHeight()); } static double boundedSize(double min, double pref, double max) { double a = pref >= min ? pref : min; double b = min >= max ? min : max; return a <= b ? a : b; } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/input/CheckBoxInputer.java package com.github.mousesrc.jblockly.fx.input; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.CheckBox; public class CheckBoxInputer extends CheckBox implements Inputer<Boolean>{ public final StringProperty nameProperty(){ if(name == null) name = new SimpleStringProperty(this, "name"); return name; } private StringProperty name; public final String getName() {return name == null ? null : nameProperty().get();} public final void setName(String name) {nameProperty().set(name);} public CheckBoxInputer() { } public CheckBoxInputer(String text) { super(text); } @Override public Boolean getValue() { return isSelected(); } @Override public void setValue(Boolean value) { setSelected(value); } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/util/BlockProviderBase.java package com.github.mousesrc.jblockly.fx.util; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import com.github.mousesrc.jblockly.fx.FXBlock; public abstract class BlockProviderBase implements BlockProvider{ private final String name; private final Map<String, Object> properties = new HashMap<>(); public BlockProviderBase(String name) { this.name = Objects.requireNonNull(name); } @Override public String getName() { return name; } public Map<String, Object> getProperties() { return properties; } public Set<String> getPropertyKeys() { return getProperties().keySet(); } @SuppressWarnings("unchecked") public <V> Optional<V> getProperty(String key) { return Optional.ofNullable((V)getProperties().get(key)); } @SuppressWarnings("unchecked") public <V> Optional<V> getProperty(String key, Class<V> type) { Object value = getProperties().get(key); return type.isAssignableFrom(value.getClass()) ? Optional.of((V) value) : Optional.empty(); } public <V> void addProperty(String key, V value) { getProperties().put(key, value); } public void removeProperty(String key) { getProperties().remove(key); } public boolean containsProperty(String key) { return getProperties().containsKey(key); } protected FXBlock preCreate() { FXBlock block = new FXBlock(); block.setName(getName()); return block; } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/input/ToggleButtonInputer.java package com.github.mousesrc.jblockly.fx.input; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.Node; import javafx.scene.control.ToggleButton; public class ToggleButtonInputer extends ToggleButton implements Inputer<Boolean> { public final StringProperty nameProperty(){ if(name == null) name = new SimpleStringProperty(this, "name"); return name; } private StringProperty name; public final String getName() {return name == null ? null : nameProperty().get();} public final void setName(String name) {nameProperty().set(name);} @Override public Boolean getValue() { return isSelected(); } @Override public void setValue(Boolean value) { setSelected(value); } public ToggleButtonInputer() { } public ToggleButtonInputer(String text) { super(text); } public ToggleButtonInputer(String text, Node graphic) { super(text, graphic); } } <file_sep>/src/main/java/com/github/mousesrc/jblockly/fx/util/JsonBlockProvider.java package com.github.mousesrc.jblockly.fx.util; import com.github.mousesrc.jblockly.fx.FXBlock; public class JsonBlockProvider extends BlockProviderBase { public JsonBlockProvider(String name, String json) { super(name); } @Override public FXBlock create() { return null; } }
38bf5142df62cc23c7ab0f90ba2a8f824616e012
[ "Java" ]
12
Java
hexnova/JBlockly
c32f3f0f90fd30d17b47618e3cf2c06fd36456fb
e4b92c439ac9a38da1216f567784e12323220ef9
refs/heads/master
<file_sep># swagger笔记 1. 第一步:添加jar包 ```xml <!-- swagger2 文档 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> ``` 2. 第二步:添加配置代码 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration //让Spring来加载该类配置 @EnableSwagger2 //启用Swagger2 public class Swagger2 { //如果需要多个文档,多加该方法就行 @Bean public Docket test() { return new Docket(DocumentationType.SWAGGER_2) .groupName("swagger测试接口文档") .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.rock"))//配置需要扫描的包 .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Rock工作文档") //创建人信息 .contact(new Contact("rock","","<EMAIL>")) //描述 .description("工作中遇到的需求记录,如果你有好的例子,请联系:<EMAIL>") //版本 .version("1.0").build(); } } ``` 3. 第三步:测试代码 实体类代码 ```java import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel public class TestInfo { @ApiModelProperty(value = "自增主键") private long id; @ApiModelProperty(value = "姓名") private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "TestInfo{" + "id=" + id + ", name='" + name + '\'' + '}'; } } ``` controller代码: ```java import com.rock.req.TestInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; @Api(value = "swagger测试接口") @RestController @RequestMapping(value = "/Swagger") public class SwaggerController { @ApiOperation(value = "查询全部") @RequestMapping(value = "/getByName/name/{name}", method = RequestMethod.GET) public String getByName(@PathVariable("name") String name) { System.out.println(name); return "/getByName"; } //@ApiIgnore//使用该注解忽略这个API @ApiOperation(value = "删除全部") @RequestMapping(value = "/getTestInfo", method = RequestMethod.POST) public TestInfo getTestInfo(@RequestBody TestInfo testInfo) { System.out.println(testInfo.toString()); return testInfo; } } ``` 4. 第四步:启动项目 访问:http://1192.168.3.11:8080/项目访问路径(没有配置就不用加)/swagger-ui.html 5. Swagger常用注解 | 注解 | <center>用法</center> | |--------|--------| |@Api|用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源 | |@ApiOperation|用在方法上,说明方法的作用,每一个url资源的定义| |@ApiModel|用在实体类上,描述一个实体| |@ApiModelProperty|用在实体的属性上,描述一个属性| <file_sep>package com.rock.Utils; import com.rock.model.TreeNode; import java.util.ArrayList; import java.util.List; public class ListToTree { public static void main(String[] args) { List<TreeNode> list = new ArrayList<>(); TreeNode treeNode4 = new TreeNode(5L, "四级节点", 4); TreeNode treeNode5 = new TreeNode(6L, "五级节点", 5); TreeNode treeNode6 = new TreeNode(7L, "六级节点", 6); TreeNode treeNode = new TreeNode(1L, "根节点", 0); TreeNode treeNode1 = new TreeNode(2L, "一级节点", 1); TreeNode treeNode2 = new TreeNode(3L, "二级节点", 2); TreeNode treeNode3 = new TreeNode(4L, "三级节点", 2); TreeNode treeNode7 = new TreeNode(8L, "七级节点", 7); TreeNode treeNode8 = new TreeNode(91L, "一级节点", 1); TreeNode treeNode9 = new TreeNode(10L, "一级节点", 1); TreeNode treeNode10 = new TreeNode(11L, "根节点", 0); list.add(treeNode); list.add(treeNode1); list.add(treeNode2); list.add(treeNode10); list.add(treeNode9); List<TreeNode> tree = getTree(list); } public static List<TreeNode> getTree(List<TreeNode> list) { List<TreeNode> reult = new ArrayList<TreeNode>(); for (TreeNode node1 : list) { boolean mark = false; for (TreeNode node2 : list) { if (node1.getParentId() != 0 && node1.getParentId() == node2.getId()) { mark = true; if (node2.getChildList() == null) node2.setChildList(new ArrayList<TreeNode>()); node2.getChildList().add(node1); break; } } if (!mark) { reult.add(node1); } } return reult; } } <file_sep>package com.rock.Utils; import java.io.*; import java.util.ArrayList; import java.util.List; public class TxtUtils { /** * 获取文件编码格式 * * @param file TXT文件路径 * @return 文件编码格式 * @throws IOException */ public static String getChatset(String file) throws IOException { BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file)); int p = (bin.read() << 8) + bin.read(); bin.close(); String code = null; switch (p) { case 0xefbb: case 0xe6b5: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; } return code; } /** * 一行一行读取文件 * * @param txtFile TXT文件路径 * @return 结果集 */ public static List<String> readLine(String txtFile) { List<String> result = new ArrayList<String>(); BufferedReader reader = null; FileInputStream fileInputStream = null; InputStreamReader isr = null; try { fileInputStream = new FileInputStream(txtFile); isr = new InputStreamReader(fileInputStream, getChatset(txtFile)); reader = new BufferedReader(isr); //读取Txt文件内容 String tempString = null; //一行一行读 while ((tempString = reader.readLine()) != null) { result.add(tempString); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (reader != null) { reader.close(); } if (isr != null) { isr.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 写TXT文件 * * @param contentList 内容集合,一个为一行 * @param filePath 存储路径 * @param fileName 文件名,带后缀 * @param ChangeLine 是否换行 * @param encoding 编码格式 * @throws IOException */ public static void writeLine(List<String> contentList, String filePath, String fileName, boolean ChangeLine, String encoding) throws IOException { //文件路径 File file = new File(filePath + "/" + fileName); //是否存在,不存在则创建 if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); // 创建新文件 } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), encoding); BufferedWriter out = new BufferedWriter(write); //一行一行写 if (ChangeLine) { //换行 for (String content : contentList) { out.write(content + "\r\n"); } } else { for (String content : contentList) { out.write(content); } } out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } } <file_sep>package com.rock.Utils; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class FTPUtils { private static Logger LOG = LogManager.getLogger(FTPUtils.class); /** * 获取FTPClient对象 * * @param host 连接地址 * @param port 端口 * @param userName 用户名 * @param password 密码 * @return * @throws IOException */ public static FTPClient getConnect(String host, int port, String userName, String password) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port); ftpClient.login(userName, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return ftpClient; } /** * 下载文件 * * @param ftpClient ftpClient * @param filename 文件名 * @param localpath 本地存储地址 * @return */ public static boolean downloadFile(FTPClient ftpClient, String filename, String localpath) { boolean status = false; OutputStream os = null; try { LOG.info("开始下载文件,文件名为:{}", filename); //判断文件夹是否存在 File file = new File(localpath); if (!file.isDirectory()) { file.mkdirs(); } File localFile = new File(localpath + "/" + filename); os = new FileOutputStream(localFile); status = ftpClient.retrieveFile(filename, os); } catch (Exception e) { LOG.error("下载文件出错"); e.printStackTrace(); } finally { if (null != os) { try { os.close(); } catch (IOException e) { LOG.error("关闭流失败,{}", e.getMessage()); } } } return status; } } <file_sep>package com.rock.Utils; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.model.FileHeader; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Expand; import java.io.File; import java.util.ArrayList; import java.util.List; public class ZipUtils { public static void main(String[] args) { List<String> unzip = unzip("D:\\uploads\\20181101_ztry.zip", "D:\\uploadssss"); } /** * 解压文件 * * @param fileSource 压缩包路径 * @param decompressionFile 解压后文件的目录, */ public static List<String> unzip(String fileSource, String decompressionFile) { ArrayList<String> result = new ArrayList<String>(); try { File zipFile = new File(fileSource); ZipFile zFile = new ZipFile(zipFile); // 首先创建ZipFile指向磁盘上的.zip文件 zFile.setFileNameCharset("GBK"); File destDir = new File(decompressionFile);// 解压目录 zFile.extractAll(decompressionFile);// 将文件抽出到解压目录(解压) //region 输出解压文件里面每个文件的文件名 List<FileHeader> headerList = zFile.getFileHeaders(); List<File> extractedFileList = new ArrayList<File>(); for (FileHeader fileHeader : headerList) { if (!fileHeader.isDirectory()) { extractedFileList.add(new File(destDir, fileHeader.getFileName())); } } File[] extractedFiles = new File[extractedFileList.size()]; extractedFileList.toArray(extractedFiles); for (File f : extractedFileList) { result.add(f.getName()); } //endregion } catch (Exception e) { e.printStackTrace(); } return result; } /** * 解压文件 * * @param zipFilepath 需要被解压的zip文件路径 * @param destDir 解压到哪个文件夹 * @return */ public static List<String> unzipAnt(String zipFilepath, String destDir) { if (!new File(zipFilepath).exists()) { System.out.println("文件夹不存在"); } Project proj = new Project(); Expand expand = new Expand(); expand.setProject(proj); expand.setTaskType("unzip"); expand.setTaskName("unzip"); expand.setEncoding("GBK"); expand.setSrc(new File(zipFilepath)); expand.setDest(new File(destDir)); expand.execute(); List<String> allFileName = getAllFileName(destDir); return allFileName; } /** * 获取文件夹下面所有文件的名称 * * @param path 路径 * @return 文件名的集合 */ public static List<String> getAllFileName(String path) { List<String> fileNames = new ArrayList<String>(); File f = new File(path); if (!f.exists()) { return null; } File fa[] = f.listFiles(); for (int i = 0; i < fa.length; i++) { File fs = fa[i]; if (fs.isDirectory()) { getAllFileName(path + "/" + fs.getName()); } else { fileNames.add(fs.getName()); } } return fileNames; } }
25eaddfeea4b75cf604290495c1fae04b1ea2bce
[ "Markdown", "Java" ]
5
Markdown
knightw23/Demo
1410e710697d53fd9dd5d6b0cd5b83f050639926
37238192046c4d0d4c050c3aab86dddf4937e695
refs/heads/master
<file_sep>import copy import os import random import sys import simplejson import time import couchdb import flickrapi import utils import config import datetime assert config.IMAGE_DIR, "You need to specify a directory to write images to in config.py" assert os.path.isdir(config.IMAGE_DIR), "Your config.IMAGE_DIR does not specify a valid directory!" assert config.OFFLINE_DIR, "You need to specify an offline directory" assert os.path.isdir(config.OFFLINE_DIR), "You need to specify a valid offline directory" assert config.COUCHDB_CONNECTION_STRING, "You need to specify a couchdb connection string in config.py" ''' Passage length parameters ''' max_lines_per_passage = 9 max_chars_per_line = 25 max_passages = 20 ''' Flickr search parameters ''' flickr_api_key = '0d5347d0ffb31395e887a63e0a543abe' _flickr = flickrapi.FlickrAPI(flickr_api_key) remove_all_stop_words = True min_taken_date_filter = '946706400' #1/1/2000 #'1262325600' #1/1/2010 safe_search_filter = 1 ''' Image parameters ''' max_original_width, min_original_width = 3600, 1200 max_original_height, min_original_height = 2400, 800 default_image = 'http://farm5.static.flickr.com/4048/4332307799_2db1a391f0_o.jpg' ''' Global properties ''' selected_images = [] db = couchdb.Server(config.COUCHDB_CONNECTION_STRING)['imagination'] filenames = {'Buddhism':'buddha.json', 'Christianity':config.OFFLINE_DIR + 'bible.json', 'Hinduism':config.OFFLINE_DIR + 'vedas.json', 'Islam':config.OFFLINE_DIR + 'quran.json'} files_to_delete = [] records_to_delete = [] ''' Given a filename, this opens the file, enumerates through the books and versus to return the maximum allowed number of passages ''' def load_passages(filename): text = simplejson.load(open(filename, 'r')) num_passages_yielded = 0 while True: #for book in text: book = choose_random_book(text) lines = [] curr_line = [] char_count = 0 for verse in book['verses']: for word in verse.split(): if char_count + 1 + len(word) < max_chars_per_line: curr_line.append(word) char_count += len(word) else: lines.append(' '.join(curr_line)) if len(lines) == max_lines_per_passage: yield lines num_passages_yielded += 1 if num_passages_yielded >= max_passages: return lines = [] curr_line = [word] char_count = 0 ''' Selects a random book from the text and removes it from the list ''' def choose_random_book(text): index = random.randint(0, len(text) - 1) book = text[index] text.pop(index) return book ''' Selects a random number between 0 and the length of the string ''' def choose_line_index(passage): return random.randint(0, len(passage) - 1) ''' Gets the URL to the original version of the image, if it's available ''' def _sizeAndURLOfImage(photo_el): sizes_el = _flickr.photos_getSizes(photo_id=photo_el.attrib['id']) for size in sizes_el.findall(".//size"): if size.attrib['label'] == 'Original': return ((int(size.attrib['width']), int(size.attrib['height'])), size.attrib['source']) return ((-1, -1), '') def find_image(line): if remove_all_stop_words: clean_line = utils.strip_all_stop_words(line) else: clean_line = utils.sStripStopWords(line) if not clean_line: return '' try: for photo in _flickr.walk(text=clean_line, sort='interestingness-desc', per_page='20', content_type='1', min_taken_date=min_taken_date_filter, safe_search=safe_search_filter): (width, height), url = _sizeAndURLOfImage(photo) if url: photo_id = photo.attrib['id'] #we have a max here, because my network or PIL doesn't like 11k by 8k pictures #if not photo_id in selected_images and max_original_width > width > min_original_width and max_original_height > height > min_original_height: if not photo_id in selected_images and width > min_original_width and height > min_original_height: print clean_line print url print selected_images.append(photo_id) return url except Exception, e: print 'An error occurred while performing a flickr API search', e return '' ''' Saves 3 copies of the image to the local directory and persists the record to the db ''' def store_passage(religion, passage, passage_num, line_index, image_url): # set defaults if no image was found if line_index == '': line_index = -1 if not image_url: image_url = default_image file_ending = image_url.rpartition('.')[-1] out_filenames = ['%s_%s.%s' % (int(time.time() * 1000), i, file_ending) for i in range(3)] # saves three copies of the image to the stored_images directory utils.crop_images(image_url, *[os.path.join(config.IMAGE_DIR, f) for f in out_filenames]) # persists the record to the db record = {'religion':religion, 'passage':passage, 'passage_num':passage_num, 'selected_line':line_index, 'images':out_filenames} try: db.save(record) except Exception, e: print 'An error occurred while saving the record to the db, trying again...' db.save(record) ''' Given a passage, this randomly selects a line from the passage and returns the line index and image url ''' def run_passage(passage): for verse in passage: print verse print destructable_passage = copy.copy(passage) while True: # infinite loop line_index = choose_line_index(destructable_passage) image_url = find_image(destructable_passage[line_index]) if not image_url: del[destructable_passage[line_index]] if not destructable_passage: return ('', '') continue break # break the infinite loop if I have a valid image_url return (line_index, image_url) ''' Given a religion name (e.g. filename) this loads the passages, finds an image, and stores the results in the db ''' def run_religion(religion): filename = filenames[religion] passages = load_passages(filename) for passage_num, passage in enumerate(passages): line_index, image_url = run_passage(passage) store_passage(religion, passage, passage_num, line_index, image_url) ''' Deletes all passages from the db while preserving any views you may have ''' def delete_all_passages(): now = datetime.datetime.now() for doc_id in db: if not doc_id.startswith('_design'): # do not delete any views we have saved! db.delete(db[doc_id]) print 'deleted ', doc_id for filename in os.listdir(config.IMAGE_DIR): os.remove(os.path.join(config.IMAGE_DIR, filename)) def delete_old_passages(): for record_id in records_to_delete: if record_id in db: db.delete(db[record_id]) print 'deleted ', record_id for filename in files_to_delete: if os.path.exists(filename): os.remove(filename) print 'removed file', filename def flag_files_for_deletion(): for filename in os.listdir(config.IMAGE_DIR): files_to_delete.append(os.path.join(config.IMAGE_DIR, filename)) def flag_records_for_deletion(): for doc in db.view('_design/religions/_view/religions'): records_to_delete.append(doc.id) def run(): print_with_time('Starting create passages...') flag_files_for_deletion() flag_records_for_deletion() run_religion('Christianity') run_religion('Hinduism') run_religion('Islam') delete_old_passages() print_with_time('Finished creating passages...') def print_with_time(text): print text, datetime.datetime.now() if __name__ == '__main__': run() <file_sep>import BeautifulSoup import simplejson import utils as u def _scrape_book(html): ret = [] doc = BeautifulSoup.BeautifulSoup(html) for p in doc.findAll('p'): if p.string: ret.append(p.string.strip()) return ret def scrape_book(url): '''Takes a url like http://www.sacred-texts.com/bud/btg/btg56.htm Returns a list of strings, each verse-ish.''' return u.scrapeWith(url, _scrape_book) def _scrape_index(html): ret = [] base_url = 'http://www.sacred-texts.com/bud/btg/' doc = BeautifulSoup.BeautifulSoup(html) for i, a_tag in enumerate(doc.findAll('a')): if i < 4: #skip garbage, preface, etc. continue book = {'name':a_tag.string, 'url':base_url + a_tag['href']} ret.append(book) return ret def scrape_index(url): '''Takes a url like http://www.sacred-texts.com/bud/btg/index.htm. Returns a list of dictionaries, each with 'name' and 'url' keys (url for scrape_book)''' return u.scrapeWith(url, _scrape_index) def scrape_all_and_store(): '''This is the main function to call. It will scrape the whole page, and write out buddha.json. Buddha.json is a list of dictionaries. Each dictionary has a 'book_name' and 'verses' keys. 'verses' is a list of verses.''' index_url = 'http://www.sacred-texts.com/bud/btg/index.htm' filename = 'buddha.json' buddha = [] for i, book in enumerate(scrape_index(index_url)): verses = scrape_book(book['url']) print 'Scraping #%s, %s...' % (i, book['name']) buddha.append({'book_name':book['name'], 'verses':verses}) print 'Done scraping, dumping...' simplejson.dump(buddha, open(filename, 'w')) if __name__ == '__main__': scrape_all_and_store() # for verse in scrape_book('http://www.sacred-texts.com/bud/btg/btg56.htm'): # print verse # for book in scrape_index('http://www.sacred-texts.com/bud/btg/index.htm'): # print book<file_sep>//As of May 27, 2010 { "_id": "_design/religions", "_rev": "5-d477e4839358b85c28dea23196c1524a", "views": { "religions": { "map": "function(doc) {emit([doc['religion'], doc['passage_num']], doc);}" } } }<file_sep>WEB_CACHE_DIR = 'C:\cygwin\home\Shawn\ImaginationEnvironment\webcache' IMAGE_DIR = 'C:\cygwin\home\Shawn\ImaginationEnvironment\static\stored_images' PATH_TO_STOP_WORDS_LIST = 'C:\cygwin\home\Shawn\ImaginationEnvironment\offline\stop_words.lst' OFFLINE_DIR = 'C:\cygwin\home\Shawn\ImaginationEnvironment\offline\' COUCHDB_CONNECTION_STRING = 'http://127.0.0.1:5984' <file_sep>var sys = require("sys"), events = require("events"), CouchDB = require('./couchdb').CouchDB; CouchDB.debug = false; var debug = true; var emitter = new events.EventEmitter(); var screens = []; //var db = CouchDB.db('imagination', 'http://yorda.cs.northwestern.edu:5984'); // note: Use the IP address, not localhost. I was receiving a DNS error with localhost. var db = CouchDB.db('imagination', 'http://127.0.0.1:5984'); /*var currIndices = {Christianity:1, Hinduism:1, Buddhism:1};*/ exports.get_screen_emitter = function () {return emitter}; /*Creates an array of 9 screens*/ exports.setup = function() { for (var i = 0; i < 9; i++) { var screen_ = {}; screen_.id = i; screen_.image_url = 'http://infolab.northwestern.edu/media/uploaded_images/featured_illumination.jpg'; screen_.text0 = 'Welcome to'; screen_.text1 = 'the'; screen_.text2 = 'Imagination Environment'; screens.push(screen_); } } function updateScreen(screen_index) { if (debug) sys.puts('screens.js - updateScreen() - screen_index = ' + screen_index); emitter.emit('screen', screens[screen_index]); } var categoryIndices = []; categoryIndices['Christianity'] = 0; categoryIndices['Hinduism'] = 0; //categoryIndices['Buddhism'] = 0; categoryIndices['Islam'] = 0; exports.run = function() { setTimeout(function() { runCategory('Christianity', 0); }, 1000); setTimeout(function() { runCategory('Islam', 1); }, 11000); setTimeout(function() { runCategory('Hinduism', 2); }, 21000); } function runCategory(category, column) { setInterval(function() { nextCategory(category, column); }, 50000); nextCategory(category, column); } function nextCategory(category, column) { db.view("religions/religions", { key: [category, categoryIndices[category]], success: function(result){ if (result.rows.length == 0) // no results returned, we must have reached our max. start over. { categoryIndices[category] = 0; nextCategory(category, column); } else { handleCouchResult(result, column); } } }); categoryIndices[category]++; } function randElement(arr) { var index = Math.floor(Math.random() * arr.length); return arr[index]; } function handleCouchResult(result, column_index) { //I hope you like array math! try { result = result.rows[0].value; } catch(e) { return; } result.passage[result.selected_line] = '<span class="key">' + result.passage[result.selected_line] + '</span>'; if (debug) sys.puts(result.passage[result.selected_line]); for (var i = 0; i < 9; i++) { var three_count = Math.floor(i / 3); var screen_index = three_count * 3 + column_index; var text_key = 'text' + (i % 3); screens[screen_index][text_key] = result.passage[i]; if (!(i % 3)) { // only do this once per screen, no need to do 3 times screens[screen_index].image_url = 'stored_images/' + result.images[three_count]; screens[screen_index].rippleDelay = 10000 * three_count; } if (i % 3 == 2) updateScreen(screen_index); } } <file_sep>import BeautifulSoup import simplejson import re import utils as u verse_start_regex = re.compile(r'^\s*\d+\.?(.*)') def _scrape_hymn(html): ret = [] doc = BeautifulSoup.BeautifulSoup(html) h3 = doc.body.h3 p = h3.findNextSibling(True) curr_verse = '' for tag in p: text = tag.string if text is not None: match = verse_start_regex.match(text) if match is not None: if curr_verse: ret.append(curr_verse.strip()) curr_verse = match.groups()[0] else: curr_verse += text return ret def scrape_hymn(url): '''Takes a url like http://www.sacred-texts.com/hin/rigveda/rv05055.htm. Returns a list of strings, each a verse-ish''' return u.scrapeWith(url, _scrape_hymn) def _scrape_book(html): ret = [] base_url = 'http://www.sacred-texts.com/hin/rigveda/' doc = BeautifulSoup.BeautifulSoup(html) for a_tag in doc.findAll(lambda tag: tag.name == 'a' and tag.string and tag.string.startswith('HYMN')): try: ret.append({'name':a_tag.string.split('.')[1].strip(), 'url':base_url + a_tag['href']}) except IndexError: #Some hymns don't have periods or something? Oh well, we aren't hurting for vedas pass return ret def scrape_book(url): '''Takes a url like http://www.sacred-texts.com/hin/rigveda/rvi01.htm. Returns a list of dictionaries, each with a 'name' and 'url' (url is for scrape_hymn)''' return u.scrapeWith(url, _scrape_book) def scrape_all_and_store(): '''This is the main function to call. It will scrape the whole page, and write out vedas.json vedas.json is a list of dictionaries. Each dictionary has a 'book_name' and 'verses' keys. 'verses' is a list of verses.''' root_url = 'http://www.sacred-texts.com/hin/rigveda/rvi%02d.htm' filename = 'vedas.json' vedas = [] for i in range(1, 11): index_url = root_url % i for j, book in enumerate(scrape_book(index_url)): print 'Scraping #%s, %s...' % (j, book['name']) verses = scrape_hymn(book['url']) vedas.append({'book_name':book['name'], 'verses':verses}) simplejson.dump(vedas, open(filename, 'w')) if __name__ == '__main__': # print scrape_hymn('http://www.sacred-texts.com/hin/rigveda/rv05055.htm') # print scrape_book('http://www.sacred-texts.com/hin/rigveda/rvi01.htm') scrape_all_and_store()<file_sep>import BeautifulSoup import simplejson import utils as u def _scrape_chapter(html): ret = [] doc = BeautifulSoup.BeautifulSoup(html) trs = doc.findAll('tr') for i, tr in enumerate(trs): if i == 0: #first one is section heading or something continue tds = tr.findAll(lambda tag: tag.p) for td in tds: verse = ' '.join(td.p.string.split()) ret.append(verse) return ret def scrape_chapter(url): '''Takes a URL like http://www.htmlbible.com/sacrednamebiblecom/B01C001.htm Returns a list of strings, each a verse.''' return u.scrapeWith(url, _scrape_chapter) def _scrape_index(html): ret = [] base_url = 'http://www.htmlbible.com/sacrednamebiblecom/' doc = BeautifulSoup.BeautifulSoup(html) trs = doc.findAll('tr') for i, tr in enumerate(trs): # print tr book = {'urls':[]} if i < 2: #first two are old-style HTML continue for j, td in enumerate(tr.findAll('td')): # print td if j == 0: book['book'] = td.p.string else: for a in td.findAll('a'): book['urls'].append(base_url + a['href']) ret.append(book) if book['book'] == 'Revelation': break return ret def scrape_index(url): '''Takes a URL like http://www.htmlbible.com/sacrednamebiblecom/index.htm. Returns a list of dictionaries, each dictionary has a 'book' (like 'Genesis'), and a 'urls', a list of URLs suitable for passing to scrape_chapter.''' return u.scrapeWith(url, _scrape_index) def scrape_all_and_store(): '''This is the main function to call. It will scrape the whole page, and write out bible.json. bible.json is a list of dictionaries. Each dictionary has a 'book_name' and 'verses' keys. 'book_name' is like "Genesis, Chapter 1" 'verses' is a list of verses.''' index_url = 'http://www.htmlbible.com/sacrednamebiblecom/index.htm' filename = 'bible.json' bible = [] for i, book in enumerate(scrape_index(index_url)): for j, url in enumerate(book['urls']): verses = scrape_chapter(url) bible.append({'book_name':'%s, Chapter %s' % (book['book'], j + 1), 'verses':verses}) print 'Scraping #%s, %s...' % (i, book['book']) print 'Done scraping, dumping...' simplejson.dump(bible, open(filename, 'w')) if __name__ == '__main__': # for verse in scrape_chapter('http://www.htmlbible.com/sacrednamebiblecom/B01C001.htm'): # print verse # for book in scrape_index('http://www.htmlbible.com/sacrednamebiblecom/index.htm'): # print book scrape_all_and_store()<file_sep>var sys = require("sys"), http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), events = require("events"), io = require('./server/socket.io'), screens = require("./server/screens"); screens.setup(); var mimetypes = {'.swf':'application/x-shockwave-flash', '.js':'text/javascript', 'html':'text/html', '.css':'text/css', '.jpg':'image/jpeg', 'jpeg':'image/jpeg', '.png':'image/png', '.gif':'image/gif'}; var static_dir = 'C:/cygwin/home/Shawn/ImaginationEnvironment/static' function send404(res) { res.sendHeader(404, {"Content-Type": "text/plain"}); res.write("404 Not Found\n"); res.close(); return; } function onScreenUpdate(screen_) { listener.broadcast(JSON.stringify(screen_)); } screens.get_screen_emitter().addListener('screen', onScreenUpdate); var server = http.createServer(function(req, res) { var parsed_req = url.parse(req.url, true); var path = parsed_req.pathname; sys.puts(path); switch (path){ case '/': var filename = static_dir + '/imagination.html' res.writeHead(200, {'Content-Type': 'text/html'}); res.write(fs.readFileSync(filename, 'utf8'), 'utf8'); res.end(); break; case '/run': sys.puts("Running!"); screens.run(); break; default: if (/\/|\.(js|html|swf)$/.test(path)){ try { var filetype = mimetypes[path.substr(-4)]; var binary = /^(application|image)/.test(filetype); sys.puts(filetype + " is binary: " + binary); res.writeHead(200, {'Content-Type': filetype}); sys.puts("going to read " + (static_dir + path)); res.write(fs.readFileSync(static_dir + path, binary ? 'binary' : 'utf8'), binary ? 'binary' : 'utf8'); res.end(); } catch(e){ sys.puts('error!'); send404(res); } break; } send404(res); break; } }); server.listen(8080); var listener = io.listen(server, {}); sys.puts("Server running at http://localhost:8080/");<file_sep>import BeautifulSoup import simplejson import re import utils as u verse_start_regex = re.compile('p. [0-9]+') def _scrape_chapter(html): ret = [] doc = BeautifulSoup.BeautifulSoup(html) p = doc.find(text=re.compile('1. ')).parent #todo: find a better way to do this i = 2 chapter_name = doc.body.h3.string while p is not None: verse = '' while p is not None and not line_starts_with(p, str(i)): line = read_line(p) match = verse_start_regex.match(line) if match is None: verse += ' ' + line p = p.findNextSibling('p') ret.append(verse) i += 1 return chapter_name, ret def line_starts_with(tag, exp): if tag.string is None: return line_starts_with(tag.contents[0], exp) return tag.string.startswith(exp) def read_line(tag): line = '' if tag.string: words = re.sub('[0-9]+\. ', '', tag.string) # remove '1.', '2.', etc. return words for i, text in enumerate(tag): line += read_line(text) return line def scrape_chapter(url): '''Takes a url like http://www.sacred-texts.com/hin/rigveda/rv05055.htm. Returns a list of strings, each a verse-ish''' return u.scrapeWith(url, _scrape_chapter) def scrape_all_and_store(): '''This is the main function to call. It will scrape the whole page, and write out quran.json quran.json is a list of dictionaries. Each dictionary has a 'book_name' and 'verses' keys. 'verses' is a list of verses.''' root_url = 'http://www.sacred-texts.com/isl/yaq/yaq{0}.htm' filename = 'quran.json' quran = [] for i in range(1, 115): index_url = root_url.format(str(i).zfill(3)) print index_url chapter_name, verses = scrape_chapter(index_url) print 'Scraping #%s, %s...' % (i, chapter_name) quran.append({'book_name':chapter_name, 'verses':verses}) simplejson.dump(quran, open(filename, 'w')) if __name__ == '__main__': scrape_all_and_store() #for i, verse in enumerate(scrape_chapter('http://www.sacred-texts.com/isl/yaq/yaq002.htm')): # print i, verse print 'DONE!'
9a07b503ab4911d08d7213049554e71d7366669f
[ "JavaScript", "Python" ]
9
Python
shawnobanion/ImaginationEnvironment
d3aa5bf3c079889453c42cc4a76e179b12c7512a
09f21ead5536108e995fda24ad4143a146cd77aa
refs/heads/master
<repo_name>KyleStach1678/FrontLine<file_sep>/Source/Frontline Engine/Frontline Engine/Process/TimerProcess.h #pragma once #include "..\FrontlineCommon.h" #include "Process.h" class TimerProcess : public Process { friend class ProcessManager; public: TimerProcess(); int m_countdownMS; protected: virtual void VOnUpdate(unsigned long deltaMs) override; public: void SetTimer(int pi_n_countdownMS) { m_countdownMS = pi_n_countdownMS; } };<file_sep>/Source/Frontline Engine/Frontline Engine/Templates.h #pragma once #include "FrontlineCommon.h" #define FL_NEW new #define _USE_MATH_DEFINES #include <math.h> #define MAX_DIGITS_IN_INT 12 class optional_empty { }; template <unsigned long size> class optional_base { public: // Default - invalid. optional_base() : m_bValid(false) { } optional_base & operator = (optional_base const & t) { m_bValid = t.m_bValid; return *this; } //Copy constructor optional_base(optional_base const & other) : m_bValid(other.m_bValid) { } //utility functions bool const valid() const { return m_bValid; } bool const invalid() const { return !m_bValid; } protected: bool m_bValid; char m_data[size]; // storage space for T }; template <class T> class optional : public optional_base<sizeof(T)> { public: // Default - invalid. optional() { } optional(T const & t) { construct(t); m_bValid = (true); } optional(optional_empty const &) { } optional & operator = (T const & t) { if (m_bValid) { *GetT() = t; } else { construct(t); m_bValid = true; // order important for exception safety. } return *this; } //Copy constructor optional(optional const & other) { if (other.m_bValid) { construct(*other); m_bValid = true; // order important for exception safety. } } optional & operator = (optional const & other) { GCC_ASSERT(!(this == &other)); // don't copy over self! if (m_bValid) { // first, have to destroy our original. m_bValid = false; // for exception safety if destroy() throws. // (big trouble if destroy() throws, though) destroy(); } if (other.m_bValid) { construct(*other); m_bValid = true; // order vital. } return *this; } bool const operator == (optional const & other) const { if ((!valid()) && (!other.valid())) { return true; } if (valid() ^ other.valid()) { return false; } return ((** this) == (*other)); } bool const operator < (optional const & other) const { // equally invalid - not smaller. if ((!valid()) && (!other.valid())) { return false; } // I'm not valid, other must be, smaller. if (!valid()) { return true; } // I'm valid, other is not valid, I'm larger if (!other.valid()) { return false; } return ((** this) < (*other)); } ~optional() { if (m_bValid) destroy(); } // Accessors. T const & operator * () const { assert (m_bValid); return *GetT(); } T & operator * () { assert (m_bValid); return *GetT(); } T const * const operator -> () const { assert (m_bValid); return GetT(); } T * const operator -> () { assert (m_bValid); return GetT(); } //This clears the value of this optional variable and makes it invalid once again. void clear() { if (m_bValid) { m_bValid = false; destroy(); } } //utility functions bool const valid() const { return m_bValid; } bool const invalid() const { return !m_bValid; } private: T const * const GetT() const { return reinterpret_cast<T const * const>(m_data); } T * const GetT() { return reinterpret_cast<T * const>(m_data); } void construct(T const & t) { FL_NEW (GetT()) T(t); } void destroy() { GetT()->~T(); } }; template <class BaseType, class SubType> BaseType* GenericObjectCreationFunction(void) { return FL_NEW SubType; } template <class BaseClass, class IdType> class GenericObjectFactory { typedef BaseClass* (*ObjectCreationFunction)(void); std::map<IdType, ObjectCreationFunction> m_creationFunctions; public: template <class SubClass> bool Register(IdType id) { auto findIt = m_creationFunctions.find(id); if (findIt == m_creationFunctions.end()) { m_creationFunctions[id] = &GenericObjectCreationFunction<BaseClass, SubClass>; // insert() is giving me compiler errors return true; } return false; } BaseClass* Create(IdType id) { auto findIt = m_creationFunctions.find(id); if (findIt != m_creationFunctions.end()) { ObjectCreationFunction pFunc = findIt->second; return pFunc(); } return NULL; } }; template <class t_type> std::shared_ptr<t_type> MakeStrongPtr(std::weak_ptr<t_type> p_weakPtr) { if (!p_weakPtr.expired()) return std::shared_ptr<t_type>(p_weakPtr); else return std::shared_ptr<t_type>(); }<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/TransformComponent.h #pragma once #include "..\FrontlineCommon.h" #include "ActorComponent.h" #include <GLM/ext.hpp> class TransformComponent : public ActorComponent { private: glm::mat4x4 mm_transform; public: const static std::string g_name; TransformComponent(); ~TransformComponent(); glm::vec3 FindPosition(); glm::vec3 FindRotation(); glm::vec3 FindScale(); glm::mat4x4 GetTransform() { return mm_transform; } virtual bool VInit(pugi::xml_node p_data) override; virtual void VPostInit() override; virtual void VUpdate(int p_deltaMs) override {} virtual pugi::xml_node VGenerateXML() override { return pugi::xml_node(); } virtual std::string VGetComponentName() override { return TransformComponent::g_name; } virtual ComponentID VGetComponentID() const override { return HashComponentName(g_name); }; };<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/BulletPhysics.h #pragma once #include "..\FrontlineCommon.h" #include "..\IPhysics.h" #include "..\Actor\TransformComponent.h" #include "ActorMotionState.h" #include "BulletDebugDrawer.h" #include "..\Event\AddCollisionPairEventData.h" #include <set> #include <cmath> #include <algorithm> struct BulletPhysicsObject : public PhysicsObject { btCollisionShape* m_physShape; }; enum collisiontypes { COL_NOTHING = 0x00, COL_ENVIRONMENT = 0x01, COL_PLAYER = 0x02, COL_VEHICLE = 0x04 }; class BulletPhysics : public IPhysics { std::auto_ptr<btDynamicsWorld> mp_dynamicsWorld; std::auto_ptr<btBroadphaseInterface> mp_broadphase; std::auto_ptr<btCollisionDispatcher> mp_collisionDispatcher; std::auto_ptr<btConstraintSolver> mp_constraintSolver; std::auto_ptr<btCollisionConfiguration> mp_collisionConfig; std::auto_ptr<BulletDebugDrawer> mp_debugDrawer; typedef std::map<std::string, float> DensityTable; typedef std::map<std::string, PhysicsMaterial> MaterialTable; DensityTable mmap_densityTable; MaterialTable mmap_materialTable; void LoadXML(); std::map<ActorID, btRigidBody*> mmap_rigidBodyLookup; std::map<btRigidBody*, ActorID> mmap_actorIDLookup; typedef std::pair<btRigidBody*, btRigidBody*> CollisionPair; std::set<CollisionPair> mset_lastTickCollisionPairs; void SendNewCollisionPairEvent(btPersistentManifold* pp_manifold, btRigidBody* pp_body0, btRigidBody* pp_body1); void SendRemoveCollisionPairEvent(btRigidBody* pp_body0, btRigidBody* pp_body1); void RemoveCollisionObject(btCollisionObject* pp_toRemove); static void BulletInternalTickCallback(btDynamicsWorld* pp_world, btScalar pf_timeStep); public: float findDensity(const std::string& ps_name); PhysicsMaterial findMaterialData(const std::string& ps_name); virtual bool VOnInit() override; virtual void VSyncVisibleScene() override; virtual void VOnUpdate(float pf_deltaSeconds); virtual void VAddRigidBody(PhysicsObject* po_physObject) override; virtual void VAddCylinder(float pf_radius, float pf_height, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel, short mi_collidesWith); virtual void VAddSphere(float pf_radius, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel, short mi_collidesWith) override; virtual void VAddBox(const glm::vec3& pf_dimensions, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel, short mi_collidesWith); void VAddPointCloud(glm::vec3* pp_verts, int pi_numPoints, WeakActorPtr pp_gameActor, const std::string ps_density, const std::string ps_material, float mass = -1); virtual void VRemoveActor(ActorID pi_id); virtual void VRenderDiagnostics() override; virtual void VCreateTrigger(PhysicsObject* po_physObject); virtual void VApplyForce(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id); virtual void VApplyTorque(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id); virtual bool VKinematicMove(const glm::mat4x4& pm_matrix, ActorID pi_id); void VStopActor(ActorID pi_id); void VSetVelocity(ActorID pi_id, glm::vec3& pv_velocity); BulletPhysics(); ~BulletPhysics(); };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/ResourceZipFile.h #pragma once #include "IResourceFile.h" #include "ZipFile.h" class ResourceZipFile : public IResourceFile { ZipFile *m_pZipFile; std::wstring m_resFileName; public: ResourceZipFile(const std::wstring resFileName) { m_pZipFile = NULL; m_resFileName = resFileName; } virtual ~ResourceZipFile(); virtual bool VOpen(); virtual int VGetRawResourceSize(const Resource &r); virtual int VGetRawResource(const Resource &r, char *buffer); virtual int VGetNumResources() const; virtual std::string VGetResourceName(int num) const; virtual bool VIsUsingDevelopmentDirectories(void) const { return false; } };<file_sep>/Source/Frontline/effectSysTestP2/flFxExt.cpp #include "flFxExt.h" static std::shared_ptr<StateInterpreter> stateInterpreter(new StateInterpreter()); std::shared_ptr<StateInterpreter> StateInterpreter::Get() { return stateInterpreter; } bool StateGroup::AddState(std::shared_ptr<BlankState> state) { for(auto iter = m_States.begin(); iter != m_States.end(); iter++) { if((*iter)->m_State == state->m_State || (*iter) == state) { return false; } } m_States.push_back(state); return true; } bool StateGroup::RemoveState(fxState state) { for(auto iter = m_States.begin(); iter != m_States.end();) { if((*iter)->m_State == state) { m_States.erase(iter); return true; } iter++; } return false; } std::shared_ptr<BlankState> StateGroup::FindState(fxState state) { for(auto iter = m_States.begin(); iter != m_States.end(); iter++) { if((*iter)->m_State = state) { return (*iter); } } return NULL; } bool Shader::Validate() { if(m_Parent.lock()) { std::shared_ptr<GPUPipeline> pipeline = std::static_pointer_cast<GPUPipeline>(m_Parent.lock()->Find(FX_PIPELINE_DESC_FLAG)); if(pipeline) { //AttachTo(pipeline); pipeline->SetShader(std::static_pointer_cast<Shader>(shared_from_this())); return true; } return false; } return false; } bool Shader::Invalidate() { if(m_Parent.lock()) { std::shared_ptr<GPUPipeline> pipeline = std::static_pointer_cast<GPUPipeline>(m_Parent.lock()->Find(FX_PIPELINE_DESC_FLAG)); if(pipeline) { pipeline->RemoveShader(m_Name); return true; } return false; } return false; } bool GPUPipeline::SetShader(std::shared_ptr<Shader> shader) { for(auto iter = m_Shaders.begin(); iter != m_Shaders.end();iter++) { if((*iter) == shader) { return false; } } m_Shaders.push_back(shader); return true; } bool GPUPipeline::RemoveShader(const char* name) { for(auto iter = m_Shaders.begin(); iter != m_Shaders.end();) { if(strcmp((*iter)->GetName(),name) == 0) { m_Shaders.erase(iter); return true; } iter++; } return false; } std::shared_ptr<Shader> GPUPipeline::GetShader(const char* name) { for(auto iter = m_Shaders.begin(); iter != m_Shaders.end();) { if(strcmp((*iter)->GetName(),name) == 0) { return (*iter); } iter++; } return NULL; } std::shared_ptr<Shader> GPUPipeline::GetShader(int index) { if(index >= m_Shaders.size()) { return NULL; } return m_Shaders[index]; } bool SamplerState::AddState(std::shared_ptr<BlankState> state) { for(auto iter = m_States.begin(); iter != m_States.end(); iter++) { if((*iter) == state) { return false; } } m_States.push_back(state); return true; } std::shared_ptr<BlankState> SamplerState::FindState(fxState state) { for(auto iter = m_States.begin(); iter != m_States.end(); iter++) { if((*iter)->m_State = state) { return (*iter); } } return NULL; } bool SamplerState::RemoveState(fxState state) { for(auto iter = m_States.begin(); iter != m_States.end();) { if ((*iter)->m_State == state) { m_States.erase(iter); return true; } iter++; } return false; } Resource::Resource(const char* name, fxState resType) : PassDesc(FX_RESOURCE_DESC_FLAG,name) { m_Data.appDepSize = false; m_Data.msaa = false; m_Data.external = false; m_ResourceType = resType; //flFxCore::Get().GetResourceRepository()->AddItem(this); } Resource::~Resource() { //flFxCore::Get().GetResourceRepository()->RemoveItem(this); } void Resource::SetDimensions(int w,int h,int d) { m_Data.dimensions[0] = w; m_Data.dimensions[1] = h; m_Data.dimensions[2] = d; } bool Resource::Validate() { /*if (m_Parent.lock()) { switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: { std::shared_ptr<FrameBufferObject> framebuffer = std::static_pointer_cast<FrameBufferObject>(m_Parent.lock()->Find(FX_FBO_TARGET_DESC_FLAG)); if (framebuffer) { framebuffer->AddTextureResource(std::static_pointer_cast<Resource>(shared_from_this())); } break; } case FX_RESOURCE_DEPTHTEX: { std::shared_ptr<FrameBufferObject> framebuffer = std::static_pointer_cast<FrameBufferObject>(m_Parent.lock()->Find(FX_FBO_TARGET_DESC_FLAG)); if (framebuffer) { framebuffer->SetDSTTexture(std::static_pointer_cast<Resource>(shared_from_this())); } break; } } }*/ return true; } bool Resource::Invalidate() { if (m_Parent.lock()) { switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: break; case FX_RESOURCE_DEPTHTEX: break; } } return true; } FrameBufferObject::FrameBufferObject(const char* name) : PassDesc(FX_FBO_TARGET_DESC_FLAG,name) { //flFxCore::Get().GetFBORepository()->RemoveItem(this); } FrameBufferObject::~FrameBufferObject() { //flFxCore::Get().GetFBORepository()->RemoveItem(this); } bool FrameBufferObject::Validate() { if (m_Parent.lock()) { } return true; } bool FrameBufferObject::Invalidate() { if (m_Parent.lock()) { } return true; } bool FrameBufferObject::AddTextureResource(std::shared_ptr<Resource> res) { for(auto iter = m_Resources.begin(); iter != m_Resources.end(); iter++) { if((*iter) == res) { return false; } } m_Resources.push_back(res); return true; } std::shared_ptr<Resource> FrameBufferObject::GetTextureResource(int index) { if(index >= m_Resources.size()) { return NULL; } return m_Resources[index]; } ShaderParameter::ShaderParameter(const char* name, float* value) : PassDesc(FX_SHADER_PARAMETER_DESC_FLAG,name) { if(value) { m_Value = value; } //flFxCore::Get().GetShaderParameterRepository()->RemoveItem(this); } ShaderParameter::~ShaderParameter() { delete[] m_Value; //flFxCore::Get().GetShaderParameterRepository()->RemoveItem(this); } void ShaderParameter::SetValue(float* value) { if (value) { m_Value = value; } } <file_sep>/Source/Frontline Engine/Frontline Engine/Resource/ZipResourceFile.h #pragma once #include "..\IResourceFile.h" #include "ZipFile.h" class ZipResourceFile : public IResourceFile { protected: std::unique_ptr<ZipFile> mp_ZipFile; public: virtual bool VOpen(const wchar_t* ps_filename) override; virtual int VGetResource(char** buffer, const char* ps_resname) override; virtual int VGetRawResourceSize(const char* ps_resname) override; virtual int VGetNumResources() const override; virtual bool VClose() override; };<file_sep>/Source/Frontline Engine/Frontline Engine/Process/main.cpp #include "Process.h" #include "ProcessManager.h" #include <Windows.h> #include <iostream> typedef std::shared_ptr<ProcessManager>ProcessManagerPtr; class ProcessTest : public Process { public: ProcessTest(int id){ID = id;} ~ProcessTest(){} void VOnInit() { currentProcessState = PROCESS_RUNNING; timer = 0; std::cout<<"initializing process!"<<std::endl; } void VOnUpdate(unsigned long deltaMs){ timer += deltaMs; std::cout<<"updating Process with VOnUpdate!"<<" "<<deltaMs<<" "<<timer<<" "<<ID<<std::endl; if(timer == 30) { currentProcessState = PROCESS_SUCCEDED; } }; void VOnExit(ProcessState exitState) { std::cout<<"successfuly exited the process with exit state: "<<exitState<<std::endl; } private: int timer; int ID; }; int main() { ProcessManagerPtr processManager(new ProcessManager()); std::shared_ptr<ProcessTest>pProcessTest(new ProcessTest(1)); std::shared_ptr<ProcessTest>pProcessTest2(new ProcessTest(2)); std::shared_ptr<ProcessTest>pChildProcess(new ProcessTest(3)); std::shared_ptr<ProcessTest>pChildProcess2(new ProcessTest(4)); //attaching the parent process processManager -> AttachProcess(pProcessTest); processManager -> AttachProcess(pProcessTest2); //attaching the child process which will be automatically //attached to the manager as a parent process when the //original parent process finishes and gets deleted pProcessTest -> AttachChild(PROCESS_SUCCEDED,pChildProcess); pProcessTest2 -> AttachChild(PROCESS_SUCCEDED,pChildProcess2); while(processManager -> m_processList.size() != 0) { processManager -> UpdateProcesses(5); } MessageBox(NULL,"No Runtime Errors","INFO",MB_OK); return 0; } <file_sep>/Source/Frontline/effectSysTestP2/texture.h #pragma once #include <GL/glew.h> #include <SFML/Audio.hpp> #include <SFML/Config.hpp> #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <SFML/OpenGL.hpp> #include <SFML/System.hpp> #include <SFML/Window.hpp> #include <glm/ext.hpp> GLuint loadTexture(const char* filename);<file_sep>/Source/Frontline Engine/Frontline Game Test/IResourceManager.cpp /*#include "IResourceManager.h" IResourceManager::IResourceManager() { } IResourceManager::~IResourceManager() { } */<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/BulletPhysics.cpp #include "BulletPhysics.h" BulletPhysics::BulletPhysics() { } BulletPhysics::~BulletPhysics() { for (int i = mp_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; --i) { btCollisionObject * const obj = mp_dynamicsWorld->getCollisionObjectArray()[i]; RemoveCollisionObject(obj); } mmap_actorIDLookup.clear(); mmap_rigidBodyLookup.clear(); mset_lastTickCollisionPairs.clear(); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VOnInit // Purpose: Initialize Physics. // Parameters: None // -------------------------------------------------------------------------- bool BulletPhysics::VOnInit() { LoadXML(); mp_collisionConfig = std::auto_ptr<btCollisionConfiguration>(FL_NEW btDefaultCollisionConfiguration()); mp_collisionDispatcher = std::auto_ptr<btCollisionDispatcher>(FL_NEW btCollisionDispatcher(mp_collisionConfig.get())); mp_broadphase = std::auto_ptr<btBroadphaseInterface>(FL_NEW btDbvtBroadphase()); mp_constraintSolver = std::auto_ptr<btConstraintSolver>(FL_NEW btSequentialImpulseConstraintSolver()); mp_dynamicsWorld = std::auto_ptr<btDynamicsWorld>(FL_NEW btDiscreteDynamicsWorld(mp_collisionDispatcher.get(), mp_broadphase.get(), mp_constraintSolver.get(), mp_collisionConfig.get())); mp_dynamicsWorld->setGravity(btVector3(0, -9.81, 0)); mp_debugDrawer = std::auto_ptr<BulletDebugDrawer>(FL_NEW BulletDebugDrawer()); if (!mp_collisionConfig.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_collisionConfig not initialized."); return false; } if (!mp_collisionDispatcher.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_collisionDispatcher not initialized."); return false; } if (!mp_broadphase.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_broadphase not initialized."); return false; } if (!mp_constraintSolver.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_constraintSolver not initialized."); return false; } if (!mp_dynamicsWorld.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_dynamicsWorld not initialized."); return false; } if (!mp_debugDrawer.get()) { ERRLOG("Physics", "BulletPhysics::VOnInit() failed: mp_debugDrawer not initialized."); return false; } mp_dynamicsWorld->setDebugDrawer(mp_debugDrawer.get()); mp_dynamicsWorld->setInternalTickCallback(BulletInternalTickCallback); mp_dynamicsWorld->setWorldUserInfo(this); return true; } // -------------------------------------------------------------------------- // Function: BulletPhysics::VOnUpdate // Purpose: Tick the simulation. // Parameters: Elapsed time in seconds // -------------------------------------------------------------------------- void BulletPhysics::VOnUpdate(float pf_deltaSeconds) { mp_dynamicsWorld->stepSimulation(pf_deltaSeconds, 4); // Run the physics simulation } // -------------------------------------------------------------------------- // Function: BulletPhysics::VSyncVisibleScene // Purpose: Sync actor positions to physics locations. // Parameters: None // -------------------------------------------------------------------------- void BulletPhysics::VSyncVisibleScene() { for (auto lit_rigidBodyLookup = mmap_rigidBodyLookup.begin(); lit_rigidBodyLookup != mmap_rigidBodyLookup.end(); ++lit_rigidBodyLookup) { const ActorID li_id = lit_rigidBodyLookup->first; ActorMotionState const* lp_motionState = static_cast<ActorMotionState*>(lit_rigidBodyLookup->second->getMotionState()); } } // -------------------------------------------------------------------------- // Function: BulletPhysics::VAddSphere // Purpose: Add a sphere to the simulation. // Parameters: Radius, weak pointer to actor, density lookup string, material lookup string, collision channel (1 bit selected), collision mask (binary OR of all collision channels) // -------------------------------------------------------------------------- void BulletPhysics::VAddSphere(float const pf_radius, WeakActorPtr pp_gameActor, const std::string& ps_densityString, const std::string& ps_physicsMaterial, short mi_collisionChannel, short mi_collidesWith) { StrongActorPtr lp_strongActor = MakeStrongPtr<Actor>(pp_gameActor); if (!lp_strongActor) return; btCollisionShape* lp_collisionShape = FL_NEW btSphereShape(pf_radius); float lf_density = findDensity(ps_densityString); const float lf_volume = (float) ((4.0F / 3.0F) * M_PI * pow(pf_radius, 3)); const float lf_mass = lf_volume * lf_density; BulletPhysicsObject* lp_object = FL_NEW BulletPhysicsObject(); lp_object->m_gameActor = lp_strongActor; lp_object->m_mass = lf_mass; lp_object->m_material = ps_physicsMaterial; lp_object->m_physShape = lp_collisionShape; lp_object->m_collisionType = mi_collisionChannel; lp_object->m_collidesWith = mi_collidesWith; VAddRigidBody(lp_object); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VAddCylinder // Purpose: Add a cylinder to the simulation. // Parameters: Radius, height, weak pointer to actor, density lookup string, material lookup string, collision channel (1 bit selected), collision mask (binary OR of all collision channels) // -------------------------------------------------------------------------- void BulletPhysics::VAddCylinder(float const pf_radius, float pf_height, WeakActorPtr pp_gameActor, const std::string& ps_densityString, const std::string& ps_physicsMaterial, short mi_collisionChannel, short mi_collidesWith) { StrongActorPtr lp_strongActor = MakeStrongPtr<Actor>(pp_gameActor); if (!lp_strongActor) return; btCollisionShape* lp_collisionShape = FL_NEW btCylinderShape(btVector3(pf_radius, pf_height / 2, pf_radius)); float lf_density = findDensity(ps_densityString); const float lf_volume = pf_radius * pf_radius * pf_height * M_PI; const float lf_mass = lf_volume * lf_density; BulletPhysicsObject* lp_object = FL_NEW BulletPhysicsObject(); lp_object->m_gameActor = lp_strongActor; lp_object->m_mass = lf_mass; lp_object->m_material = ps_physicsMaterial; lp_object->m_physShape = lp_collisionShape; lp_object->m_collisionType = mi_collisionChannel; lp_object->m_collidesWith = mi_collidesWith; VAddRigidBody(lp_object); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VAddBox // Purpose: Add a box to the simulation. // Parameters: Dimensions, weak pointer to actor, density lookup string, material lookup string, collision channel (1 bit selected), collision mask (binary OR of all collision channels) // -------------------------------------------------------------------------- void BulletPhysics::VAddBox(const glm::vec3& pf_dimensions, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_physicsMaterial, short mi_collisionChannel, short mi_collidesWith) { StrongActorPtr lp_strongActor = MakeStrongPtr<Actor>(pp_gameActor); if (!lp_strongActor) return; btCollisionShape* lp_collisionShape = FL_NEW btBoxShape(btVector3(pf_dimensions[0], pf_dimensions[1], pf_dimensions[2])); float lf_density = findDensity(ps_density); const float lf_volume = pf_dimensions[0] * pf_dimensions[1] * pf_dimensions[2]; const float lf_mass = lf_volume * lf_density; BulletPhysicsObject* lp_object = FL_NEW BulletPhysicsObject(); lp_object->m_gameActor = lp_strongActor; lp_object->m_mass = lf_mass; lp_object->m_material = ps_physicsMaterial; lp_object->m_physShape = lp_collisionShape; lp_object->m_collisionType = mi_collisionChannel; lp_object->m_collidesWith = mi_collidesWith; VAddRigidBody(lp_object); } // -------------------------------------------------------------------------- // Function: BulletPhysics::SendNewCollisionPairEvent // Purpose: Helper function to notify the event system of a new collision pair. // Parameters: Manifold, rigid body 1, rigid body 2 // -------------------------------------------------------------------------- void BulletPhysics::SendNewCollisionPairEvent(btPersistentManifold* pp_manifold, btRigidBody* pp_body0, btRigidBody* pp_body1) { std::shared_ptr<CollisionPairEventData> lp_eventdata; lp_eventdata = std::shared_ptr<CollisionPairEventData>(FL_NEW CollisionPairEventData()); lp_eventdata->m_actor1 = mmap_actorIDLookup[pp_body0]; lp_eventdata->m_actor2 = mmap_actorIDLookup[pp_body1]; lp_eventdata->m_addOrRemove = true; IGame::gp_game->mp_eventManager->VQueueEvent(lp_eventdata); } // -------------------------------------------------------------------------- // Function: BulletPhysics::SendRemoveCollisionPairEvent // Purpose: Helper function to notify the event system of a removed collision pair. // Parameters: Rigid body 1, rigid body 2 // -------------------------------------------------------------------------- void BulletPhysics::SendRemoveCollisionPairEvent(btRigidBody* pp_body0, btRigidBody* pp_body1) { std::shared_ptr<CollisionPairEventData> lp_eventdata; lp_eventdata = std::shared_ptr<CollisionPairEventData>(FL_NEW CollisionPairEventData()); lp_eventdata->m_actor1 = mmap_actorIDLookup[pp_body0]; lp_eventdata->m_actor2 = mmap_actorIDLookup[pp_body1]; lp_eventdata->m_addOrRemove = false; IGame::gp_game->mp_eventManager->VQueueEvent(lp_eventdata); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VAddRigidBody // Purpose: Add a rigid body to the simulation. // Parameters: BulletPhysicsObject to be added // -------------------------------------------------------------------------- void BulletPhysics::VAddRigidBody(PhysicsObject* po_physObject) { BulletPhysicsObject* lo_objectBTCast = static_cast<BulletPhysicsObject*>(po_physObject); FL_ASSERT(lo_objectBTCast->m_gameActor); ActorID pid_actorID = lo_objectBTCast->m_gameActor->GetID(); FL_ASSERT(mmap_rigidBodyLookup.find(pid_actorID) == mmap_rigidBodyLookup.end()); PhysicsMaterial lmd_physMaterial(findMaterialData(lo_objectBTCast->m_material)); btVector3 lv_localInertia; if (lo_objectBTCast->m_mass > 0.0F) lo_objectBTCast->m_physShape->calculateLocalInertia(lo_objectBTCast->m_mass, lv_localInertia); glm::mat4 lm_transform = glm::mat4(1); std::shared_ptr<TransformComponent> lp_transformComponent = MakeStrongPtr<TransformComponent>(lo_objectBTCast->m_gameActor->GetComponent<TransformComponent>(TransformComponent::g_name)); FL_ASSERT(lp_transformComponent); if (!lp_transformComponent) return; lm_transform = lp_transformComponent->GetTransform(); ActorMotionState* lp_motionState = FL_NEW ActorMotionState(lm_transform); btRigidBody::btRigidBodyConstructionInfo lc_constructInfo(lo_objectBTCast->m_mass, lp_motionState, lo_objectBTCast->m_physShape, lv_localInertia); lc_constructInfo.m_restitution = lmd_physMaterial.mf_restitution; lc_constructInfo.m_friction = lmd_physMaterial.mf_friction; btRigidBody* lp_newBody = FL_NEW btRigidBody(lc_constructInfo); mp_dynamicsWorld->addRigidBody(lp_newBody, po_physObject->m_collisionType, po_physObject->m_collidesWith); mmap_rigidBodyLookup[pid_actorID] = lp_newBody; mmap_actorIDLookup[lp_newBody] = pid_actorID; delete po_physObject; } // -------------------------------------------------------------------------- // Function: BulletPhysics::VAddPointCloud // Purpose: Add a convex hull to the simulation. // Parameters: Array of vertices, number of vertices, density lookup string, material lookup string, collision channel (1 bit selected), collision mask (binary OR of all collision channels), mass // -------------------------------------------------------------------------- void BulletPhysics::VAddPointCloud(glm::vec3* pp_verts, int pi_numPoints, WeakActorPtr pp_gameActor, const std::string ps_density, const std::string ps_physicsMaterial, float pi_mass) { StrongActorPtr lp_strongActor = MakeStrongPtr<Actor>(pp_gameActor); if (!lp_strongActor) return; btConvexHullShape* const lp_collisionShape = FL_NEW btConvexHullShape(); for (int i = 0; i < pi_numPoints; ++i) { lp_collisionShape->addPoint(btVector3(pp_verts[i][0], pp_verts[i][1], pp_verts[i][2])); } if (pi_mass == -1) { btVector3 lv_aabbMin, lv_aabbMax; lp_collisionShape->getAabb(btTransform::getIdentity(), lv_aabbMin, lv_aabbMax); btVector3 lv_aabbSize = lv_aabbMax - lv_aabbMin; float volume = lv_aabbSize.x() * lv_aabbSize.y() * lv_aabbSize.z(); pi_mass = volume * findDensity(ps_density); } BulletPhysicsObject* lp_object = FL_NEW BulletPhysicsObject(); lp_object->m_gameActor = lp_strongActor; lp_object->m_mass = pi_mass; lp_object->m_material = ps_physicsMaterial; lp_object->m_physShape = lp_collisionShape; VAddRigidBody(lp_object); } /* TODO: Redo VAdd- functions to return PhysicsObject* */ // -------------------------------------------------------------------------- // Function: BulletPhysics::VCreateTrigger // Purpose: Add a trigger to the simulation. // Parameters: BulletPhysicsObject to be added as trigger // -------------------------------------------------------------------------- void BulletPhysics::VCreateTrigger(PhysicsObject* po_physObject) { po_physObject->m_mass = 0; BulletPhysicsObject* lo_objectBTCast = static_cast<BulletPhysicsObject*>(po_physObject); FL_ASSERT(lo_objectBTCast->m_gameActor); ActorID pid_actorID = lo_objectBTCast->m_gameActor->GetID(); FL_ASSERT(mmap_rigidBodyLookup.find(pid_actorID) == mmap_rigidBodyLookup.end()); btVector3 lv_localInertia; if (lo_objectBTCast->m_mass > 0.0F) lo_objectBTCast->m_physShape->calculateLocalInertia(lo_objectBTCast->m_mass, lv_localInertia); glm::mat4 lm_transform = glm::mat4(1); std::shared_ptr<TransformComponent> lp_transformComponent = MakeStrongPtr<TransformComponent>(lo_objectBTCast->m_gameActor->GetComponent<TransformComponent>(TransformComponent::g_name)); FL_ASSERT(lp_transformComponent); if (!lp_transformComponent) return; lm_transform = lp_transformComponent->GetTransform(); ActorMotionState* lp_motionState = FL_NEW ActorMotionState(lm_transform); btRigidBody::btRigidBodyConstructionInfo lc_constructInfo(lo_objectBTCast->m_mass, lp_motionState, lo_objectBTCast->m_physShape, lv_localInertia); btRigidBody* lp_newBody = new btRigidBody(lc_constructInfo); mp_dynamicsWorld->addRigidBody(lp_newBody); lp_newBody->setCollisionFlags(lp_newBody->getCollisionFlags() | btRigidBody::CF_NO_CONTACT_RESPONSE); mmap_rigidBodyLookup[pid_actorID] = lp_newBody; mmap_actorIDLookup[lp_newBody] = pid_actorID; delete po_physObject; } // -------------------------------------------------------------------------- // Function: BulletPhysics::VApplyForce // Purpose: Apply force to an actor. // Parameters: Direction, power in newtons, actor id // -------------------------------------------------------------------------- void BulletPhysics::VApplyForce(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id) { btRigidBody* lp_body = mmap_rigidBodyLookup[pi_id]; if (!lp_body) return; FL_ASSERT(lp_body); lp_body->applyCentralImpulse(btVector3(pv_dir.x * pf_newtons, pv_dir.y * pf_newtons, pv_dir.z * pf_newtons)); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VApplyTorque // Purpose: Apply torque to a specified actor. // Parameters: Direction, power in newtons, actor id // -------------------------------------------------------------------------- void BulletPhysics::VApplyTorque(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id) { btRigidBody* lp_body = mmap_rigidBodyLookup[pi_id]; if (!lp_body) return; FL_ASSERT(lp_body); lp_body->applyTorqueImpulse(btVector3(pv_dir.x * pf_newtons, pv_dir.y * pf_newtons, pv_dir.z * pf_newtons)); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VStopActor // Purpose: Halt an actor's motion. // Parameters: Actor id to stop // -------------------------------------------------------------------------- void BulletPhysics::VStopActor(ActorID pi_id) { VSetVelocity(pi_id, glm::vec3(0, 0, 0)); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VSetVelocity // Purpose: Set an actor's velocity // Parameters: Actor id, velocity // -------------------------------------------------------------------------- void BulletPhysics::VSetVelocity(ActorID pi_id, glm::vec3& pv_velocity) { btRigidBody* lp_body = mmap_rigidBodyLookup[pi_id]; if (!lp_body) return; lp_body->setLinearVelocity(btVector3(pv_velocity[0], pv_velocity[1], pv_velocity[2])); } // -------------------------------------------------------------------------- // Function: BulletPhysics::findDensity // Purpose: Find the value of a density string // Parameters: Name of the density material // -------------------------------------------------------------------------- float BulletPhysics::findDensity(const std::string& ps_name) { return mmap_densityTable[ps_name]; } // -------------------------------------------------------------------------- // Function: BulletPhysics::findMaterialData // Purpose: Find the value of a material string // Parameters: Name of the material // -------------------------------------------------------------------------- PhysicsMaterial BulletPhysics::findMaterialData(const std::string& ps_name) { return mmap_materialTable[ps_name]; } // -------------------------------------------------------------------------- // Function: BulletPhysics::VRemoveActor // Purpose: Remove an actor from the simulation // Parameters: Actor id to be removed // -------------------------------------------------------------------------- void BulletPhysics::VRemoveActor(ActorID pi_id) { mmap_actorIDLookup.erase(mmap_rigidBodyLookup[pi_id]); delete mmap_rigidBodyLookup[pi_id]; mmap_rigidBodyLookup.erase(pi_id); } // -------------------------------------------------------------------------- // Function: BulletPhysics::VRenderDiagnostics // Purpose: Render debug drawing // Parameters: None // -------------------------------------------------------------------------- void BulletPhysics::VRenderDiagnostics() { mp_dynamicsWorld->debugDrawWorld(); } // -------------------------------------------------------------------------- // Function: BulletPhysics::RemoveCollisionObject // Purpose: Helper function to remove a specific object from the simulation // Parameters: Collision object to be removed // -------------------------------------------------------------------------- void BulletPhysics::RemoveCollisionObject(btCollisionObject* pp_toRemove) { mp_dynamicsWorld->removeCollisionObject(pp_toRemove); delete pp_toRemove; } // -------------------------------------------------------------------------- // Function: BulletPhysics::LoadXML // Purpose: Load physics settings // Parameters: None // -------------------------------------------------------------------------- void BulletPhysics::LoadXML() { PhysicsMaterial lm_defaultMaterial; lm_defaultMaterial.mf_friction = 0.5; lm_defaultMaterial.mf_restitution = 0.2; mmap_densityTable["Default"] = 1.0F; mmap_materialTable["Default"] = lm_defaultMaterial; mmap_densityTable["Static"] = 0.0F; PhysicsMaterial lm_bouncyBall; lm_bouncyBall.mf_friction = 0.5; lm_bouncyBall.mf_restitution = 1; mmap_materialTable["Bouncy"] = lm_bouncyBall; } // -------------------------------------------------------------------------- // Function: BulletPhysics::BulletInternalTickCallback // Purpose: Static tick callback - called every step by bullet // Parameters: Physics world, elapsed time in seconds // -------------------------------------------------------------------------- void BulletPhysics::BulletInternalTickCallback(btDynamicsWorld* pp_dynamicsWorld, btScalar pf_timeStep) { FL_ASSERT(pp_dynamicsWorld); FL_ASSERT(pp_dynamicsWorld->getWorldUserInfo()); BulletPhysics* lp_physics = static_cast<BulletPhysics*>(pp_dynamicsWorld->getWorldUserInfo()); int numManifolds = pp_dynamicsWorld->getDispatcher()->getNumManifolds(); std::set<CollisionPair> lset_currentTickCollisionPairs; for (int i = 0; i<numManifolds; i++) { btPersistentManifold* contactManifold = pp_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); btRigidBody* obA = (btRigidBody*) (contactManifold->getBody0()); btRigidBody* obB = (btRigidBody*) (contactManifold->getBody1()); btRigidBody* obASort = (obA > obB) ? obA : obB; btRigidBody* obBSort = (obA > obB) ? obB : obA; CollisionPair lpair_collisionPair = std::make_pair(obASort, obBSort); if (lp_physics->mset_lastTickCollisionPairs.find(lpair_collisionPair) == lp_physics->mset_lastTickCollisionPairs.end() && lset_currentTickCollisionPairs.find(lpair_collisionPair) == lset_currentTickCollisionPairs.end()) { lp_physics->SendNewCollisionPairEvent(contactManifold, obASort, obBSort); } lset_currentTickCollisionPairs.insert(lpair_collisionPair); } std::set<CollisionPair> lset_removedPairs; std::set_difference(lp_physics->mset_lastTickCollisionPairs.begin(), lp_physics->mset_lastTickCollisionPairs.end(), lset_currentTickCollisionPairs.begin(), lset_currentTickCollisionPairs.end(), std::inserter(lset_removedPairs, lset_removedPairs.begin())); for (std::set<CollisionPair>::iterator i = lset_removedPairs.begin(); i != lset_removedPairs.end(); i++) { lp_physics->SendRemoveCollisionPairEvent(i->first, i->second); } lp_physics->mset_lastTickCollisionPairs = lset_currentTickCollisionPairs; } // -------------------------------------------------------------------------- // Function: BulletPhysics::VKinematicMove // Purpose: Set a new transformation for an actor // Parameters: New transform, actor id // -------------------------------------------------------------------------- bool BulletPhysics::VKinematicMove(const glm::mat4x4& pm_matrix, ActorID pi_id) { return true; }<file_sep>/Source/Frontline Engine/Frontline Engine/IResourceFile.h #pragma once #include "Resource\IResource.h" class IResourceFile { protected: std::wstring ms_filename; public: virtual bool VOpen(const wchar_t* ps_filename) = 0; virtual int VGetResource(char** buffer, const char* ps_resname) = 0; virtual int VGetRawResourceSize(const char* ps_resname) = 0; virtual int VGetNumResources() const = 0; virtual bool VClose() = 0; virtual std::wstring GetFilename() { return ms_filename; } virtual ~IResourceFile() {} };<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/ActorComponent.h #pragma once #include "../FrontlineCommon.h" #include "Actor.h" #include <memory> #include <XML/pugixml.hpp> class ActorComponent; typedef unsigned int ComponentID; typedef std::shared_ptr<ActorComponent> StrongActorComponentPtr; class ActorComponent { friend class ActorFactory; friend class Actor; protected: std::shared_ptr<Actor> m_owner; public: virtual ~ActorComponent() {} virtual bool VInit(pugi::xml_node p_data) = 0; virtual void VPostInit() {} virtual void VUpdate(int p_deltaMs) {} virtual ComponentID VGetComponentID() const = 0; virtual std::string VGetComponentName() = 0; virtual pugi::xml_node VGenerateXML() = 0; static int HashComponentName(std::string ps_name) { int li_pos = ps_name.find("Component"); ps_name.erase(li_pos, ps_name.length() - li_pos); int li_hash = 0; for (unsigned int i = 0; i < ps_name.length(); i++) { li_hash = li_hash * 31 + ps_name[i]; } return li_hash; } private: void SetOwner(std::shared_ptr<Actor> p_owner) { m_owner = p_owner; } };<file_sep>/Source/Frontline Engine/Frontline Engine/System/IWindowManager.h #pragma once #include "../FrontlineCommon.h" #include "../IGame.h" #include <GLEW/glew.h> #include <memory> struct WindowStyle { bool m_hasBorder; bool m_hasCaption; bool m_isChild; bool m_clipChildren; bool m_clipSiblings; bool m_isDisabled; bool m_dlgFrame; bool m_isGroup; bool m_hScroll; bool m_vScroll; bool m_iconic; bool m_maximize; bool m_maximizeButton; bool m_minimize; bool m_minimizeButton; bool m_isPopup; bool m_hasResizeBox; bool m_hasSystemMenu; bool m_tabStop; bool m_visible; WindowStyle() { m_hasBorder = m_hasCaption = m_isChild = m_clipChildren = m_clipSiblings = m_isDisabled = m_dlgFrame = m_isGroup = m_hScroll = m_vScroll = m_iconic = m_maximize = m_maximizeButton = m_minimize = m_minimizeButton = m_isPopup = m_hasResizeBox = m_hasSystemMenu = m_tabStop = m_visible = false; } WindowStyle(bool p_hasBorder, bool p_hasCaption, bool p_maximizeButton, bool p_minimizeButton, bool p_dlgFrame, bool p_hasSystemMenu) : m_hasBorder(p_hasBorder), m_hasCaption(p_hasCaption), m_minimizeButton(p_minimizeButton), m_maximizeButton(p_maximizeButton), m_dlgFrame(p_dlgFrame), m_hasSystemMenu(p_hasSystemMenu) { } }; const WindowStyle OVERLAPPEDWINDOW = WindowStyle(true, true, true, true, true, true); class IWindowManager { public: IWindowManager() {} virtual void open(int p_sizeX, int p_sizeY, std::string p_windowTitle, bool p_singleInstance, bool p_fullscreen, WindowStyle p_style = OVERLAPPEDWINDOW, int p_posX = 0, int p_posY = 0) = 0; virtual bool resize(int p_sizeX_n, int p_sizeY_n, int p_posX_n = 0, int p_posY_n = 0) = 0; virtual void close() = 0; virtual void createGLContext() = 0; virtual void destroyGLContext() = 0; virtual void makeGLContextCurrent() = 0; virtual void swapGLBuffers() = 0; virtual void updateWindow() = 0; virtual bool setFullscreen(bool p_Fullscreen) = 0; virtual bool isOpen() = 0; ~IWindowManager() {} protected: IWindowManager(IWindowManager& manager); int m_sizeX, m_sizeY; int m_desktopSizeX, m_desktopSizeY; bool m_fullscreen; WindowStyle m_style; std::string m_windowTitle; };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Pool.h #pragma once #include <list> #include <cstdint> class Pool { struct AllocationHeader { size_t size; uint8_t adjustment; }; struct FreeBlock { size_t size; FreeBlock* next; }; void* mp_begin; size_t mi_size; size_t mi_usedMem; size_t mi_numAllocations; Pool(const Pool&); Pool& operator=(const Pool&); FreeBlock* mp_freeBlocks; public: Pool(int pi_KB, void* pp_begin); ~Pool(); void* Alloc(size_t pi_size, uint8_t pi_alignment); void DeAlloc(void* pp_toDelete); int CombineFreeBlocks(); template <typename T> T* create() { T* lp_retval = (T*) (alloc->Alloc(sizeof(T), 4)); new(test) TestGame(); } }; template<class T> void destroy(T* pt, Pool* a) //<-you can't do this with 'delete' { if (pt) { pt->~T(); // run the destructor a->DeAlloc(pt); // deallocate the object pt = NULL; // nulls the pointer on the caller side. } } #define FL_POOL_NEW(pool, t) new(pool->Alloc(sizeof(t), 4)) #define FL_POOL_DELETE destroy<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/IResource.h #pragma once #include "..\FrontlineCommon.h" #include <cctype> class IResource; typedef std::shared_ptr<IResource> ResHandle; class IResource { protected: std::string ms_resourcename; int size; public: IResource(const std::string &ps_resname = "") { ms_resourcename = ps_resname; std::transform(ms_resourcename.begin(), ms_resourcename.end(), ms_resourcename.begin(), (int(*)(int)) std::tolower); } ~IResource(); virtual int VGetType(); virtual int VGetSize() = 0; ResHandle GetHandle() { return ResHandle(this); } std::string GetName() { return ms_resourcename; } };<file_sep>/Source/Frontline Engine/Frontline Game Test/TestGame.h #pragma once #include <gl/GLEW.h> #include <IGame.h> #include <FrontlineCommon.h> #include <Actor\ActorFactory.h> #include <Physics\BulletPhysics.h> #include <System\IWindowManager.h> #include <ActorComponents.h> #include <fstream> #include <System\Time.h> #include <Resource\ZipResourceFile.h> #include <Event\AddCollisionPairEventData.h> #include <Resource\ResCache.h> #ifdef _WIN32 #include <System\Win32WindowManager.h> #define WindowManager Win32WindowManager #endif class TestGame : public IGame { protected: WindowManager* window; ZipResourceFile* zrf; public: Pool* alloc; TestGame(); ~TestGame(); virtual void start() override; void CollisionEventCallback(IEventDataPtr pp_event); void KeyboardCallback(IEventDataPtr pp_event); };<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/Actor.cpp #include "../FrontlineCommon.h" #include <sstream> #include <iostream> Actor::Actor(ActorID p_id) { m_id = p_id; } Actor::~Actor() { } // -------------------------------------------------------------------------- // Function: Actor::Init // Purpose: Initialize an actor. // Parameters: The actor xml node // -------------------------------------------------------------------------- bool Actor::Init(pugi::xml_node pData) { std::stringstream l_msg; l_msg << "Initializing Actor " << m_id; MSGLOG("ACTOR", l_msg.str()); return true; m_components; } // -------------------------------------------------------------------------- // Function: Actor::PostInit // Purpose: Finish component initialization. // Parameters: None // -------------------------------------------------------------------------- void Actor::PostInit(void) { for (ActorComponents::iterator it = m_components.begin(); it != m_components.end(); ++it) { it->second->VPostInit(); } } // -------------------------------------------------------------------------- // Function: Actor::Destroy // Purpose: Destroy an actor and its components. // Parameters: None // -------------------------------------------------------------------------- void Actor::Destroy(void) { m_components.clear(); } // -------------------------------------------------------------------------- // Function: Actor::ToXML // Purpose: Generate the actor XML. // Parameters: None // -------------------------------------------------------------------------- std::string Actor::ToXML() { pugi::xml_document l_outDoc; // Actor element pugi::xml_node l_actorElement = pugi::xml_node(); // components for (auto it = m_components.begin(); it != m_components.end(); ++it) { StrongActorComponentPtr l_component = it->second; pugi::xml_node l_componentElement = l_component->VGenerateXML(); l_actorElement.append_child().set_name(l_componentElement.name()); l_actorElement.child(l_componentElement.name()) = l_componentElement; } std::stringbuf l_retValBuffer; std::ostream l_xmlStream(&l_retValBuffer); l_outDoc.save(l_xmlStream); return l_retValBuffer.str(); } // -------------------------------------------------------------------------- // Function: Actor::AddComponent // Purpose: Attach a component to the actor. // Parameters: A shared pointer to the component // -------------------------------------------------------------------------- void Actor::AddComponent(StrongActorComponentPtr pComponent) { std::pair<ActorComponents::iterator, bool> success = m_components.insert(std::make_pair(pComponent->VGetComponentID(), pComponent)); FL_ASSERT(success.second); } void Actor::Update(int p_deltaMs) { for (ActorComponents::iterator it = m_components.begin(); it != m_components.end(); ++it) { it->second->VUpdate(p_deltaMs); } }<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/PhysicsComponent.cpp #include "PhysicsComponent.h" const std::string PhysicsComponent::g_name = "PhysicsComponent"; PhysicsComponent::PhysicsComponent() { } PhysicsComponent::~PhysicsComponent() { } // -------------------------------------------------------------------------- // Function: PhysicsComponent::VGenerateXML // Purpose: Convert the component to xml // Parameters: None // -------------------------------------------------------------------------- pugi::xml_node PhysicsComponent::VGenerateXML() { pugi::xml_node ln_outNode; ln_outNode.set_name(VGetComponentName().c_str()); std::stringbuf l_retValBuffer; std::ostream l_xmlStream(&l_retValBuffer); return ln_outNode; } // -------------------------------------------------------------------------- // Function: PhysicsComponent::VInit // Purpose: Initialize the component with an xml node // Parameters: The xml node to be used // -------------------------------------------------------------------------- bool PhysicsComponent::VInit(pugi::xml_node pn_data) { std::shared_ptr<IPhysics> l_strongPhysicsPtr = IGame::gp_game->mp_physics; mp_gamePhysics = std::weak_ptr<IPhysics>(l_strongPhysicsPtr); if (!l_strongPhysicsPtr) return false; pugi::xml_node ln_shape = pn_data.child("Shape").first_child(); if (ln_shape.value() != "") { ms_shape = ln_shape.value(); mn_shapeInfo = ln_shape; } pugi::xml_node ln_density = pn_data.child("Density").first_child(); if (ln_density.value() != "") { ms_density = ln_density.value(); } pugi::xml_node ln_material = pn_data.child("Material").first_child(); if (ln_material.value() != "") { ms_material = ln_material.value(); } pugi::xml_node ln_transform = pn_data.child("Transform"); BuildRigidBodyTransform(ln_transform); pugi::xml_node ln_channels = pn_data.child("CollisionChannels"); m_collisionType = atoi(ln_channels.child("Type").first_child().value()); m_collidesWith = atoi(ln_channels.child("CollideWith").first_child().value()); return true; } // -------------------------------------------------------------------------- // Function: PhysicsComponent::BuildRigidBodyTransform // Purpose: A helper function to build a transform matrix using an xml node // Parameters: The xml node to be used // -------------------------------------------------------------------------- void PhysicsComponent::BuildRigidBodyTransform(pugi::xml_node pn_data) { glm::vec3 lv_translate, lv_rotate, lv_scale; pugi::xml_node ln_translation = pn_data.child("Translation"); //if (ln_translation.value() != "") { if (ln_translation.child("x").first_child().value() != "") lv_translate.x = atof(ln_translation.child("x").first_child().value()); if (ln_translation.child("y").first_child().value() != "") lv_translate.x = atof(ln_translation.child("y").first_child().value()); if (ln_translation.child("z").first_child().value() != "") lv_translate.x = atof(ln_translation.child("z").first_child().value()); } pugi::xml_node ln_rotation = pn_data.child("Rotation"); //if (ln_rotation.value() != "") { if (ln_rotation.child("x").first_child().value() != "") lv_rotate.x = atof(ln_rotation.child("x").first_child().value()); if (ln_rotation.child("y").first_child().value() != "") lv_rotate.y = atof(ln_rotation.child("y").first_child().value()); if (ln_rotation.child("z").first_child().value() != "") lv_rotate.z = atof(ln_rotation.child("z").first_child().value()); } pugi::xml_node ln_scale = pn_data.child("Scale"); //if (ln_scale.value() != "") { if (ln_scale.child("x").first_child().value() != "") lv_scale.x = atof(ln_scale.child("x").first_child().value()); if (ln_scale.child("y").first_child().value() != "") lv_scale.y = atof(ln_scale.child("y").first_child().value()); if (ln_scale.child("z").first_child().value() != "") lv_scale.z = atof(ln_scale.child("z").first_child().value()); } glm::mat4 lm_translate = glm::translate(lv_translate); glm::mat4 lm_rotate = glm::translate(lv_rotate); glm::mat4 lm_scale = glm::translate(lv_scale); mm_transform = lm_scale * lm_rotate; mm_transform *= lm_translate; } // -------------------------------------------------------------------------- // Function: PhysicsComponent::VPostInit // Purpose: Finish component initialization // Parameters: None // -------------------------------------------------------------------------- void PhysicsComponent::VPostInit() { if (m_owner) { if (ms_shape == "Sphere") { MakeStrongPtr<IPhysics>(mp_gamePhysics)->VAddSphere(getScaleFromMat(mm_transform).x, std::weak_ptr<Actor>(m_owner), ms_density, ms_material, m_collisionType, m_collidesWith); } else if (ms_shape == "Box") { MakeStrongPtr<IPhysics>(mp_gamePhysics)->VAddBox(getScaleFromMat(mm_transform), std::weak_ptr<Actor>(m_owner), ms_density, ms_material, m_collisionType, m_collidesWith); } else if (ms_shape == "Cylinder") { MakeStrongPtr<IPhysics>(mp_gamePhysics)->VAddCylinder(getScaleFromMat(mm_transform).x, getScaleFromMat(mm_transform).y, std::weak_ptr<Actor>(m_owner), ms_density, ms_material, m_collisionType, m_collidesWith); } else if (ms_shape == "PointCloud") { ERRLOG("Physics", "Point Cloud not supported"); } } }<file_sep>/Source/Frontline/effectSysTestP2/flFxParserGL.h #pragma once #include "flFxParser.h" class flFxParserGL : public flFxParser { public: flFxParserGL(); ~flFxParserGL(); bool HandleEffectNode(pugi::xml_node node); //no references bool HandleTechniqueNode(pugi::xml_node node); bool HandlePassNode(pugi::xml_node node); bool HandleShaderBodyNode(pugi::xml_node node); bool HandleResourceBodyNode(pugi::xml_node node); bool HandleFrameBufferObjectBodyNode(pugi::xml_node node); bool HandleStateNode(pugi::xml_node node); static flFxParserGL* Get(); }; <file_sep>/Source/Frontline Engine/Frontline Engine/Event/EventManager.cpp #include "EventManager.h" static EventManager* eventManager = FL_NEW EventManager(); // -------------------------------------------------------------------------- // Function: EventManager::Get // Purpose: Static method to get the singleton event manager. // Parameters: None // -------------------------------------------------------------------------- EventManager* EventManager::Get(void) { return eventManager; } // -------------------------------------------------------------------------- // Function: EventManager::VAddListener // Purpose: Add a new event listener. // Parameters: Delegate function, event type to listen to // -------------------------------------------------------------------------- bool EventManager::VAddListener(const EventListenerDelegate& eventDelegate, const EventType& type) { auto it = m_eventListeners.find(type); if (it == m_eventListeners.end()) { EventListenerList ell; ell.push_back(eventDelegate); m_eventListeners[type] = ell; } else { for (auto iter = it->second.begin(); iter != it->second.end(); iter++) { if (eventDelegate == (*iter)) { return false; } } m_eventListeners[type].push_back(eventDelegate); } return true; } // -------------------------------------------------------------------------- // Function: EventManager::VRemoveListener // Purpose: Remove an event listener // Parameters: Delegate to be removed, event type of delegate // -------------------------------------------------------------------------- bool EventManager::VRemoveListener(const EventListenerDelegate& eventDelegate, const EventType& type) { //basically //auto it = m_eventListeners.find(type); //m_eventListeners[type].erase(it); bool success = false; auto it = m_eventListeners.find(type); if (it != m_eventListeners.end()) { for (auto iter = it->second.begin(); iter != it->second.end(); iter++) { if (eventDelegate == (*iter)) { m_eventListeners[type].erase(iter); success = true; break; } } } return success; } // -------------------------------------------------------------------------- // Function: EventManager::VTriggerEvent // Purpose: Fire event with immediate callbacks - VQueueEvent usually better // Parameters: Event to trigger // -------------------------------------------------------------------------- bool EventManager::VTriggerEvent(const IEventDataPtr& pEvent) const { bool processed = false; auto it = m_eventListeners.find(pEvent->VGetEventType()); if (it != m_eventListeners.end()) { for (auto iter = it->second.begin(); iter != it->second.end(); iter++){ EventListenerDelegate listener = (*iter); listener(pEvent); processed = true; } } return processed; } // -------------------------------------------------------------------------- // Function: EventManager::VQueueEvent // Purpose: Add an event to the queue for processing. // Parameters: Event to queue // -------------------------------------------------------------------------- bool EventManager::VQueueEvent(const IEventDataPtr& pEvent) { auto findIt = m_eventListeners.find(pEvent->VGetEventType()); if (findIt != m_eventListeners.end()) { m_queues[m_activeQueue].push_back(pEvent); return true; } return false; } // -------------------------------------------------------------------------- // Function: EventManager::VAbortEvent // Purpose: Abort a single event or all events of a specific type // Parameters: Type to abort, should delete all of type // -------------------------------------------------------------------------- bool EventManager::VAbortEvent(const EventType& inType, bool allOfType) { bool success = false; //check to see if the event has delegates auto it = m_eventListeners.find(inType); if (it != m_eventListeners.end()) { //if so, iterate through the queue deleting the //events that match inType auto it = m_queues[m_activeQueue].begin(); while (it != m_queues[m_activeQueue].end()) { auto thisIt = it; it++; if ((*thisIt)->VGetEventType() == inType) { m_queues[m_activeQueue].erase(thisIt); success = true; if (!allOfType) break; } } } return success; } // -------------------------------------------------------------------------- // Function: EventManager::VUpdate // Purpose: Process the events in queue // Parameters: Maximum time to run before leaving the remaining events for the next call // -------------------------------------------------------------------------- bool EventManager::VUpdate(unsigned long maxMillis) { while (!m_queues[m_activeQueue].empty()) { //get front of queue IEventDataPtr pEvent = m_queues[m_activeQueue].front(); //delete or "pop" the front of the queue m_queues[m_activeQueue].pop_front(); auto it = m_eventListeners.find(pEvent->VGetEventType()); if (it != m_eventListeners.end()) { for (auto iter = it->second.begin(); iter != it->second.end(); iter++) { EventListenerDelegate listener = (*iter); listener(pEvent); } } } return true; } <file_sep>/Source/Frontline/effectSysTestP2/StatesGL.h #pragma once #include "flFxGL.h" struct BlendGL : public State1<bool> { BlendGL() { m_State = FX_BLEND; } bool Load(pugi::xml_node node) { m_v = node.attribute("blend").as_bool(); return true; } bool Apply() { if (m_v == true) glEnable(GL_BLEND); else glDisable(GL_BLEND); return true; } bool Cleanup() { if (m_v == true) glDisable(GL_BLEND); else glEnable(GL_BLEND); return true; } }; struct BlendFuncGL : public State2<GLenum, GLenum> { BlendFuncGL() { m_State = FX_BLEND_FUNC; } bool Load(pugi::xml_node node) { m_v1 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("src").value()); m_v2 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("dst").value()); return true; } bool Apply() { glBlendFunc(m_v1, m_v2); return true; } }; struct AlphaFuncGL : public State2<GLenum, GLclampf> { AlphaFuncGL() { m_State = FX_ALPHA_FUNC; } bool Load(pugi::xml_node node) { m_v1 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("func").value()); m_v2 = StateInterpreter::Get()->Convert<GLclampf>(node.attribute("ref").value()); return true; } bool Apply() { glAlphaFunc(m_v1, m_v2); return true; } }; struct BlendFuncSeparateGL : public State4<GLenum, GLenum, GLenum, GLenum> { BlendFuncSeparateGL() { m_State = FX_BLEND_FUNC_SEPARATE; } bool Load(pugi::xml_node node) { m_v1 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("srcRGB").value()); m_v2 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("dstRGB").value()); m_v3 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("srcAlpha").value()); m_v4 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("dstAlpha").value()); return true; } bool Apply() { glBlendFuncSeparate(m_v1, m_v2, m_v3, m_v4); return true; } }; struct BlendEquationSeparateGL : public State2<GLenum, GLenum> { BlendEquationSeparateGL() { m_State = FX_BLEND_EQUATION_SEPARATE; } bool Load(pugi::xml_node node) { m_v1 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("modeRGB").value()); m_v2 = StateInterpreter::Get()->Convert<GLenum>(node.attribute("modeAlpha").value()); return true; } bool Apply() { glBlendEquationSeparate(m_v1, m_v2); return true; } }; struct LogicOpGL : public State1<GLenum> { LogicOpGL() { m_State = FX_LOGIC_OP; } bool Load(pugi::xml_node node) { m_v = StateInterpreter::Get()->Convert<GLenum>("opcode"); return true; } bool Apply() { glEnable(GL_COLOR_LOGIC_OP); glLogicOp(m_v); return true; } bool Cleanup() { glDisable(GL_COLOR_LOGIC_OP); return true; } }; struct ColorMaskGL : public State4<bool, bool, bool, bool> { ColorMaskGL() { m_State = FX_COLOR_MASK; } bool Load(pugi::xml_node node) { m_v1 = node.attribute("red").as_bool(); m_v2 = node.attribute("green").as_bool(); m_v3 = node.attribute("blue").as_bool(); m_v4 = node.attribute("alpha").as_bool(); return true; } bool Apply() { GLboolean red = m_v1 ? GL_TRUE : GL_FALSE; GLboolean green = m_v2 ? GL_TRUE : GL_FALSE; GLboolean blue = m_v3 ? GL_TRUE : GL_FALSE; GLboolean alpha = m_v4 ? GL_TRUE : GL_FALSE; glColorMask(red, green, blue, alpha); return true; } }; struct BlendColorGL : public State4<GLfloat, GLfloat, GLfloat, GLfloat> { BlendColorGL() { m_State = FX_BLEND_COLOR; } bool Load(pugi::xml_node node) { m_v1 = StateInterpreter::Get()->Convert<GLfloat>(node.attribute("red").value()); m_v2 = StateInterpreter::Get()->Convert<GLfloat>(node.attribute("green").value()); m_v3 = StateInterpreter::Get()->Convert<GLfloat>(node.attribute("blue").value()); m_v4 = StateInterpreter::Get()->Convert<GLfloat>(node.attribute("alpha").value()); return true; } bool Apply() { glBlendColor(m_v1, m_v2, m_v3, m_v4); return true; } };<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/BulletDebugDrawer.h #pragma once #include "..\FrontlineCommon.h" #include <PHYSICS\LinearMath\btIDebugDraw.h> #include <gl/GL.h> class BulletDebugDrawer : public btIDebugDraw { int m_debugMode; public: BulletDebugDrawer(); ~BulletDebugDrawer(); virtual void drawLine(const btVector3& pv_from, const btVector3& pv_to, const btVector3& pv_color) override; virtual void drawLine(const btVector3& pv_from, const btVector3& pv_to, const btVector3& pv_colorFrom, const btVector3& pv_colorTo) override; virtual void drawContactPoint(const btVector3& pv_point, const btVector3& pv_normal, btScalar pf_distance, int pi_lifeTime, const btVector3& pv_color) override; virtual void reportErrorWarning(const char* ps_warningString) override; virtual void setDebugMode(int pi_mode) override; virtual int getDebugMode() const override; virtual void draw3dText(const btVector3& pv_location, const char* ps_textString) override; virtual void drawTriangle(const btVector3& pv_vert1, const btVector3& pv_vert2, const btVector3& pv_vert3, const btVector3& pv_color, btScalar pv_alpha); virtual void drawSphere(const btVector3& pv_center, btScalar pf_radius, const btVector3& pv_color); };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Log.cpp #include "Log.h" #include <fstream> #include <cctype> #include "Win32Console.h" Log::Log() { c = new Win32Console(); } Log::~Log() { } // -------------------------------------------------------------------------- // Function: Log::LogError // Purpose: Log an error message // Parameters: The message to be logged // -------------------------------------------------------------------------- void Log::logError(std::string p_cat, std::string p_error) { std::transform(p_cat.begin(), p_cat.end(), p_cat.begin(), (int(*)(int)) std::toupper); m_log.push_back(std::pair<int, std::string>(0xFFFFFFFF, "[" + Time::g_Time->getFormattedDateTime() + "] [ERROR] [" + p_cat + "] " + p_error)); } // -------------------------------------------------------------------------- // Function: Log::LogWarning // Purpose: Log a warning message // Parameters: The message to be logged // -------------------------------------------------------------------------- void Log::logWarning(std::string p_cat, std::string p_warning) { std::transform(p_cat.begin(), p_cat.end(), p_cat.begin(), (int(*)(int)) std::toupper); m_log.push_back(std::pair<int, std::string>(1, "{color:1,1,0}[" + Time::g_Time->getFormattedDateTime() + "] [WARNING] [" + p_cat + "] " + p_warning)); } // -------------------------------------------------------------------------- // Function: Log::LogOther // Purpose: Log a debug message // Parameters: The message category, the message to be logged // -------------------------------------------------------------------------- void Log::logOther(std::string p_cat, std::string p_message) { std::transform(p_cat.begin(), p_cat.end(), p_cat.begin(), (int(*)(int)) std::toupper); m_log.push_back(std::pair<int, std::string>(0, "{color:1,1,0}[" + Time::g_Time->getFormattedDateTime() + "] [" + p_cat + "] " + p_message)); } // -------------------------------------------------------------------------- // Function: Log::dumpLog // Purpose: Dump the contents of the log to a string and return them // Parameters: None // -------------------------------------------------------------------------- std::vector<std::pair<int, std::string>> Log::dumpLog() { auto l_retval = m_log; m_log.clear(); for (int i = 0; i < l_retval.size(); i++) { // TODO Get rid of this, it is for testing the console c->printf(l_retval[i].second.append("\n").c_str()); } return l_retval; } // -------------------------------------------------------------------------- // Function: Log::dumpToFile // Purpose: Dump the contents of the log to a specified file // Parameters: The name of the file // -------------------------------------------------------------------------- bool Log::dumpToFile(std::string p_fileName) { std::ofstream l_logFile; l_logFile.open(p_fileName); std::string ls_text; for (int i = 0; i < m_log.size(); i++) { ls_text.append(m_log[i].second); ls_text.append("\n"); } if (l_logFile.is_open()) { l_logFile << ls_text; l_logFile.close(); m_log.clear(); return true; } logError("Log", "Log dump failed: cannot open file " + p_fileName + ". Dumping instead to default file (logs\\M-D-Y H.M.S"); return false; } // -------------------------------------------------------------------------- // Function: Log::dumpToFile // Purpose: Dump the contents of the log to the default file // Parameters: None // -------------------------------------------------------------------------- bool Log::dumpToFile() { return dumpToFile("logs\\" + Time::g_Time->getFormattedDateTime() + ".log"); }<file_sep>/Source/Frontline/effectSysTestP2/texture.cpp #include "texture.h" GLuint loadTexture(const char* filename) { GLuint id; sf::Image Image; Image.loadFromFile(filename); glGenTextures(1, &id); // Bind the texture object glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 0, 4, Image.getSize().x, Image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, Image.getPixelsPtr()); // Set the texture's stretching properties /*glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);*/ return id; }<file_sep>/Source/Frontline/effectSysTestP2/flFxGL.h #pragma once #include "GL.h" #include "flFxExt.h" #include "StatesGL.h" #include "GLenum.h" #include <fstream> /*class PassGL : public Pass { public: PassGL(const char* name) : Pass(name) {} ~PassGL() {} virtual bool Execute(); };*/ class flFxCoreGL : public flFxCore { private: GLuint m_FullscreenQuadId; public: flFxCoreGL() {} ~flFxCoreGL() {} bool Init(); bool Shutdown(); void DrawFullscreenQuad(); static std::shared_ptr<flFxCoreGL> Get(); }; class StateGroupGL : public StateGroup { private: public: StateGroupGL(); virtual ~StateGroupGL(); bool Apply(); bool Execute() { return Apply(); } bool Cleanup(); }; class GLSLShader : public Shader { private: GLuint m_Id; GLenum m_Type; public: GLSLShader(const char* name,GLenum type, const char* string = NULL); virtual ~GLSLShader(); bool LoadShader(const char* string); bool LoadShaderFromFile(const char* filePath); bool Validate(); //create shaderprogram bool Invalidate(); //destroy shaderprogram void Bind(); void Unbind(); bool IsValid() {return (m_Validated && m_Id) ? true : false;} GLenum GetType() {return m_Type;} GLuint GetProgramId() {return m_Id;} friend class flFxParser; //temp }; class PipelineGL : public GPUPipeline { private: GLuint m_Id; public: PipelineGL(){} virtual ~PipelineGL(); bool Validate(); bool Execute() { Bind(); return true; } bool Cleanup() { Unbind(); return true; } bool Invalidate(); bool SetShader(std::shared_ptr<Shader> shader); void SetShaders(std::shared_ptr<Shader>* shaders,int count) {} bool RemoveShader(const char* name); //GetShader doesnt need to be overrided, handled by GPUPipeline already void ClearAll() {} bool IsValid() {return m_Id ? true : false;} void Bind(); void Unbind(); }; class ShaderParameterGL : public ShaderParameter { public: enum Type { T1F, T1I, T1FV, T2F, T2I, T2FV, T3F, T3I, T3FV, TMATRIX4FV, TSUBROUTINE }; struct Target { GLenum shaderType; //for subroutines int shaderNumber; int uniformLocation; }; private: Type m_Type; std::vector<Target> m_Targets; GLsizei m_Size; GLboolean m_Transpose; public: ShaderParameterGL(const char* name,Type type,float* value = NULL); //single uniforms ShaderParameterGL(const char* name,Type type,GLsizei count, float* value = NULL); //arrays of uniforms ShaderParameterGL(const char* name,Type type,GLsizei count, GLboolean transpose ,float* value = NULL); //matrices virtual ~ShaderParameterGL(); bool Validate(); bool Invalidate(); bool Update(); bool Execute() { return Update(); } void SetValue(GLsizei count, float* value) {} void SetValue(GLsizei count, GLboolean transpose, float* value) {} }; class SamplerStateGL : public SamplerState { private: bool m_HasChanged; GLuint m_Id; public: SamplerStateGL(const char* name); virtual ~SamplerStateGL(); bool Validate(); bool Invalidate(); bool AddState(std::shared_ptr<BlankState> state); bool RemoveState(fxState state); bool UpdateTexture(int texUnit); }; class ResourceGL : public Resource { private: GLuint m_Id; int m_TexUnit; int m_FBOAttachment; bool CreateRenderTexture(); bool CreateDepthTexture(); public: ResourceGL(const char* name, fxState resType); virtual ~ResourceGL(); bool Validate(); bool Execute() { Bind(); return true; } bool Cleanup() { Unbind(); return true; } bool Invalidate(); void SetTexture(GLuint id) { m_Id = id; } void SetTexture(GLuint id, int unit) { m_Id = id; m_TexUnit = unit; } void SetTexUnit(int unit) { m_TexUnit = unit; } GLuint GetTextureId() { return m_Id; } int GetTexUnit() { return m_TexUnit; } void SetFBOAttachment(int attachment) { m_FBOAttachment = attachment; } int GetFBOAttachment() { return m_FBOAttachment; } void Bind(); void Unbind(); bool IsValid(); // bool Update(); //well all this can be handled in ResourceGL::Bind() including updating samplers }; class FrameBufferObjectGL : public FrameBufferObject { private: GLuint m_Id; fxState m_ClearMode[3]; //make independent? public: FrameBufferObjectGL(const char* name) : FrameBufferObject(name) { m_Id = NULL; } ~FrameBufferObjectGL(); bool Validate(); bool Execute(); bool Cleanup() { ReleaseCurrent(); return true; } bool Invalidate(); void SetDSTTexture(std::shared_ptr<Resource> res); bool AddTextureResource(std::shared_ptr<Resource> res); GLuint GetFBOId() { return m_Id; } void SetCurrent(); void ReleaseCurrent(); void SetClearMode(fxState clear1, fxState clear2 = NULL, fxState clear3 = NULL); }; class RenderingModeGL : public PassDesc { private: fxState m_RenderingMode; public: RenderingModeGL(fxState renderMode); ~RenderingModeGL() {} fxState GetRenderingMode() { return m_RenderingMode; } bool Execute(); //draw fullscreen quad or do nothing }; class ClearModeGL : public PassDesc { private: fxState m_ClearMode[3]; public: ClearModeGL(fxState clear1, fxState clear2 = FX_DO_NOTHING, fxState clear3 = FX_DO_NOTHING); ~ClearModeGL() {} void SetClearMode(fxState clear1, fxState clear2 = FX_DO_NOTHING, fxState clear3 = FX_DO_NOTHING); bool Execute(); };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/DefaultResource.h #pragma once #include "IResourceLoader.h" #include "ResCache.h" #define RESOURCE_TEXT 0x00000001 class DefaultResource : public IResource { std::string* contents; public: DefaultResource(const std::string &ps_resname = ""); std::string getContents(); void setContents(std::string ps_contents); void setContents(std::string* ps_contents); virtual int VGetSize() override; virtual int VGetType() override; }; class DefaultResourceLoader : public IResourceLoader { public: virtual std::string VGetPattern() { return "*"; } virtual bool VUseRawFile(); virtual unsigned int VGetLoadedResourceSize(char *rawBuffer, unsigned int rawSize); virtual bool VLoadResource(ResHandle& pp_retval, char *rawBuffer, const char* name, AllocationFunction alloc); };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Win32WindowManager.h #pragma once #include "../FrontlineCommon.h" #include "../IGame.h" #include <Windows.h> #include "IWindowManager.h" #include "..\KeyboardEventData.h" class Win32WindowManager : public IWindowManager { public: static std::map<HWND, Win32WindowManager*> g_managerLookup; virtual void createGLContext() override; virtual void open(int p_sizeX, int p_sizeY, std::string p_windowTitle, bool p_singleInstance, bool p_fullscreen, WindowStyle p_style = OVERLAPPEDWINDOW, int p_posX = 0, int p_posY = 0) override; virtual bool resize(int p_sizeX_n, int p_sizeY_n, int p_posX_n = 0, int p_posY_n = 0) override; virtual void destroyGLContext() override; virtual void makeGLContextCurrent() override; virtual void swapGLBuffers() override; virtual void close() override; virtual bool setFullscreen(bool p_Fullscreen) override; virtual void updateWindow() override; virtual bool isOpen() override; Win32WindowManager(void); ~Win32WindowManager(void); void Win32WindowManager::processKeyboardEvent(WPARAM p_code, bool p_down); protected: WNDCLASSEX m_windowClass; HWND m_windowHandle; HDC m_deviceContextHandle; HGLRC m_glContextHandle; HDC m_oldDeviceContextHandle; HGLRC m_oldGLContextHandle; bool m_open; };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/Resource.h #pragma once #include "..\FrontlineCommon.h" #include <cctype> class Resource; typedef std::shared_ptr<Resource> ResHandle; class Resource { public: std::string m_name; ResHandle GetHandle() { return ResHandle(this); } Resource(const std::string &name) { m_name = name; std::transform(m_name.begin(), m_name.end(), m_name.begin(), (int(*)(int)) std::tolower); } };<file_sep>/Source/Frontline Engine/Frontline Engine/ActorComponents.h #include "Physics\PhysicsComponent.h" #include "Actor\TransformComponent.h"<file_sep>/Source/Frontline/effectSysTestP2/flFx.h #pragma once #include <map> #include <iostream> #include <list> #include <vector> #include <memory> #include <stack> #include "GL.h" #include "flFxConfig.h" class PassDesc; class Pass; class Technique; class Effect; class Repository; typedef unsigned int fxState; class flFxCore { public: virtual bool Init() { return true; } virtual bool Shutdown() { return true; } virtual void DrawFullscreenQuad() {} virtual void DrawTriangle(int x, int y, int z) {} }; class PassDesc : public std::enable_shared_from_this<PassDesc> { protected: struct Dependency { Dependency() : flag(NULL), name(NULL) {} const char* name; fxState flag; }; bool m_Active; bool m_Validated; bool m_Modified; //if the PassDesc has been modified since validation const char* m_Name; fxState m_Flag; std::weak_ptr<Pass> m_Parent; std::vector<Dependency> m_Owners; std::vector<Dependency> m_Data; public: PassDesc(fxState flag,const char* name = NULL); virtual ~PassDesc(); virtual void SetName(const char* name) {m_Name = name;} virtual const char* GetName() {return m_Name;} virtual void SetFlag(fxState flag) {m_Flag = flag;} virtual fxState GetFlag() {return m_Flag;} virtual void SetActive(bool active) { m_Active = active; } virtual bool IsActive() { return m_Active; } virtual bool IsValid() {return m_Validated;} virtual bool HasChanged() { return m_Modified; } virtual void SetParent(std::shared_ptr<Pass> parent) {m_Parent = parent;} protected: virtual void SetValidated(bool validated) { m_Validated = validated; } virtual bool Attach(std::shared_ptr<PassDesc> dep) { return true; } //atach the shit on create data virtual bool Attach(const char* name) { return true; } virtual bool Attach(fxState flag) { return true; } virtual bool Detach(std::shared_ptr<PassDesc> dep) { return true; } virtual bool Detach(const char* name) { return true; } virtual bool Detach(fxState flag) { return true; } virtual bool AttachTo(std::shared_ptr<PassDesc> owner) { return true; } //creates a dependency ref to it virtual bool AttachTo(const char* name) { return true; } virtual bool AttachTo(fxState flag) { return true; } virtual bool DetachFrom(std::shared_ptr<PassDesc> owner) { return true; } virtual bool DetachFrom(const char* name) { return true; } virtual bool DetachFrom(fxState flag) { return true; } virtual std::shared_ptr<PassDesc> GetFromDependency(Dependency dep) { return nullptr; } virtual void GetFromDependency(Dependency dep, std::vector<Dependency> deps) {} virtual bool OnCreateData() { return true; } //do attachments, not called in CreateData of pass virtual void RunAttachments() {} //called internally in Pass::Validate to attach everything virtual bool Validate() { SetValidated(true); return true; } //virtual bool ValidateImpl() { return true; } virtual bool Execute() { return true; } virtual bool Cleanup() { return true; } virtual bool Invalidate() { SetValidated(false); return true; } //virtual bool InvalidateImpl() { return true; } virtual bool OnDestroyData() { return true; } //detach the shit friend class Pass; }; class Pass : public std::enable_shared_from_this<Pass> { protected: typedef std::vector<std::shared_ptr<PassDesc>> PassDataVec; struct Layer { Layer() {} ~Layer() {} PassDataVec dataForValidation; PassDataVec dataForExecution; }; std::map<int,Layer> m_Layers; PassDataVec m_Overrides; int m_BaseLayer; int m_ActiveLayer; std::weak_ptr<Technique> m_Parent; std::map<fxState,std::vector<std::shared_ptr<PassDesc>>> m_PassInfo; static std::vector<fxState> m_ExecutionConfig; std::map<std::shared_ptr<Pass>,int> m_OverrideIds; bool m_Validated; const char* m_Name; public: Pass(const char* name); ~Pass(); void SetParent(std::shared_ptr<Technique> parent) {m_Parent = parent;} void SetName(const char* name) {m_Name = name;} const char* GetName() {return m_Name;} bool IsValid() {return m_Validated;} static void ConfigureExecution(std::vector<fxState> flags) { m_ExecutionConfig = flags; } bool Validate(); bool Execute(); bool Cleanup(); bool Invalidate(); void SetActiveLayer(int layer, bool copyFromPrev); void CreateData(std::shared_ptr<PassDesc> data); void CreateDataOverride(std::shared_ptr<PassDesc> data); void Replace(std::shared_ptr<PassDesc> data); void Replace(const char* name, std::shared_ptr<PassDesc> data); std::shared_ptr<PassDesc> Find(const char* name); std::shared_ptr<PassDesc> Find(fxState flag); void Find(fxState flag, std::vector<std::shared_ptr<PassDesc>>* data); std::shared_ptr<PassDesc> FindOverride(const char* name); std::shared_ptr<PassDesc> FindOverride(fxState flag); void FindOverride(fxState flag, std::vector<std::shared_ptr<PassDesc>>* data); bool RemoveData(std::shared_ptr<PassDesc> data); bool RemoveData(const char* name); bool RemoveData(fxState flag); void ClearData() {m_Layers[m_ActiveLayer].dataForExecution.clear();} void SetupOverrides(std::shared_ptr<Technique>* dest,int numTechs); void SetupOverrides(std::shared_ptr<Pass>* dest,int numPasses); void ReleaseOverrides(std::shared_ptr<Technique>* dest,int numTechs); void ReleaseOverrides(std::shared_ptr<Pass>* dest,int numPasses); bool RemoveLayer(int layer); bool RemoveActiveLayer(); Layer& GetLayer() {return m_Layers[m_ActiveLayer];} Layer& GetBaseLayer() {return m_Layers[0];} int GetActiveLayerId() {return m_ActiveLayer;} friend class PassDesc; }; class Technique : public std::enable_shared_from_this<Technique> { private: struct PassInfo { std::shared_ptr<Pass> pass; bool isActive; }; std::vector<PassInfo> m_Passes; const char* m_Name; public: Technique(const char* name) {m_Name = name;} ~Technique(); void SetName(const char* name) {m_Name = name;} const char* GetName() {return m_Name;} bool Validate(); bool Invalidate(); bool AddPass(std::shared_ptr<Pass> pass); bool RemovePass(std::shared_ptr<Pass> pass); int GetNumPasses() {return (int)m_Passes.size();} void SetPassActive(int index,bool active); void SetPassActive(const char* name,bool active); bool GetPassActive(int index); bool GetPassActive(const char* name); std::shared_ptr<Pass> GetPass(int index); std::shared_ptr<Pass> GetPass(const char* name); }; class Effect : public std::enable_shared_from_this<Effect> { private: std::vector<std::shared_ptr<Technique>>m_Techniques; const char* m_Name; public: Effect(const char* name) {m_Name = name;} ~Effect(); void SetName(const char* name) {m_Name = name;} const char* GetName() {return m_Name;} bool AddTechnique(std::shared_ptr<Technique> technique); bool RemoveTechnique(std::shared_ptr<Technique> technique); std::shared_ptr<Technique> GetTechnique(int index); std::shared_ptr<Technique> GetTechnique(const char* name); int GetNumTechniques() {return (int)m_Techniques.size();} }; class Repository { private: std::vector<std::shared_ptr<PassDesc>>m_Items; public: virtual ~Repository(); virtual bool AddItem(std::shared_ptr<PassDesc> item); virtual bool RemoveItem(const char* name); virtual bool RemoveItem(std::shared_ptr<PassDesc> item); virtual std::shared_ptr<PassDesc> Find(const char* name); virtual std::shared_ptr<PassDesc> Find(unsigned int index); virtual unsigned int GetSize() {return (unsigned int)m_Items.size();} std::shared_ptr<Repository> Get(); }; <file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/ResourceZipFile.cpp #include "ResourceZipFile.h" ResourceZipFile::~ResourceZipFile() { SAFE_DELETE(m_pZipFile); } bool ResourceZipFile::VOpen() { m_pZipFile = FL_NEW ZipFile; if (m_pZipFile) { return m_pZipFile->Init(m_resFileName.c_str()); } return false; } int ResourceZipFile::VGetRawResourceSize(const Resource &r) { int resourceNum = m_pZipFile->Find(r.m_name.c_str()); if (resourceNum == -1) return -1; return m_pZipFile->GetFileLen(resourceNum); } int ResourceZipFile::VGetRawResource(const Resource &r, char *buffer) { int size = 0; optional<int> resourceNum = m_pZipFile->Find(r.m_name.c_str()); if (resourceNum.valid()) { size = m_pZipFile->GetFileLen(*resourceNum); m_pZipFile->ReadFile(*resourceNum, buffer); } return size; } int ResourceZipFile::VGetNumResources() const { return (m_pZipFile == NULL) ? 0 : m_pZipFile->GetNumFiles(); } std::string ResourceZipFile::VGetResourceName(int num) const { std::string resName = ""; if (m_pZipFile != NULL && num >= 0 && num<m_pZipFile->GetNumFiles()) { resName = m_pZipFile->GetFilename(num); } return resName; }<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/IResourceLoader.h #pragma once #include "..\FrontlineCommon.h" #include "Resource.h" class IResourceLoader { public: virtual std::string VGetPattern() = 0; virtual bool VUseRawFile() = 0; virtual unsigned int VGetLoadedResourceSize( char *rawBuffer, unsigned int rawSize) = 0; virtual ResHandle VLoadResource(char *rawBuffer, char* name) = 0; };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/IResourceLoader.h #pragma once #include "IResource.h" typedef fastdelegate::FastDelegate1<unsigned int, char*> AllocationFunction; class IResourceLoader { public: virtual std::string VGetPattern() = 0; virtual bool VUseRawFile() = 0; virtual unsigned int VGetLoadedResourceSize( char *rawBuffer, unsigned int rawSize) = 0; virtual bool VLoadResource(ResHandle& pp_retval, char *rawBuffer, const char* name, AllocationFunction alloc) = 0; };<file_sep>/Source/Frontline Engine/Frontline Engine/KeyboardEventData.h #pragma once #include "FrontlineCommon.h" #include "Event\EventManager.h" class KeyboardEventData : public BaseEventData { public: static EventType sk_eventType; bool m_down; int code; KeyboardEventData(); ~KeyboardEventData(); virtual const EventType& VGetEventType(void) const override { return sk_eventType; }; virtual void VSerialize(std::ostrstream &out) const override { } virtual void VDeserialize(std::istrstream& in) override { } virtual const char* GetName(void) const { return "EvtData_Keyboard"; }; };<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/Actor.h #pragma once #include "../FrontlineCommon.h" #include <map> #include <memory> #include <XML/pugixml.hpp> #include <sstream> #include "ActorComponent.h" class Actor; typedef unsigned long ActorID; typedef std::shared_ptr<Actor> StrongActorPtr; typedef std::weak_ptr<Actor> WeakActorPtr; class Actor { friend class ActorFactory; typedef std::map<ComponentID, StrongActorComponentPtr> ActorComponents; ActorID m_id; ActorComponents m_components; public: explicit Actor(ActorID p_id); ~Actor(void); bool Init(pugi::xml_node p_Data); void PostInit(); void Destroy(); void Update(int p_deltaMs); ActorID GetID() { return m_id; } std::string ToXML(); template <class ComponentType> std::weak_ptr<ComponentType> GetComponent(ComponentID p_id) { ActorComponents::iterator l_findIt = m_components.find(p_id); if (l_findIt != m_components.end()) { StrongActorComponentPtr lp_base(l_findIt->second); // cast to subclass version of the pointer std::shared_ptr<ComponentType> l_sub(std::static_pointer_cast<ComponentType>(lp_base)); std::weak_ptr<ComponentType> l_weakSub(l_sub); // convert strong pointer to weak pointer return l_weakSub; // return the weak pointer } else { return std::weak_ptr<ComponentType>(); } } template <class ComponentType> std::weak_ptr<ComponentType> GetComponent(std::string ps_name) { return GetComponent<ComponentType>(ActorComponent::HashComponentName(ps_name)); } private: void AddComponent(StrongActorComponentPtr p_component); };<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/PhysicsComponent.h #pragma once #include "..\FrontlineCommon.h" #include "..\IPhysics.h" #include <PHYSICS\btBulletDynamicsCommon.h> #include <PHYSICS\btBulletCollisionCommon.h> #include "..\Actor\TransformComponent.h" class PhysicsComponent : public ActorComponent { protected: std::weak_ptr<IPhysics> mp_gamePhysics; std::string ms_shape, ms_density, ms_material; glm::mat4 mm_transform; pugi::xml_node mn_shapeInfo; void BuildRigidBodyTransform(pugi::xml_node pn_transform); short m_collisionType, m_collidesWith; public: const static std::string g_name; PhysicsComponent(); virtual ~PhysicsComponent(); virtual bool VInit(pugi::xml_node p_data) override; virtual void VPostInit() override; virtual void VUpdate(int p_deltaMs) {} virtual std::string VGetComponentName() override { return PhysicsComponent::g_name; } virtual ComponentID VGetComponentID() const override { return HashComponentName(g_name); }; virtual pugi::xml_node VGenerateXML(); };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Time.h #pragma once #include "..\FrontlineCommon.h" #include "../IGame.h" #include <Windows.h> #include <iomanip> #include <ctime> #include <sstream> class Time { int m_timer; public: Time(); ~Time(); unsigned long m_startMs; unsigned long sysTimeMs(); unsigned long timeElapsedSinceMS(long time); unsigned long getSysTimeS(); void sleep(long sleepMS); inline unsigned long ticksSinceLastCall() { long l_retval = timeElapsedSinceMS(m_timer); m_timer = sysTimeMs(); return l_retval; } std::string getFormattedDateTime(); static Time* g_Time; }; <file_sep>/Source/Frontline Engine/Frontline Engine/FLMemory.cpp #include "FLMemory.h" namespace fl { template<typename t> class unique_ptr { }; }<file_sep>/Source/Frontline Engine/Frontline Engine/Process/Process.h #pragma once #include "..\FrontlineCommon.h" #include <list> #define PROCESS_UNINITIALIZED 0 #define PROCESS_REMOVED 1 #define PROCESS_PAUSED 2 #define PROCESS_SUCCEDED 3 #define PROCESS_FAILED 4 #define PROCESS_ABORTED 5 #define PROCESS_RUNNING 6 #define PROCESS_DECISION_TREE 1 << 31 class Process; typedef std::shared_ptr<Process> StrongProcessPtr; typedef std::list<StrongProcessPtr> StrongProcessPtrList; typedef unsigned short ProcessState; //the ints are the states so u can call certain child functions when u wanna typedef std::map<int,StrongProcessPtrList>ChildProcessMap; class Process { friend class ProcessManager; public: Process(); virtual ~Process(); ChildProcessMap m_childProcessMap; ProcessState currentProcessState; protected: //these functions should be overridden by the subclass as needed //StrongProcessPtr getProcess() {return std::make_shared<Process>(this);} virtual void VOnInit() { currentProcessState = PROCESS_RUNNING; } virtual void VOnUpdate(unsigned long deltaMs) = 0; virtual void VOnExit(ProcessState exitState) {} public: // Functions for ending the process. inline void Succeed() {currentProcessState = PROCESS_SUCCEDED;} inline void Fail() {currentProcessState = PROCESS_FAILED;} // pause inline void Pause() {currentProcessState = PROCESS_PAUSED;} inline void UnPause() {currentProcessState = PROCESS_RUNNING;} bool IsAlive() const { return (currentProcessState == PROCESS_RUNNING || currentProcessState == PROCESS_PAUSED); } bool IsDead() const { return !IsAlive(); } ProcessState GetState() { return currentProcessState; } // child functions void AttachChild(ProcessState state, StrongProcessPtr pChild); void RemoveChild(ProcessState state); // releases ownership of the child void RemoveChild(ProcessState state, StrongProcessPtr pChild); // releases ownership of the child private: void SetState(ProcessState newState) { currentProcessState = newState; } }; <file_sep>/Source/Frontline Engine/Frontline Game Test/TestGame.cpp #include "TestGame.h" #include <Process\ProcessManager.h> #include <Process\TimerProcess.h> #include "TestPhysicsProcess.h" #include "LockFramerateProcess.h" #include <iostream> TestGame::TestGame() { mp_eventManager = FL_NEW EventManager(); mp_actorFactory = ActorFactory::g_ActorFactory; mp_log = FL_NEW Log(); mp_time = FL_NEW Time(); mp_processManager = FL_NEW ProcessManager(); window = FL_NEW WindowManager(); mp_physics = std::shared_ptr<IPhysics>(FL_NEW BulletPhysics()); mp_physics->VOnInit(); } TestGame::~TestGame() { } void TestGame::CollisionEventCallback(IEventDataPtr pp_event) { CollisionPairEventData lp_cast = *((CollisionPairEventData*) (pp_event.get())); std::string addremovetext = (lp_cast.m_addOrRemove) ? "Added" : "Removed"; char* A1TXT = FL_NEW char(), *A2TXT = FL_NEW char(); _itoa(lp_cast.m_actor1, A1TXT, 10); _itoa(lp_cast.m_actor2, A2TXT, 10); mp_log->logOther("PHYSICS", addremovetext + " collision between actors " + std::string(A1TXT) + " and " + std::string(A2TXT)); } void TestGame::KeyboardCallback(IEventDataPtr pp_event) { KeyboardEventData lp_cast = *((KeyboardEventData*) (pp_event.get())); char* downuptext = (lp_cast.m_down) ? "down" : "up"; char* codeTXT = FL_NEW char(); //_itoa(lp_cast.code, codeTXT, 10); mp_log->logOther("Keyboard", "Key " + std::string(codeTXT) + " is " + downuptext); std::shared_ptr<TimerProcess> lp_processPtr = std::shared_ptr<TimerProcess>(FL_NEW TimerProcess()); lp_processPtr->m_countdownMS = 1000; mp_processManager->AttachProcess(lp_processPtr); mp_log->logOther("PROCESS", "Timer process started"); } void TestGame::start() { float AccumMS = 0; IGame::gp_game = this; mp_eventManager->VAddListener(fastdelegate::MakeDelegate(this, &TestGame::CollisionEventCallback), CollisionPairEventData::sk_eventType); mp_eventManager->VAddListener(fastdelegate::MakeDelegate(this, &TestGame::KeyboardCallback), KeyboardEventData::sk_eventType); ActorFactory::g_ActorFactory->RegisterComponentType<PhysicsComponent>("PhysicsComponent"); ActorFactory::g_ActorFactory->RegisterComponentType<TransformComponent>("TransformComponent"); zrf = FL_NEW ZipResourceFile(); zrf->VOpen(L"testzip.zip"); int size; // The first actor is a small sphere size = zrf->VGetRawResourceSize("actorsrc1.xml"); char* RawBuffer = FL_NEW char[size]; zrf->VGetResource(&RawBuffer, "actorsrc1.xml"); StrongActorPtr sphere = ActorFactory::g_ActorFactory->CreateActor(RawBuffer); delete RawBuffer; // The second actor is a larger sphere below the first sphere size = zrf->VGetRawResourceSize("actorsrc2.xml"); char* RawBuffer2 = FL_NEW char[size]; zrf->VGetResource(&RawBuffer2, "actorsrc2.xml"); StrongActorPtr sphere2 = ActorFactory::g_ActorFactory->CreateActor(RawBuffer2); delete RawBuffer2; // The third actor is a box that serves as the ground size = zrf->VGetRawResourceSize("actorsrc3.xml"); char* RawBuffer3 = FL_NEW char[size]; zrf->VGetResource(&RawBuffer3, "actorsrc3.xml"); StrongActorPtr box = ActorFactory::g_ActorFactory->CreateActor(RawBuffer3); delete RawBuffer3; // Open the game window window->open(800, 600, "Frontline", false, false); // Set up OpenGL window->createGLContext(); // Select old OpenGL settings (for diagnostic rendering) glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90, 800.0 / 600.0, .01, 10000); glDepthFunc(GL_LESS); // This function needs to be called to provide a baseline for when the game starts IGame::gp_game->mp_time->ticksSinceLastCall(); // Set up the processes StrongProcessPtr phys = StrongProcessPtr(new TestPhysicsProcess(mp_physics)); mp_processManager->AttachProcess(phys); StrongProcessPtr frameLock = StrongProcessPtr(new LockFramerateProcess(60)); mp_processManager->AttachProcess(frameLock); while (window->isOpen()) { long ll_deltaMS = IGame::gp_game->mp_time->ticksSinceLastCall(); // Deal with events mp_eventManager->VUpdate(10000); // Update the running processes - Physics, Framerate lock, etc mp_processManager->UpdateProcesses(ll_deltaMS); // Clear the screen for rendering glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Reset the OpenGL matrices glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(10, 10, 10, 0, 0, 0, 0, 1, 0); // Sync the physics with the actors mp_physics->VSyncVisibleScene(); // Render the scene mp_physics->VRenderDiagnostics(); window->swapGLBuffers(); window->updateWindow(); } } int main() { // Clear the default empty game object delete IGame::gp_game; // Create the memory pool Pool* p = new Pool(1024, malloc(1024 * 1024)); // Initialize the game TestGame* test = FL_POOL_NEW(p, TestGame) TestGame(); test->alloc = p; // Start the game. This function is blocking, meaning that the next line of code will not run until // the game has been ended. test->start(); // When the game has been exited, capture the logs std::vector<std::pair<int, std::string>> log = IGame::gp_game->mp_log->dumpLog(); // Print the log to the console std::string ls_text; for (int i = 0; i < log.size(); i++) { ls_text.append(log[i].second); ls_text.append("\n"); } std::cout << ls_text; destroy<IGame>(test, p); system("pause"); FL_POOL_DELETE(test, p); }<file_sep>/Source/Frontline Engine/Frontline Engine/System/Win32Console.cpp #include "Win32Console.h" #include <stdarg.h> #include <cstdio> #include <string> Win32Console::Win32Console() { hConsole = GetStdHandle(STD_OUTPUT_HANDLE); } Win32Console::~Win32Console() { } void Win32Console::printf(const char* format, ...) { va_list arg; // TODO Color handling va_start(arg, format); vfprintf(stdout, format, arg); va_end(arg); } void Win32Console::setColor(Color f) { SetConsoleTextAttribute(hConsole, f.to8Bit()); }<file_sep>/Source/Frontline Engine/Frontline Game Test/TestPhysicsProcess.cpp #include "TestPhysicsProcess.h" TestPhysicsProcess::TestPhysicsProcess(std::shared_ptr<IPhysics> physics) { mp_physics = physics; ups = 120; accum = 0; } void TestPhysicsProcess::VOnUpdate(unsigned long deltaMs) { accum += deltaMs; while (accum >= 1000.0F / ups) { mp_physics->VOnUpdate(1.0F / ups); accum -= 1000.0F / ups; } } TestPhysicsProcess::~TestPhysicsProcess() { } <file_sep>/Source/Frontline Engine/Frontline Engine/Resource/ResCache.cpp #include "ResCache.h" #include <tchar.h> #include "DefaultResource.h" ResCache::ResCache(const unsigned int sizeInMb, IResourceFile *resFile) { m_cacheSize = sizeInMb * 1024 * 1024; m_allocated = 0; m_file = resFile; } ResCache::~ResCache() { while (!m_lru.empty()) { FreeOneResource(); } SAFE_DELETE(m_file); } bool ResCache::Init() { alloc = fastdelegate::MakeDelegate(this, &ResCache::Allocate); bool retValue = false; if (m_file->VOpen(m_file->GetFilename().c_str())) { RegisterLoader(std::shared_ptr<IResourceLoader>(FL_NEW DefaultResourceLoader())); retValue = true; } return retValue; } ResHandle ResCache::GetHandle(const char* ps_resname) { ResHandle handle(m_resources[std::string(ps_resname)]); if (handle == NULL) handle = Load(ps_resname); else Update(handle); return handle; } ResHandle ResCache::Load(const char* ps_resname) { std::shared_ptr<IResourceLoader> loader; // The resource loader ResHandle handle(NULL); // The pointer to the resource /**************** FIND THE CORRECT LOADER ****************/ for (ResourceLoaders::iterator it = m_resourceLoaders.begin(); it != m_resourceLoaders.end(); ++it) { std::shared_ptr<IResourceLoader> testLoader = *it; if (WildcardMatch(testLoader->VGetPattern().c_str(), ps_resname)) { loader = testLoader; break; } } /**************** IF THE LOADER DOES NOT EXIST ****************/ if (!loader) { FL_ASSERT(loader && _T(std::string("Default resource loader not found! Resource Name: ").append(ps_resname).c_str())); return handle; // Resource not loaded! } /**************** ALLOCATE SPACE FOR THE FILE BUFFER ****************/ unsigned int rawSize = m_file->VGetRawResourceSize(ps_resname); // File size char *rawBuffer = loader->VUseRawFile() ? Allocate(rawSize) : FL_NEW char[rawSize]; // The raw file buffer /**************** IF THERE IS NOT ENOUGH MEMORY ****************/ if (rawBuffer == NULL) { ERRLOG("ResCache", std::string("ResCache", "Out of memory in resource cache. Resource Name: ").append(ps_resname)); // Generate an error return ResHandle(); // Return a null resource handle } /**************** READ THE FILE ****************/ m_file->VGetResource(&rawBuffer, ps_resname); // Read from IResourceFile char *buffer = NULL; // The resource memory buffer unsigned int size = 0; // The size in memory of the loaded resource /**************** RAW TEXT ****************/ if (loader->VUseRawFile()) { buffer = rawBuffer; } /**************** CUSTOM LOADER ****************/ else { size = loader->VGetLoadedResourceSize(rawBuffer, rawSize); // The loaded size in memory /**************** NOT INITIALIZED ****************/ if (rawBuffer == NULL) { ERRLOG("ResCache", "Out of memory in resource cache."); // Out of memory error return handle; } bool success = loader->VLoadResource(handle, rawBuffer, ps_resname, alloc); // Load the resource SAFE_DELETE_ARRAY(rawBuffer); /**************** NOT INITIALIZED ****************/ if (!success) { ERRLOG("ResCache", "Out of memory in resource cache."); // Out of memory error return handle; } } /**************** INITIALIZED ****************/ if (handle) { m_lru.push_front(handle); m_resources[ps_resname] = handle; } return handle; } char* ResCache::Allocate(unsigned int size) { if (!MakeRoom(size)) return NULL; char *mem = FL_NEW char[size]; if (mem) m_allocated += size; return mem; } bool ResCache::MakeRoom(unsigned int size) { if (size > m_cacheSize) { return false; } // return null if there’s no possible way to allocate the memory while (size > (m_cacheSize - m_allocated)) { // The cache is empty, and there’s still not enough room. if (m_lru.empty()) return false; FreeOneResource(); } return true; } void ResCache::FreeOneResource() { ResHandleList::iterator gonner = m_lru.end(); gonner--; ResHandle handle = *gonner; m_lru.pop_back(); m_resources.erase(handle->GetName()); }<file_sep>/Source/Frontline Engine/Frontline Engine/IGame.h #pragma once #include <memory> class ProcessManager; class EventManager; class ActorFactory; class Log; class Time; class IPhysics; class Pool; class IGame { public: EventManager* mp_eventManager; ActorFactory* mp_actorFactory; Log* mp_log; Time* mp_time; ProcessManager* mp_processManager; Pool* mp_defaultPool; std::shared_ptr<IPhysics> mp_physics; static IGame* gp_game; virtual void start(); virtual ~IGame() {}; };<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/ActorMotionState.cpp #include "ActorMotionState.h" ActorMotionState::ActorMotionState() { } ActorMotionState::~ActorMotionState() { } // -------------------------------------------------------------------------- // Function: ActorMotionState::setWorldTransform // Purpose: Set the bullet transform of the motion state. // Parameters: The new bullet motion state // -------------------------------------------------------------------------- void ActorMotionState::setWorldTransform(const btTransform& pt_worldTrans) { mm_worldToPositionTransform = btTransformToGLM(pt_worldTrans); } // -------------------------------------------------------------------------- // Function: ActorMotionState::getWorldTransform // Purpose: Get the bullet transform of the motion state. // Parameters: A reference to the bullet transform // -------------------------------------------------------------------------- void ActorMotionState::getWorldTransform(btTransform& pt_worldTrans) const { pt_worldTrans = glmMatToBT(mm_worldToPositionTransform); }<file_sep>/Source/Frontline Engine/Frontline Engine/Math/Math.cpp #include "Math.h" // -------------------------------------------------------------------------- // Function: btTransformToGLM // Purpose: Convert a bullet transform into a glm matrix // Parameters: A const reference to the bullet transform // -------------------------------------------------------------------------- const glm::mat4x4 btTransformToGLM(const btTransform& pt_transform) { glm::mat4x4 lm_retVal; pt_transform.getOpenGLMatrix(glm::value_ptr(lm_retVal)); return lm_retVal; } // -------------------------------------------------------------------------- // Function: glmMatToBT // Purpose: Convert a glm matrix into a bullet transform // Parameters: A const reference to the glm matrix // -------------------------------------------------------------------------- const btTransform glmMatToBT(const glm::mat4x4& pm_matrix) { btTransform lt_retval; lt_retval.setFromOpenGLMatrix(glm::value_ptr(pm_matrix)); return lt_retval; } // -------------------------------------------------------------------------- // Function: getTranslationFromMat // Purpose: Find the translation component of a transformation matrix // Parameters: The glm matrix // -------------------------------------------------------------------------- const glm::vec3 getTranslationFromMat(const glm::mat4x4 pm_matrix) { return glm::vec3(pm_matrix[0][0], pm_matrix[1][1], pm_matrix[2][2]); } // -------------------------------------------------------------------------- // Function: getScaleFromMat // Purpose: Find the scale component of a transformation matrix // Parameters: The glm matrix // -------------------------------------------------------------------------- const glm::vec3 getScaleFromMat(const glm::mat4x4 pm_matrix) { return glm::vec3(pm_matrix[3][0], pm_matrix[3][1], pm_matrix[3][2]); } // -------------------------------------------------------------------------- // Function: fastInverseSqrRoot // Purpose: Find 1/sqr(x) quickly - used for normalizing vectors // Parameters: X // -------------------------------------------------------------------------- float fastInverseSqrRoot(float x) { long i; float x2, y; const float threehalfs = 1.5F; x2 = x * 0.5F; y = x; i = *(long *) &y; i = 0x5f3759df - (i >> 1); y = *(float *) &i; y = y * (threehalfs - (x2 * y * y)); return y; } // -------------------------------------------------------------------------- // Function: normalize // Purpose: Normalize a vector - make its length 1 // Parameters: A reference to the vector // -------------------------------------------------------------------------- inline void normalize(glm::vec3& vec) { glm::inversesqrt(10); vec *= fastInverseSqrRoot(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z); }<file_sep>/Source/Frontline Engine/Frontline Engine/Event/AddCollisionPairEventData.h #pragma once #include "..\FrontlineCommon.h" #include <PHYSICS\btBulletDynamicsCommon.h> class CollisionPairEventData : public BaseEventData { public: static EventType sk_eventType; ActorID m_actor1, m_actor2; bool m_addOrRemove; CollisionPairEventData(); ~CollisionPairEventData(); virtual const EventType& VGetEventType(void) const override { return sk_eventType; }; virtual void VSerialize(std::ostrstream &out) const override { } virtual void VDeserialize(std::istrstream& in) override { } virtual const char* GetName(void) const { return "EvtData_AddCollisionPair"; }; };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Win32WindowManager.cpp #include "Win32WindowManager.h" #include <iostream> #if _MSC_VER >= 1300 // for VC 7.0 // from ATL 7.0 sources #ifndef _delayimp_h extern "C" IMAGE_DOS_HEADER __ImageBase; #endif #endif std::map<HWND, Win32WindowManager*> Win32WindowManager::g_managerLookup = std::map<HWND, Win32WindowManager*>(); HMODULE GetCurrentModule() { #if _MSC_VER < 1300 // earlier than .NET compiler (VC 6.0) // Here's a trick that will get you the handle of the module // you're running in without any a-priori knowledge: // http://www.dotnet247.com/247reference/msgs/13/65259.aspx MEMORY_BASIC_INFORMATION mbi; static int dummy; VirtualQuery(&dummy, &mbi, sizeof(mbi)); return reinterpret_cast<HMODULE>(mbi.AllocationBase); #else // VC 7.0 // from ATL 7.0 sources return reinterpret_cast<HMODULE>(&__ImageBase); #endif } Win32WindowManager::Win32WindowManager(void) { } void Win32WindowManager::makeGLContextCurrent() { m_oldDeviceContextHandle = wglGetCurrentDC(); m_oldGLContextHandle = wglGetCurrentContext(); wglMakeCurrent(m_deviceContextHandle, m_glContextHandle); } void Win32WindowManager::swapGLBuffers() { SwapBuffers(m_deviceContextHandle); } LRESULT CALLBACK WindowProcedure(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CLOSE: Win32WindowManager::g_managerLookup[hWnd]->close(); break; case WM_KEYDOWN: Win32WindowManager::g_managerLookup[hWnd]->processKeyboardEvent(wParam, true); break; case WM_KEYUP: Win32WindowManager::g_managerLookup[hWnd]->processKeyboardEvent(wParam, false); break; default: // Do not handle this message; make windows call it instead in the default way return DefWindowProc(hWnd, message, wParam, lParam); } } void Win32WindowManager::processKeyboardEvent(WPARAM p_code, bool p_down) { KeyboardEventData* le_event = FL_NEW KeyboardEventData(); le_event->code = p_code; le_event->m_down = p_down; IGame::gp_game->mp_eventManager->VQueueEvent(std::shared_ptr<KeyboardEventData>(le_event)); } bool Win32WindowManager::setFullscreen(bool p_fullscreen) { m_fullscreen = p_fullscreen; // Turn the WindowStyle struct into something that win32 can understand DWORD l_windowStyle = ((m_style.m_clipChildren) ? WS_CLIPCHILDREN : 0) | ((m_style.m_clipSiblings) ? WS_CLIPSIBLINGS : 0) | ((m_style.m_dlgFrame) ? WS_DLGFRAME : 0) | ((m_style.m_hasBorder) ? WS_BORDER : 0) | ((m_style.m_hasCaption) ? WS_CAPTION : 0) | ((m_style.m_hasResizeBox) ? WS_SIZEBOX : 0) | ((m_style.m_hasSystemMenu) ? WS_SYSMENU : 0) | ((m_style.m_hScroll) ? WS_HSCROLL : 0) | ((m_style.m_iconic) ? WS_ICONIC : 0) | ((m_style.m_isChild) ? WS_SYSMENU : 0) | ((m_style.m_isDisabled) ? WS_DISABLED : 0) | ((m_style.m_isGroup) ? WS_GROUP : 0) | ((m_style.m_isPopup) ? WS_POPUP : 0) | ((m_style.m_maximize) ? WS_MAXIMIZE : 0) | ((m_style.m_maximizeButton) ? WS_MAXIMIZEBOX : 0) | ((m_style.m_minimize) ? WS_MINIMIZE : 0) | ((m_style.m_minimizeButton) ? WS_MINIMIZEBOX : 0) | ((m_style.m_tabStop) ? WS_TABSTOP : 0) | ((m_style.m_visible) ? WS_VISIBLE : 0) | ((m_style.m_vScroll) ? WS_VSCROLL : 0); if (p_fullscreen) { l_windowStyle = l_windowStyle | WS_POPUP | WS_EX_TOPMOST; l_windowStyle = l_windowStyle & ~WS_OVERLAPPEDWINDOW; DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = m_sizeX; // Selected Screen Width dmScreenSettings.dmPelsHeight = m_sizeY; // Selected Screen Height dmScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { setFullscreen(false); return false; } } else { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = m_desktopSizeX; // Selected Screen Width dmScreenSettings.dmPelsHeight = m_desktopSizeY + 62; // Selected Screen Height dmScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { return false; } } // Modify the window values SetWindowLongPtr(m_windowHandle, GWL_STYLE, l_windowStyle); SetWindowPos(m_windowHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); ShowWindow(m_windowHandle, SW_NORMAL); return true; } void Win32WindowManager::close() { setFullscreen(false); destroyGLContext(); DestroyWindow(m_windowHandle); g_managerLookup.erase(m_windowHandle); m_open = false; } void Win32WindowManager::createGLContext() { // Get the device context handle for the window m_deviceContextHandle = GetDC(m_windowHandle); // Set the pixel format descriptor PIXELFORMATDESCRIPTOR l_pfd; ZeroMemory(&l_pfd, sizeof(l_pfd)); l_pfd.nSize = sizeof(l_pfd); l_pfd.nVersion = 1; l_pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; // Set the pfd flags l_pfd.iPixelType = PFD_TYPE_RGBA; // The pixel type l_pfd.cColorBits = 24; // Color bits per pixel l_pfd.cDepthBits = 16; // Bits in the depth buffer per pixel l_pfd.iLayerType = PFD_MAIN_PLANE; int l_iFormat = ChoosePixelFormat(m_deviceContextHandle, &l_pfd); SetPixelFormat(m_deviceContextHandle, l_iFormat, &l_pfd); // Finally set the created pfd // Create the OpenGL Context m_glContextHandle = wglCreateContext(m_deviceContextHandle); wglMakeCurrent(m_deviceContextHandle, m_glContextHandle); // Initialize GLEW (OpenGL Extension Wrangler) glewInit(); } void Win32WindowManager::destroyGLContext() { if (m_glContextHandle) { wglMakeCurrent(NULL, NULL); wglDeleteContext(m_glContextHandle); } if (m_windowHandle && m_deviceContextHandle) { ReleaseDC(m_windowHandle, m_deviceContextHandle); } } void Win32WindowManager::open(int p_sizeX, int p_sizeY, std::string p_windowTitle, bool p_singleInstance, bool p_fullscreen, WindowStyle p_style, int p_posX, int p_posY) { m_desktopSizeX = GetSystemMetrics(SM_CXFULLSCREEN); m_desktopSizeY = GetSystemMetrics(SM_CYFULLSCREEN); m_windowTitle = p_windowTitle; m_style = p_style; ZeroMemory(&m_windowClass, sizeof(WNDCLASSEX)); // Set attributes for the window class m_windowClass.cbClsExtra = NULL; m_windowClass.cbSize = sizeof(WNDCLASSEX); m_windowClass.cbWndExtra = NULL; // If the window is fullscreen, the hbrBackground field should be left alone if (!p_fullscreen) m_windowClass.hbrBackground = (HBRUSH) COLOR_WINDOW; m_windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); m_windowClass.hIcon = NULL; m_windowClass.hIconSm = NULL; m_windowClass.hInstance = GetCurrentModule(); m_windowClass.lpszClassName = "Window Class"; m_windowClass.lpszMenuName = NULL; m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.lpfnWndProc = (WNDPROC) WindowProcedure; // Register the window class and check for errors if (!RegisterClassEx(&m_windowClass)) { // Errors occured //int nResult=GetLastError(); //MessageBox(NULL, //"Window class creation failed", //"Window Class Failed", //MB_ICONERROR); } // Turn the WindowStyle struct into a DWORD that windows explicitly understands DWORD l_windowStyle = ((p_style.m_clipChildren) ? WS_CLIPCHILDREN : 0) | ((p_style.m_clipSiblings) ? WS_CLIPSIBLINGS : 0) | ((p_style.m_dlgFrame) ? WS_DLGFRAME : 0) | ((p_style.m_hasBorder) ? WS_BORDER : 0) | ((p_style.m_hasCaption) ? WS_CAPTION : 0) | ((p_style.m_hasResizeBox) ? WS_SIZEBOX : 0) | ((p_style.m_hasSystemMenu) ? WS_SYSMENU : 0) | ((p_style.m_hScroll) ? WS_HSCROLL : 0) | ((p_style.m_iconic) ? WS_ICONIC : 0) | ((p_style.m_isChild) ? WS_SYSMENU : 0) | ((p_style.m_isDisabled) ? WS_DISABLED : 0) | ((p_style.m_isGroup) ? WS_GROUP : 0) | ((p_style.m_isPopup) ? WS_POPUP : 0) | ((p_style.m_maximize) ? WS_MAXIMIZE : 0) | ((p_style.m_maximizeButton) ? WS_MAXIMIZEBOX : 0) | ((p_style.m_minimize) ? WS_MINIMIZE : 0) | ((p_style.m_minimizeButton) ? WS_MINIMIZEBOX : 0) | ((p_style.m_tabStop) ? WS_TABSTOP : 0) | ((p_style.m_visible) ? WS_VISIBLE : 0) | ((p_style.m_vScroll) ? WS_VSCROLL : 0); m_sizeX = p_sizeX; m_sizeY = p_sizeY; // If the window should be fullscreen, add the popup and topmost styles if (p_fullscreen) { l_windowStyle = l_windowStyle | WS_POPUP | WS_EX_TOPMOST; l_windowStyle = l_windowStyle & ~WS_OVERLAPPEDWINDOW; if (!setFullscreen(true)) { ERRLOG("Window", "Fullscreen failed"); } } // Create the window with the specified parameters m_windowHandle = CreateWindowEx(NULL, "Window Class", p_windowTitle.c_str(), l_windowStyle, 0, 0, m_sizeX, m_sizeY, NULL, NULL, m_windowClass.hInstance, NULL); ShowWindow(m_windowHandle, SW_SHOWNORMAL); g_managerLookup[m_windowHandle] = this; m_open = true; } Win32WindowManager::~Win32WindowManager(void) { } bool Win32WindowManager::resize(int p_sizeX_n, int p_sizeY_n, int p_posX_n, int p_posY_n) { // Turn the WindowStyle struct into something that win32 can understand DWORD l_windowStyle = ((m_style.m_clipChildren) ? WS_CLIPCHILDREN : 0) | ((m_style.m_clipSiblings) ? WS_CLIPSIBLINGS : 0) | ((m_style.m_dlgFrame) ? WS_DLGFRAME : 0) | ((m_style.m_hasBorder) ? WS_BORDER : 0) | ((m_style.m_hasCaption) ? WS_CAPTION : 0) | ((m_style.m_hasResizeBox) ? WS_SIZEBOX : 0) | ((m_style.m_hasSystemMenu) ? WS_SYSMENU : 0) | ((m_style.m_hScroll) ? WS_HSCROLL : 0) | ((m_style.m_iconic) ? WS_ICONIC : 0) | ((m_style.m_isChild) ? WS_SYSMENU : 0) | ((m_style.m_isDisabled) ? WS_DISABLED : 0) | ((m_style.m_isGroup) ? WS_GROUP : 0) | ((m_style.m_isPopup) ? WS_POPUP : 0) | ((m_style.m_maximize) ? WS_MAXIMIZE : 0) | ((m_style.m_maximizeButton) ? WS_MAXIMIZEBOX : 0) | ((m_style.m_minimize) ? WS_MINIMIZE : 0) | ((m_style.m_minimizeButton) ? WS_MINIMIZEBOX : 0) | ((m_style.m_tabStop) ? WS_TABSTOP : 0) | ((m_style.m_visible) ? WS_VISIBLE : 0) | ((m_style.m_vScroll) ? WS_VSCROLL : 0); m_sizeX = p_sizeX_n; m_sizeY = p_sizeY_n; glViewport(0, 0, m_sizeX, m_sizeY); SetWindowPos(m_windowHandle, HWND_TOP, p_posX_n, p_posY_n, m_sizeX, m_sizeY, SWP_SHOWWINDOW); return true; } void Win32WindowManager::updateWindow() { MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } bool Win32WindowManager::isOpen() { return m_open; }<file_sep>/Source/Frontline Engine/Frontline Engine/System/Console.h #pragma once #include "..\Graphics\Color.h" class Console { public: virtual void setColor(Color f) = 0; virtual void printf(const char* format, ...) = 0; virtual ~Console() {}; };<file_sep>/Source/Frontline/effectSysTestP2/flFxConfig.h #pragma once enum Flags { FX_STATE_GROUP_DESC_FLAG, FX_FBO_TARGET_DESC_FLAG, FX_FBO_BLIT_SRC_DESC_FLAG, FX_FBO_RES_SWAP_DESC_FLAG, FX_CLEARMODE_DESC_FLAG, FX_CLEARCOLOR_DESC_FLAG, FX_CLEAR_DESC_FLAG, FX_RENDERMODE_DESC_FLAG, FX_SHADER_PARAMETER_DESC_FLAG, FX_SHADER_DESC_FLAG, FX_PIPELINE_DESC_FLAG, FX_RESOURCE_DESC_FLAG, }; enum fxStates { FX_RESOURCE_1D, FX_RESOURCE_2D, FX_RESOURCE_3D, FX_RESOURCE_1D_IMAGE, FX_RESOURCE_2D_IMAGE, FX_RESOURCE_3D_IMAGE, FX_RESOURCE_RENDERTEX, FX_RESOURCE_DEPTHTEX, FX_LINEAR, FX_REPEAT, FX_RGB32F, FX_RGBA8, FX_RGBA16, FX_RGBA16F, FX_RGBA32F, FX_DEPTH_COMPONENT, FX_DEPTH_COMPONENT16, FX_DEPTH_COMPONENT24, FX_DEPTH_COMPONENT32, FX_DEPTH_COMPONENT32F, FX_BLEND, FX_BLEND_FUNC, FX_ALPHA_FUNC, FX_BLEND_FUNC_SEPARATE, FX_BLEND_EQUATION_SEPARATE, FX_LOGIC_OP, FX_COLOR_MASK, FX_BLEND_COLOR, //blend func and func separate parameters FX_ZERO, FX_ONE, FX_SRC_COLOR, FX_ONE_MINUS_SRC_COLOR, FX_DST_COLOR, FX_ONE_MINUS_DST_COLOR, FX_SRC_ALPHA, FX_ONE_MINUS_SRC_ALPHA, FX_DST_ALPHA, FX_ONE_MINUS_DST_ALPHA, FX_CONSTANT_COLOR, FX_ONE_MINUS_CONSTANT_COLOR, FX_CONSTANT_ALPHA, FX_ONE_MINUS_CONSTANT_ALPHA, FX_SRC_ALPHA_SATURATE, FX_SRC1_COLOR, FX_ONE_MINUS_SRC1_COLOR, FX_SRC1_ALPHA, FX_ONE_MINUS_SRC1_ALPHA, //alpha func parameters FX_NEVER, FX_LESS, FX_EQUAL, FX_LEQUAL, FX_GREATER, FX_NOTEQUAL, FX_GEQUAL, FX_ALWAYS, //blend equation separate FX_FUNC_ADD, FX_FUNC_SUBTRACT, FX_FUNC_REVERSE_SUBTRACT, FX_MIN, FX_MAX, //logic operations FX_CLEAR, FX_SET, FX_COPY, FX_COPY_INVERTED, FX_NOOP, FX_INVERT, FX_AND, FX_NAND, FX_OR, FX_NOR, FX_XOR, FX_EQUIV, FX_AND_REVERSE, FX_AND_INVERTED, FX_OR_REVERSE, FX_OR_INVERTED, //general (colormask) FX_TRUE, FX_FALSE, FX_TEXTURE_WRAP_S, FX_TEXTURE_WRAP_T, FX_TEXTURE_MIN_FILTER, FX_TEXTURE_MAG_FILTER, FX_TEXTURE_MAX_ANISOTROPY, FX_DEPTH_TEST, FX_DO_NOTHING, FX_DRAW_FULLSCREEN_QUAD, FX_DRAW_TRIANGLE, FX_COLOR_BUFFER_BIT, FX_DEPTH_BUFFER_BIT, FX_STENCIL_BUFFER_BIT, FX_STATE_LAST };<file_sep>/Source/Frontline/effectSysTestP2/flFxParser.h #pragma once #include "flFxConfig.h" #include "flFx.h" #include "flFxExt.h" #include "flFxGL.h" #include "pugixml/pugiconfig.hpp" #include "pugixml/pugixml.hpp" #include "fastdelegate/FastDelegate.h" #include "fastdelegate/FastDelegateBind.h" typedef fastdelegate::FastDelegate1<pugi::xml_node,bool> NodeHandle; class flFxParser : public pugi::xml_tree_walker { protected: std::shared_ptr<Effect> m_TmpEffect; std::shared_ptr<Technique> m_CurrTechnique; std::shared_ptr<Pass> m_CurrPass; private: std::vector<std::shared_ptr<PassDesc>> m_CurrObjects; //make this a vector std::vector<std::shared_ptr<PassDesc>> m_QueuedObjects; //make this a vector std::vector<std::shared_ptr<PassDesc>> m_SavedObjects; pugi::xml_node m_CurrXmlScope; //curent node std::map<const char*,NodeHandle> m_NodeHandlers; protected: void RegisterXmlNodeHandle(const char* name, NodeHandle node) { m_NodeHandlers[name] = node; } ///queued = an object that has been declared but not set ///current = the object the current scope iterator is in void SetCurrentObject(std::shared_ptr<PassDesc> obj); std::shared_ptr<PassDesc> GetCurrentObject(fxState flag); void SetQueuedObject(std::shared_ptr<PassDesc> obj); std::shared_ptr<PassDesc> GetQueuedObject(const char* name); //std::shared_ptr<PassDesc> GetQueuedObjectCopy(const char* name) { return nullptr; } void SaveObject(std::shared_ptr<PassDesc> obj); //std::shared_ptr<PassDesc> GetSavedObject(fxState flag); std::shared_ptr<PassDesc> GetSavedObject(const char* name); virtual bool for_each(pugi::xml_node& node); public: flFxParser(void); ~flFxParser(void) {} std::shared_ptr<Effect> LoadEffect(pugi::xml_document& doc); static flFxParser* Get(); };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/ZipFile.h #pragma once #include "..\FrontlineCommon.h" #include <ZLIB\zlib.h> #include <string> #include <stdio.h> #include <map> // This maps a path to a zip content id typedef std::map<std::string, int> ZipContentsMap; class ZipFile { struct TZipDirHeader; struct TZipDirFileHeader; struct TZipLocalHeader; FILE* mp_file; char* ms_dirData; int m_nEntries; const TZipDirFileHeader** m_papDir; public: ZipFile() { m_nEntries = 0; mp_file = NULL; ms_dirData = NULL; } virtual ~ZipFile() { End(); fclose(mp_file); } bool Init(const std::wstring& ps_filename); void End(); int GetNumFiles() const { return m_nEntries; } bool ReadFile(int i, void* pBuf); bool ReadLargeFile(int i, void* pp_buf, void(*progressCallback)(int, bool&)); int Find(const std::string ps_path); int GetFileLen(int i) const; std::string GetFilename(int i) const; ZipContentsMap mmap_zipContents; };<file_sep>/Source/Frontline Engine/Frontline Engine/KeyboardEventData.cpp #include "KeyboardEventData.h" EventType KeyboardEventData::sk_eventType = 0xc2ce7c0a; KeyboardEventData::KeyboardEventData() { } KeyboardEventData::~KeyboardEventData() { } <file_sep>/Source/Frontline Engine/Frontline Engine/Actor/TransformComponent.cpp #include "TransformComponent.h" const std::string TransformComponent::g_name = "TransformComponent"; TransformComponent::TransformComponent() { } TransformComponent::~TransformComponent() { } glm::vec3 TransformComponent::FindPosition() { glm::vec3 l_retval; l_retval = glm::vec3(mm_transform[0][3], mm_transform[1][3], mm_transform[2][3]); return l_retval; } glm::vec3 TransformComponent::FindRotation() { glm::vec3 l_retval; l_retval = glm::vec3(mm_transform[0][3], mm_transform[1][3], mm_transform[2][3]); return l_retval; } glm::vec3 TransformComponent::FindScale() { glm::vec3 l_retval; l_retval = glm::vec3(mm_transform[0][3], mm_transform[1][3], mm_transform[2][3]); return l_retval; } bool TransformComponent::VInit(pugi::xml_node pn_data) { glm::vec3 lv_translate, lv_rotate, lv_scale; pugi::xml_node ln_translation = pn_data.child("Translation"); if (ln_translation.child("x").first_child().value() != "") lv_translate.x = atof(ln_translation.child("x").first_child().value()); if (ln_translation.child("y").first_child().value() != "") lv_translate.y = atof(ln_translation.child("y").first_child().value()); if (ln_translation.child("z").first_child().value() != "") lv_translate.z = atof(ln_translation.child("z").first_child().value()); pugi::xml_node ln_rotation = pn_data.child("Rotation"); if (ln_rotation.child("x").first_child().value() != "") lv_rotate.x = atof(ln_rotation.child("x").first_child().value()); if (ln_rotation.child("y").first_child().value() != "") lv_rotate.y = atof(ln_rotation.child("y").first_child().value()); if (ln_rotation.child("z").first_child().value() != "") lv_rotate.z = atof(ln_rotation.child("z").first_child().value()); pugi::xml_node ln_scale = pn_data.child("Scale"); if (ln_scale.child("x").first_child().value() != "") lv_scale.x = atof(ln_scale.child("x").first_child().value()); if (ln_scale.child("y").first_child().value() != "") lv_scale.y = atof(ln_scale.child("y").first_child().value()); if (ln_scale.child("z").first_child().value() != "") lv_scale.z = atof(ln_scale.child("z").first_child().value()); glm::mat4 lm_translate = glm::translate(lv_translate); glm::mat4 lm_rotate = glm::translate(lv_rotate); glm::mat4 lm_scale = glm::translate(lv_scale); mm_transform = glm::mat4(1) * lm_rotate * lm_scale; mm_transform *= lm_translate; return true; } void TransformComponent::VPostInit() { }<file_sep>/Source/Frontline/effectSysTestP2/flFxParser.cpp #include "flFxParser.h" static flFxParser* parser = new flFxParser(); flFxParser::flFxParser() { } flFxParser* flFxParser::Get() { return parser; } void flFxParser::SetCurrentObject(std::shared_ptr<PassDesc> obj) { m_CurrObjects.push_back(obj); } std::shared_ptr<PassDesc> flFxParser::GetCurrentObject(fxState flag) { for(auto iter = m_CurrObjects.begin(); iter != m_CurrObjects.end(); iter++) { if((*iter)->GetFlag() == flag) { return (*iter); } } return NULL; } void flFxParser::SetQueuedObject(std::shared_ptr<PassDesc> obj) { m_QueuedObjects.push_back(obj); } std::shared_ptr<PassDesc> flFxParser::GetQueuedObject(const char* name) { for(auto iter = m_QueuedObjects.begin(); iter != m_QueuedObjects.end(); iter++) { if(strcmp((*iter)->GetName(),name) == 0) { return (*iter); } } return NULL; } void flFxParser::SaveObject(std::shared_ptr<PassDesc> obj) { m_SavedObjects.push_back(obj); } std::shared_ptr<PassDesc> flFxParser::GetSavedObject(const char* name) { for (auto iter = m_SavedObjects.begin(); iter != m_SavedObjects.end(); iter++) { if (strcmp((*iter)->GetName(), name) == 0) { return (*iter); } } return NULL; } bool flFxParser::for_each(pugi::xml_node& node) { for(auto iter = m_NodeHandlers.begin(); iter != m_NodeHandlers.end(); iter++) { if(strcmp(iter->first,node.name()) == 0) { NodeHandle func = iter->second; func(node); return true; } } return true; } //no K&R bracing here because of readability issues std::shared_ptr<Effect> flFxParser::LoadEffect(pugi::xml_document& doc) { doc.traverse(*this); return m_TmpEffect; }<file_sep>/Source/Frontline Engine/Frontline Engine/System/Time.cpp #include "Time.h" Time* Time::g_Time = FL_NEW Time(); Time::Time() { m_startMs = GetTickCount64(); m_timer = 0; } Time::~Time() { } unsigned long Time::sysTimeMs() { return GetTickCount64(); } unsigned long Time::timeElapsedSinceMS(long p_timeSince) { return GetTickCount64() - p_timeSince; } unsigned long Time::getSysTimeS() { return (unsigned long) time(0); } std::string Time::getFormattedDateTime() { std::time_t l_time = std::time(nullptr); std::tm l_tm; localtime_s(&l_tm, &l_time); std::stringstream l_timeBuffer; l_timeBuffer << std::put_time(&l_tm, "%b-%d-%Y %H.%M.%S"); return l_timeBuffer.str(); } void sleep(long sleepMS) { Sleep(sleepMS); }<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/XMLResource.h #pragma once #include "..\FrontlineCommon.h" #include "ResCache.h" #include <XML/pugixml.hpp> #include "Resource.h" class XmlResourceLoader : public IResourceLoader { public: virtual bool VUseRawFile() { return false; } virtual bool VDiscardRawBufferAfterLoad() { return true; } virtual unsigned int VGetLoadedResourceSize(char *rawBuffer, unsigned int rawSize) { return rawSize; } virtual bool VLoadResource(char *rawBuffer, unsigned int rawSize, ResHandle handle); virtual std::string VGetPattern() { return "*.xml"; } // convenience function static pugi::xml_node* LoadAndReturnRootXmlElement(const char* resourceString); }; class XMLResource : public Resource { public: XMLResource(const std::string &name); ~XMLResource(); }; <file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/TextResource.h #pragma once #include "Resource.h" #include "IResourceLoader.h" class TextResource : public Resource { std::string ms_contents; public: ~TextResource(); std::string GetContents(); void SetContents(std::string ps_contents); }; class TextResourceLoader : public IResourceLoader { };<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/XMLResource.cpp #include "XMLResource.h" XMLResource::~XMLResource() { } bool XmlResourceLoader::VLoadResource(char *rawBuffer, unsigned int rawSize, ResHandle handle) { pugi::xml_document* lp_doc = FL_NEW pugi::xml_document(); pugi::xml_parse_result lr_result = lp_doc->load(rawBuffer); if (lr_result.status == pugi::xml_parse_status::status_ok) { } else return false; } static pugi::xml_node** LoadAndReturnRootXmlElement(const char* resourceString);<file_sep>/Source/Frontline/effectSysTestP2/flFxGL.cpp #include "flFxGL.h" //cud be handled internally /*bool PassGL::Execute() { Pass::Execute(); /*std::shared_ptr<PipelineGL> glslPipeline = std::static_pointer_cast<PipelineGL>(m_PassInfo[FX_PIPELINE_DESC_FLAG][0]); //GetPassInfo(FX_PIPELINE_DESC_FLAG,glslPipeline); std::vector<std::shared_ptr<ShaderParameterGL>> shaderParameters; //GetPassInfo(FX_SHADER_PARAMETER_DESC_FLAG,shaderParameters); //put the vector has to have PassDesc for(auto iter = m_PassInfo[FX_SHADER_PARAMETER_DESC_FLAG].begin(); iter != m_PassInfo[FX_SHADER_PARAMETER_DESC_FLAG].end(); iter++) { shaderParameters.push_back(std::static_pointer_cast<ShaderParameterGL>(*iter)); } std::shared_ptr<StateGroupGL> stateGroup; if(m_PassInfo[FX_STATE_GROUP_DESC_FLAG].size() > 0) { //safety stateGroup = std::static_pointer_cast<StateGroupGL>(m_PassInfo[FX_STATE_GROUP_DESC_FLAG][0]); } if(stateGroup) { stateGroup->Apply(); } glslPipeline->Bind(); for(auto iter = shaderParameters.begin(); iter != shaderParameters.end(); iter++) { (*iter)->Update(); } return true; }*/ static std::shared_ptr<flFxCoreGL> coreGL(new flFxCoreGL()); bool flFxCoreGL::Init() { std::vector<fxState> execution = { FX_FBO_TARGET_DESC_FLAG, FX_CLEARMODE_DESC_FLAG, FX_STATE_GROUP_DESC_FLAG, FX_PIPELINE_DESC_FLAG, FX_RESOURCE_DESC_FLAG, FX_SHADER_PARAMETER_DESC_FLAG, FX_RENDERMODE_DESC_FLAG }; Pass::ConfigureExecution(execution); StateInterpreter::Get()->RegisterState(FX_DRAW_FULLSCREEN_QUAD, FX_DRAW_FULLSCREEN_QUAD, "FX_DRAW_FULLSCREEN_QUAD"); StateInterpreter::Get()->RegisterState(FX_DO_NOTHING, FX_DO_NOTHING, "FX_DO_NOTHING"); StateInterpreter::Get()->RegisterState(FX_COLOR_BUFFER_BIT, GL_COLOR_BUFFER_BIT, "FX_COLOR_BUFFER_BIT"); StateInterpreter::Get()->RegisterState(FX_DEPTH_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, "FX_DEPTH_BUFFER_BIT"); StateInterpreter::Get()->RegisterState(FX_STENCIL_BUFFER_BIT, GL_STENCIL_BUFFER_BIT, "FX_STENCIL_BUFFER_BIT"); StateInterpreter::Get()->RegisterState(FX_RESOURCE_1D, GL_TEXTURE_1D, "FX_RESOURCE_1D"); StateInterpreter::Get()->RegisterState(FX_RESOURCE_2D, GL_TEXTURE_2D, "FX_RESOURCE_2D"); StateInterpreter::Get()->RegisterState(FX_RESOURCE_3D, GL_TEXTURE_3D, "FX_RESOURCE_3D"); StateInterpreter::Get()->RegisterState(FX_LINEAR, GL_LINEAR, "FX_LINEAR"); StateInterpreter::Get()->RegisterState(FX_REPEAT, GL_REPEAT, "FX_REPEAT"); StateInterpreter::Get()->RegisterState(FX_BLEND, GL_BLEND, "FX_BLEND"); StateInterpreter::Get()->RegisterState(FX_ZERO, GL_ZERO, "FX_ZERO"); StateInterpreter::Get()->RegisterState(FX_ONE, GL_ONE, "FX_ONE"); StateInterpreter::Get()->RegisterState(FX_SRC_COLOR, GL_SRC_COLOR, "FX_SRC_COLOR"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, "FX_ONE_MINUS_SRC_COLOR"); StateInterpreter::Get()->RegisterState(FX_DST_COLOR, GL_DST_COLOR, "FX_DST_COLOR"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, "FX_ONE_MINUS_DST_COLOR"); StateInterpreter::Get()->RegisterState(FX_SRC_ALPHA, GL_SRC_ALPHA, "FX_SRC_ALPHA"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, "FX_ONE_MINUS_SRC_ALPHA"); StateInterpreter::Get()->RegisterState(FX_DST_ALPHA, GL_DST_ALPHA, "FX_DST_ALPHA"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, "FX_ONE_MINUS_DST_ALPHA"); StateInterpreter::Get()->RegisterState(FX_CONSTANT_COLOR, GL_CONSTANT_COLOR, "FX_CONSTANT_COLOR"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, "FX_ONE_MINUS_CONSTANT_COLOR"); StateInterpreter::Get()->RegisterState(FX_CONSTANT_ALPHA, GL_CONSTANT_ALPHA, "FX_CONSTANT_ALPHA"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, "FX_ONE_MINUS_CONSTANT_ALPHA"); StateInterpreter::Get()->RegisterState(FX_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE, "FX_SRC_ALPHA_SATURATE"); StateInterpreter::Get()->RegisterState(FX_SRC1_COLOR, GL_SRC1_COLOR, "FX_SRC1_COLOR"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_SRC1_COLOR, GL_ONE_MINUS_SRC1_COLOR, "FX_ONE_MINUS_SRC1_COLOR"); StateInterpreter::Get()->RegisterState(FX_SRC1_ALPHA, GL_SRC1_ALPHA, "FX_SRC1_ALPHA"); StateInterpreter::Get()->RegisterState(FX_ONE_MINUS_SRC1_ALPHA, GL_ONE_MINUS_SRC1_ALPHA, "FX_ONE_MINUS_SRC1_ALPHA"); StateInterpreter::Get()->RegisterState(FX_DEPTH_TEST, GL_DEPTH_TEST, "FX_DEPTH_TEST"); StateInterpreter::Get()->RegisterState(FX_RGBA16F, GL_RGBA16F, "FX_RGBA16F"); StateInterpreter::Get()->RegisterState(FX_RGB32F, GL_RGB32F, "FX_RGB32F"); StateInterpreter::Get()->RegisterState(FX_RGBA32F, GL_RGBA32F, "FX_RGBA32F"); StateInterpreter::Get()->RegisterState(FX_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, "FX_DEPTH_COMPONENT"); StateInterpreter::Get()->RegisterState(FX_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, "FX_DEPTH_COMPONENT16"); StateInterpreter::Get()->RegisterState(FX_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, "FX_DEPTH_COMPONENT24"); StateInterpreter::Get()->RegisterState(FX_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT32, "FX_DEPTH_COMPONENT32"); StateInterpreter::Get()->RegisterState(FX_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, "FX_DEPTH_COMPONENT32F"); //resource GLfloat vertices[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; GLfloat uv[] = { 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f }; /*const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; const GLfloat g_uv_buffer_data[] = { -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, };*/ glGenVertexArrays(1, &m_FullscreenQuadId); glBindVertexArray(m_FullscreenQuadId); GLuint vertId; glGenBuffers(1, &vertId); glBindBuffer(GL_ARRAY_BUFFER, vertId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(0); GLuint uvId; glGenBuffers(1, &uvId); glBindBuffer(GL_ARRAY_BUFFER, uvId); glBufferData(GL_ARRAY_BUFFER, sizeof(uv), uv, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(1); glBindVertexArray(0); return true; } void flFxCoreGL::DrawFullscreenQuad() { glBindVertexArray(m_FullscreenQuadId); glDrawArrays(GL_TRIANGLES, 0, 6); } bool flFxCoreGL::Shutdown() { glDeleteVertexArrays(1, &m_FullscreenQuadId); return true; } std::shared_ptr<flFxCoreGL> flFxCoreGL::Get() { return coreGL; } StateGroupGL::StateGroupGL() : StateGroup() { } StateGroupGL::~StateGroupGL() { } bool StateGroupGL::Apply() { for(auto iter = m_States.begin(); iter != m_States.end(); iter++) { (*iter)->Apply(); } return true; } bool StateGroupGL::Cleanup() { for (auto iter = m_States.begin(); iter != m_States.end(); iter++) { (*iter)->Cleanup(); } return true; } GLSLShader::GLSLShader(const char* name,GLenum type, const char* string) : Shader(name) { m_Type = type; if(string) { m_Code = string; } } GLSLShader::~GLSLShader() { glDeleteProgram(m_Id); } bool GLSLShader::LoadShader(const char* string) { m_Code = string; return true; } bool GLSLShader::LoadShaderFromFile(const char* filePath) { std::string shaderCode; std::ifstream shaderStream(filePath, std::ios::in); if(shaderStream.is_open()) { std::string Line = ""; while(getline(shaderStream, Line)) shaderCode += "\n" + Line; shaderStream.close(); } m_Code = shaderCode; return true; } bool GLSLShader::Validate() { if(m_Validated) { return false; //dont wanna validate twice } const char* code = m_Code.c_str(); m_Id = glCreateShaderProgramv(m_Type,1,&code); GLint Result = GL_FALSE; int InfoLogLength; glGetProgramiv(m_Id, GL_LINK_STATUS, &Result); glGetProgramiv(m_Id, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage(std::max(InfoLogLength, int(1))); if (InfoLogLength > 0) { glGetProgramInfoLog(m_Id, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); } SetValidated(true); Shader::Validate(); //AttachTo(pipeline); std::cout<<"Shader: Validated"<<std::endl; return true; } bool GLSLShader::Invalidate() { if(!m_Validated) { return false; } glDeleteProgram(m_Id); m_Id = NULL; Shader::Invalidate(); SetValidated(false); return true; } void GLSLShader::Bind() { glUseProgram(m_Id); } void GLSLShader::Unbind() { glUseProgram(0); } PipelineGL::~PipelineGL() { glDeleteProgramPipelines(1,&m_Id); } bool PipelineGL::Validate() { glGenProgramPipelines(1,&m_Id); for(auto iter = m_Shaders.begin(); iter != m_Shaders.end(); iter++) { std::shared_ptr<GLSLShader> glslShader = std::static_pointer_cast<GLSLShader>(*iter); GLenum bit; switch(glslShader->GetType()) { case GL_VERTEX_SHADER: bit = GL_VERTEX_SHADER_BIT; break; case GL_FRAGMENT_SHADER: bit = GL_FRAGMENT_SHADER_BIT; break; } glUseProgramStages(m_Id,bit,glslShader->GetProgramId()); } std::cout<<"PipelineGL: Validated"<<std::endl; SetValidated(true); return true; } bool PipelineGL::Invalidate() { glDeleteProgramPipelines(1,&m_Id); SetValidated(false); return true; } bool PipelineGL::SetShader(std::shared_ptr<Shader> shader) { if(!GPUPipeline::SetShader(shader)) { return false; } std::shared_ptr<GLSLShader> glslShader = std::static_pointer_cast<GLSLShader>(shader); glProgramParameteri(glslShader->GetProgramId(),GL_PROGRAM_SEPARABLE,GL_TRUE); //just as a precaution GLenum bit; switch(glslShader->GetType()) { case GL_VERTEX_SHADER: bit = GL_VERTEX_SHADER_BIT; break; case GL_FRAGMENT_SHADER: bit = GL_FRAGMENT_SHADER_BIT; break; } glUseProgramStages(m_Id,bit,glslShader->GetProgramId()); return true; } bool PipelineGL::RemoveShader(const char* name) { if(!GPUPipeline::RemoveShader(name)) { return false; } std::shared_ptr<GLSLShader> glslShader; for(auto iter = m_Shaders.begin(); iter != m_Shaders.end(); iter++) { if(strcmp((*iter)->GetName(),name) == 0) { glslShader = std::static_pointer_cast<GLSLShader>(*iter); } } glProgramParameteri(glslShader->GetProgramId(),GL_PROGRAM_SEPARABLE,GL_FALSE); return true; } void PipelineGL::Bind() { glBindProgramPipeline(m_Id); } void PipelineGL::Unbind() { glBindProgramPipeline(0); } ShaderParameterGL::ShaderParameterGL(const char* name, Type type, float* value) : ShaderParameter(name,value) { m_Type = type; } ShaderParameterGL::ShaderParameterGL(const char* name, Type type, GLsizei count, float* value) : ShaderParameter(name,value) { m_Type = type; m_Size = count; } ShaderParameterGL::ShaderParameterGL(const char* name, Type type,GLsizei count,GLboolean transpose, float* value) : ShaderParameter(name,value) { m_Type = type; m_Size = count; m_Transpose = transpose; } ShaderParameterGL::~ShaderParameterGL() { } bool ShaderParameterGL::Validate() { if(IsValid()) { return false; } if(!m_Parent.lock()) { return false; } int p = 0; std::shared_ptr<PipelineGL> glslPipeline = std::static_pointer_cast<PipelineGL>(m_Parent.lock()->Find(FX_PIPELINE_DESC_FLAG)); std::shared_ptr<GLSLShader> glslShader = std::static_pointer_cast<GLSLShader>(glslPipeline->GetShader(p)); while(glslShader) { Target t; glslShader->Bind(); if(m_Type == TSUBROUTINE) { t.uniformLocation = glGetSubroutineIndex(glslShader->GetProgramId(), glslShader->GetType(), m_Name); } else { t.uniformLocation = glGetUniformLocation(glslShader->GetProgramId(), m_Name); } if(t.uniformLocation >= 0) { std::cout<<"found uniform location: "<<t.uniformLocation<<std::endl; } t.shaderNumber = p; bool emplaced = false; for(auto iter = m_Targets.begin(); iter != m_Targets.end(); iter++) { if(iter->shaderNumber == t.shaderNumber && t.uniformLocation == iter->uniformLocation) { m_Targets.emplace(iter,t); emplaced = true; break; } } if(!emplaced) { m_Targets.push_back(t); } glslShader->Unbind(); p++; glslShader = std::static_pointer_cast<GLSLShader>(glslPipeline->GetShader(p)); } SetValidated(true); return true; } bool ShaderParameterGL::Invalidate() { if(!IsValid()) { return false; } if(!m_Parent.lock()) { return false; } SetValidated(false); return true; } bool ShaderParameterGL::Update() { for(auto iter = m_Targets.begin(); iter != m_Targets.end(); iter++) { Target t = (*iter); std::shared_ptr<PipelineGL> glslPipeline = std::static_pointer_cast<PipelineGL>(m_Parent.lock()->Find(FX_PIPELINE_DESC_FLAG)); std::shared_ptr<GLSLShader> glslShader = std::static_pointer_cast<GLSLShader>(glslPipeline->GetShader(t.shaderNumber)); if(glslShader) {///if glslProgram is valid switch(m_Type) { //if not resType, the m_Type case Type::T1I: glProgramUniform1i(glslShader->GetProgramId(),t.uniformLocation,(int)m_Value[0]); break; case Type::T1F: glProgramUniform1f(glslShader->GetProgramId(),t.uniformLocation,m_Value[0]); break; case Type::T3F: glProgramUniform3f(glslShader->GetProgramId(),t.uniformLocation,m_Value[0],m_Value[1],m_Value[2]); break; case Type::T1FV: glProgramUniform1fv(glslShader->GetProgramId(),t.uniformLocation,m_Size,m_Value); break; case Type::T3FV: glProgramUniform3fv(glslShader->GetProgramId(),t.uniformLocation,m_Size,m_Value); break; case Type::TMATRIX4FV: //shud be total array size / size of individual matrix glProgramUniformMatrix4fv(glslShader->GetProgramId(),t.uniformLocation,m_Size,m_Transpose,m_Value); //oh the count is the number of matrices passed break; case Type::TSUBROUTINE: //TODO break; } } } return true; } SamplerStateGL::SamplerStateGL(const char* name) : SamplerState(name) { m_HasChanged = false; } SamplerStateGL::~SamplerStateGL() { glDeleteSamplers(1, &m_Id); } bool SamplerStateGL::Validate() { glGenSamplers(1, &m_Id); return true; } bool SamplerStateGL::Invalidate() { glDeleteSamplers(1, &m_Id); return true; } bool SamplerStateGL::AddState(std::shared_ptr<BlankState> state) { SamplerState::AddState(state); m_HasChanged = true; return true; } bool SamplerStateGL::RemoveState(fxState state) { SamplerState::RemoveState(state); m_HasChanged = true; return true; } bool SamplerStateGL::UpdateTexture(int unit) { if (!m_Id) { return false; } if (m_HasChanged) { for (auto iter = m_States.begin(); iter != m_States.end(); iter++) { switch ((*iter)->m_State) { case FX_TEXTURE_WRAP_S: case FX_TEXTURE_WRAP_T: case FX_TEXTURE_MIN_FILTER: case FX_TEXTURE_MAG_FILTER: { std::shared_ptr<State2<GLenum, GLenum>> state = std::static_pointer_cast<State2<GLenum, GLenum>>(*iter); glSamplerParameteri(m_Id, state->m_v1, state->m_v2); //well, m_v1 in this case is the GLenum state, while the m_v2 is the value break; } case FX_TEXTURE_MAX_ANISOTROPY: { std::shared_ptr<State2<GLenum, GLfloat>> state = std::static_pointer_cast<State2<GLenum, GLfloat>>(*iter); glSamplerParameterf(m_Id, state->m_v1, state->m_v2); break; } } } m_HasChanged = false; } glBindSampler(unit, m_Id); return true; } ResourceGL::ResourceGL(const char* name, fxState resType) : Resource(name,resType) { m_TexUnit = -1; } ResourceGL::~ResourceGL() { glDeleteTextures(1, &m_Id); } bool ResourceGL::CreateRenderTexture() { GLenum format = StateInterpreter::Get()->Convert<GLenum>(m_Data.format); //glActiveTexture(GL_TEXTURE0 + m_TexUnit); glGenTextures(1, &m_Id); if (m_Data.msaa) { glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_Id); //glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Data.msaaSamples, m_Data.format, m_Data.dimensions[0], m_Data.dimensions[1], GL_TRUE); glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Data.msaaSamples, format, GetWidth(), GetHeight(), GL_TRUE); glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glBindTexture(GL_TEXTURE_2D, m_Id); glTexImage2D(GL_TEXTURE_2D, 0, format, GetWidth(), GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glTexImage2D(GL_TEXTURE_2D, 0, m_Data.format, m_Data.dimensions[0], m_Data.dimensions[1], 0, externalFormat, pixelStorageType, NULL); //glTexStorage2D(GL_TEXTURE_2D, 1, format, GetWidth(), GetHeight()); //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, GetWidth(), GetHeight(), 0, GL_RGB, GL_FLOAT, NULL); /*glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);*/ } return true; } bool ResourceGL::CreateDepthTexture() { glGenRenderbuffers(1, &m_Id); glBindRenderbuffer(GL_RENDERBUFFER, m_Id); GLenum format = StateInterpreter::Get()->Convert<GLenum>(m_Data.format); if (m_Data.msaa) { glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_Data.msaaSamples, format, GetWidth() , GetHeight()); } else { glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,800,800); } return true; } bool ResourceGL::Validate() { if (IsValid()) { return true; //dont validate twice } switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: if (!CreateRenderTexture()) { return false; } break; case FX_RESOURCE_DEPTHTEX: if (!CreateDepthTexture()) { return false; } break; } Resource::Validate(); SetValidated(true); return true; } bool ResourceGL::Invalidate() { if (!IsValid()) { return true; } switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: glDeleteTextures(1, &m_Id); case FX_RESOURCE_DEPTHTEX: glDeleteRenderbuffers(1, &m_Id); } Resource::Invalidate(); SetValidated(false); return true; } void ResourceGL::Bind() { switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: if (glIsEnabled(GL_TEXTURE_2D) == GL_FALSE) { glEnable(GL_TEXTURE_2D); //change it all bak ltr } glActiveTexture(GL_TEXTURE0 + m_TexUnit); glBindTexture(GL_TEXTURE_2D, m_Id); break; case FX_RESOURCE_DEPTHTEX: break; default: GLenum resTypeGL = StateInterpreter::Get()->Convert<GLenum>(m_ResourceType); if (glIsEnabled(resTypeGL) == GL_FALSE) { glEnable(resTypeGL); //change it all bak ltr } glActiveTexture(GL_TEXTURE0 + m_TexUnit); glBindTexture(resTypeGL, m_Id); std::shared_ptr<SamplerStateGL> samplerState = std::static_pointer_cast<SamplerStateGL>(m_Data.samplerState); if (samplerState) { samplerState->UpdateTexture(m_TexUnit); } break; } } void ResourceGL::Unbind() { switch (m_ResourceType) { case FX_RESOURCE_RENDERTEX: if (glIsEnabled(GL_TEXTURE_2D) == GL_TRUE) { glDisable(GL_TEXTURE_2D); } break; case FX_RESOURCE_DEPTHTEX: break; default: GLenum resTypeGL = StateInterpreter::Get()->Convert<GLenum>(m_ResourceType); if (glIsEnabled(resTypeGL) == GL_TRUE) { glDisable(resTypeGL); } break; } } bool ResourceGL::IsValid() { if (!PassDesc::IsValid()) { return false; } if (m_TexUnit < 0 || (!m_Id)) { return false; } return true; } FrameBufferObjectGL::~FrameBufferObjectGL() { glDeleteFramebuffers(1, &m_Id); } bool FrameBufferObjectGL::Validate() { for (auto iter = m_Resources.begin(); iter != m_Resources.end(); iter++) { (*iter)->Validate(); } m_DSTResource->Validate(); glGenFramebuffers(1, &m_Id); int size = GetNumResources(); if (size > 0) { glBindFramebuffer(GL_FRAMEBUFFER, m_Id); for (int i = 0; i < size; i++) { std::shared_ptr<ResourceGL> renderTex = std::static_pointer_cast<ResourceGL>(m_Resources.at(i)); glBindTexture(GL_TEXTURE_2D, renderTex->GetTextureId()); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + renderTex->GetFBOAttachment(), GL_TEXTURE_2D, renderTex->GetTextureId(), 0); //glBindTexture(GL_TEXTURE_2D, 0); } //glBindTexture(GL_TEXTURE_2D, 0); std::shared_ptr<ResourceGL> depthTex = std::static_pointer_cast<ResourceGL>(m_DSTResource); glBindRenderbuffer(GL_RENDERBUFFER, depthTex->GetTextureId()); //new glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthTex->GetTextureId()); GLenum* drawBuffers = new GLenum[size]; for (int i = 0; i < size; i++) { drawBuffers[i] = GL_COLOR_ATTACHMENT0 + (std::static_pointer_cast<ResourceGL>(m_Resources.at(i)))->GetFBOAttachment(); } glDrawBuffers(size, drawBuffers); int status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { std::cout << "something went wrong in the framebuffer!" << std::endl; } else { std::cout << "FBO SUCCESS!" << std::endl; } glBindFramebuffer(GL_FRAMEBUFFER, 0); } SetValidated(true); //add render textures back to pass return true; } bool FrameBufferObjectGL::Invalidate() { for (auto iter = m_Resources.begin(); iter != m_Resources.end(); iter++) { (*iter)->Invalidate(); } m_DSTResource->Invalidate(); glDeleteFramebuffers(1, &m_Id); //remove render textures from pass return true; } void FrameBufferObjectGL::SetDSTTexture(std::shared_ptr<Resource> res) { std::shared_ptr<ResourceGL> resGL = std::static_pointer_cast<ResourceGL>(res); FrameBufferObject::SetDSTTexture(res); if (!m_Id) { return; } glBindRenderbuffer(GL_RENDERBUFFER, resGL->GetTextureId()); //new glBindFramebuffer(GL_FRAMEBUFFER, m_Id); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, resGL->GetTextureId()); glBindFramebuffer(GL_FRAMEBUFFER, 0); SetValidated(false); } bool FrameBufferObjectGL::AddTextureResource(std::shared_ptr<Resource> res) { if (!FrameBufferObject::AddTextureResource(res)) { return false; } if (!m_Id) { //if(!IsValid()) { return true; } std::shared_ptr<ResourceGL> resGL = std::static_pointer_cast<ResourceGL>(res); glBindTexture(GL_TEXTURE_2D, resGL->GetTextureId()); glBindFramebuffer(GL_FRAMEBUFFER, m_Id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + resGL->GetFBOAttachment(), GL_TEXTURE_2D, resGL->GetTextureId(), 0); int size = GetNumResources(); if (size > 0) { GLenum* drawBuffers = new GLenum[size]; for (int i = 0; i < size; i++) { drawBuffers[i] = GL_COLOR_ATTACHMENT0 + (std::static_pointer_cast<ResourceGL>(m_Resources.at(i)))->GetFBOAttachment(); } glDrawBuffers(size, drawBuffers); int status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { std::cout << "something went wrong in the framebuffer!" << std::endl; } else { std::cout << "FBO SUCCESS!" << std::endl; } } glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); //glBindFramebuffer(GL_FRAMEBUFFER, 0); return true; } void FrameBufferObjectGL::SetCurrent() { glBindFramebuffer(GL_FRAMEBUFFER, m_Id); } bool FrameBufferObjectGL::Execute() { SetCurrent(); GLenum clear1 = StateInterpreter::Get()->Convert<GLenum>(m_ClearMode[0]); GLenum clear2 = StateInterpreter::Get()->Convert<GLenum>(m_ClearMode[1]); GLenum clear3 = StateInterpreter::Get()->Convert<GLenum>(m_ClearMode[2]); if (m_ClearMode[0] != NULL) { if (m_ClearMode[1] != NULL) { if (m_ClearMode[2] != NULL) { glClear(clear1 | clear2 | clear3); return true; } glClear(clear1 | clear2); return true; } glClear(clear1); return true; } //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); return true; } void FrameBufferObjectGL::ReleaseCurrent() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void FrameBufferObjectGL::SetClearMode(fxState clear1, fxState clear2, fxState clear3) { m_ClearMode[0] = clear1; m_ClearMode[1] = clear2; m_ClearMode[2] = clear3; } RenderingModeGL::RenderingModeGL(fxState renderMode) : PassDesc(FX_RENDERMODE_DESC_FLAG) { m_RenderingMode = renderMode; } bool RenderingModeGL::Execute() { switch (m_RenderingMode) { case FX_DRAW_FULLSCREEN_QUAD: flFxCoreGL::Get()->DrawFullscreenQuad(); break; case FX_DRAW_TRIANGLE: flFxCoreGL::Get()->DrawTriangle(0, 0, 0); break; case FX_DO_NOTHING: break; } return true; }<file_sep>/Source/Frontline Engine/Frontline Engine/Event/EventManager.h #pragma once #include "../FrontlineCommon.h" #include "../IGame.h" #include <iostream> #include <strstream> #include <map> #include <list> #include "DELEGATE\FastDelegate.h" #include <memory> #define EVENTMANAGER_NUM_QUEUES 2 class IEventData; typedef unsigned long EventType; typedef std::shared_ptr<IEventData> IEventDataPtr; //pointer to class IEventData typedef fastdelegate::FastDelegate1<IEventDataPtr> EventListenerDelegate; //for a one parameter delegate class IEventData { public: virtual ~IEventData(void) {} virtual const EventType& VGetEventType(void) const = 0; virtual float GetTimeStamp(void) const = 0; virtual void VSerialize(std::ostrstream& out) const = 0; virtual void VDeserialize(std::istrstream& in) = 0; //virtual IEventDataPtr VCopy(void) const = 0; virtual const char* GetName(void) const = 0; }; class BaseEventData : public IEventData { const float m_timeStamp; public: explicit BaseEventData(const float timeStamp = 0.0f) : m_timeStamp(timeStamp) { } virtual const EventType& VGetEventType(void) const = 0; float GetTimeStamp(void) const { return m_timeStamp; } virtual void VSerialize(std::ostrstream &out) const { } virtual void VDeserialize(std::istrstream& in) { } }; class EventManager { typedef std::list<EventListenerDelegate> EventListenerList; //may not be needed typedef std::map<EventType, EventListenerList> EventListenerMap; typedef std::list<IEventDataPtr> EventQueue; public: EventListenerMap m_eventListeners; EventQueue m_queues[EVENTMANAGER_NUM_QUEUES]; int m_activeQueue; explicit EventManager() { m_activeQueue = 0; } ~EventManager() { } bool VAddListener(const EventListenerDelegate& eventDelegate, const EventType& type); bool VRemoveListener(const EventListenerDelegate& eventDelegate, const EventType& type); bool VTriggerEvent(const IEventDataPtr& pEvent) const; bool VQueueEvent(const IEventDataPtr& pEvent); bool VThreadSafeQueueEvent(const IEventDataPtr& pEvent); bool VAbortEvent(const EventType& type, bool allOfType = false); bool VUpdate(unsigned long maxMillis); static EventManager* Get(); }; void RegisterEngineScriptEvents();<file_sep>/Source/Frontline Engine/Frontline Game Test/LockFramerateProcess.h #pragma once #include <Process\Process.h> #include <FrontlineCommon.h> class LockFramerateProcess : public Process { int delayMS; int accumMS; public: virtual void VOnUpdate(unsigned long deltaMs) override; void SetFramerate(int fps); LockFramerateProcess(int fps); ~LockFramerateProcess(); };<file_sep>/Source/Frontline/effectSysTestP2/GLenum.cpp #include "GLenum.h" static GLenums enums; GLenums::GLenums() { REGISTER_AS_STRING(GL_TRUE, "GL_TRUE"); REGISTER_AS_STRING(GL_FALSE, "GL_FALSE"); REGISTER_AS_STRING(GL_ONE, "GL_ONE"); REGISTER_AS_STRING(GL_ONE_MINUS_DST_ALPHA, "GL_ONE_MINUS_DST_ALPHA"); //texture states REGISTER_AS_STRING(GL_LINEAR, "GL_LINEAR"); REGISTER_AS_STRING(GL_REPEAT, "GL_REPEAT"); } GLenums::~GLenums() { } const char* GLenums::ToString(GLenum state) { for (auto iter = m_Enums.begin(); iter != m_Enums.end(); iter++) { if (iter->first == state) { return iter->second; } } return "GL_INVALID_ENUM"; } GLenum GLenums::ToGLenum(const char* state) { for (auto iter = m_Enums.begin(); iter != m_Enums.end(); iter++) { if (strcmp(iter->second, state) == 0) { return iter->first; } } return GL_INVALID_ENUM; } GLenums GLenums::Get() { return enums; }<file_sep>/Source/Frontline/effectSysTestP2/flFxParserGL.cpp #include "flFxParserGL.h" flFxParserGL::flFxParserGL() { RegisterXmlNodeHandle("Effect", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleEffectNode)); RegisterXmlNodeHandle("Technique", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleTechniqueNode)); RegisterXmlNodeHandle("Pass", fastdelegate::MakeDelegate(this, &flFxParserGL::HandlePassNode)); RegisterXmlNodeHandle("VertexShaderBody", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleShaderBodyNode)); RegisterXmlNodeHandle("FragmentShaderBody", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleShaderBodyNode)); RegisterXmlNodeHandle("FrameBufferObjectBody", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleFrameBufferObjectBodyNode)); RegisterXmlNodeHandle("ResourceBody", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleResourceBodyNode)); RegisterXmlNodeHandle("State", fastdelegate::MakeDelegate(this, &flFxParserGL::HandleStateNode)); } flFxParserGL::~flFxParserGL() { } static flFxParserGL* parserGL = new flFxParserGL(); flFxParserGL* flFxParserGL::Get() { return parserGL; } bool flFxParserGL::HandleEffectNode(pugi::xml_node node) { m_TmpEffect = std::shared_ptr<Effect>(new Effect(node.attribute("name").value())); return true; } bool flFxParserGL::HandleTechniqueNode(pugi::xml_node node) { std::shared_ptr<Technique> technique(new Technique(node.attribute("name").value())); m_TmpEffect->AddTechnique(technique); m_CurrTechnique = technique; return true; } bool flFxParserGL::HandlePassNode(pugi::xml_node node) { std::shared_ptr<Pass>pass(new Pass(node.attribute("name").value())); std::shared_ptr<PipelineGL>pipeline(new PipelineGL()); std::shared_ptr<StateGroupGL>stateGroup(new StateGroupGL()); std::shared_ptr<FrameBufferObjectGL> fboCopy = NULL; fxState clear[3]; pass->CreateData(pipeline); pass->CreateData(stateGroup); for (pugi::xml_node child = node.first_child(); child; child = child.next_sibling()) { if ((strcmp(child.name(), "VertexShader") == 0) || (strcmp(child.name(), "FragmentShader") == 0)) { std::shared_ptr<GLSLShader> shader = std::static_pointer_cast<GLSLShader>(GetQueuedObject(child.first_child().value())); if (shader) { std::shared_ptr<GLSLShader> shaderCopy(new GLSLShader(*shader)); //shaderCopy->SetName(child.attribute("name").value()); //remove this line pass->CreateData(shaderCopy); } continue; } if (strcmp(child.name(), "Resource") == 0) { //check the saved object list first std::shared_ptr<ResourceGL> resource = std::static_pointer_cast<ResourceGL>(GetSavedObject(child.first_child().value())); if (resource) { pass->CreateData(resource); //this is the render texture filled by the fbo of the previous pass } else { std::shared_ptr<ResourceGL> resource = std::static_pointer_cast<ResourceGL>(GetQueuedObject(child.first_child().value())); if (resource) { std::shared_ptr<ResourceGL> resourceCopy(new ResourceGL(*resource)); //resourceCopy->SetName(child.attribute("name").value()); //remove this item pass->CreateData(resourceCopy); } } continue; } if (strcmp(child.name(), "RenderTarget") == 0) { const char* targetName = child.first_child().value(); if (strcmp(targetName, "FX_BACKBUFFER") == 0) { continue; } else { //if this is framebuffer std::shared_ptr<FrameBufferObjectGL> fbo = std::static_pointer_cast<FrameBufferObjectGL>(GetQueuedObject(targetName)); if (fbo) { fboCopy = std::shared_ptr<FrameBufferObjectGL>(new FrameBufferObjectGL(fbo->GetName())); for (int i = 0; i < fbo->GetNumResources(); i++) { std::shared_ptr<ResourceGL> renderTex(new ResourceGL(*std::static_pointer_cast<ResourceGL>(fbo->GetTextureResource(i)))); SaveObject(renderTex); //instead of SaveObject, use the repository fboCopy->AddTextureResource(renderTex); //pass->CreateData(renderTex); //DO NOT ADD TO PASS CUZ IT DOESNT NEED BINDING //renderTex->SetActive(false); //you dont want it to execute here... } std::shared_ptr<ResourceGL> depthTex(new ResourceGL(*std::static_pointer_cast<ResourceGL>(fbo->GetDSTTexture()))); if (depthTex) { SaveObject(depthTex); fboCopy->SetDSTTexture(depthTex); //pass->CreateData(depthTex); //depthTex->SetActive(false); } pass->CreateData(fboCopy); } } continue; } if (strcmp(child.name(), "ClearMode") == 0) { const char* clear1 = child.attribute("clear1").value(); const char* clear2 = child.attribute("clear2").value(); const char* clear3 = child.attribute("clear3").value(); if (strcmp(clear1, "") != 0) { clear[0] = StateInterpreter::Get()->ToState(clear1); } else { clear[0] = NULL; } if (strcmp(clear2, "") != 0) { clear[1] = StateInterpreter::Get()->ToState(clear2); } else { clear[1] = NULL; } if (strcmp(clear3, "") != 0) { clear[2] = StateInterpreter::Get()->ToState(clear3); } else { clear[2] = NULL; } continue; } if (strcmp(child.name(), "RenderingMode") == 0) { const char* mode = child.attribute("mode").value(); std::shared_ptr<RenderingModeGL> renderingMode(new RenderingModeGL(StateInterpreter::Get()->ToState(mode))); pass->CreateData(renderingMode); continue; } } if (fboCopy) { fboCopy->SetClearMode(clear[0], clear[1], clear[2]); } m_CurrTechnique->AddPass(pass); m_CurrPass = pass; return true; } bool flFxParserGL::HandleShaderBodyNode(pugi::xml_node node) { if (strcmp(node.name(), "VertexShaderBody") == 0) { std::shared_ptr<GLSLShader> vertexShader(new GLSLShader(node.attribute("name").value(), GL_VERTEX_SHADER, node.first_child().value())); SetQueuedObject(vertexShader); } else if (strcmp(node.name(), "FragmentShaderBody") == 0) { std::shared_ptr<GLSLShader> fragmentShader(new GLSLShader(node.attribute("name").value(), GL_FRAGMENT_SHADER, node.first_child().value())); SetQueuedObject(fragmentShader); } return true; } bool flFxParserGL::HandleResourceBodyNode(pugi::xml_node node) { fxState type = NULL; //try to find a way to loop through the different types of resources so u dont have to manually specify if (strcmp(node.attribute("type").value(), "FX_RESOURCE_2D") == 0) { type = FX_RESOURCE_2D; } if (strcmp(node.attribute("type").value(), "FX_RESOURCE_RENDERTEX") == 0) { type = FX_RESOURCE_RENDERTEX; } if (strcmp(node.attribute("type").value(), "FX_RESOURCE_DEPTHTEX") == 0) { type = FX_RESOURCE_DEPTHTEX; } if (!type) { return false; } std::shared_ptr<ResourceGL> resource(new ResourceGL(node.attribute("name").value(), type)); for (pugi::xml_node child = node.first_child(); child; child = child.next_sibling()) { if (strcmp(child.name(), "Texture") == 0) { int unit = child.attribute("binding").as_int(); resource->SetTexUnit(unit); continue; } if (strcmp(child.name(), "SamplerState") == 0) { std::shared_ptr<SamplerStateGL> samplerState(new SamplerStateGL(child.attribute("name").value())); for (pugi::xml_node sstateChild = child.first_child(); sstateChild; sstateChild = sstateChild.next_sibling()) { if (strcmp(sstateChild.name(), "FX_TEXTURE_MIN_FILTER") == 0) { std::shared_ptr<State2<GLenum, GLenum>> minFilter(new State2<GLenum, GLenum>(FX_TEXTURE_MIN_FILTER, GL_TEXTURE_MIN_FILTER, StateInterpreter::Get()->Convert<GLenum>(StateInterpreter::Get()->ToState(sstateChild.attribute("value").value())))); samplerState->AddState(minFilter); continue; } if (strcmp(sstateChild.name(), "FX_TEXTURE_MAG_FILTER") == 0) { std::shared_ptr<State2<GLenum, GLenum>> magFilter(new State2<GLenum, GLenum>(FX_TEXTURE_MAG_FILTER, GL_TEXTURE_MAG_FILTER, StateInterpreter::Get()->Convert<GLenum>(StateInterpreter::Get()->ToState(sstateChild.attribute("value").value())))); samplerState->AddState(magFilter); continue; } if (strcmp(sstateChild.name(), "FX_TEXTURE_WRAP_S") == 0) { std::shared_ptr<State2<GLenum, GLenum>> texWrapS(new State2<GLenum, GLenum>(FX_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_S, StateInterpreter::Get()->Convert<GLenum>(StateInterpreter::Get()->ToState(sstateChild.attribute("value").value())))); samplerState->AddState(texWrapS); continue; } if (strcmp(sstateChild.name(), "FX_TEXTURE_WRAP_T") == 0) { std::shared_ptr<State2<GLenum, GLenum>> texWrapT(new State2<GLenum, GLenum>(FX_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_T, StateInterpreter::Get()->Convert<GLenum>(StateInterpreter::Get()->ToState(sstateChild.attribute("value").value())))); samplerState->AddState(texWrapT); continue; } } samplerState->Validate(); resource->SetSamplerState(samplerState); continue; } //now for the render textures if (strcmp(child.name(), "InternalFormat") == 0) { fxState internalFormat = StateInterpreter::Get()->ToState(child.attribute("format").value()); std::cout << child.attribute("format").value() << ":" << internalFormat << std::endl; resource->SetFormat(internalFormat); continue; } if (strcmp(child.name(), "Size") == 0) { int w = child.attribute("w").as_int(); int h = child.attribute("h").as_int(); int d = child.attribute("d").as_int(); resource->SetDimensions(w, h, d); continue; } } SetQueuedObject(resource); return true; } bool flFxParserGL::HandleFrameBufferObjectBodyNode(pugi::xml_node node) { std::shared_ptr<FrameBufferObjectGL> fbo(new FrameBufferObjectGL(node.attribute("name").value())); for (pugi::xml_node child = node.first_child(); child; child = child.next_sibling()) { if (strcmp(child.name(), "RenderTexture") == 0) { int attachment = child.attribute("attachment").as_int(); const char* resName = child.first_child().value(); std::shared_ptr<ResourceGL> res = std::static_pointer_cast<ResourceGL>(GetQueuedObject(resName)); if (res) { std::shared_ptr<ResourceGL> resCopy(new ResourceGL(*res)); resCopy->SetFBOAttachment(attachment); //SaveObject(resCopy); //to be accessed for later use fbo->AddTextureResource(resCopy); } continue; } if (strcmp(child.name(), "DepthTexture") == 0) { const char* resName = child.first_child().value(); std::shared_ptr<ResourceGL> res = std::static_pointer_cast<ResourceGL>(GetQueuedObject(resName)); if (res) { std::shared_ptr<ResourceGL> resCopy(new ResourceGL(*res)); //SaveObject(resCopy); //to be accessed for later use fbo->SetDSTTexture(resCopy); } continue; } } SetQueuedObject(fbo); return true; } bool flFxParserGL::HandleStateNode(pugi::xml_node node) { const char* name = node.attribute("type").value(); std::shared_ptr<StateGroupGL> stateGroup = std::static_pointer_cast<StateGroupGL>(m_CurrPass->Find(FX_STATE_GROUP_DESC_FLAG)); std::shared_ptr<BlankState> state; if (strcmp(name, "FX_BLEND") == 0) { state = std::shared_ptr<BlendGL>(new BlendGL()); } if (strcmp(name, "FX_BLEND_FUNC") == 0) { state = std::shared_ptr<BlendFuncGL>(new BlendFuncGL()); } if (strcmp(name, "FX_ALPHA_FUNC") == 0) { state = std::shared_ptr<AlphaFuncGL>(new AlphaFuncGL()); } if (strcmp(name, "FX_BLEND_FUNC_SEPARATE") == 0) { state = std::shared_ptr<BlendFuncSeparateGL>(new BlendFuncSeparateGL()); } if (strcmp(name, "FX_BLEND_EQUATION_SEPARATE") == 0) { state = std::shared_ptr<BlendEquationSeparateGL>(new BlendEquationSeparateGL()); } if (strcmp(name, "FX_LOGIC_OP") == 0) { state = std::shared_ptr<LogicOpGL>(new LogicOpGL()); } if (strcmp(name, "FX_COLOR_MASK") == 0) { state = std::shared_ptr<ColorMaskGL>(new ColorMaskGL()); } if (strcmp(name, "FX_BLEND_COLOR") == 0) { state = std::shared_ptr<BlendColorGL>(new BlendColorGL()); } if (state) { state->Load(node); stateGroup->AddState(state); } return true; }<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/ActorFactory.cpp #include "ActorFactory.h" #include <vector> ActorFactory* ActorFactory::g_ActorFactory = FL_NEW ActorFactory(); ActorFactory::ActorFactory() { } // -------------------------------------------------------------------------- // Function: ActorFactory::CreateActor // Purpose: Create an actor from XML source // Parameters: The source XML // -------------------------------------------------------------------------- StrongActorPtr ActorFactory::CreateActor(const char* actorResource) { // Grab the root XML node pugi::xml_document l_xmlDoc; l_xmlDoc.load(actorResource); pugi::xml_node l_root = l_xmlDoc.root(); if (!l_root) { ERRLOG("Actor", "Failed to create actor from resource : " + std::string(actorResource)); return StrongActorPtr(); } // create the actor instance StrongActorPtr l_actor(FL_NEW Actor(GetNextActorId())); if (!l_actor->Init(l_root)) { ERRLOG("Actor", "Failed to initialize actor : " + std::string(actorResource)); return StrongActorPtr(); } // Loop through each child element and load the component for (pugi::xml_node l_node = l_root.first_child(); l_node; l_node = l_node.next_sibling()) { StrongActorComponentPtr pComponent(CreateComponent(l_node)); if (pComponent) { l_actor->AddComponent(pComponent); pComponent->SetOwner(l_actor); } else { return StrongActorPtr(); } } // Now that the actor has been fully created, run the post init phase l_actor->PostInit(); return l_actor; } // -------------------------------------------------------------------------- // Function: ActorFactory::CreateComponent // Purpose: Create and initialize a component from XML. // Parameters: The XML node of the new component // -------------------------------------------------------------------------- StrongActorComponentPtr ActorFactory::CreateComponent(pugi::xml_node l_data) { const char* name = l_data.name(); StrongActorComponentPtr pComponent(m_componentFactory.Create(name)); // initialize the component if we found one if (pComponent) { if (!pComponent->VInit(l_data)) { ERRLOG("Actor", "Component failed to initialize: " + std::string(name)); return StrongActorComponentPtr(); } } else { ERRLOG("Actor", "Couldn't find ActorComponent named " + std::string(name)); return StrongActorComponentPtr(); // fail } // pComponent will be NULL if the component wasn't found. This isn't necessarily an error since you might have a // custom CreateComponent() function in a sub class. return pComponent; }<file_sep>/Source/Frontline/effectSysTestP2/StatesGL.cpp #include "StatesGL.h"<file_sep>/Source/Frontline Engine/Frontline Engine/Actor/ActorFactory.h #pragma once #include "..\FrontlineCommon.h" #include "..\IGame.h" #include "Actor.h" #include "ActorComponent.h" typedef ActorComponent *(*ActorComponentCreator)(void); typedef std::map<std::string, ActorComponentCreator> ActorComponentCreatorMap; // some actor typedefs to make our life easier typedef unsigned long ActorId; typedef std::shared_ptr<Actor> StrongActorPtr; typedef std::shared_ptr<ActorComponent> StrongActorComponentPtr; class ActorFactory { ActorID m_lastActorID; protected: GenericObjectFactory<ActorComponent, std::string> m_componentFactory; virtual ~ActorFactory() {}; public: ActorFactory(void); StrongActorPtr CreateActor(const char* p_actorResource); template<class t_ComponentClass> bool RegisterComponentType(std::string name) { m_componentFactory.Register<t_ComponentClass>(name); return true; } static ActorFactory* g_ActorFactory; protected: virtual StrongActorComponentPtr CreateComponent(pugi::xml_node p_data); private: ActorId GetNextActorId(void) { ++m_lastActorID; return m_lastActorID; } };<file_sep>/Source/Frontline Engine/Frontline Engine/Process/Process.cpp #include "Process.h" Process::Process() { currentProcessState = PROCESS_UNINITIALIZED; } Process::~Process() { m_childProcessMap.clear(); } // -------------------------------------------------------------------------- // Function: Process::AttachChild // Purpose: Attach a new child process // Parameters: The child's completion state, a shared pointer to the new child // -------------------------------------------------------------------------- void Process::AttachChild(ProcessState state, StrongProcessPtr pChild) { m_childProcessMap[state].push_back(pChild); } // -------------------------------------------------------------------------- // Function: Process::RemoveChild // Purpose: Remove a specific child process // Parameters: The completion state of the child, a shared pointer to the child // -------------------------------------------------------------------------- void Process::RemoveChild(ProcessState state, StrongProcessPtr pChild) { auto findIt = m_childProcessMap.find(state); if(findIt != m_childProcessMap.end()) { for(auto iter = findIt -> second.begin(); iter != findIt -> second.end();) { if(pChild == (*iter)) { m_childProcessMap[state].erase(iter); break; } else { iter++; } } } } // -------------------------------------------------------------------------- // Function: Process::RemoveChild // Purpose: Remove all child processes with a specific completion state // Parameters: The completion state to clear // -------------------------------------------------------------------------- void Process::RemoveChild(ProcessState state) { m_childProcessMap[state].clear(); }<file_sep>/Source/Frontline Engine/Frontline Engine/System/Win32Console.h #pragma once #include "Console.h" #include <Windows.h> class Win32Console : public Console { HANDLE hConsole; public: virtual void setColor(Color f) override; virtual void printf(const char* format, ...); Win32Console(); ~Win32Console(); }; <file_sep>/Source/Frontline Engine/Frontline Game Test/TestPhysicsProcess.h #pragma once #include <Process\Process.h> #include <Physics\BulletPhysics.h> class TestPhysicsProcess : public Process { std::shared_ptr<IPhysics> mp_physics; int ups; float accum; protected: virtual void VOnUpdate(unsigned long deltaMs) override; public: TestPhysicsProcess(std::shared_ptr<IPhysics> physics); ~TestPhysicsProcess(); }; <file_sep>/Source/Frontline Engine/Frontline Engine/Process/ProcessManager.h #pragma once #include "..\FrontlineCommon.h" #include "Process.h" class ProcessManager { typedef std::list<StrongProcessPtr> ProcessList; public: ~ProcessManager(void) {} ProcessList m_processList; unsigned int UpdateProcesses(unsigned long deltaMs); // updates all attached processes void AttachProcess(StrongProcessPtr pProcess); // attaches a process to the process mgr void AbortAllProcesses(bool immediate); unsigned int GetProcessCount() const { return m_processList.size(); } private: void ClearAllProcesses(); // should only be called by the destructor }; <file_sep>/Source/Frontline Engine/Frontline Engine/Resource/ResCache.h #pragma once #include "..\FrontlineCommon.h" #include "IResourceLoader.h" #include "IResource.h" #include "..\IResourceFile.h" typedef std::list<ResHandle> ResHandleList; typedef std::map<std::string, ResHandle> ResHandleMap; typedef std::list< std::shared_ptr < IResourceLoader > > ResourceLoaders; typedef fastdelegate::FastDelegate1<unsigned int, char*> AllocationFunction; class ResCache { protected: AllocationFunction alloc; ResHandleList m_lru; // LRU (least recently used) list ResHandleMap m_resources; // STL map for fast resource lookup ResourceLoaders m_resourceLoaders; IResourceFile *m_file; // Object that implements IResourceFile unsigned int m_cacheSize; // total memory size unsigned int m_allocated; // total memory allocated const void *Update(ResHandle handle); ResHandle Load(const char* ps_resname); void Free(ResHandle gonner); bool MakeRoom(unsigned int size); char* Allocate(unsigned int size); void FreeOneResource(); void MemoryHasBeenFreed(unsigned int size); public: ResCache(const unsigned int sizeInMb, IResourceFile *resFile); ~ResCache(); bool Init(); void RegisterLoader(std::shared_ptr<IResourceLoader> loader); ResHandle GetHandle(const char* ps_resname); int Preload(const std::string pattern, void(*progressCallback)(int, bool &)); void Flush(void); };<file_sep>/Source/Frontline Engine/Frontline Engine/Process/TimerProcess.cpp #include "TimerProcess.h" TimerProcess::TimerProcess() { } void TimerProcess::VOnUpdate(unsigned long deltaMs) { m_countdownMS -= deltaMs; if (m_countdownMS <= 0) { Succeed(); IGame::gp_game->mp_log->logOther("TIMERPROCESS", "Timer process finished"); } }<file_sep>/Source/Frontline Engine/Frontline Game Test/LockFramerateProcess.cpp #include "LockFramerateProcess.h" #include <Windows.h> LockFramerateProcess::LockFramerateProcess(int fps) { delayMS = 1000 / fps; } LockFramerateProcess::~LockFramerateProcess() { } void LockFramerateProcess::VOnUpdate(unsigned long deltaMs) { if (delayMS - deltaMs > 0 && deltaMs < delayMS) { Sleep(delayMS - deltaMs); } }<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/ResCache.cpp #include "ResCache.h" #include <tchar.h> ResCache::ResCache(const unsigned int sizeInMb, IResourceFile *resFile) { m_cacheSize = sizeInMb * 1024 * 1024; m_allocated = 0; m_file = resFile; } ResCache::~ResCache() { while (!m_lru.empty()) { FreeOneResource(); } SAFE_DELETE(m_file); } bool ResCache::Init() { bool retValue = false; if (m_file->VOpen()) { RegisterLoader(std::shared_ptr<IResourceLoader>(FL_NEW DefaultResourceLoader())); retValue = true; } return retValue; } ResHandle ResCache::GetHandle(Resource * r) { ResHandle handle(Find(r)); if (handle == NULL) handle = Load(r); else Update(handle); return handle; } ResHandle ResCache::Load(Resource *r) { std::shared_ptr<IResourceLoader> loader; ResHandle handle; for (ResourceLoaders::iterator it = m_resourceLoaders.begin(); it != m_resourceLoaders.end(); ++it) { std::shared_ptr<IResourceLoader> testLoader = *it; if (WildcardMatch(testLoader->VGetPattern().c_str(), r->m_name.c_str())) { loader = testLoader; break; } } if (!loader) { FL_ASSERT(loader && _T("Default resource loader not found!")); return handle; // Resource not loaded! } unsigned int rawSize = m_file->VGetRawResourceSize(*r); char *rawBuffer = loader->VUseRawFile() ? Allocate(rawSize) : FL_NEW char[rawSize]; if (rawBuffer == NULL) { // resource cache out of memory return ResHandle(); } m_file->VGetRawResource(*r, rawBuffer); char *buffer = NULL; unsigned int size = 0; if (loader->VUseRawFile()) { buffer = rawBuffer; handle = ResHandle(r); } else { size = loader->VGetLoadedResourceSize(rawBuffer, rawSize); buffer = Allocate(size); if (rawBuffer == NULL || buffer == NULL) { // resource cache out of memory return ResHandle(); } handle = ResHandle(r); bool success = loader->VLoadResource(rawBuffer, "").get(); // TODO fix name thing SAFE_DELETE_ARRAY(rawBuffer); if (!success) { // resource cache out of memory return ResHandle(); } } if (handle) { m_lru.push_front(handle); m_resources[r->m_name] = handle; } FL_ASSERT(loader && _T("Default resource loader not found!")); return handle; // ResCache is out of memory! } char* ResCache::Allocate(unsigned int size) { if (!MakeRoom(size)) return NULL; char *mem = FL_NEW char[size]; if (mem) m_allocated += size; return mem; } bool ResCache::MakeRoom(unsigned int size) { if (size > m_cacheSize) { return false; } // return null if there’s no possible way to allocate the memory while (size > (m_cacheSize - m_allocated)) { // The cache is empty, and there’s still not enough room. if (m_lru.empty()) return false; FreeOneResource(); } return true; } void ResCache::FreeOneResource() { ResHandleList::iterator gonner = m_lru.end(); gonner--; ResHandle handle = *gonner; m_lru.pop_back(); m_resources.erase(handle->m_name); }<file_sep>/Source/Frontline/effectSysTestP2/flFxExt.h #pragma once #include <tuple> #include "flFx.h" #include "pugixml/pugiconfig.hpp" #include "pugixml/pugixml.hpp" //for all state parameters: //for example: //FX_BLEND_FUNC src = "FX_ONE" dst = "FX_ONE" //FX_BLEND_FUNC is function name //src and dst are parameters that take place of GL state //maybe put the typename T in the member functions class StateInterpreter { private: //state GLenum std::map<fxState,std::pair<void*,const char*>> m_States; public: StateInterpreter() {} ~StateInterpreter() {} template<typename T> void RegisterState(fxState state, T state1, const char* xmlName) { m_States[state].first = static_cast<void*>(new T(state1)); m_States[state].second = xmlName; } template<typename T> T Convert(fxState state) { if (m_States.count(state) > 0) { return *static_cast<T*>(m_States.at(state).first); } return NULL; } template<typename T> T Convert(const char* state) { return Convert<T>(ToState(state)); } template<typename T> fxState Convert(T state) { for (auto iter = m_States.begin(); iter != m_States.end(); iter++) { T s = *static_cast<T*>(iter->second.first); if (state == s) { return iter->first; } } return NULL; } const char* ToString(fxState state) { if (m_States.count(state) > 0) { return m_States.at(state).second; } return NULL; } fxState ToState(const char* state) { for (auto iter = m_States.begin(); iter != m_States.end(); iter++) { if (strcmp(state, iter->second.second) == 0) { return iter->first; } } return NULL; } static std::shared_ptr<StateInterpreter> Get(); }; struct BlankState { fxState m_State; BlankState() {} BlankState(fxState state) {m_State = state;} virtual ~BlankState() {} virtual const char* GetName() { return StateInterpreter::Get()->ToString(m_State); } virtual bool Load(pugi::xml_node node) { return true; } //for flFxParserGL virtual bool Apply() { return true; } virtual bool Cleanup() { return true; } }; template<typename T> struct State1 : public BlankState { T m_v; State1(fxState state, T v) : BlankState(state) { m_v = v; } State1() {} virtual ~State1() {} }; template<typename T1, typename T2> struct State2 : public BlankState { T1 m_v1; T2 m_v2; State2(fxState state, T1 v1, T2 v2) : BlankState(state) { m_v1 = v1; m_v2 = v2; } State2() {} virtual ~State2() {} }; template<typename T1, typename T2, typename T3> struct State3 : public BlankState { T1 m_v1; T2 m_v2; T3 m_v3; State3(fxState state, T1 v1, T2 v2, T3 v3) : BlankState(state) { m_v1 = v1; m_v2 = v2; m_v3 = v3; } State3() {} virtual ~State3() {} }; template<typename T1, typename T2, typename T3, typename T4> struct State4 : public BlankState { T1 m_v1; T2 m_v2; T3 m_v3; T4 m_v4; State4(fxState state, T1 v1, T2 v2, T3 v3, T4 v4) : BlankState(state) { m_v1 = v1; m_v2 = v2; m_v3 = v3; m_v4 = v4; } State4() {} virtual ~State4() {} }; class StateGroup : public PassDesc { protected: std::list<std::shared_ptr<BlankState>>m_States; public: StateGroup() : PassDesc(FX_STATE_GROUP_DESC_FLAG) {} //register fxState converts here ~StateGroup() {} virtual bool AddState(std::shared_ptr<BlankState> state); virtual bool RemoveState(fxState state); std::shared_ptr<BlankState> FindState(fxState state); virtual bool Apply() {return true;} }; //........// class Shader : public PassDesc { protected: std::string m_Code; public: Shader(const char* name) : PassDesc(FX_SHADER_DESC_FLAG,name) {} virtual ~Shader() {} virtual bool Validate(); //dont need Pass* pass = NULL cuz of m_Parent virtual bool Invalidate(); }; class GPUPipeline : public PassDesc { protected: std::vector<std::shared_ptr<Shader>> m_Shaders; //this is better public: GPUPipeline() : PassDesc(FX_PIPELINE_DESC_FLAG) {} virtual ~GPUPipeline() {} virtual bool SetShader(std::shared_ptr<Shader> shader); virtual void SetShaders(std::shared_ptr<Shader>* shaders,int count) {} virtual bool RemoveShader(const char* name); virtual std::shared_ptr<Shader> GetShader(const char* name); virtual std::shared_ptr<Shader> GetShader(int index); virtual void ClearAll() {m_Shaders.clear();} }; //........// class SamplerState { protected: const char* m_Name; std::vector<std::shared_ptr<BlankState>>m_States; public: SamplerState(const char* name) {m_Name = name;} virtual ~SamplerState() {} void SetName(const char* name) {m_Name = name;} const char* GetName() {return m_Name;} virtual bool Validate() {return true;} virtual bool Invalidate() {return true;} virtual bool AddState(std::shared_ptr<BlankState> state); virtual std::shared_ptr<BlankState> FindState(fxState state); virtual bool RemoveState(fxState state); }; //........// class Resource : public PassDesc { protected: struct ResourceData { bool appDepSize; unsigned int dimensions[3]; bool msaa; unsigned int msaaSamples; std::shared_ptr<SamplerState> samplerState; fxState format; //BlankState format; bool external; }; fxState m_ResourceType; //BlankState m_ResourceType; ResourceData m_Data; public: Resource(const char* name,fxState resType); virtual ~Resource(); virtual bool Validate(); //if is rendertex, add to fbo virtual bool Invalidate(); //if is rendertex, remove from fbo virtual void SetSamplerState(std::shared_ptr<SamplerState> sstate) {m_Data.samplerState = sstate;} virtual std::shared_ptr<SamplerState> GetSamplerState() {return m_Data.samplerState;} virtual void SetDimensions(int w,int h = 0, int d = 0); virtual int GetWidth() {return m_Data.dimensions[0];} virtual int GetHeight() {return m_Data.dimensions[1];} virtual int GetDepth() {return m_Data.dimensions[2];} virtual void SetDimensionAppDependent(bool size) {m_Data.appDepSize = size;} virtual bool GetDimensionAppDependent() {return m_Data.appDepSize;} virtual void SetMSAAActive(bool msaa) {m_Data.msaa = msaa;} virtual bool GetMSAAActive() {return m_Data.msaa;} virtual void SetMSAASamples(unsigned int samples) {m_Data.msaaSamples = samples;} virtual unsigned int GetMSAASamples() {return m_Data.msaaSamples;} virtual void SetFormat(fxState fmt) {m_Data.format = fmt;} virtual fxState GetFormat() {return m_Data.format;} virtual bool IsValid() {return false;} virtual bool Update() {return true;} }; class FrameBufferObject : public PassDesc { protected: std::shared_ptr<Resource> m_DSTResource; std::vector<std::shared_ptr<Resource>>m_Resources; //std::vector<const char*> m_Resources; //u can hold names instead for searchup public: FrameBufferObject(const char* name); virtual ~FrameBufferObject(); virtual bool Validate(); virtual bool Invalidate(); virtual void SetDSTTexture(std::shared_ptr<Resource> res) {m_DSTResource = res;} virtual std::shared_ptr<Resource> GetDSTTexture() {return m_DSTResource;} virtual bool AddTextureResource(std::shared_ptr<Resource> res); virtual std::shared_ptr<Resource> GetTextureResource(int index); virtual void SetCurrent() {} virtual void ReleaseCurrent() {} virtual void BlitTo(std::shared_ptr<FrameBufferObject> dst) {} virtual int GetNumResources() {return (int)m_Resources.size();} }; class ShaderParameter : public PassDesc { protected: //dont need layerid cuz only one layer is ever active float* m_Value; //an array public: //allocate size depending on value ShaderParameter(const char* name,float* value = NULL); virtual ~ShaderParameter(); virtual void SetValue(float* value); virtual bool Update() {return true;} }; //........//<file_sep>/Source/Frontline Engine/Frontline Engine/System/Pool.cpp #include "Pool.h" #include "..\FrontlineCommon.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline uint8_t alignForwardAdjustment(const void* address, uint8_t alignment) { uint8_t adjustment = alignment - (reinterpret_cast<uintptr_t>(address) & static_cast<uintptr_t>(alignment - 1)); if (adjustment == alignment) return 0; //already aligned return adjustment; } inline uint8_t alignForwardAdjustmentWithHeader(const void* address, uint8_t alignment, uint8_t headerSize) { uint8_t adjustment = alignForwardAdjustment(address, alignment); uint8_t neededSpace = headerSize; if (adjustment < neededSpace) { neededSpace -= adjustment; //Increase adjustment to fit header adjustment += alignment * (neededSpace / alignment); if (neededSpace % alignment > 0) adjustment += alignment; } return adjustment; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// Pool::Pool(int pi_KB, void* pp_begin) : mp_freeBlocks((FreeBlock*) pp_begin) { if (pi_KB < 1) { ERRLOG("Pool", "Pool cannot have a size of zero."); return; } mp_begin = pp_begin; mi_numAllocations = 0; mi_size = pi_KB * 1024; mi_usedMem = 0; mp_freeBlocks->next = nullptr; mp_freeBlocks->size = pi_KB * 1024; } Pool::~Pool() { if (mi_numAllocations != 0 || mi_usedMem != 0) { ERRLOG("Pool", "Not all memory has been deallocated."); return; } mp_freeBlocks = nullptr; memset(mp_begin, 0xcd, mi_size); } void* Pool::Alloc(size_t pi_size, uint8_t pi_alignment) { FreeBlock* lp_currBlock = mp_freeBlocks, *lp_prevBlock = nullptr; // Current block in list, previous block while (lp_currBlock != nullptr) // Loop through the list { uint8_t adjustment = alignForwardAdjustmentWithHeader(lp_currBlock, pi_alignment, sizeof(AllocationHeader)); // Find the adjustment to byte - align the object size_t total_size = adjustment + pi_size; // The total amount of memory occupied by the object if (lp_currBlock->size < total_size) // If the current free block is not large enough { lp_prevBlock = lp_currBlock; lp_currBlock = lp_currBlock->next; continue; } if (lp_currBlock->size - total_size <= sizeof(AllocationHeader)) // If there is not enough space for another object { total_size = lp_currBlock->size; // Occupy the entire block } else { /// TODO order list from smallest to largest FreeBlock* next_block = (FreeBlock*) ((int) lp_currBlock + total_size); // Create a free block after the allocated space next_block->next = lp_currBlock->next; // Set up the new block next_block->size = lp_currBlock->size - total_size; if (lp_prevBlock != nullptr) lp_prevBlock->next = next_block; // Let the previous block know about the new one else mp_freeBlocks = next_block; // Set the first block to the new one } void* alignedAddress = lp_currBlock + adjustment; // Find the actual address of initialized data AllocationHeader* header = (AllocationHeader*) lp_currBlock; // Create the header header->adjustment = adjustment; // Set the header properties header->size = total_size; mi_usedMem += total_size; // Find the total memory used by the pool mi_numAllocations++; // Increment the number of allocations return (void*) alignedAddress; // Return the memory address } } int Pool::CombineFreeBlocks() { FreeBlock* lp_currBlock = mp_freeBlocks; FreeBlock* lp_prevBlock = nullptr; while (lp_currBlock != nullptr) { FreeBlock* adjacent = lp_currBlock + lp_currBlock->size; if (adjacent == lp_currBlock->next) { lp_currBlock->next = adjacent->next; lp_currBlock->size += adjacent->size; } lp_prevBlock = lp_currBlock; lp_currBlock = lp_currBlock->next; } return 0; } void Pool::DeAlloc(void* pp_toDelete) { if (pp_toDelete == nullptr) { ERRLOG("Pool", "Tried to delete NULL pointer."); return; } AllocationHeader* header = (AllocationHeader*) pp_toDelete - sizeof(AllocationHeader); FreeBlock* lp_currBlock = mp_freeBlocks; FreeBlock* lp_prevBlock = nullptr; size_t li_size = header->size; while (lp_currBlock != nullptr) { if (lp_currBlock > (void*) header) break; lp_prevBlock = lp_currBlock; lp_currBlock = lp_prevBlock->next; } FreeBlock* lp_newBlock = (FreeBlock*) pp_toDelete - header->adjustment; lp_newBlock->next = lp_currBlock; if (lp_prevBlock == nullptr) { mp_freeBlocks = lp_newBlock; } else if (lp_prevBlock + lp_prevBlock->size >= lp_newBlock) { lp_prevBlock->size += lp_newBlock->size; lp_prevBlock->next = lp_newBlock->next; lp_newBlock = lp_prevBlock; } else { lp_prevBlock->next = lp_newBlock; } FreeBlock* lp_nextBlock = lp_newBlock->next; if (lp_nextBlock != nullptr) { if (lp_newBlock + lp_newBlock->size >= lp_nextBlock) { lp_newBlock->size += lp_nextBlock->size; lp_newBlock->next = lp_nextBlock->next; } } mi_numAllocations--; mi_usedMem -= li_size; }<file_sep>/Source/Frontline Engine/Frontline Game Test/IResourceManager.h /*#pragma once #include <ZLIB\zlib.h> class IResourceManager { public: IResourceManager(); ~IResourceManager(); }; */<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/DefaultResource.cpp #include "DefaultResource.h" #include <new> DefaultResource::DefaultResource(const std::string& ps_resname) { ms_resourcename = ps_resname; std::transform(ms_resourcename.begin(), ms_resourcename.end(), ms_resourcename.begin(), (int(*)(int)) std::tolower); } std::string DefaultResource::getContents() { return *contents; } void DefaultResource::setContents(std::string ps_contents) { contents = FL_NEW std::string(ps_contents); } void DefaultResource::setContents(std::string* ps_contents) { contents = ps_contents; } int DefaultResource::VGetSize() { return contents->size(); } int DefaultResource::VGetType() { return RESOURCE_TEXT; } bool DefaultResourceLoader::VLoadResource(ResHandle& pp_retval, char *rawBuffer, const char* name, AllocationFunction alloc) { void* resloc = alloc(sizeof(DefaultResource)); DefaultResource* retval = FL_NEW(resloc) DefaultResource(name); void* strloc = alloc(sizeof(std::string)); std::string* strval = FL_NEW(strloc) std::string(rawBuffer); retval->setContents(strval); pp_retval = ResHandle(retval); return true; }<file_sep>/Source/Frontline/effectSysTestP2/Main.cpp #pragma once #include <GL/glew.h> #include "GL.h" #include "flFxConfig.h" #include "flFx.h" #include "flFxExt.h" #include "flFxGL.h" #include "flFxParser.h" #include "flFxParserGL.h" #include "LoadShaders.h" #include "texture.h" /* I'm keeping this file in because it contains a lot of work that should be moved over to the Frontline Game Test project, but it will not be run right now. In addition, we need to remove the SFML content, as we are moving over to our own window library and should write a texture library soon. -Kyle */ struct TestData : public PassDesc { int var; TestData(fxState flag,const char* name) : PassDesc(flag,name) {} virtual bool Validate() {std::cout<<"Validating..."<<std::endl;return true;} virtual bool Invalidate() {std::cout<<"Invalidating..."<<std::endl;return true;} }; GLuint createFBO() { // Create and bind the FBO GLuint fboId, depth, pos, norm; glGenFramebuffers(1, &fboId); glBindFramebuffer(GL_FRAMEBUFFER, fboId); // The depth buffer glGenRenderbuffers(1, &depth); glBindRenderbuffer(GL_RENDERBUFFER, depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 800, 800); // The position buffer glActiveTexture(GL_TEXTURE0); // Use texture unit 0 glGenTextures(1, &pos); glBindTexture(GL_TEXTURE_2D, pos); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, 800, 800, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // The normal buffer glActiveTexture(GL_TEXTURE1); glGenTextures(1, &norm); glBindTexture(GL_TEXTURE_2D, norm); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, 800, 800, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Attach the images to the framebuffer glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pos, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, norm, 0); GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, drawBuffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); return fboId; } void blitFramebuffer(GLuint fboId, int sizeX, int sizeY) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindFramebuffer(GL_READ_FRAMEBUFFER, fboId); glReadBuffer(GL_COLOR_ATTACHMENT0); glBlitFramebuffer(0, 0, sizeX, sizeY, 0, sizeY / 2, sizeX, sizeY, GL_COLOR_BUFFER_BIT, GL_LINEAR); glReadBuffer(GL_COLOR_ATTACHMENT1); glBlitFramebuffer(0, 0, sizeX, sizeY, 0, 0, sizeY, sizeY / 2, GL_COLOR_BUFFER_BIT, GL_LINEAR); } int main() { //tests sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!"); glewInit(); flFxCoreGL::Get()->Init(); pugi::xml_document doc; doc.load_file("effect.xml"); std::shared_ptr<Effect> effect = flFxParserGL::Get()->LoadEffect(doc); std::cout<<effect->GetName()<<std::endl; std::cout<<effect->GetTechnique("Technique0")->GetName()<<std::endl; std::shared_ptr<Technique> demoTech = effect->GetTechnique("Technique0"); std::shared_ptr<Pass> pass(new Pass("testPass")); std::shared_ptr<Pass> pass1(new Pass("testPass1")); std::shared_ptr<TestData> testData(new TestData(FX_DO_NOTHING,"testData")); std::shared_ptr<TestData> testData1(new TestData(FX_DO_NOTHING,"testData")); testData->var = 5; testData1->var = 19; pass->CreateData(testData); pass1->CreateDataOverride(testData1); pass->Validate(); std::cout<<"Before: "<<(std::static_pointer_cast<TestData>(pass->Find("testData")))->var<<std::endl; pass1->SetupOverrides(&pass,1); pass->Validate(); std::cout<<"After: "<<(std::static_pointer_cast<TestData>(pass->Find("testData")))->var<<std::endl; pass1->ReleaseOverrides(&pass,1); pass->Validate(); std::cout<<"Now: "<<(std::static_pointer_cast<TestData>(pass->Find("testData")))->var<<std::endl; pass->RemoveData("testData"); demoTech->Validate(); std::shared_ptr<GPUPipeline> pipeline(new GPUPipeline()); std::shared_ptr<Shader> shader(new Shader("testShader")); pass->CreateData(pipeline); pass->CreateData(shader); pass->Validate(); std::shared_ptr<Shader> s1 = std::static_pointer_cast<Shader>(pass->Find("testShader")); if(s1 == pipeline->GetShader("testShader")) { std::cout<<"true"<<std::endl; } GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; static const GLfloat g_uv_buffer_data[] = { -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_uv_buffer_data), g_uv_buffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); /*std::shared_ptr<Pass> demoPass(new Pass("demoPass")); std::shared_ptr<GLSLShader> glslVertShader(new GLSLShader("shader1",GL_VERTEX_SHADER)); std::shared_ptr<GLSLShader> glslFragShader(new GLSLShader("shader2",GL_FRAGMENT_SHADER)); glslVertShader->LoadShaderFromFile("VertShader.glsl"); //glslVertShader->Validate(); glslFragShader->LoadShaderFromFile("FragShader.glsl"); //glslFragShader->Validate(); std::shared_ptr<PipelineGL> glslPipeline(new PipelineGL()); //glslPipeline->SetShader(glslVertShader); //glslPipeline->SetShader(glslFragShader); //glslPipeline->Validate(); demoPass->CreateData(glslPipeline); demoPass->CreateData(glslVertShader); demoPass->CreateData(glslFragShader); //order of validation screwed up demoPass->Validate(); std::cout<<typeid(*demoPass.get()).name()<<std::endl; //maybe make ALL the flags typeid*/ //maybe make it so when using Pass::Find on flags, just put the class type u want to recieve glm::vec3 color(1.0f,0.0f,0.0f); std::shared_ptr<ShaderParameterGL> uniform(new ShaderParameterGL("uniform_color",ShaderParameterGL::Type::T3F,glm::value_ptr(color))); //count maybe cud be dyn. generated /*std::shared_ptr<StateGroupGL> states(new StateGroupGL()); std::shared_ptr<State1<bool>> blend(new State1<bool>(FX_BLEND,true)); std::shared_ptr<State2<GLenum,GLenum>> blendFunc(new State2<GLenum,GLenum>(FX_BLEND_FUNC,GL_ONE,GL_ONE)); states->AddState(blend); states->AddState(blendFunc);*/ demoTech->GetPass(0)->CreateData(uniform); //demoTech->GetPass(0)->CreateData(states); State1<bool> fx_blend(FX_BLEND,true); State2<GLenum,GLenum>fx_blendfunc(FX_BLEND_FUNC,GL_ONE,GL_ONE); std::cout << "ATTENTION: STARTING REPLACEMENT FUNCTION TESTING!" << std::endl; std::shared_ptr<Pass> demoPass2(new Pass("demoPass2")); demoPass2->Validate(); std::shared_ptr<PassDesc> demoPassDesc1(new PassDesc(FX_DO_NOTHING, "demo1")); demoPass2->CreateData(demoPassDesc1); std::shared_ptr<PassDesc> demoPassRandom(new PassDesc(FX_CLEAR_DESC_FLAG, "random")); demoPass2->CreateData(demoPassRandom); std::cout << "Before: " << demoPass2->Find(FX_DO_NOTHING)->GetName() << std::endl; std::shared_ptr<PassDesc> demoPassDesc2(new PassDesc(FX_DO_NOTHING, "demo2")); demoPass2->Replace("demo1", demoPassDesc2); std::cout << "After: " << demoPass2->Find(FX_DO_NOTHING)->GetName() << std::endl; //GLuint uvBuffer; //glGenBuffers(1, &uvBuffer); GLuint textureId = loadTexture("texture.bmp"); //std::shared_ptr<ResourceGL> resource(new ResourceGL("res1", FX_RESOURCE_2D)); //resource->SetTexture(textureId, 0); //demoTech->GetPass(0)->CreateData(resource); std::cout << "***********RESOURCE TESTING************" << std::endl; std::shared_ptr<ResourceGL> resource = std::static_pointer_cast<ResourceGL>(demoTech->GetPass(0)->Find("resource")); if (resource) { std::cout << "resource exists: " << resource->GetName() << std::endl; std::cout << "is valid before: " << resource->IsValid() << std::endl; resource->SetTexture(textureId); std::cout << "is valid after: " << resource->IsValid() << std::endl; } /*std::shared_ptr<SamplerStateGL> samplerState(new SamplerStateGL("sstate0")); samplerState->Validate(); std::shared_ptr<State2<GLenum, GLenum>> minFilter(new State2<GLenum,GLenum>(FX_TEXTURE_MIN_FILTER, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); std::shared_ptr<State2<GLenum, GLenum>> magFilter(new State2<GLenum, GLenum>(FX_TEXTURE_MAG_FILTER, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); std::shared_ptr<State2<GLenum, GLenum>> texWrapS(new State2<GLenum, GLenum>(FX_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_S, GL_REPEAT)); std::shared_ptr<State2<GLenum, GLenum>> texWrapT(new State2<GLenum, GLenum>(FX_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_T, GL_REPEAT)); samplerState->AddState(minFilter); samplerState->AddState(magFilter); samplerState->AddState(texWrapS); samplerState->AddState(texWrapT); resource->SetSamplerState(samplerState);*/ //StateInterpreter::Get()->RegisterState(FX_LINEAR, GL_LINEAR, "FX_LINEAR"); //StateInterpreter::Get()->RegisterState(FX_RESOURCE_2D, GL_TEXTURE_2D, "FX_RESOURCE_2D"); GLenum texture2D = StateInterpreter::Get()->Convert<GLenum>(FX_RESOURCE_2D); fxState fxTexture2D = StateInterpreter::Get()->Convert(GL_TEXTURE_2D); if ((texture2D == GL_TEXTURE_2D) && (fxTexture2D == FX_RESOURCE_2D)) { std::cout << "it is a GL_TEXTURE_2D" << std::endl; std::cout << "its a: " << StateInterpreter::Get()->ToString(FX_RESOURCE_2D) << std::endl; } std::cout << "GLenum: " << texture2D << "," << GL_TEXTURE_2D << std::endl; std::cout << "fxState: " << fxTexture2D << "," << FX_RESOURCE_2D << std::endl; State2<fxState, fxState> state(FX_BLEND_FUNC, FX_ONE, FX_ONE); State3<float, float, float> blendColor(FX_BLEND_COLOR, 1.0f, 0.0f, 0.0f); //glBlendColor(blendColor.m_v1, blendColor.m_v2, blendColor.m_v3, 1.0f); //glBlendFunc(spm.Convert<GLenum>(state.m_v1), spm.Convert<GLenum>(state.m_v2)); /*std::shared_ptr<FrameBufferObjectGL> framebuffer(new FrameBufferObjectGL("fbo0")); demoTech->GetPass(0)->CreateData(framebuffer); std::shared_ptr<ResourceGL> posTex(new ResourceGL("posTex", FX_RESOURCE_RENDERTEX)); posTex->SetFormat(FX_RGB32F); posTex->SetDimensions(800, 800); posTex->SetFBOAttachment(0); posTex->Validate(); //demoTech->GetPass(0)->CreateData(posTex); std::shared_ptr<ResourceGL> diffTex(new ResourceGL("diffTex", FX_RESOURCE_RENDERTEX)); diffTex->SetFormat(FX_RGB32F); diffTex->SetDimensions(800, 800); diffTex->SetFBOAttachment(1); diffTex->Validate(); //demoTech->GetPass(0)->CreateData(diffTex); std::shared_ptr<ResourceGL> depthTex(new ResourceGL("depthTex", FX_RESOURCE_DEPTHTEX)); depthTex->SetFormat(FX_DEPTH_COMPONENT); depthTex->SetDimensions(800, 800); depthTex->Validate(); //demoTech->GetPass(0)->CreateData(depthTex); framebuffer->AddTextureResource(posTex); framebuffer->AddTextureResource(diffTex); framebuffer->SetDSTTexture(depthTex);*/ //GLuint fbo = createFBO(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Pass::Begin(); //demoPass->Execute(); //framebuffer->SetCurrent(); //glBindFramebuffer(GL_FRAMEBUFFER, fbo); //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); demoTech->GetPass(0)->Execute(); //glEnableVertexAttribArray(0); //glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBindVertexArray(VertexArrayID); /*glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset );*/ glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle //glDisableVertexAttribArray(0); //std::shared_ptr<PipelineGL> pipeline = FX_CAST(PipelineGL)(demoTech->GetPass(0)->Find(FX_PIPELINE_DESC_FLAG)); //flFxCoreGL::Get()->DrawFullscreenQuad(); //blitFramebuffer(std::static_pointer_cast<FrameBufferObjectGL>(demoTech->GetPass(0)->Find(FX_FBO_TARGET_DESC_FLAG))->GetFBOId()/*framebuffer->GetFBOId() */, 800, 800); //blitFramebuffer(framebuffer->GetFBOId(), 800, 800); demoTech->GetPass(0)->Cleanup(); demoTech->GetPass(1)->Execute(); demoTech->GetPass(1)->Cleanup(); /*bool enabled = glIsEnabled(GL_BLEND); std::cout << "Blend Status: " << enabled << std::endl;*/ //pipeline->Unbind(); window.display(); } return 0; }<file_sep>/Source/Frontline Engine/Frontline Engine/FLMemory.h #pragma once #include "System\Pool.h" typedef void functype(void*); template<typename T> class FLStrongPtr { int* mp_refCount; T* mp_object; Pool* mp_pool; public: int GetRefCount() { return mp_refCount; } FLStrongPtr(T* pp_rawPtr, Pool* pool) { mp_refCount = new int(); *mp_refCount = 1; mp_pool = pool; } FLStrongPtr(FLStrongPtr<T>& copy) { mp_refCount = copy->GetRefCount(); mp_pool = copy->mp_pool; } ~FLStrongPtr(); };<file_sep>/Source/Frontline Engine/Frontline Engine/System/Log.h #pragma once #include "..\FrontlineCommon.h" #include "../IGame.h" #include "Console.h" #include <vector> class Log { std::vector<std::pair<int, std::string>> m_log; Console* c; public: Log(); ~Log(); void logError(std::string p_cat, std::string p_error); void logWarning(std::string p_cat, std::string p_warning); void logOther(std::string p_cat, std::string p_message); std::vector<std::pair<int, std::string>> dumpLog(); bool dumpToFile(std::string p_fileName); bool dumpToFile(); };<file_sep>/Source/Frontline Engine/Frontline Engine/Event/AddCollisionPairEventData.cpp #include "AddCollisionPairEventData.h" EventType CollisionPairEventData::sk_eventType = 0xc18e48cd; CollisionPairEventData::CollisionPairEventData() { } CollisionPairEventData::~CollisionPairEventData() { } <file_sep>/Source/Frontline Engine/Frontline Engine/Physics/ActorMotionState.h #pragma once #include "..\FrontlineCommon.h" #include <PHYSICS\btBulletDynamicsCommon.h> #include <GLM\ext.hpp> class ActorMotionState : public btMotionState { public: glm::mat4x4 mm_worldToPositionTransform; ActorMotionState(const glm::mat4x4& pm_initialTransform) : mm_worldToPositionTransform(pm_initialTransform) { }; virtual void getWorldTransform(btTransform& pt_worldTrans) const override; virtual void setWorldTransform(const btTransform& pt_worldTrans) override; ActorMotionState(); ~ActorMotionState(); };<file_sep>/Source/Frontline/effectSysTestP2/LoadShaders.h #pragma once #include <GL/glew.h> #include <gl/GL.h> #include <gl/GLU.h> #include <string> #include <vector> #include <iostream> #include <fstream> #include <glm/glm.hpp> GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path);<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/TextResource.cpp #include "TextResource.h" TextResource::~TextResource() { } std::string TextResource::GetContents() { return ms_contents; } void TextResource::SetContents(std::string ps_contents) { ms_contents = ps_contents; }<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/ZipResourceFile.cpp #include "ZipResourceFile.h" bool ZipResourceFile::VOpen(const wchar_t* ps_filename) { mp_ZipFile = std::unique_ptr<ZipFile>(FL_NEW ZipFile()); if (mp_ZipFile) { return mp_ZipFile->Init(ps_filename); } return false; } bool ZipResourceFile::VClose() { mp_ZipFile->End(); return true; } int ZipResourceFile::VGetResource(char** buffer, const char* ps_resname) { int size = 0; optional<int> resourceNum = mp_ZipFile->Find(ps_resname); if (resourceNum.valid()) { size = mp_ZipFile->GetFileLen(*resourceNum); mp_ZipFile->ReadFile(*resourceNum, *buffer); } return size; } int ZipResourceFile::VGetRawResourceSize(const char* ps_resname) { int resourceNum = mp_ZipFile->Find(ps_resname); if (resourceNum == -1) return -1; return mp_ZipFile->GetFileLen(resourceNum); } int ZipResourceFile::VGetNumResources() const { return (mp_ZipFile == NULL) ? 0 : mp_ZipFile->GetNumFiles(); }<file_sep>/Source/Frontline Engine/Frontline Engine/Math/Math.h #pragma once #include "..\FrontlineCommon.h" #include <PHYSICS/btBulletDynamicsCommon.h> #include <GLM/ext.hpp> #define max(a, b) a > b ? a : b const glm::mat4x4 btTransformToGLM(const btTransform& pt_transform); const btTransform glmMatToBT(const glm::mat4x4& pm_matrix); const glm::vec3 getTranslationFromMat(const glm::mat4x4 pm_matrix); const glm::vec3 getScaleFromMat(const glm::mat4x4 pm_matrix); inline float fastInverseSqrRoot(float x); inline void normalize(glm::vec3& vec);<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/ZipFile.cpp #include "ZipFile.h" #include <cctype> #include <tchar.h> #include "..\FrontlineCommon.h" typedef unsigned long dword; typedef unsigned short word; #pragma pack(1) struct ZipFile::TZipLocalHeader { enum { SIGNATURE = 0x04034b50 }; dword sig; word version; word flag; word compression; word modTime; word modDate; dword crc32; dword cSize; dword ucSize; word fnameLen; word xtraLen; }; struct ZipFile::TZipDirHeader { enum { SIGNATURE = 0x06054b50 }; dword sig; word nDisk; word nStartDisk; word nDirEntries; word totalDirEntries; dword dirSize; dword dirOffset; word cmntLen; }; struct ZipFile::TZipDirFileHeader { enum { SIGNATURE = 0x02014b50 }; dword sig; word verMade; word verNeeded; word flag; word compression; // COMP_xxxx word modTime; word modDate; dword crc32; dword cSize; // Compressed size dword ucSize; // Uncompressed size word fnameLen; // Filename string follows header. word xtraLen; // Extra field follows filename. word cmntLen; // Comment field follows extra field. word diskStart; word intAttr; dword extAttr; dword hdrOffset; char *GetName() const { return (char *) (this + 1); } char *GetExtra() const { return GetName() + fnameLen; } char *GetComment() const { return GetExtra() + xtraLen; } }; #pragma pack() bool ZipFile::Init(const std::wstring& ps_filename) { End(); _wfopen_s(&mp_file, ps_filename.c_str(), _T(L"rb")); if (!mp_file) return false; TZipDirHeader l_dirHeader; fseek(mp_file, -(int)sizeof(l_dirHeader), SEEK_END); long ll_dhOffset = ftell(mp_file); memset(&l_dirHeader, 0, sizeof(l_dirHeader)); fread(&l_dirHeader, sizeof(l_dirHeader), 1, mp_file); if (l_dirHeader.sig != TZipDirHeader::SIGNATURE) return false; fseek(mp_file, ll_dhOffset - l_dirHeader.dirSize, SEEK_SET); ms_dirData = FL_NEW char[l_dirHeader.dirSize + l_dirHeader.nDirEntries * sizeof(*m_papDir)]; if (!ms_dirData) return false; memset(ms_dirData, 0, l_dirHeader.dirSize + l_dirHeader.nDirEntries*sizeof(*m_papDir)); fread(ms_dirData, l_dirHeader.dirSize, 1, mp_file); // Now process each entry. char *pfh = ms_dirData; m_papDir = (const TZipDirFileHeader **) (ms_dirData + l_dirHeader.dirSize); bool success = true; for (int i = 0; i < l_dirHeader.nDirEntries && success; i++) { TZipDirFileHeader &fh = *(TZipDirFileHeader*) pfh; // Store the address of nth file for quicker access. m_papDir[i] = &fh; // Check the directory entry integrity. if (fh.sig != TZipDirFileHeader::SIGNATURE) success = false; else { pfh += sizeof(fh); // Convert UNIX slashes to DOS backlashes. for (int j = 0; j < fh.fnameLen; j++) if (pfh[j] == '/') pfh[j] = '\\'; char fileName[_MAX_PATH]; memcpy(fileName, pfh, fh.fnameLen); fileName[fh.fnameLen] = 0; _strlwr_s(fileName, _MAX_PATH); std::string spath = fileName; mmap_zipContents[spath] = i; // Skip name, extra and comment fields. pfh += fh.fnameLen + fh.xtraLen + fh.cmntLen; } } if (!success) { SAFE_DELETE_ARRAY(ms_dirData); } else { m_nEntries = l_dirHeader.nDirEntries; } return success; } int ZipFile::Find(const std::string ps_path) { std::string lowerCase = ps_path; std::transform(lowerCase.begin(), lowerCase.end(), lowerCase.begin(), (int(*)(int)) std::tolower); ZipContentsMap::const_iterator i = mmap_zipContents.find(lowerCase); if (i == mmap_zipContents.end()) return -1; return i->second; } // -------------------------------------------------------------------------- // Function: End // Purpose: Finish the object // Parameters: // -------------------------------------------------------------------------- void ZipFile::End() { mmap_zipContents.clear(); SAFE_DELETE_ARRAY(ms_dirData); m_nEntries = 0; } // -------------------------------------------------------------------------- // Function: GetFilename // Purpose: Return the name of a file // Parameters: The file index and the buffer where to store the filename // -------------------------------------------------------------------------- std::string ZipFile::GetFilename(int i) const { std::string fileName = ""; if (i >= 0 && i < m_nEntries) { char pszDest[_MAX_PATH]; memcpy(pszDest, m_papDir[i]->GetName(), m_papDir[i]->fnameLen); pszDest[m_papDir[i]->fnameLen] = '\0'; fileName = pszDest; } return fileName; } // -------------------------------------------------------------------------- // Function: GetFileLen // Purpose: Return the length of a file so a buffer can be allocated // Parameters: The file index. // -------------------------------------------------------------------------- int ZipFile::GetFileLen(int i) const { if (i < 0 || i >= m_nEntries) return -1; else return m_papDir[i]->ucSize; } // -------------------------------------------------------------------------- // Function: ReadFile // Purpose: Uncompress a complete file // Parameters: The file index and the pre-allocated buffer // -------------------------------------------------------------------------- bool ZipFile::ReadFile(int i, void *pBuf) { if (pBuf == NULL || i < 0 || i >= m_nEntries) return false; // Quick'n dirty read, the whole file at once. // Ungood if the ZIP has huge files inside // Go to the actual file and read the local header. fseek(mp_file, m_papDir[i]->hdrOffset, SEEK_SET); TZipLocalHeader h; memset(&h, 0, sizeof(h)); fread(&h, sizeof(h), 1, mp_file); if (h.sig != TZipLocalHeader::SIGNATURE) return false; // Skip extra fields fseek(mp_file, h.fnameLen + h.xtraLen, SEEK_CUR); if (h.compression == Z_NO_COMPRESSION) { // Simply read in raw stored data. fread(pBuf, h.cSize, 1, mp_file); return true; } else if (h.compression != Z_DEFLATED) return false; // Alloc compressed data buffer and read the whole stream char *pcData = FL_NEW char[h.cSize]; if (!pcData) return false; memset(pcData, 0, h.cSize); fread(pcData, h.cSize, 1, mp_file); bool ret = true; // Setup the inflate stream. z_stream stream; int err; stream.next_in = (Bytef*) pcData; stream.avail_in = (uInt) h.cSize; stream.next_out = (Bytef*) pBuf; stream.avail_out = h.ucSize; stream.zalloc = (alloc_func) 0; stream.zfree = (free_func) 0; // Perform inflation. wbits < 0 indicates no zlib header inside the data. err = inflateInit2(&stream, -MAX_WBITS); if (err == Z_OK) { err = inflate(&stream, Z_FINISH); inflateEnd(&stream); if (err == Z_STREAM_END) err = Z_OK; inflateEnd(&stream); } if (err != Z_OK) ret = false; delete[] pcData; return ret; } // -------------------------------------------------------------------------- // Function: ReadLargeFile // Purpose: Uncompress a complete file with callbacks. // Parameters: The file index and the pre-allocated buffer // -------------------------------------------------------------------------- bool ZipFile::ReadLargeFile(int i, void *pBuf, void(*progressCallback)(int, bool &)) { if (pBuf == NULL || i < 0 || i >= m_nEntries) return false; // Quick'n dirty read, the whole file at once. // Ungood if the ZIP has huge files inside // Go to the actual file and read the local header. fseek(mp_file, m_papDir[i]->hdrOffset, SEEK_SET); TZipLocalHeader h; memset(&h, 0, sizeof(h)); fread(&h, sizeof(h), 1, mp_file); if (h.sig != TZipLocalHeader::SIGNATURE) return false; // Skip extra fields fseek(mp_file, h.fnameLen + h.xtraLen, SEEK_CUR); if (h.compression == Z_NO_COMPRESSION) { // Simply read in raw stored data. fread(pBuf, h.cSize, 1, mp_file); return true; } else if (h.compression != Z_DEFLATED) return false; // Alloc compressed data buffer and read the whole stream char *pcData = FL_NEW char[h.cSize]; if (!pcData) return false; memset(pcData, 0, h.cSize); fread(pcData, h.cSize, 1, mp_file); bool ret = true; // Setup the inflate stream. z_stream stream; int err; stream.next_in = (Bytef*) pcData; stream.avail_in = (uInt) h.cSize; stream.next_out = (Bytef*) pBuf; stream.avail_out = (128 * 1024); // read 128k at a time h.ucSize; stream.zalloc = (alloc_func) 0; stream.zfree = (free_func) 0; // Perform inflation. wbits < 0 indicates no zlib header inside the data. err = inflateInit2(&stream, -MAX_WBITS); if (err == Z_OK) { uInt count = 0; bool cancel = false; while (stream.total_in < (uInt) h.cSize && !cancel) { err = inflate(&stream, Z_SYNC_FLUSH); if (err == Z_STREAM_END) { err = Z_OK; break; } else if (err != Z_OK) { FL_ASSERT(0 && "Something happened."); break; } stream.avail_out = (128 * 1024); stream.next_out += stream.total_out; progressCallback(count * 100 / h.cSize, cancel); } inflateEnd(&stream); } if (err != Z_OK) ret = false; delete[] pcData; return ret; }<file_sep>/Source/Frontline Engine/Frontline Engine/Physics/BulletDebugDrawer.cpp #include "BulletDebugDrawer.h" #include "BulletDebugDrawer.h" #include <stdio.h> //printf debugging BulletDebugDrawer::BulletDebugDrawer() { setDebugMode(btIDebugDraw::DBG_MAX_DEBUG_DRAW_MODE); } BulletDebugDrawer::~BulletDebugDrawer() { } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::drawLine // Purpose: Draw a physics debug line // Parameters: Line origin, line end, origin color, end color // -------------------------------------------------------------------------- void BulletDebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor) { glBegin(GL_LINES); glColor3f(fromColor.getX(), fromColor.getY(), fromColor.getZ()); glVertex3d(from.getX(), from.getY(), from.getZ()); glColor3f(toColor.getX(), toColor.getY(), toColor.getZ()); glVertex3d(to.getX(), to.getY(), to.getZ()); glEnd(); } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::drawLine // Purpose: Draw a physics debug line // Parameters: Line origin, line end, color // -------------------------------------------------------------------------- void BulletDebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) { drawLine(from, to, color, color); } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::drawSphere // Purpose: Draw a physics debug sphere // Parameters: Position, radius, color // -------------------------------------------------------------------------- void BulletDebugDrawer::drawSphere(const btVector3& p, btScalar radius, const btVector3& color) { glColor4f(color.getX(), color.getY(), color.getZ(), btScalar(1.0f)); glPushMatrix(); glTranslatef(p.getX(), p.getY(), p.getZ()); int lats = 5; int longs = 5; int i, j; for (i = 0; i <= lats; i++) { btScalar lat0 = SIMD_PI * (-btScalar(0.5) + (btScalar) (i - 1) / lats); btScalar z0 = radius*sin(lat0); btScalar zr0 = radius*cos(lat0); btScalar lat1 = SIMD_PI * (-btScalar(0.5) + (btScalar) i / lats); btScalar z1 = radius*sin(lat1); btScalar zr1 = radius*cos(lat1); glBegin(GL_QUAD_STRIP); for (j = 0; j <= longs; j++) { btScalar lng = 2 * SIMD_PI * (btScalar) (j - 1) / longs; btScalar x = cos(lng); btScalar y = sin(lng); glNormal3f(x * zr0, y * zr0, z0); glVertex3f(x * zr0, y * zr0, z0); glNormal3f(x * zr1, y * zr1, z1); glVertex3f(x * zr1, y * zr1, z1); } glEnd(); } glPopMatrix(); } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::drawTriangle // Purpose: Draw a physics debug triangle // Parameters: First point, second point, third point, color, alpha // -------------------------------------------------------------------------- void BulletDebugDrawer::drawTriangle(const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& color, btScalar alpha) { // if (m_debugMode > 0) { const btVector3 n = btCross(b - a, c - a).normalized(); glBegin(GL_TRIANGLES); glColor4f(color.getX(), color.getY(), color.getZ(), alpha); glNormal3d(n.getX(), n.getY(), n.getZ()); glVertex3d(a.getX(), a.getY(), a.getZ()); glVertex3d(b.getX(), b.getY(), b.getZ()); glVertex3d(c.getX(), c.getY(), c.getZ()); glEnd(); } } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::setDebugMode // Purpose: Set the debug mode // Parameters: The new debug mode (a binary OR of the enum btIDebugDraw::DebugDrawModes) // -------------------------------------------------------------------------- void BulletDebugDrawer::setDebugMode(int debugMode) { m_debugMode = debugMode; } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::getDebugMode // Purpose: Get the debug mode (a binary OR of the enum btIDebugDraw::DebugDrawModes) // Parameters: None // -------------------------------------------------------------------------- int BulletDebugDrawer::getDebugMode() const { return m_debugMode; } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::draw3dText // Purpose: Draw debug text in the 3d world // Parameters: Location, text to render // -------------------------------------------------------------------------- void BulletDebugDrawer::draw3dText(const btVector3& location, const char* textString) { glRasterPos3f(location.x(), location.y(), location.z()); //BMF_DrawString(BMF_GetFont(BMF_kHelvetica10),textString); } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::reportErrorWarning // Purpose: Report an error // Parameters: Error text // -------------------------------------------------------------------------- void BulletDebugDrawer::reportErrorWarning(const char* warningString) { WARNLOG("Debug Draw", warningString); } // -------------------------------------------------------------------------- // Function: BulletDebugDrawer::drawContactPoint // Purpose: Draw a contact point between two objects // Parameters: Point, direction of line, line length, time to keep drawing line, color // -------------------------------------------------------------------------- void BulletDebugDrawer::drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) { btVector3 to = pointOnB + normalOnB * 1;//distance; const btVector3&from = pointOnB; glColor4f(color.getX(), color.getY(), color.getZ(), 1.f); glBegin(GL_LINES); { glVertex3d(from.getX(), from.getY(), from.getZ()); glVertex3d(to.getX(), to.getY(), to.getZ()); } glEnd(); }<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/IResourceFile.h #pragma once #include "..\FrontlineCommon.h" #include "Resource.h" class IResourceFile { public: virtual bool VOpen() = 0; virtual int VGetRawResourceSize(const Resource &r) = 0; virtual int VGetRawResource(const Resource &r, char *buffer) = 0; virtual int VGetNumResources() const = 0; virtual std::string VGetResourceName(int num) const = 0; virtual ~IResourceFile() { } };<file_sep>/Source/Frontline Engine/Frontline Engine/Process/ProcessManager.cpp #include "ProcessManager.h" //pushes a process to be run in the processList void ProcessManager::AttachProcess(StrongProcessPtr pProcess) { m_processList.push_front(pProcess); } //deletes all processes from processList; void ProcessManager::ClearAllProcesses() { m_processList.clear(); } void ProcessManager::AbortAllProcesses(bool immediate) { auto it = m_processList.begin(); while (it != m_processList.end()) { ProcessList::iterator tempIt = it; ++it; StrongProcessPtr pProcess = *tempIt; if (pProcess->IsAlive()) { pProcess->SetState(PROCESS_ABORTED); if (immediate) { pProcess->VOnExit(PROCESS_ABORTED); m_processList.erase(tempIt); auto findIt = pProcess->m_childProcessMap.find(PROCESS_ABORTED); if(findIt != pProcess->m_childProcessMap.end()) { for(auto iter = findIt -> second.begin(); iter != findIt -> second.end(); iter++) { AttachProcess(*iter); } } } } } } //runs through all processes and takes appropriate procedures according to //the state unsigned int ProcessManager::UpdateProcesses(unsigned long deltaMs) { unsigned short int successCount = 0; unsigned short int failCount = 0; ProcessList::iterator it = m_processList.begin(); while (it != m_processList.end()) { // grab the next process StrongProcessPtr pCurrProcess = (*it); // save the iterator and increment the old one in case we need to remove this process from the list ProcessList::iterator thisIt = it; ++it; // process is uninitialized, so initialize it if (pCurrProcess->currentProcessState == PROCESS_UNINITIALIZED) pCurrProcess->VOnInit(); // give the process an update tick if it's running if (pCurrProcess->currentProcessState == PROCESS_RUNNING) pCurrProcess->VOnUpdate(deltaMs); // check to see if the process is dead if (pCurrProcess->IsDead()) { // run the appropriate exit function pCurrProcess->VOnExit(pCurrProcess->currentProcessState); auto findIt = pCurrProcess->m_childProcessMap.find(pCurrProcess->currentProcessState); if(findIt != pCurrProcess->m_childProcessMap.end()) { for(auto iter = findIt -> second.begin(); iter != findIt -> second.end(); iter++) { IGame::gp_game->mp_log->logOther("PROCESS", "Parent Process Finished with Success: Now Attaching Child Process!"); AttachProcess(*iter); } } m_processList.erase(thisIt); } } return ((successCount << 16) | failCount); }<file_sep>/Source/Frontline Engine/Frontline Engine/IGame.cpp #include "IGame.h" #include "FrontlineCommon.h" IGame* IGame::gp_game = FL_NEW IGame(); int FLMain() { return 0; } void IGame::start() { }<file_sep>/Plan/SceneGraphIdeas.h enum TransformType { LOCAL, GLOBAL }; class NodeProperties { friend class Node; protected: ActorId m_ActorId; glm::mat4 m_GlobalTransform; glm::mat4 m_GlobalAltTransform; glm::mat4 m_LocalTransform; glm::mat4 m_LocalAltTransform; float m_Radius; RenderPass m_RenderPass; Material m_Material; AlphaType m_AlphaType; void SetAlpha(const float alpha) { m_AlphaType = AlphaMaterial; m_Material.SetAlpha(alpha); } public: NodeProperties(void); ~NodeProperties(void) {} const ActorId &ActorId() const { return m_ActorId; } glm::mat4 const &GlobalTransform() const { return m_GlobalTransform; } glm::mat4 const &GlobalAltTransform() const { return m_GlobalAltTransform; } glm::mat4 const &LocalTransform() const { return m_LcoalTransform; } glm::mat4 const &LocallAltTransform() const { return m_LocalAltTransform; } void Transform(glm::mat4* toWorld, glm::mat4* fromWorld) const; bool HasAlpha() const { return m_Material.HasAlpha(); } float Alpha() const { return m_Material.GetAlpha(); } AlphaType AlphaType() const { return m_AlphaType; } RenderPass RenderPass() const { return m_RenderPass; } float Radius() const { return m_Radius; } Material GetMaterial() const { return m_Material; } }; class Node : public std::enable_shared_from_this { protected: enum TraversalType { NODE_INITIALIZE, NODE_UPDATE, NODE_CULLING, NODE_RENDER, NODE_DESTROY }; bool m_NeedsInitialize; //set to true bool m_NeedsUpdate; //set to false bool m_NeedsCulling; bool m_NeedsRender; //set to true bool m_NeedsDestroy; //set to false bool m_InheritTransform; bool m_InheritScale; bool m_Active; bool m_Visible; //set to true default std::list<std::shared_ptr<Node>> m_Parents; std::list<std::shared_ptr<NodeVisitor>> m_QueuedVisitors; //remove from queue after visitor carried out duty std::map<TraversalType,std::shared_ptr<NodeCallback>> m_Callbacks; NodeProperties m_Props; const char* m_Name; public: Node(ActorId actorId, RenderPass renderPass, glm::mat4* transform, glm::mat4* altTransform = NULL, const char* name = NULL); virtual ~Node(); void SetName(const char* name); const char* GetName(); virtual const NodeProperties* const GetProperties() const { return &m_Props; } virtual void Accept(std::shared_ptr<NodeVisitor> visitor); virtual void Cancel(std::shared_ptr<NodeVisitor> visitor); //only for queued visits virtual void Ascend(std::shared_ptr<NodeVisitor> visitor); virtual void Traverse(std::shared_ptr<NodeVisitor> visitor); virtual void AddParent(std::shared_ptr<Group> parent); virtual std::shared_ptr<Group> GetParent(int index); virtual const std::shared_ptr<Group> GetParent(int index) const; virtual std::list<std::shared_ptr<Group>> GetParents(); virtual const std::list<std::shared_ptr<Group>> GetParents() const; virtual int GetNumParents(); virtual void SetCallback(TraversalType type, std::shared_ptr<NodeCallback> callback); virtual void AddCallback(TraversalType type, std::shared_ptr<NodeCallback> callback); virtual void RemoveCallback(std::shared_ptr<NodeCallback> callback); virtual std::shared_ptr<NodeCallback> GetCallback(TraversalType type); virtual const std::shared_ptr<NodeCallback> GetCallback(TraversalType type) const; virtual void SetVisible(bool visible); //this is set by the culling callback virtual bool IsVisible(); virtual bool SetNodeActive(bool active); virtual bool IsActive(); virtual void FlagActive(TraversalType type); virtual void FlagInactive(TraversalType type); void SetRadius(int radius); const int GetRadius() const; //if has children, update the children too void SetTransform(TransformType relativeTo, glm::mat4* transform, glm::mat4* altTransform = NULL); void MultiplyTransform(TransformType relativeTo, glm::mat4* transform, glm::mat4* altTransform = NULL); bool InheritTransform(bool inherit); const bool InheritsTranform(); void SetMaterial(Material& mat); Material* GetMaterial(); bool HasAlpha() const { return m_Material.HasAlpha(); } float Alpha() const { return m_Material.GetAlpha(); } AlphaType AlphaType() const { return m_AlphaType; } void SetPosition(glm::vec3& position, TransformType relativeTo); const glm::vec3 GetPosition(TransformType relativeTo) const; glm::vec3 ToWorldPosition(glm::vec3& localPosition); glm::vec3 ToLocalPosition(glm::vec3& worldPosition); virtual void Scale(glm::vec3& factor, TransformType relativeTo); virtual void Scale(float fx, float fy, float fz, TransformType relativeTo); virtual void Translate(glm::vec3& dest, TransformType relativeTo); virtual void Translate(float dx, float dy, float dz, TransformType relativeTo); virtual void Rotate(glm::vec3& axis, float angle, TransformType relativeTo); virtual void ResetTransform(); }; class NodeCallback : public std::enable_shared_from_this { friend class Node; friend class Group; protected: std::shared_ptr<NodeCallback> m_LinkedCallback; public: NodeCallback(); virtual ~NodeCallback(); void SetLinkedCallback(std::shared_ptr<Node> callback); void AddLinkedCallback(std::shared_ptr<NodeCallback> callback); std::shared_ptr<NodeCallback> GetLinkedCallback(); const std::shared_ptr<NodeCallback> GetLinkedCallback() const; void RemoveLinkedCallback(std::shared_ptr<NodeCallback> callback); virtual bool operator()(std::shared_ptr<Node> node, std::shared_ptr<NodeVisitor> visitor); //the ones for Render virtual bool NodePreRendered(std::shared_ptr<Node> node); //set defaults for this virtual bool NodePostRendered(std::shared_ptr<Node> node); }; class Group : public Node { public: Group(/*...*/); virtual ~Group(); typedef unsigned int Bitfield; bool Traverse(TraversalType type); //traverse and operate only on the nodes that requested bool Traverse(Bitfield type, bool separate); //for multiple traversal operations ex. if((type & NODE_UPDATE) == 0)... bool Ascend(TraversalType type, bool separate); bool Ascend(Bitfield type); void AddChild(std::shared_ptr<Node> node); void InsertChild(std::shared_ptr<Node> node, int index); //gets and removes void CreateChild(/*pass constructor here*/); }; class Switch : public Group { protected: std::map<unsigned int, std::vector<int>> m_LevelMap; //index child positions to levels public: Switch(); ~Switch(); bool AddChild(std::shared_ptr<Node> node, int level); void InsertChild(std::shared_ptr<Node> node, int index, int level); bool RemoveChild(std::shared_ptr<Node> node, int level); std::shared_ptr<Node> GetChild(int index, int level); const std::shared_ptr<Node> GetChild(int index, int level) const; int GetChildLevel(std::shared_ptr<Node> node, int index); void EnableAllLevels(); void DisableAllLevels(); void EnableLevel(int level); void DisableLevel(int level); void EnableChild(int index, int level); void EnableSingleChild(int index, int level); void DisableChild(int index, int level); }; class NodeVisitor : public std::enable_shared_from_this { public: enum VisitingMode { VISIT_IMMEDIATLY, VISIT_ON_INITIALIZE, VISIT_ON_UPDATE, VISIT_ON_RENDER, VISIT_ON_DESTROY }; void SetVisitingMode(VisitingMode vm); VisitingMode GetVisitingMode(); virtual void Visit(std::shared_ptr<Node> node); virtual void Visit(std::shared_ptr<Group> node); virtual void Visit(std::shared_ptr<Switch> node); }; class NodeObserver : public std::enable_shared_from_this { public: virtual void Notify(std::shared_ptr<Node> node); virtual void Notify(std::shared_ptr<Group> node); virtual void Notify(std::shared_ptr<Switch> node); };<file_sep>/Source/Frontline Engine/Frontline Engine/FrontlineCommon.h #pragma once #include "System\Pool.h" #define DEFAULT_POOL IGame::gp_game->mp_defaultPool #include "IGame.h" #include <string> #include <map> #include <algorithm> #include "Math\Math.h" #include "Templates.h" #include "System\Log.h" #include "System\Time.h" #include "Actor\Actor.h" #include "Event\EventManager.h" #include <GLM/ext.hpp> #include "flstringutils.h" #include <intrin.h> #ifdef _DEBUG #define ERRLOG(Category, Message) IGame::gp_game->mp_log->logError(Category, Message); __debugbreak() #else #define ERRLOG IGame::gp_game->mp_log->logError #endif #define WARNLOG IGame::gp_game->mp_log->logWarning #define MSGLOG IGame::gp_game->mp_log->logOther #define FL_ASSERT assert #define FL_NEW new #define FL_DELETE delete #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if (p) { delete (p); (p)=NULL; } } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p)=NULL; } } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } } #endif<file_sep>/Source/Frontline Engine/Frontline Engine/Resource/old/DefaultResourceLoader.h #pragma once #include "..\FrontlineCommon.h" #include "IResourceLoader.h" class DefaultResource : public Resource { std::string contents; public: DefaultResource(std::string ps_name); std::string getContents(); void setContents(std::string ps_contents); }; class DefaultResourceLoader : public IResourceLoader { public: virtual bool VUseRawFile() { return true; } virtual unsigned int VGetLoadedResourceSize(char *rawBuffer, unsigned int rawSize) { return rawSize; } virtual ResHandle VLoadResource(char *rawBuffer, char* name) { DefaultResource* lp_res = FL_NEW DefaultResource(std::string(name)); lp_res->setContents(std::string(rawBuffer)); return ResHandle(lp_res); } virtual std::string VGetPattern() { return "*"; } };<file_sep>/Source/Frontline/effectSysTestP2/flFx.cpp #include "flFx.h" PassDesc::PassDesc(fxState flag,const char* name) { m_Flag = flag; m_Name = name; m_Active = true; m_Validated = false; } PassDesc::~PassDesc() { //delete m_Parent; //handled in technique automatically by shared_ptr } //pass stuff std::vector<fxState> Pass::m_ExecutionConfig; Pass::Pass(const char* name) { m_Name = name; m_BaseLayer = 0; m_ActiveLayer = 0; m_Validated = false; SetActiveLayer(0,false); } Pass::~Pass() { } bool Pass::Validate() { std::cout<<"Calling Validate from Pass at layer: "<<m_ActiveLayer<<std::endl; PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for (auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { if (!(*iter)->IsValid()) { if (!(*iter)->Validate()) { continue; } } (*iter)->SetValidated(true); } m_Validated = true; return true; } bool Pass::Execute() { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; m_PassInfo.clear(); for(auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { m_PassInfo[(*iter)->m_Flag].push_back(*iter); } if (!Pass::m_ExecutionConfig.empty()) { for (auto iter = Pass::m_ExecutionConfig.begin(); iter != Pass::m_ExecutionConfig.end(); iter++) { fxState current = *iter; for (auto iter = m_PassInfo[current].begin(); iter != m_PassInfo[current].end(); iter++) { if ((*iter)->IsActive() && (*iter)->IsValid()) { (*iter)->Execute(); } } } } return true; } //cleanup is called manually bool Pass::Cleanup() { bool success = true; PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for (auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { if ((*iter)->IsActive()) { if (!(*iter)->Cleanup()) { success = false; } } } return success; } bool Pass::Invalidate() { std::cout<<"Calling Invalidate from Pass at layer: "<<m_ActiveLayer<<std::endl; PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { if ((*iter)->IsValid()) { if (!(*iter)->Invalidate()) { continue; } } (*iter)->SetValidated(false); } m_Validated = false; return true; } void Pass::SetActiveLayer(int layer, bool copyFromPrev) { if(layer < 0 || layer == m_ActiveLayer) { return; } //check if layer exists, if does, then set that to active for(auto iter = m_Layers.begin(); iter != m_Layers.end(); iter++) { if(iter->first == layer) { m_ActiveLayer = iter->first; return; } } //if layer doesnt exist, create new layer Layer newLayer; if(copyFromPrev) { //copies from prev active layer newLayer = m_Layers[m_ActiveLayer]; //all operations on top layer should reflect all layers //newLayer.Copy(m_Layers[m_ActiveLayer]); } //Invalidate(); //maybe invalidate previous layer? //m_Validated = false; //since new layer, maybe umm set validated to false? m_Layers[layer] = newLayer; m_ActiveLayer = layer; std::cout<<"Set ActiveLayer to: "<<m_ActiveLayer<<std::endl; } void Pass::CreateData(std::shared_ptr<PassDesc> data) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { if((*iter)->m_Name && data->m_Name) { if(strcmp((*iter)->m_Name,data->m_Name) == 0) { return; } } if(data == (*iter)) { return; } } data->SetParent(shared_from_this()); //this line >:( if(m_Validated) { //if(m_Validated) //if the pass was already validated, validate here then for consistency data->Validate(); data->m_Validated = true; //set flag here too } m_Layers[m_ActiveLayer].dataForExecution.push_back(data); } void Pass::CreateDataOverride(std::shared_ptr<PassDesc> data) { for(auto iter = m_Overrides.begin(); iter != m_Overrides.end(); iter++) { if((*iter)->m_Name && data->m_Name) { if(strcmp((*iter)->m_Name,data->m_Name) == 0) { return; } } if(data == (*iter)) { return; } } //data->SetParent(shared_from_this()); //validation and set parent not needed cuz it relies on the pass it overrides m_Overrides.push_back(data); } void Pass::Replace(std::shared_ptr<PassDesc> data) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for (auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if ((*iter)->m_Name && data->m_Name) { if (strcmp((*iter)->m_Name,data->m_Name) == 0) { data->SetParent(shared_from_this()); if (m_Validated) { data->Validate(); data->m_Validated = true; } (*iter) = data; return; } } iter++; } } void Pass::Replace(const char* name, std::shared_ptr<PassDesc> data) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for (auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if ((*iter)->m_Name && name) { if (strcmp(name,(*iter)->m_Name) == 0) { data->SetParent(shared_from_this()); if (m_Validated) { data->Validate(); data->m_Validated = true; } (*iter) = data; return; } } iter++; } } std::shared_ptr<PassDesc> Pass::Find(const char* name) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if((*iter)->m_Name) { if(strcmp((*iter)->m_Name,name) == 0) { //oh thats why, violation was in strcmp cuz of null string return (*iter); //wtf access violation??! } } iter++; } return NULL; } std::shared_ptr<PassDesc> Pass::Find(fxState flag) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if((*iter)->m_Flag == flag) { return (*iter); } iter++; } return NULL; } void Pass::Find(fxState flag, std::vector<std::shared_ptr<PassDesc>>* data) { std::vector<std::shared_ptr<PassDesc>> sortedData; PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for (auto iter = dataForExecution.begin(); iter != dataForExecution.end(); iter++) { if ((*iter)->GetFlag() == flag) { sortedData.push_back(*iter); } } data = &sortedData; } std::shared_ptr<PassDesc> Pass::FindOverride(const char* name) { for(auto iter = m_Overrides.begin(); iter != m_Overrides.end();) { if((*iter)->m_Name) { if(strcmp((*iter)->m_Name,name) == 0) { return (*iter); } } iter++; } return NULL; } std::shared_ptr<PassDesc> Pass::FindOverride(fxState flag) { for(auto iter = m_Overrides.begin(); iter != m_Overrides.end();) { if((*iter)->m_Flag == flag) { return (*iter); } iter++; } return NULL; } void Pass::FindOverride(fxState flag, std::vector<std::shared_ptr<PassDesc>>* data) { std::vector<std::shared_ptr<PassDesc>> sortedData; for (auto iter = m_Overrides.begin(); iter != m_Overrides.end(); iter++) { if ((*iter)->GetFlag() == flag) { sortedData.push_back(*iter); } } data = &sortedData; } bool Pass::RemoveData(std::shared_ptr<PassDesc> data) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if((*iter) == data) { (*iter)->Invalidate(); (*iter)->m_Validated = false; dataForExecution.erase(iter); return true; } iter++; } return false; } bool Pass::RemoveData(const char* name) { PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if((*iter)->m_Name) { if(strcmp((*iter)->m_Name,name) == 0) { (*iter)->Invalidate(); (*iter)->m_Validated = false; dataForExecution.erase(iter); return true; } } iter++; } return false; } bool Pass::RemoveData(fxState flag) { bool removed = false; PassDataVec& dataForExecution = m_Layers[m_ActiveLayer].dataForExecution; for(auto iter = dataForExecution.begin(); iter != dataForExecution.end();) { if((*iter)->m_Flag == flag) { (*iter)->Invalidate(); (*iter)->m_Validated = false; dataForExecution.erase(iter); removed = true; } iter++; } return removed; } void Pass::SetupOverrides(std::shared_ptr<Technique>* dest, int numTechs) { for(int i = 0; i < numTechs; i++) { std::shared_ptr<Technique> destTech = dest[i]; for(int i = 0; i < destTech->GetNumPasses(); i++) { std::shared_ptr<Pass> pass = destTech->GetPass(i); SetupOverrides(&pass,1); } } } //program is bound on the active layer void Pass::SetupOverrides(std::shared_ptr<Pass>* dest, int numPasses) { for(int i = 0; i < numPasses; i++) { std::shared_ptr<Pass> passDst = dest[i]; if(m_Overrides.size() > 0) { int layer = passDst->GetActiveLayerId(); layer++; m_OverrideIds[passDst] = layer; passDst->Invalidate(); //can be handled in SetActiveLayer passDst->SetActiveLayer(m_OverrideIds[passDst],true); //create new layer for(auto iter = m_Overrides.begin(); iter != m_Overrides.end();iter++) { //if names match up,usually names are multiples, invalidated already?? bool removed = passDst->RemoveData((*iter)->m_Name); //remove and replace if(removed) { std::cout<<"Overrided "<<(*iter)->m_Name<<" in Pass "<<passDst->GetName()<<std::endl; passDst->CreateData((*iter)); } //passDst->Replace(*iter); //to save locations } //passDst->Validate(); //validate new layer } } } void Pass::ReleaseOverrides(std::shared_ptr<Technique>* dest, int numTechniques) { for(int i = 0; i < numTechniques; i++) { std::shared_ptr<Technique> destTech = dest[i]; for(int i = 0; i < destTech->GetNumPasses(); i++) { std::shared_ptr<Pass> pass = destTech->GetPass(i); ReleaseOverrides(&pass,1); } } } //usually, SetActiveLayer() to designated layer will be called before ReleaseingOverrides to avoid setting active layer to 0 void Pass::ReleaseOverrides(std::shared_ptr<Pass>* dest, int numPasses) { for(int i = 0; i < numPasses; i++) { std::shared_ptr<Pass> passDst = dest[i]; passDst->RemoveLayer(m_OverrideIds[passDst]); //passDst->Validate(); //validate the layer that is now uncovered m_OverrideIds.erase(passDst); } } bool Pass::RemoveLayer(int layer) { m_Layers.erase(layer); if(layer == m_ActiveLayer) { std::cout<<"Warning, removing active layer, resetting active layer"<<std::endl; SetActiveLayer(0,false); } return true; } Technique::~Technique() { } bool Technique::Validate() { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(!iter->pass->Validate()) { return false; } } return true; } bool Technique::Invalidate() { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(!iter->pass->Invalidate()) { return false; } } return true; } bool Technique::AddPass(std::shared_ptr<Pass> pass) { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(iter->pass == pass) { return false; } } PassInfo passInfo; passInfo.isActive = true; pass->SetParent(shared_from_this()); passInfo.pass = pass; m_Passes.push_back(passInfo); return true; } bool Technique::RemovePass(std::shared_ptr<Pass> pass) { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(iter->pass == pass) { m_Passes.erase(iter); return true; } } return false; } void Technique::SetPassActive(int index, bool active) { if(index >= m_Passes.size()) { return; } m_Passes[index].isActive = active; } void Technique::SetPassActive(const char* name, bool active) { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(strcmp(iter->pass->GetName(),name) == 0) { iter->isActive = active; break; } } } bool Technique::GetPassActive(int index) { if(index >= m_Passes.size()) { return false; } return m_Passes[index].isActive; } bool Technique::GetPassActive(const char* name) { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(strcmp(iter->pass->GetName(),name) == 0) { return iter->isActive; } } return false; } std::shared_ptr<Pass> Technique::GetPass(int index) { if(index >= m_Passes.size()) { return NULL; } return std::shared_ptr<Pass>(m_Passes[index].pass); } std::shared_ptr<Pass> Technique::GetPass(const char* name) { for(auto iter = m_Passes.begin(); iter != m_Passes.end(); iter++) { if(strcmp(iter->pass->GetName(),name) == 0) { return iter->pass; } } return NULL; } Effect::~Effect() { } bool Effect::AddTechnique(std::shared_ptr<Technique> technique) { for(auto iter = m_Techniques.begin(); iter != m_Techniques.end(); iter++) { if((*iter) == technique) { return false; } } m_Techniques.push_back(technique); return true; } bool Effect::RemoveTechnique(std::shared_ptr<Technique> technique) { for(auto iter = m_Techniques.begin(); iter != m_Techniques.end(); iter++) { if((*iter) == technique) { m_Techniques.erase(iter); return true; } } return false; } std::shared_ptr<Technique> Effect::GetTechnique(int index) { if(index >= m_Techniques.size()) { return NULL; } return std::shared_ptr<Technique>(m_Techniques[index]); } std::shared_ptr<Technique> Effect::GetTechnique(const char* name) { for(auto iter = m_Techniques.begin(); iter != m_Techniques.end(); iter++) { if(strcmp((*iter)->GetName(),name) == 0) { return (*iter); } } return NULL; } Repository::~Repository() { } bool Repository::AddItem(std::shared_ptr<PassDesc> item) { for(auto iter = m_Items.begin(); iter != m_Items.end(); iter++) { if((*iter) == item) { return false; } } m_Items.push_back(item); return true; } bool Repository::RemoveItem(const char* name) { for(auto iter = m_Items.begin(); iter != m_Items.end();) { if(strcmp((*iter)->GetName(),name) == 0) { m_Items.erase(iter); return true; } iter++; } return false; } bool Repository::RemoveItem(std::shared_ptr<PassDesc> item) { for(auto iter = m_Items.begin(); iter != m_Items.end();) { if((*iter) == item) { m_Items.erase(iter); return true; } iter++; } return false; } std::shared_ptr<PassDesc> Repository::Find(const char* name) { for(auto iter = m_Items.begin(); iter != m_Items.end();) { if(strcmp((*iter)->GetName(),name) == 0) { return (*iter); } iter++; } return NULL; } std::shared_ptr<PassDesc> Repository::Find(unsigned int index) { if(index >= m_Items.size()) { return NULL; } return m_Items[index]; } <file_sep>/Source/Frontline Engine/Frontline Engine/IPhysics.h #pragma once #include "FrontlineCommon.h" struct PhysicsObject { float m_mass; std::string m_material; StrongActorPtr m_gameActor; short m_collisionType; short m_collidesWith; }; struct PhysicsMaterial { float mf_restitution; float mf_friction; }; class IPhysics { public: virtual bool VOnInit() = 0; virtual void VOnUpdate(float pf_deltaSeconds) = 0; virtual void VSyncVisibleScene() = 0; virtual void VAddRigidBody(PhysicsObject* po_physObject) = 0; virtual void VAddSphere(float pf_radius, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel = 1, short mi_collidesWith = 1) = 0; virtual void VAddCylinder(float pf_radius, float pf_height, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel = 1, short mi_collidesWith = 1) = 0; virtual void VAddBox(const glm::vec3& pf_dimensions, WeakActorPtr pp_gameActor, const std::string& ps_density, const std::string& ps_material, short mi_collisionChannel = 1, short mi_collidesWith =1) = 0; virtual void VRemoveActor(ActorID pi_id) = 0; virtual void VRenderDiagnostics() = 0; virtual void VCreateTrigger(PhysicsObject* po_physObject) = 0; virtual void VApplyForce(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id) = 0; virtual void VApplyTorque(const glm::vec3& pv_dir, float pf_newtons, ActorID pi_id) = 0; virtual bool VKinematicMove(const glm::mat4x4& pm_matrix, ActorID pi_id) = 0; virtual ~IPhysics() {}; };
88ee0cc35bd394599357462592e92ed783774bd9
[ "C", "C++" ]
99
C++
KyleStach1678/FrontLine
a231a002697e98cf93b67f87d68dbef15abe1fab
1a4c45745602c41a395a80c24abe25744ed22529
refs/heads/master
<file_sep>package god.arti.app.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.google.gson.Gson import god.arti.app.R import god.arti.app.adapter.ObjAartiList import god.arti.app.databinding.FragmentDetailedAartiBinding import kotlinx.android.synthetic.main.activity_home.* class DetailedAartiFragment : Fragment() { companion object { } lateinit var fragmentDetailedAartiBinding: FragmentDetailedAartiBinding lateinit var objAartiList: ObjAartiList override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment fragmentDetailedAartiBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_detailed_aarti,container,false) initView() return fragmentDetailedAartiBinding.root } fun initView() { var selectedItem="" var args=arguments if (args!=null && args.getString("selected_data") != null) { selectedItem = args.getString("selected_data")!! when (selectedItem){ "श्री गणेश आरती 1" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesh) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.ganesh_aarti)) } "श्री गणेश आरती 2" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesha) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.ganesh_aarti_2)) } "दुर्गा माँ की आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.durga) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.durga)) } "जय सन्तोषी माता: आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.santoshi) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.santoshi)) } "माँ लक्ष्मी की आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.laxmi) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.laxmi)) } "ॐ जय जगदीश हरे आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.jagdish) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.jagdish)) } "श्री शिव, शंकर, भोलेनाथ आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.mahadev) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.shiv)) } "आरती कुंजबिहारी की" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.krishana) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.kunj)) } "श्री हनुमान जी आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.hanuman) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.hanuman)) } "श्री राम स्तुति: श्री रामचन्द्र कृपालु भजुमन" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ram) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.ram)) } "श्री सत्यनारायण जी आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.vishnu) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.satyanarayan)) } "महाराजा अग्रसेन की आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.agrasen) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.agrasen)) } "दुर्गा पूजा पुष्पांजली!" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.durga) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.durga1)) } "ओवळा ओवळा माझ्या सद्गुरू राया" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesha) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.owada)) } "कर्पूर गौरम करूणावतारम" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesh) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.kapur)) } "तुलसी माता की आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.tulsi) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.tulsi)) } "तुळशीच्या लग्नाची मंगलाष्टके" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.tulsi) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.tulsi1)) } "अम्बे तू है जगदम्बे काली: माँ दुर्गा, माँ काली आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ambe) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.ambe)) } "आरती: श्री शनिदेव - जय जय श्री शनिदेव" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.shanidev) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.shanidev)) } "रघुवर श्री रामचन्द्र जी आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ram) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.raghuvar)) } "आरती: श्री गणेश - शेंदुर लाल चढ़ायो" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesha) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.arti_shree_ganesh)) } "दत्ताची आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.datta) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.dattaji)) } "आरती: वैष्णो माता" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.vaishno) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.vaishno)) } "श्री सिद्धिविनायक आरती: जय देव जय देव" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesh) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.siddhivinayak)) } "श्री शंकराची आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.mahadev) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.shankarji)) } "श्री विठोबाची आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.vidhoba) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.vithoba)) } "गायत्री मंत्र" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ganesha) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.gayatri)) } "आरती साई बाबा" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.saibaba) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.sai)) } "पसायदान" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.santdhaneshwar) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.pasaydan)) } "श्री गजानन महाराज (शेगाव) आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.gajananmaharaj) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.gajanan)) } "अनसुया आईची आरती" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.anushaya) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.anusaya)) } "जय आद्य शक्ती, विश्वंभरी (गुजराती)" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.durga) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.gujrati)) } "जय आद्या शक्ति (गुजराती)" ->{ fragmentDetailedAartiBinding.ivGod.setImageResource(R.drawable.ambe) fragmentDetailedAartiBinding.tvAaratiName.setText(selectedItem) fragmentDetailedAartiBinding.tvAaratiDetail.setText(getString(R.string.adishakti_gujrati)) } } } } }<file_sep>package god.arti.app.activity import android.R.id.message import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.MenuItem import android.view.Window import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.GravityCompat import androidx.databinding.DataBindingUtil import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.NavigationUI import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.InterstitialAd import com.google.android.material.navigation.NavigationView import com.google.android.play.core.review.ReviewManagerFactory import god.arti.app.R import god.arti.app.databinding.ActivityHomeBinding import god.arti.app.fragment.AartiListFragment import god.arti.app.openUrl import god.arti.app.toast import kotlinx.android.synthetic.main.activity_home.* class HomeActivity : AppCompatActivity() , NavigationView.OnNavigationItemSelectedListener { lateinit var activityHomeBinding:ActivityHomeBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityHomeBinding=DataBindingUtil.setContentView(this,R.layout.activity_home) setSupportActionBar(toolbar) navController = Navigation.findNavController(this, R.id.fragment_home) setupDrawerLayout() setStatusBarColor() toolbar.setTitle("The Aarti App") } private fun setStatusBarColor() { val window: Window = this.getWindow() window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary)) } override fun onSupportNavigateUp(): Boolean { return NavigationUI.navigateUp( navController, drawer_layout) } private fun setupDrawerLayout() { NavigationUI.setupWithNavController(nav_view,navController) NavigationUI.setupActionBarWithNavController(this, navController,drawer_layout) nav_view.setNavigationItemSelectedListener(this) } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) }else{ super.onBackPressed() } } override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { when(menuItem.itemId){ R.id.aboutUsScreen ->{ openUrl(this,"http://godinc.in/") // toast("aboutUsScreen clicked") } R.id.recomendationScreen ->{ val intent = Intent( Intent.ACTION_SENDTO, Uri.fromParts( "mailto", "<EMAIL>", null ) ) intent.putExtra(Intent.EXTRA_SUBJECT, "God Inc Ads Work") intent.putExtra(Intent.EXTRA_TEXT, message) startActivity(Intent.createChooser(intent, "Choose an Email client :")) } R.id.businessScreen ->{ openUrl(this,"http://businessnetworks.in/") } R.id.rateUsScreen ->{ inAppReview() /* val manager = ReviewManagerFactory.create(this) val request = manager.requestReviewFlow() request.addOnCompleteListener { request -> if (request.isSuccessful) { // We got the ReviewInfo object val reviewInfo = request.result val flow = manager.launchReviewFlow(this, reviewInfo) flow.addOnCompleteListener { _ -> // The flow has finished. The API does not indicate whether the user // reviewed or not, or even whether the review dialog was shown. Thus, no // matter the result, we continue our app flow. } } else { // There was some problem, continue regardless of the result. } }*/ } } menuItem.setChecked(true); drawer_layout.closeDrawer(GravityCompat.START); return true; } fun inAppReview() { val reviewManager = ReviewManagerFactory.create(this) val requestReviewFlow = reviewManager.requestReviewFlow() requestReviewFlow.addOnCompleteListener { request -> if (request.isSuccessful) { // We got the ReviewInfo object val reviewInfo = request.result val flow = reviewManager.launchReviewFlow(this, reviewInfo) flow.addOnCompleteListener { // The flow has finished. The API does not indicate whether the user // reviewed or not, or even whether the review dialog was shown. Thus, no // matter the result, we continue our app flow. } } else { Log.d("Error: ", request.exception.toString()) // There was some problem, continue regardless of the result. } } } } <file_sep>package god.arti.app.callbackInterface import god.arti.app.adapter.ObjAartiList interface IAartiListInterface { fun onItemSelected(objAartiList: ObjAartiList) fun onBackButtonClick() }<file_sep>include ':app' rootProject.name = "The Aarti app"<file_sep>package god.arti.app import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.view.View import android.widget.Toast import androidx.core.content.ContextCompat.startActivity import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar fun <A : Activity> Activity.startNewActivity(activity: Class<A>) { Intent(this, activity).also { it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(it) } } fun View.visible(isVisible: Boolean) { visibility = if (isVisible) View.VISIBLE else View.GONE } fun View.enable(enabled: Boolean) { isEnabled = enabled alpha = if (enabled) 1f else 0.5f } fun View.snackbar(message: String, action: (() -> Unit)? = null) { val snackbar = Snackbar.make(this, message, Snackbar.LENGTH_LONG) action?.let { snackbar.setAction("Retry") { it() } } snackbar.show() } fun Context.toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun openUrl(context: Context,url:String) { val intent = Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)) context.startActivity(intent) } <file_sep>package god.arti.app.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.gms.ads.* import god.arti.app.R import god.arti.app.adapter.AartiListAdapter import god.arti.app.adapter.ObjAartiList import god.arti.app.callbackInterface.IAartiListInterface import god.arti.app.databinding.FragmentAartiListBinding class AartiListFragment : Fragment(), IAartiListInterface { lateinit var listOfCountry: ArrayList<ObjAartiList> private lateinit var mInterstitialAd: InterstitialAd companion object { } lateinit var fragmentArtiListBinding: FragmentAartiListBinding lateinit var aartiListAdapter: AartiListAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment fragmentArtiListBinding=DataBindingUtil.inflate(inflater,R.layout.fragment_aarti_list,container,false) initView() return fragmentArtiListBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adView = AdView(context) adView.adSize = AdSize.BANNER adView.adUnitId = getString(R.string.test_banner_id) MobileAds.initialize(context) {} val adRequest = AdRequest.Builder().build() fragmentArtiListBinding.adView.loadAd(adRequest) mInterstitialAd = InterstitialAd(context) mInterstitialAd.adUnitId =getString(R.string.test_interstrisialID) mInterstitialAd.loadAd(AdRequest.Builder().build()) } private fun initView() { fragmentArtiListBinding.countryListRecyclerView.layoutManager = LinearLayoutManager(context) as RecyclerView.LayoutManager? val list = ArrayList<ObjAartiList>() list.add(ObjAartiList("श्री गणेश आरती 1",R.drawable.ganesh)) list.add(ObjAartiList("श्री गणेश आरती 2",R.drawable.ganesha)) list.add(ObjAartiList("दुर्गा माँ की आरती",R.drawable.durga)) list.add(ObjAartiList("जय सन्तोषी माता: आरती",R.drawable.santoshi)) list.add(ObjAartiList("माँ लक्ष्मी की आरती",R.drawable.laxmi)) list.add(ObjAartiList("ॐ जय जगदीश हरे आरती",R.drawable.jagdish)) list.add(ObjAartiList("श्री शिव, शंकर, भोलेनाथ आरती",R.drawable.mahadev)) list.add(ObjAartiList("आरती कुंजबिहारी की",R.drawable.krishana)) list.add(ObjAartiList("श्री हनुमान जी आरती",R.drawable.hanuman)) list.add(ObjAartiList("श्री राम स्तुति: श्री रामचन्द्र कृपालु भजुमन",R.drawable.ram)) list.add(ObjAartiList("श्री सत्यनारायण जी आरती",R.drawable.vishnu)) list.add(ObjAartiList("महाराजा अग्रसेन की आरती",R.drawable.agrasen)) list.add(ObjAartiList("दुर्गा पूजा पुष्पांजली!",R.drawable.durga)) list.add(ObjAartiList("ओवळा ओवळा माझ्या सद्गुरू राया",R.drawable.ganesha)) list.add(ObjAartiList("कर्पूर गौरम करूणावतारम",R.drawable.ganesh)) list.add(ObjAartiList("तुलसी माता की आरती",R.drawable.tulsi)) list.add(ObjAartiList("तुळशीच्या लग्नाची मंगलाष्टके",R.drawable.tulsi)) list.add(ObjAartiList("अम्बे तू है जगदम्बे काली: माँ दुर्गा, माँ काली आरती",R.drawable.ambe)) list.add(ObjAartiList("आरती: श्री शनिदेव - जय जय श्री शनिदेव",R.drawable.shanidev)) list.add(ObjAartiList("रघुवर श्री रामचन्द्र जी आरती",R.drawable.ram)) list.add(ObjAartiList("आरती: श्री गणेश - शेंदुर लाल चढ़ायो",R.drawable.ganesha)) list.add(ObjAartiList("दत्ताची आरती",R.drawable.datta)) list.add(ObjAartiList("आरती: वैष्णो माता",R.drawable.vaishno)) list.add(ObjAartiList("श्री सिद्धिविनायक आरती: जय देव जय देव",R.drawable.ganesh)) list.add(ObjAartiList("श्री शंकराची आरती",R.drawable.mahadev)) list.add(ObjAartiList("श्री विठोबाची आरती",R.drawable.vidhoba)) list.add(ObjAartiList("गायत्री मंत्र",R.drawable.ganesha)) list.add(ObjAartiList("आरती साई बाबा",R.drawable.saibaba)) list.add(ObjAartiList("पसायदान",R.drawable.santdhaneshwar)) list.add(ObjAartiList("श्री गजानन महाराज (शेगाव) आरती",R.drawable.gajananmaharaj)) list.add(ObjAartiList("अनसुया आईची आरती",R.drawable.anushaya)) list.add(ObjAartiList("जय आद्य शक्ती, विश्वंभरी (गुजराती)",R.drawable.durga)) list.add(ObjAartiList("जय आद्या शक्ति (गुजराती)",R.drawable.ambe)) if (!list.isEmpty()) { listOfCountry = list } setDataToAdapter() activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (mInterstitialAd.isLoaded) { mInterstitialAd.show() } mInterstitialAd.adListener = object: AdListener() { override fun onAdClosed() { // Code to be executed when the interstitial ad is closed. activity!!.finish() } } }}) } private fun setDataToAdapter() { if (!listOfCountry.isEmpty()){ aartiListAdapter= AartiListAdapter(listOfCountry,requireActivity(),this) fragmentArtiListBinding.countryListRecyclerView.adapter = aartiListAdapter } } override fun onItemSelected(objAartiList: ObjAartiList) { /* if (mInterstitialAd.isLoaded) { mInterstitialAd.show() } else {*/ findNavController().navigate(R.id.action_aartiListFragment_to_detailedAartiFragment, bundleOf("selected_data" to objAartiList.name)) // } /* mInterstitialAd.adListener = object: AdListener() { override fun onAdClosed() { // Code to be executed when the interstitial ad is closed. findNavController().navigate(R.id.action_aartiListFragment_to_detailedAartiFragment, bundleOf("selected_data" to objAartiList.name)) } }*/ } override fun onBackButtonClick() { } }<file_sep>package god.arti.app.adapter import android.content.Context import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import god.arti.app.R import god.arti.app.callbackInterface.IAartiListInterface import kotlinx.android.synthetic.main.aarti_list_item_layout.view.* class AartiListAdapter(val listOfAarti: ArrayList<ObjAartiList>, context: Context,var iAartiListInterface: IAartiListInterface) : RecyclerView.Adapter<AartiListAdapter.MyAartiListViewHolder>(){ var aartiList = ArrayList<ObjAartiList>() var mcontext :Context var previousHolder : MyAartiListViewHolder?=null var clicked: Boolean = false init { aartiList = listOfAarti mcontext=context } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAartiListViewHolder { return AartiListAdapter.MyAartiListViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.aarti_list_item_layout, parent, false) ) } override fun getItemCount(): Int { return aartiList.size } override fun onBindViewHolder(holder: MyAartiListViewHolder, position: Int) { var list = aartiList[position] holder.itemView.txtCountryName.setText(list.name) holder.itemView.imgvCountryFlag.setImageResource(list.image) holder.itemView.setOnClickListener{ if(clicked) { return@setOnClickListener } /* if (previousHolder!=null) { previousHolder?.itemView?.coutry_coontainer_without_isdCode?.imgRightTick?.visibility=View.INVISIBLE previousHolder=null } clicked = true holder.itemView.coutry_coontainer_without_isdCode.imgRightTick.visibility=View.VISIBLE */ clicked = true Handler().postDelayed({ clicked=false iAartiListInterface.onItemSelected(aartiList[position]) }, 500) } } public class MyAartiListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) }<file_sep>package god.arti.app.adapter data class ObjAartiList(var name:String,var image:Int)
ac2ea638cdf4769346e0f39c51f32a3b3e14bfe3
[ "Kotlin", "Gradle" ]
8
Kotlin
Ankita-M94/Aarti_App
71c7a52a5cd08fce68741ca270dbd74c09456f89
d66f595614eb8f43be70eb1a7ef4061d309a5905
refs/heads/master
<file_sep>import React, { Component } from 'react'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import moment from 'moment'; import Button from '@material-ui/core/Button'; class Training_List extends Component { constructor(props) { super(props); this.state = {training: []} } componentDidMount() { this.loadTraining(); } loadTraining = () => { fetch ('https://customerrest.herokuapp.com/gettrainings', {method:'GET'}) .then(response => response.json()) .then (jsondata => this.setState({training: jsondata})) .catch(err => console.error(err)); } // training will be deleted based on the ID caught from the /gettrainings json data deleteTraining = (id) => { if(window.confirm('Are you sure?')){ fetch('https://customerrest.herokuapp.com/api/trainings/'+id, {method:'DELETE'}) .then(res => this.loadTraining()) .catch(err => console.error(err)); } } render() { const columns = [ { Header: 'Date', accessor: 'date', Cell: row => <span>{moment.utc(row.value).format('DD.MM.YYYY hh:mm a')}</span> }, { Header: 'Duration', accessor: 'duration' }, { Header: 'Activity', accessor: 'activity' }, { Header: 'Client', accessor: 'customer', Cell: row => { return ( <div> <span>{row.row.customer.firstname}</span> <span>{' '}</span> <span>{row.row.customer.lastname}</span> </div> ) } }, { Header: '', accessor: 'id', Cell: ({value}) => <Button color="primary" onClick={() => this.deleteTraining(value)}>Delete</Button> }, ]; return ( <div> <ReactTable data={this.state.training} columns={columns} filterable={true} /> </div> ); } } export default Training_List; <file_sep>import React, { Component } from 'react'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; class Add_training extends Component { constructor(props) { super(props); this.state = {open: false, date:'', duration:'', activity:''}; this.props = {customer: props.link}; } handleClickOpen = () => { this.setState({ open: true }); }; handleClose = () => { this.setState({ open: false }); }; handleChange = (event) => { this.setState({[event.target.name]: event.target.value }); }; addTraining = () => { console.log('Cust: ' + this.props.link ) const addedTraining = { date: this.state.date + ":00.000", duration: this.state.duration, activity: this.state.activity, customer: this.props.link } this.props.newTraining(addedTraining); this.handleClose(); } render() { return ( <div> <Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title">New training session</DialogTitle> <DialogContent> <TextField onChange={this.handleChange} autoFocus margin="dense" name="date" id="datetime-local" type="datetime-local" label="Date" fullWidth/> <TextField onChange={this.handleChange} margin="dense" name="duration" label="Duration" fullWidth/> <TextField onChange={this.handleChange} margin="dense" name="activity" label="Activity" fullWidth/> </DialogContent> <DialogActions> <Button onClick={this.handleClose} color="primary"> Cancel </Button> <Button onClick={this.addTraining} color="primary"> Save </Button> </DialogActions> </Dialog> <Button color="primary" onClick={this.handleClickOpen}>ADD TRAINING</Button> </div> ); } } export default Add_training; <file_sep> import React, { Component, useState } from 'react'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Customers_List from './Components/Customers_List'; import Training_List from './Components/Training_List'; import Calendar from './Components/Calendar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import './App.css'; const TabApp = () => { const [value, setValue] = useState('one'); const handleChange = (event, value) => { setValue(value); }; return ( <div className="App"> <AppBar position="static"> <Toolbar> <Typography variant="h6" color="inherit" > The Gym </Typography> </Toolbar> </AppBar> <Tabs value={value} onChange={handleChange}> <Tab value="one" label="Clients" /> <Tab value="two" label="Training" /> <Tab value="three" label="Calendar" /> </Tabs> {value === 'one' && <div> <Customers_List /></div>} {value === 'two' && <div><Training_List /></div>} {value === 'three' && <div><Calendar /></div>} </div> ); } export default TabApp;
e447dcec6e86838c187be3c0ee7e0385301475e5
[ "JavaScript" ]
3
JavaScript
gitpaula/HH_gym
8d505a5b13dd1e4241ec7f57b5f06637493a5679
5fb3c6e22bdcf1583412a10f1e13d383092eb478
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dataset extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_displaytable'); $this->load->model('m_cruddataset'); $this->load->model('m_doc_extraction'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'dataset'; $this->load->view('dataset',$data); } public function review(){ $query = $this->m_displaytable->displaydataset($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['judul_review'], $key['sentimen_review'], $key['kategori_review'], //explode( "\n",$key['isi_review'])[0], $key['isi_review'], '<button data-target="#modaldataset" data-toggle="modal" class="btn btn-circle btn-default btn-edit" data-id="'.$key['id_review'].'"><i class="material-icons">edit</i></button> <button a href="#deletereviewmodal" data-toggle="modal" data-id="'.$key['id_review'].'" class="btn btn-circle btn-danger btn-delete"><i class="material-icons">delete</i></button>' ]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function fetchid(){ $id_review = $this->input->post('id'); $data = $this->m_displaytable->fetchreview($id_review); echo json_encode($data); } public function inputdataset(){ $judul = $this->input->post('judulreview'); $isi = $this->input->post('teksreview'); $kategori = $this->input->post('kategori'); $sentimen = $this->input->post('sentimenawal'); $lastid = $this->m_cruddataset->inputdataset($judul,$isi,$kategori,$sentimen); $this->m_doc_extraction->insertterm($lastid, $isi); if($lastid){ $this->session->set_flashdata('notification','input_review_success'); } else{ $this->session->set_flashdata('notification','input_review_error'); } redirect('dataset'); } public function editdataset(){ $judul = $this->input->post('judulreview'); $isi = $this->input->post('teksreview'); $kategori = $this->input->post('kategori'); $sentimen = $this->input->post('sentimenawal'); $idreview = $this->input->post('id_review'); $edit_review = $this->m_cruddataset->editdataset($judul,$isi,$kategori,$sentimen,$idreview); $this->m_doc_extraction->editterm($idreview,$isi); if($edit_review){ $this->session->set_flashdata('notification','edit_review_success'); } else{ $this->session->set_flashdata('notification','edit_review_error'); } redirect('dataset'); } public function deletedataset(){ $idreview = $this->input->post('id_review'); $delete_review = $this->m_cruddataset->deletedataset($idreview); if($delete_review){ $this->session->set_flashdata('notification','delete_review_success'); } else{ $this->session->set_flashdata('notification','delete_review_error'); } redirect('dataset'); } } ?><file_sep>$(document).ready(function () { var url = $("meta[name=url]").attr("content"); $('#dataTables-example').dataTable({ "language": { "info": "Menampilkan halaman _PAGE_ dari _PAGES_", "sLengthMenu": "_MENU_ kata per halaman", "sSearch": "Cari: ", "sNext": "Selanjutnya", "sPrevious": "Sebelumnya" }, "processing": true, "serverSide": true, "ajax": url + "displayterm/tabelfiltered" }); });<file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/toastr.css"> </head> <body> <div id="wrapper"> <!--/. SIDEBAR TOP --> <?php $this->load->view('template'); ?> <!-- /. AKHIR DARI SIDEBAR --> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header"> Kata Dasar Review Film </h2> </div> </div> <!--BUTTON TAMBAH --> <div class="btn-fixed"> <button a href="#modalkatadasar" data-toggle = "modal" class="btn btn-circle btn-circle-lg btn-primary btn-add text-right"><i class="material-icons material-icons-2x">playlist_add</i></button> </div> <div class="row"> <div class="col-md-12 panel panel-default"> <div class="panel-heading text-center"> Tabel Kumpulan Kata Dasar Bahasa Indonesia </div> <!-- Datatable --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>No.</th> <th>Kata</th> <th>Tindakan</th> </tr> </thead> </table> </div> </div> </div> <!--Akhir dari datatable --> </div> </div> <!-- FOOTER--> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis | All right reserved.</a></p></footer> </div> <!-- PAGE INNER --> </div> <!-- PAGE WRAPPER --> </div> <!-- MODAL FORM TAMBAH DAN EDIT KATA DASAR--> <div aria-hidden="true" aria-labelledby="modalkatadasarlabel" role="dialog" tabindex="-1" id="modalkatadasar" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>katadasar/inputkatadasar" method="post" id="formkatadasar"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" class="close" type="button">&times;</button> <h4 class="modal-title text-center"><span class="modal-action">Tambah</span> Kata Dasar</h4> </div> <div class="modal-body"> <input type="hidden" name="id_katadasar" id="id_katadasar" value=""> <div class="form-group"> <label for="katadasarbaru">Kata Dasar</label> <input type="text" class="form-control" id="katadasarbaru" name="katadasarbaru" onkeyup="count_katdas(this);" placeholder="Masukkan kata dasar baru"> <div class="pull-right"> <span class="text-muted" id="countkatdaschar">0</span> <span class="text-muted">/30 karakter</span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-success"> <i class = "material-icons">save</i> Simpan</button> </div> </div> </form> </div> </div> <!--AKHIR DARI MODAL FORM--> <!-- MODAL FORM HAPUS KATA DASAR--> <div aria-hidden="true" aria-labelledby="modalkatadasarlabel" role="dialog" tabindex="-1" id="deletekatadasarmodal" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>katadasar/deletekatadasar" method="post"> <input type="hidden" name="id_katadasar" id="id_katadasar" value=""> <div class="modal-content"> <div class="modal-body"> <p class="text-center"><strong>PERINGATAN:</strong> <br> Kata yang anda pilih akan terhapus dan tidak dapat dikembalikan lagi.<br> Apakah anda yakin untuk menghapus kata ini?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-danger"> <i class = "material-icons">delete</i> Hapus</button> </div> </div> </form> </div> </div> <!--AKHIR DARI MODAL FORM--> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <script src="<?=base_url()?>assets/js/crud/katadasar.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> <!-- CHARACTER COUNTERS UNTUK INPUT--> <script src="<?=base_url()?>assets/js/countcharacters.js"></script> <!-- FORM VALIDATION--> <script src="<?=base_url()?>assets/js/validation/jquery.validate.js"></script> <script src="<?=base_url()?>assets/js/validation/additional-methods.min.js"></script> <script src="<?=base_url()?>assets/js/validation/formvalidation.js"></script> <!-- TOASTR NOTIFICATIONS--> <script src="<?=base_url()?>assets/js/toastr.js"></script> <?php $notification= $this->session->flashdata('notification'); if(isset($notification)){ if($notification == 'input_kd_success'){ ?> <script> $(document).ready(function(){ toastr.success('Tambah kata dasar baru berhasil.','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification == 'input_kd_error'){ ?> <script> $(document).ready(function(){ toastr.error('Kata gagal tersimpan. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_kd_success'){ ?> <script> $(document).ready(function(){ toastr.success('Edit kata dasar berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_kd_error'){ ?> <script> $(document).ready(function(){ toastr.error('Kata gagal diedit. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='delete_kd_success'){ ?> <script> $(document).ready(function(){ toastr.success('Hapus kata dasar berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification='delete_kd_error'){ ?> <script> $(document).ready(function(){ toastr.error('Kata gagal dihapus. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } } ?> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_Doc_Extraction extends CI_Model{ private $arraykatadasar = array(); private $arraytoken = array(); private $arrayfiltered = array(); private $arraystemmed = array(); /*------------TOKENIZING------------*/ public function tokenizing($review){ $lowercase = strtolower($review); $tokens = preg_replace('/\s+/', ' ', $lowercase); $tokens = preg_replace('/[^a-z \-]/','', $tokens); return $tokens; } /*------------FILTERING------------*/ public function filtering($hasiltoken){ //ubah string ke array $this->arraytoken = explode(" ",$hasiltoken); //ambil stop words dan diubah ke array $this->db->select('kata_stopwords'); $this->db->from('sa_stopwords'); $arraystopwords = $this->db->get()->result_array(); //ubah ke associative array $arraystopwords= array_column($arraystopwords,'kata_stopwords'); //bandingkan dua array $this->arrayfiltered = array_diff($this->arraytoken,$arraystopwords); //ubah hasil filter ke string $hasilfilter = implode(" ",$this->arrayfiltered); return $hasilfilter; } /*------------STEMMING------------*/ public function stemming($hasilfiltered){ //ubah string ke array $this->arrayfiltered = explode(" ",$hasilfiltered); //ambil katadasar words dan diubah ke array $this->db->select('kata_katadasar'); $this->db->from('sa_katadasar'); $arraykatdas = $this->db->get()->result_array(); //ubah ke associative array $this->arraykatadasar = array_column($arraykatdas,'kata_katadasar'); //looping foreach ($this->arrayfiltered as $kataawal){ $term = $kataawal; if(strlen($term)<=3){ //jangan stem kata pendek (di bawah tiga huruf) array_push($this->arraystemmed,$term); continue; } $cekterm = $this->cekterm($term); if($cekterm==true){ array_push($this->arraystemmed, $term); continue; } else{ if(preg_match('/\-/',$term)){ //stem untuk kata ulang $split = explode("-",$term); $katasatu = $split[0]; $katadua = $split[1]; if($katasatu==$katadua){ $term = $katasatu; array_push($this->arraystemmed, $term); continue; } else{ $katasatu = $this->cek_reduplikasi($katasatu); $katadua = $this->cek_reduplikasi($katadua); if($katasatu==$katadua){ array_push($this->arraystemmed, $katasatu); } else{ array_push($this->arraystemmed, $katasatu); array_push($this->arraystemmed, $katadua); } continue; } } $term = $this->del_inf_suff($term); $cekterm = $this->cekterm($term); if($cekterm==true){ array_push($this->arraystemmed, $term); continue; } $term = $this->del_der_suff($term); $cekterm = $this->cekterm($term); if($cekterm==true){ array_push($this->arraystemmed, $term); continue; } $term = $this->del_der_pre($term); $cekterm = $this->cekterm($term); if($cekterm==true){ array_push($this->arraystemmed, $term); continue; } //jika setelah dipotong semua awalan dan akhiran tetap tidak ada //maka kata awal dimasukkan ke array hasil stem array_push($this->arraystemmed, $kataawal); } } $hasilstemming= implode(" ",$this->arraystemmed); return $hasilstemming; } /*------------NAZIEF ADRIANI------------*/ //cek apakah term ada di tabel kata dasar public function cekterm($term){ if(in_array($term,$this->arraykatadasar)){ return true; } else{ return false; } } //hilangkan inflection suffix ("-lah","-kah", "-ku", "-mu", atau "-nya") public function del_inf_suff($term){ $thisterm = $term; if(preg_match('/([km]u|nya|[kl]ah|pun)\z/i',$term)){ $__term = preg_replace('/([km]u|nya|[kl]ah|pun)\z/i','',$term); if(preg_match('/([klt]ah|pun)\z/i',$term)){ if(preg_match('/([km]u|nya)\z/i',$__term)){ $__term__ = preg_replace('/([km]u|nya)\z/i','',$__term); return $__term__; } } return $__term; } return $thisterm; } //cek kombinasi awalan dan akhiran yang dilarang public function cek_restr_presuff($term){ // be- dan -i if(preg_match('/^(be)[[:alpha:]]+(i)\z/i',$term)){ return true; } // di- dan -an if(preg_match('/^(di)[[:alpha:]]+(an)\z/i',$term)){ return true; } // ke- dan -i |-kan if(preg_match('/^(ke)[[:alpha:]]+(i|kan)\z/i',$term)){ return true; } // me- dan -an if(preg_match('/^(me)[[:alpha:]]+(an)\z/i',$term)){ return true; } // se- dan -i |-kan if(preg_match('/^(se)[[:alpha:]]+(i|kan)\z/i',$term)){ return true; } return false; } //hilangkan derivation suffix ("-i","-an" atau "-kan") public function del_der_suff($term){ $thisterm = $term; //hilangkan akhiran "an"|"i" if(preg_match('/(i|an)\z/i',$term)){ $__term = preg_replace('/(i|an)\z/i','',$term); if($this->cekterm($__term)){ return $__term; } } //hilangkan akhiran "-kan" if(preg_match('/(kan)\z/i',$term)){ $__term = preg_replace('/(kan)\z/i','',$term); if($this->cekterm($__term)){ return $__term; } } //jika ada kombinasi awalan dan akhiran yang dilarang, return kata awal if($this->cek_restr_presuff($term)){ return $term; } return $thisterm; } //hilangkan derivation prefix public function del_der_pre($term){ $thisterm = $term; if(strlen($thisterm)>=5){ //jumlah huruf minimal dari kata yang akan dipotong prefiksnya adalah 5 //jika "di-", "ke-" atau "se-" if(preg_match('/^(di|[ks]e)/',$term)){ $__term = preg_replace('/^(di|[ks]e)/','',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "diper-" if(preg_match('/^(diper)/',$term)){ $__term = preg_replace('/^(diper)/','',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "diper-" ada "r" luluh, ditambahkan "r" kembali di depan kata | diperingkas" -> "ringkas" $__term = preg_replace('/^(diper)/','r',$term); if($this->cekterm($__term)){ return $__term; } $__term__ + $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //awalan "be-" "me-", "pe-" atau "te-" if(preg_match('/^([btmp]e)/',$term)){ //awalan "be-" if(preg_match('/^(be)/', $term)){ //jika "ber-" if(preg_match('/^(ber)[aiueo]/',$term)){ //ATURAN 1 berV | ber-V $__term = preg_replace('/^(ber)/','',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "ber-" ada "r" luluh, ditambahkan "r" kembali di depan kata | "berakit" -> "rakit" $__term = preg_replace('/^(ber)/','r',$term); //ATURAN 1 berV.. > ber-V.. | be-rV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "ber-" diikuti huruf konsonan selain "r" dan huruf apa saja lalu partikel selain "er" if(preg_match('/^(ber)[^aiueor][a-z](?!er)/',$term)){ $__term = preg_replace('/^(ber)/','',$term); //ATURAN 2 berCAP.. > ber-CAP.. di mana C!='r' & P!='er' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "ber-" diikuti huruf selain "r" dan partikel "er" lalu huruf vokal if(preg_match('/^(ber)[^r][a-z]er[aiueo]/',$term)){ $__term = preg_replace('/^(ber)/','',$term); //ATURAN 3 berCAerV.. | ber-CAerV.. di mana C!='r' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "belajar" if(preg_match('/\b(belajar)\b/',$term)){ $__term = preg_replace('/^(bel)/','',$term); //ATURAN 4 belajar > bel-ajar if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "ber-" diikuti huruf selain "r","l" dan partikel "er" lalu huruf konsonan if(preg_match('/^(be)[^rl]er[^aiueo]/',$term)){ $__term = preg_replace('/^(be)/','',$term); //ATURAN 5 beC1erC2.. > be-C1erC2.. di mana C1!='r' | 'l' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } } //awalan "te-" if(preg_match('/^(te)/',$term)){ //jika "ter-" diikuti huruf vokal if(preg_match('/^(ter)[aiueo]/',$term)){ $__term = preg_replace('/^(ter)/','',$term); //ATURAN 6 terV.. > ter-V |te-rV if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "ter-" ada "r" luluh, ditambahkan "r" kembali di depan kata | "terawat" -> "rawat" $__term = preg_replace('/^(ter)/','r',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "ter-" diikuti huruf konsonan selain "r" dan partikel "er" lalu huruf vokal if(preg_match('/^(ter)[^aiueor]er[aiueo]/',$term)){ $__term = preg_replace('/^(ter)/','',$term); //ATURAN 7 terCerV.. > ter-CerV.. di mana C!='r' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "ter-" diikuti huruf selain "r" dan partikel selain "er" if(preg_match('/^(ter)[^r](?!er)/',$term)){ $__term = preg_replace('/^(ter)/','',$term); //ATURAN 8 terCP.. > ter-CP.. di mana C!='r' & P!='er' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "te-" diikuti huruf konsonan selain "r" dan partikel "er" lalu huruf konsonan if(preg_match('/^(te)[^aiueor]er[^aiueo]/',$term)){ $__term = preg_replace('/^(te)/','',$term); //ATURAN 9 teC1erC2.. > te-C1erC2.. di mana C!='r' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "te-" diikuti huruf konsonan selain "r" dan partikel "er" lalu huruf konsonan if(preg_match('/^(te)[^aiueor]er[^aiueo]/',$term)){ $__term = preg_replace('/^(ter)/','',$term); //ATURAN 34 terC1erC2.. > ter-C1erC2.. di mana C!='r' if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } } //awalan "me-" if(preg_match('/^(me)/',$term)){ //jika "me-" diikuti huruf "l","r","w","y" dan huruf vokal if(preg_match('/^(me)[lrwy][aiueo]/',$term)){ $__term = preg_replace('/^(me)/','',$term); //ATURAN 10 me{l|r|w|y}V.. > me-{l|r|w|y}V.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "mem-" diikuti huruf "b","f","v" if(preg_match('/^(mem)[bfv]/',$term)){ $__term = preg_replace('/^(mem)/','',$term); //ATURAN 11 mem{b|f|v}.. > mem-{b|f|v}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "mempe-" if(preg_match('/^(mempe)[lr]/',$term)){ $__term = preg_replace('/^(mempe)[lr]/','',$term); //ATURAN 12 mempe{l|r}.. > mempe{l|r}-.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "memper-" ada "r" luluh, ditambahkan "r" kembali di depan kata | "memperumit" -> "rumit" $__term = preg_replace('/^(memper)/','r',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "mem-" diikuti oleh huruf vokal atau huruf "r" if(preg_match('/^(mem)[aiueor]/',$term)){ $__term = preg_replace('/^(me)/','',$term); //ATURAN 13 mem{rV|V}.. > me-m{rV|V}.. | me-p{rV|V}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "mem-" ada "p" luluh, ditambahkan "p" kembali di depan kata | "memutar" -> "putar" $__term = preg_replace('/^(mem)/','p',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } // jika "men-" diikuti huruf "c","j","d","z" if(preg_match('/^(men)[cdjsz]/',$term)){ $__term = preg_replace('/^(men)/','',$term); //ATURAN 14 men{c|d|j|s|z}.. > men-{c|d|j|s|z}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "men-" diikuti oleh huruf vokal if(preg_match('/^(men)[aiueo]/',$term)){ $__term = preg_replace('/^(me)/','',$term); //ATURAN 15 menV.. > me-nV | me-tV .. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "men-" ada "t" luluh, ditambahkan "t" kembali di depan kata | "menarik" -> "tarik" $__term = preg_replace('/^(men)/','t',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } // jika "meng-" diikuti huruf "g","h","q" if(preg_match('/^(meng)[ghq]/',$term)){ $__term = preg_replace('/^(meng)/','',$term); //ATURAN 16 meng{g|h|q}.. > meng-{g|h|q}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } // jika "meng-" diikuti huruf vokal if(preg_match('/^(meng)[aiueo]/',$term)){ $__term = preg_replace('/^(meng)/','',$term); //ATURAN 17 mengV.. > meng-V.. |meng-kV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "meng-" ada "k" luluh, ditambahkan "k" kembali di depan kata | "mengikis" -> "kikis" $__term = preg_replace('/^(meng)/','k',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "meny-" diikuti huruf vokal if(preg_match('/^(meny)[aiueo]/',$term)){ $__term = preg_replace('/^(meny)/','s',$term); //ATURAN 18 menyV.. > meny-sV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "memp-" diikuti huruf vokal apapun selain "e" if(preg_match('/^(memp)[aiuo]/',$term)){ $__term = preg_replace('/^(mem)/','',$term); //ATURAN 19 mempA.. > mem-pA di mana A!='e'.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } } //awalan "pe-" if(preg_match('/^(pe)/',$term)){ //jika "pe-" diikuti huruf "w","y" atau huruf vokal if(preg_match('/^(pe)[wy][aiueo]/',$term)){ $__term = preg_replace('/^(pe)/','',$term); //ATURAN 20 pe{w|y|}V.. > pe-{w|y}V.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "per-" diikuti huruf vokal if(preg_match('/^(per)[aiueo]/',$term)){ $__term = preg_replace('/^(per)/','',$term); //ATURAN 21 perV.. > per-V | pe-rV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "per-" ada "r" luluh, ditambahkan "r" kembali di depan kata | "perantau" -> "rantau" $__term = preg_replace('/^(per)/','r',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "per-" diikuti huruf konsonan selain "r" dan huruf apapun lalu partikel selain "er" if(preg_match('/^(per)[^aiueor]+[a-z]+(?!er)/',$term)){ $__term = preg_replace('/^(per)/','',$term); //ATURAN 22 perCAP.. > per-CAP di mana C!="r" & P!="er" if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "per-" diikuti huruf konsonan selain "r" dan huruf apapun lalu partikel selain "er" if(preg_match('/^(per)[^aiueor][a-z]er[aiueo]/',$term)){ $__term = preg_replace('/^(per)/','',$term); //ATURAN 23 perCAerV.. > per-CAerV di mana C!="r" if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pem-" diikuti "r"huruf vokal atau huruf vokal if(preg_match('/^pemr?[aiueo]/',$term)){ $__term = preg_replace('/^(pe)/','',$term); //ATURAN 25 pem{rV|V}.. > pe-m{rV|V}.. | pe-p{rV|V}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "pem-" ada "p" luluh, ditambahkan "p" kembali di depan kata | "pemprakarsa" -> "prakarsa" $__term = preg_replace('/^(pem)/','p',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pem-" diikuti huruf "b","v" atau huruf vokal if(preg_match('/^(pem)[bfaiueo]/',$term)){ $__term = preg_replace('/^(pem)/','',$term); //ATURAN 24 pem{b|f|V}.. > pem-{b|f|V}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pen-" diikuti huruf "c","d","j","z" if(preg_match('/^(pen)[cdjsz]/',$term)){ $__term = preg_replace('/^(pen)/','',$term); //ATURAN 26 pen{c|d|j|z}.. > pen-{c|d|j|z}.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pen-" diikuti huruf vokal if(preg_match('/^(pen)[aiueo]/',$term)){ $__term = preg_replace('/^(pe)/','',$term); //ATURAN 27 penV.. > pe-nV.. | pe-tV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "pen-" ada "t" luluh, ditambahkan "t" kembali di depan kata | "penonton" -> "tonton" $__term = preg_replace('/^(pen)/','t',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "peng-" diikuti huruf konsonan if(preg_match('/^(peng)[^aiueo]/',$term)){ $__term = preg_replace('/^(peng)/','',$term); //ATURAN 28 pengC.. > peng-C.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "peng-" diikuti huruf vokal if(preg_match('/^(peng)[aiueo]/',$term)){ if(preg_match('/^(peng)[e]/',$term)){ $__term = preg_replace('/^(penge)/','',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } $__term = preg_replace('/^(peng)/','',$term); //ATURAN 29 pengV.. > peng-V.. | peng-kV.. | pengV- jika V="e" if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } //jika setelah "peng-" ada "k" luluh, ditambahkan "k" kembali di depan kata | "pengawal" -> "kawal" $__term = preg_replace('/^(peng)/','k',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "peny-" diikuti huruf vokal if(preg_match('/^(peny)[aiueo]/',$term)){ $__term = preg_replace('/^(peny)/','s',$term); //ATURAN 30 penyV.. > peny-sV.. if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pel-" diikuti huruf vokal & jika "pelajar" if(preg_match('/^(pel)[aiueo]/',$term)){ if(preg_match('/\b(pelajar)\b/',$term)){ $__term = preg_replace('/^(pel)/','',$term); //ATURAN 31 pelV.. > pe-lV.. kecuali pelajar > pel-ajar if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } $__term = preg_replace('/^(pe)/','',$term); if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pe-" diikuti konsonan selain "r","w","y","l","m","n" dan partikel "er" lalu huruf vokal if(preg_match('/^(pe)[^aiueorwylmn]er[aiueo]/',$term)){ $__term = preg_replace('/^(per)/','',$term); //ATURAN 32 peCerV.. > per-erV.. di mana C!= {r|w|y|l|m|n} if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pe-" diikuti konsonan selain "r","w","y","l","m","n" dan partikel selain "er" if(preg_match('/^(pe)[^aiueorwylmn](?!er)/',$term)){ $__term = preg_replace('/^(pe)/','',$term); //ATURAN 33 peCP.. > pe-CP.. di mana P!= "er" if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } //jika "pe-" diikuti konsonan selain "r","w","y","l","m","n" dan partikel selain "er" if(preg_match('/^(pe)[^aiueorwylmn]er[^aiueo]/',$term)){ $__term = preg_replace('/^(pe)/','',$term); //ATURAN 35 peC1erC2.. > pe-CP.. di mana C1!= {r|w|y|l|m|n} if($this->cekterm($__term)){ return $__term; } $__term__ = $this->del_der_suff($__term); if($this->cekterm($__term__)){ return $__term__; } } } } //cek ada tidaknya awalan di-, ke-, se-, te-, be-, me- atau pe- if(preg_match('/^(di|[kstbmp]e)/',$term) == false){ return $term; } } return $thisterm; } //aturan tambahan untuk kata ulang public function cek_reduplikasi($kata){ $term = $this->del_inf_suff($kata); $cekterm = $this->cekterm($term); if($cekterm==true){ return $term; } $term = $this->del_der_suff($term); $cekterm = $this->cekterm($term); if($cekterm==true){ return $term; } $term = $this->del_der_pre($term); $cekterm = $this->cekterm($term); if($cekterm==true){ return $term; } return $kata; } /*------------INSERT BAG OF WORDS KE DATABASE------------*/ public function insertterm($id,$isi){ $hasiltoken = $this->tokenizing($isi); $hasilfilter = $this->filtering($hasiltoken); $hasilstemming = $this->stemming($hasilfilter); //insert ke database $this->db->insert('sa_bagofwords',['id_review'=>$id,'term_tokenized'=>$hasiltoken,'term_filtered'=>$hasilfilter,'term_stemmed'=>$hasilstemming]); } public function editterm($id,$isi){ $hasiltoken = $this->tokenizing($isi); $hasilfilter = $this->filtering($hasiltoken); $hasilstemming = $this->stemming($hasilfilter); //update database $this->db->where('id_review',$id); $this->db->update('sa_bagofwords',['term_tokenized'=>$hasiltoken, 'term_filtered'=>$hasilfilter,'term_stemmed'=>$hasilstemming]); } } ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Auth extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->model('m_authentication'); $this->load->library('form_validation'); } public function index(){ if($this->session->userdata('logged_in')){ redirect ('dashboard'); } $this->load->view('login'); } public function login(){ $username= $this->input->post("username"); $password= $this->input->post("password"); //cek input validation $this->form_validation->set_rules('username','Username','trim|required|max_length[40]'); $this->form_validation->set_rules('password','Password','trim|required|max_length[40]'); if ($this->form_validation->run() == FALSE){ $this->session->set_flashdata('message','Input username atau password tidak valid!'); $this->session->set_flashdata('type','danger'); redirect('/'); } else { $statuslogin = $this->m_authentication->checklogin($username, $password); if($statuslogin){ redirect ('dashboard'); } else{ $this->session->set_flashdata('message','Username atau password salah!'); $this->session->set_flashdata('type','danger'); redirect('/'); } } } public function logout(){ $this->m_authentication->logout(); redirect('auth'); } } ?><file_sep>var url = $("meta[name=url]").attr("content"); function extract_review(){ isi_review = $("#visitor-review").val(); $.ajax({ url: url + "visitor/process_visitor_review/", dataType: "json", type: "POST", data: {'isi_review':isi_review}, success: function(results){ var arr = []; for(var i in results){ arr.push(results[i]); } $('#loader-wrapper').removeClass("loader"); print_analysis_contents(arr); $('#analisis-wrapper').show(); }, error: function(){ $('#loader-wrapper').removeClass("loader"); $('#analisis-wrapper').show(); alert("Tidak dapat memroses hasil analisis."); } }); } function print_analysis_contents(contents){ $("#pos-prob").append(contents[0]); $("#neg-prob").append(contents[1]); $("#visitor-sentimen").append(contents[2]); console.log(contents); } $(document).ready(function(){ var counterZero = '0'; $('.intro-number').text(counterZero); $('.intro-number').waypoint(function() { $('.intro-number').each(function() { var $this = $(this); $({ Counter: 0 }).animate({ Counter: $this.attr('data-stop') }, { duration: 2000, easing: 'swing', step: function(now) { $this.text(Math.ceil(now)); } }); }); this.destroy(); }, { offset: '70%' }); $('#visitor-form').submit(function(e){ var review_text = document.getElementById("visitor-review").value.length; e.preventDefault(); $('#analisis-wrapper').html(''); if(review_text==0 || review_text>7500){ //jika textarea tidak diisi atau isi melebihi 7500 karakter $('#modal-error').modal('show'); } else{ $('#loader-wrapper').addClass("loader"); $('#analisis-wrapper').hide(); $('#analisis-wrapper').load(url+'visitor/display_analisis'); extract_review(); } }); });<file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> </head> <body> <div id="wrapper"> <?php $this->load->view('template');?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header">Dashboard</h2> </div> </div> <!-- CARDS --> <div class="row"> <div class="col-md-3 col-sm-12 col-xs-12"> <div class="panel panel-primary text-center no-border bg-color-blue"> <div class="panel-body"> <i class="material-icons material-icons-5x">library_books</i> <h3 id="jumlah-data-latih"><?php echo $total_traindata; ?></h3> </div> <div class="panel-footer back-footer-blue"> Jumlah Review Data Latih </div> </div> </div> <div class="col-md-3 col-sm-12 col-xs-12"> <div class="panel panel-primary text-center no-border bg-color-green"> <div class="panel-body"> <i class="material-icons material-icons-5x">thumb_up</i> <h3 id="jumlah-data-latih-positif"><?php echo $pos_traindata; ?></h3> </div> <div class="panel-footer back-footer-green"> Review Data Latih Positif </div> </div> </div> <div class="col-md-3 col-sm-12 col-xs-12"> <div class="panel panel-primary text-center no-border bg-color-red"> <div class="panel-body"> <i class="material-icons material-icons-5x">thumb_down</i> <h3 id="jumlah-data-latih-negatif"><?php echo $neg_traindata; ?></h3> </div> <div class="panel-footer back-footer-red"> Review Data Latih Negatif </div> </div> </div> <div class="col-md-3 col-sm-12 col-xs-12"> <div class="panel panel-primary text-center no-border bg-color-brown"> <div class="panel-body"> <i class="material-icons material-icons-5x">library_books</i> <h3 id="jumlah-data-uji"><?php echo $total_testdata; ?></h3> </div> <div class="panel-footer back-footer-brown"> Jumlah Review Data Uji </div> </div> </div> </div> <!-- AKHIR DARI CARDS --> <!--CHART--> <div class="row"> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="panel panel-default text-center no-border"> <div class="panel-heading-small"> Perbandingan Data Latih dan Data Uji </div> <div class="panel-body"> <div id="latih-dan-uji-chart" class="chart"></div> </div> </div> </div> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="panel panel-default text-center no-border"> <div class="panel-heading-small"> Perbandingan Data Latih Positif dan Negatif </div> <div class="panel-body"> <div id="pos-neg-chart" class="chart"></div> </div> </div> </div> </div> <!--AKHIR DARI CHART--> <?php print_r($testing);?> </div> <footer><p class="text-center">Copyright &copy 2017 Sentiment Analysis | All right reserved.</a></p></footer> </div> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- MORRIS JS --> <script src="<?=base_url()?>assets/js//charts/raphael.min.js"></script> <script src="<?=base_url()?>assets/js//charts/morris.min.js"></script> <!-- Custom JS --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> <script src="<?=base_url()?>assets/js/dashboard.js"></script> </body> </html><file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> </head> <body> <div id="wrapper"> <?php $this->load->view('template'); ?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header">Setelah Tokenizing</h2> </div> </div> <div class="row"> <div class="col-md-12 panel panel-default"> <div class="panel-heading text-center"> Tabel Kumpulan Term Setelah Proses Tokenizing </div> <!-- Datatable --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>No.</th> <th width="25%">Judul Review</th> <th>Kumpulan Term Setelah Tokenizing</th> </tr> </thead> </table> </div> </div> </div> <!--Akhir dari datatable --> </div> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis | All right reserved.</a></p></footer> </div> </div> </div> </div> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <script src="<?=base_url()?>assets/js/displayterm/tokenized.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> </body> </html><file_sep><?php class M_Classifier extends CI_Model{ //hitung total review di data latih public function count_total_traindata(){ $this->db->select('id_review'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA LATIH'); $total_traindata = $this->db->count_all_results(); return $total_traindata; } //hitung total review positif di data latih public function count_pos_traindata(){ $this->db->select('id_review'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA LATIH'); $this->db->where('sentimen_review','POSITIF'); $total_pos_traindata = $this->db->count_all_results(); return $total_pos_traindata; } //hitung total review negatif di data latih public function count_neg_traindata(){ $this->db->select('id_review'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA LATIH'); $this->db->where('sentimen_review','NEGATIF'); $total_neg_traindata = $this->db->count_all_results(); return $total_neg_traindata; } //ambil semua term dari semua data latih public function all_terms_traindata(){ $this->db->select('term_stemmed'); $this->db->from('sa_bagofwords'); $this->db->join('sa_review', 'sa_review.id_review = sa_bagofwords.id_review'); $this->db->where('kategori_review','DATA LATIH'); $array_terms = $this->db->get()->result_array(); $array_terms= array_column($array_terms,'term_stemmed'); $all_terms = implode(" ",$array_terms); $all_terms = preg_replace('/\s+/', ' ', $all_terms); $all_terms = trim($all_terms); $array_terms = explode(" ",$all_terms); return $array_terms; } //ambil array semua term dari data latih positif public function array_pos_terms(){ $this->db->select('term_stemmed'); $this->db->from('sa_bagofwords'); $this->db->join('sa_review', 'sa_review.id_review = sa_bagofwords.id_review'); $this->db->where('sa_review.sentimen_review','POSITIF'); $this->db->where('sa_review.kategori_review','DATA LATIH'); $array_pos_terms = $this->db->get()->result_array(); $array_pos_terms= array_column($array_pos_terms,'term_stemmed'); $all_pos_terms = implode(" ",$array_pos_terms); $all_pos_terms = preg_replace('/\s+/', ' ', $all_pos_terms); $all_pos_terms = trim($all_pos_terms); $array_pos_terms = explode(" ",$all_pos_terms); return $array_pos_terms; } //ambil array semua term dari data latih negatif public function array_neg_terms(){ $this->db->select('term_stemmed'); $this->db->from('sa_bagofwords'); $this->db->join('sa_review', 'sa_review.id_review = sa_bagofwords.id_review'); $this->db->where('sa_review.sentimen_review','NEGATIF'); $this->db->where('sa_review.kategori_review','DATA LATIH'); $array_neg_terms = $this->db->get()->result_array(); $array_neg_terms= array_column($array_neg_terms,'term_stemmed'); $all_neg_terms = implode(" ",$array_neg_terms); $all_neg_terms = preg_replace('/\s+/', ' ', $all_neg_terms); $all_neg_terms = trim($all_neg_terms); $array_neg_terms = explode(" ",$all_neg_terms); return $array_neg_terms; } //ambil array semua term yang unik dari semua data latih (vocabulary) public function vocabulary(){ $array_terms = $this->all_terms_traindata(); $vocabulary = array_unique($array_terms); $array_vocabulary = array(); foreach ($vocabulary as $unique_term) { array_push($array_vocabulary,$unique_term); } return $array_vocabulary; } /*---------------------------PROSES TRAINING---------------------------*/ //PRIOR PROBABILITY //prior probability kelas positif public function pos_prior_prob(){ $total_traindata = $this->count_total_traindata(); $pos_traindata = $this->count_pos_traindata(); //prior prob positif = jumlah data latih positif/jumlah semua data latih $pos_prior = $pos_traindata/$total_traindata; return $pos_prior; } //prior probability kelas negatif public function neg_prior_prob(){ $total_traindata = $this->count_total_traindata(); $neg_traindata = $this->count_neg_traindata(); //prior prob negatif = jumlah data latih negatif/jumlah semua data latih $neg_prior = $neg_traindata/$total_traindata; return $neg_prior; } //hitung kemunculan (occurences) term t di data latih positif lalu masukkan nilainya ke dalam array public function get_pos_occurences(){ $array_pos_occs = array(); $vocab = $this->vocabulary(); $array_pos_terms = $this->array_pos_terms(); $array_pos_values = array_count_values($array_pos_terms); foreach ($vocab as $term) { if(isset($array_pos_values[$term])){ $array_pos_occs[] = $array_pos_values[$term]; } else{ $array_pos_occs[] = 0; } } return $array_pos_occs; } //hitung kemunculan (occurences) term t di data latih negatif lalu masukkan nilainya ke dalam array public function get_neg_occurences(){ $array_neg_occs = array(); $vocab = $this->vocabulary(); $array_neg_terms = $this->array_neg_terms(); $array_neg_values = array_count_values($array_neg_terms); foreach ($vocab as $term) { if(isset($array_neg_values[$term])){ $array_neg_occs[] = $array_neg_values[$term]; } else{ $array_neg_occs[] = 0; } } return $array_neg_occs; } //LIKELIHOOD //fungsi untuk menghitung likelihood public function likelihood($term_occ,$total_term_in_cat,$vocabulary_count){ $likelihood = ($term_occ+1)/($total_term_in_cat+$vocabulary_count); $likelihood = log($likelihood); //agar tidak terjadi underflow return $likelihood; } public function training(){ $array_training_terms=array(); $vocab = $this->vocabulary(); $pos_terms_count = count($this->array_pos_terms()); //jumlah semua term di data latih positif $neg_terms_count = count($this->array_neg_terms()); //jumlah semua term di data latih negatif $array_pos_occ = $this->get_pos_occurences(); $array_neg_occ = $this->get_neg_occurences(); $vocab_count = count($vocab); //jumlah semua term di vocabulary for($i=0; $i<$vocab_count; $i++){ //hitung likelihood kelas positif dan negatif untuk setiap term di vocabulary $pos_likelihood = $this->likelihood($array_pos_occ[$i],$pos_terms_count,$vocab_count); $neg_likelihood = $this->likelihood($array_neg_occ[$i],$neg_terms_count,$vocab_count); $array_training_terms[] = array("term"=>$vocab[$i],"pos_occ"=>$array_pos_occ[$i],"neg_occ"=>$array_neg_occ[$i],"pos_likelihood"=>$pos_likelihood, "neg_likelihood"=>$neg_likelihood); } return $array_training_terms; } //insert hasil proses training ke database public function insert_train(){ $this->db->truncate('sa_vocabulary'); $data = $this->training(); $this->db->insert_batch('sa_vocabulary',$data); } /*---------------------------PROSES TESTING---------------------------*/ //hitung total review di data uji public function count_total_testdata(){ $this->db->select('id_review'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA UJI'); $total_testdata = $this->db->count_all_results(); return $total_testdata; } //ambil semua review data uji public function all_test_docs(){ $this->db->select('sa_review.id_review, sa_bagofwords.term_stemmed'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA UJI'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $array_test_docs = $this->db->get()->result_array(); return $array_test_docs; } //ambil semua isi tabel vocabulary (frekuensi kemunculan term dan likelihood) public function all_vocabs(){ $this->db->select('*'); $this->db->from('sa_vocabulary'); $array_all_vocabs = $this->db->get()->result_array(); return $array_all_vocabs; } //normalisasi log posterior probability public function normalize_log($pos,$neg){ $max_val = max($pos,$neg);//cari nilai log terbesar $pos = $max_val/$pos; $neg = $max_val/$neg; $exp_pos = exp($pos); $exp_neg = exp($neg); $pos_prob = $exp_pos/($exp_pos+$exp_neg); $neg_prob = $exp_neg/($exp_pos+$exp_neg); $array_results = array("pos_prob"=>$pos_prob, "neg_prob"=>$neg_prob); return $array_results; } //tentukan kelas sentimen terbaik public function best_class($positive,$negative){ $best_class = "POSITIF"; if($positive<$negative){ $best_class = "NEGATIF"; } return $best_class; } //fungsi naive bayes classifier untuk mengklasifikasikan data uji public function naive_bayes(){ $array_results=array(); $vocab = $this->all_vocabs(); $pos_terms_count = count($this->array_pos_terms()); //jumlah semua term di data latih positif $neg_terms_count = count($this->array_neg_terms()); //jumlah semua term di data latih negatif $vocab_count = count($vocab); //jumlah semua term di vocabulary $array_test_docs = $this->all_test_docs(); //ambil semua review data uji $pos_prior_prob = log($this->pos_prior_prob()); //log dari prior probability kelas positif $neg_prior_prob = log($this->neg_prior_prob()); //log dari prior probability kelas negatif foreach($array_test_docs as $test_doc){ //loop untuk semua review data uji $id = $test_doc["id_review"]; $terms_in_doc = explode(" ", $test_doc["term_stemmed"]); $total_pos_likelihood = 0; $total_neg_likelihood = 0; foreach($terms_in_doc as $term){ $pos_likelihood = 0; $neg_likelihood = 0; $found = false; for($i=0; $i < $vocab_count;$i++){ if($vocab[$i]["term"] == $term){ $pos_likelihood = $vocab[$i]["pos_likelihood"]; $neg_likelihood = $vocab[$i]["neg_likelihood"]; $found= true; break; } } if(!$found){ $pos_likelihood = $this->likelihood(0,$pos_terms_count,$vocab_count); $neg_likelihood = $this->likelihood(0,$neg_terms_count,$vocab_count); } $total_pos_likelihood += $pos_likelihood; $total_neg_likelihood += $neg_likelihood; } //posterior probability kelas positif dokumen C = log(prior probability) + total likelihood $pos_post_prob = $pos_prior_prob + $total_pos_likelihood; //posterior probability kelas negatif dokumen C = log(prior probability) + total likelihood $neg_post_prob = $neg_prior_prob + $total_neg_likelihood; //normalisasi log posterior probability $array_prob = $this->normalize_log($pos_post_prob,$neg_post_prob); $pos_post_prob = $array_prob["pos_prob"]; $neg_post_prob = $array_prob["neg_prob"]; //ambil kelas terbaik (kelas dengan posterior probability tertinggi) $best_class= $this->best_class($pos_post_prob,$neg_post_prob); //masukkan ke array results $array_results[] = array("id_review"=>$id,"pos_post_prob"=>$pos_post_prob, "neg_post_prob"=>$neg_post_prob,"sentimen_datauji"=>$best_class); } return $array_results; } public function insert_datauji(){ $this->db->truncate('sa_datauji'); $data = $this->naive_bayes(); $this->db->insert_batch('sa_datauji',$data); } //isi badge di tabel public function accuracy_badge($predicted,$result){ $badge="<span class='badge bg-gray'>BLM DIKETAHUI</span>"; if(isset($result)){ if($predicted==$result){ $badge="<span class='badge bg-green'>AKURAT</span>"; }else{ $badge="<span class='badge bg-red'>TDK AKURAT</span>"; } } return $badge; } //ambil sentimen asli dan sentimen hasil analisis public function get_sentiments(){ $this->db->select('sa_review.sentimen_review, sa_datauji.sentimen_datauji'); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA UJI'); $this->db->join('sa_datauji', 'sa_datauji.id_review = sa_review.id_review'); $array_all_sentiments = $this->db->get()->result_array(); return $array_all_sentiments; } public function matrix_akurasi(){ $array_sentiments = $this->get_sentiments(); $total_datauji = count($array_sentiments); $true_positives =0; $true_negatives =0; $false_positives =0; $false_negatives =0; foreach($array_sentiments as $sentiment){ if($sentiment["sentimen_review"]=="POSITIF" && $sentiment["sentimen_datauji"]=="POSITIF"){ $true_positives = $true_positives+1; } else if($sentiment["sentimen_review"]=="NEGATIF" && $sentiment["sentimen_datauji"]=="NEGATIF"){ $true_negatives = $true_negatives+1; } else if($sentiment["sentimen_review"]=="POSITIF" && $sentiment["sentimen_datauji"]=="NEGATIF"){ $false_positives = $false_positives+1; } else if($sentiment["sentimen_review"]=="NEGATIF" && $sentiment["sentimen_datauji"]=="POSITIF"){ $false_negatives = $false_negatives+1; } } $akurasi = ($true_positives+$true_negatives)/$total_datauji; //AKURASI :(true positives+true negatives)/total data uji $error_rate = 1- $akurasi; //ERROR-RATE : 1 - akurasi (tingkat kesalahan sistem) $ppv = $true_positives/($true_positives+$false_positives); //POSITIVE PREDICTION VALUE /PRESISI : true positives/(true positives+false positives) $npv = $true_negatives/($true_negatives+$false_negatives); //NEGATIVE PREDICTION VALUE : true negatives/(true negatives+false negatives) $sensitivity = $true_positives/($true_positives+$false_negatives); //SENSITIVITY /RECALL : true positives/(true positives+false negatives) $specificity = $true_negatives/($true_negatives+$false_positives); //SPECIFICITY : true negatives/(true negatives+false positives) $array_data_matriks = array($total_datauji, $true_positives, $true_negatives, $false_positives, $false_negatives, $akurasi, $error_rate, $ppv, $npv, $sensitivity, $specificity); return $array_data_matriks; } /*---------------------------LIHAT SENTIMEN VISITOR---------------------------*/ //bersihkan whitespaces dan ubah ke array public function visitor_clean_space($stemmed_review){ $all_terms = preg_replace('/\s+/', ' ', $stemmed_review); $array_terms = explode(" ",$all_terms); return $array_terms; } //fungsi naive bayes untuk mengklasifikasikan review dari visitor public function naive_bayes_visitor($stemmed_review){ $array_results=array(); $vocab = $this->all_vocabs(); $pos_terms_count = count($this->array_pos_terms()); //jumlah semua term di data latih positif $neg_terms_count = count($this->array_neg_terms()); //jumlah semua term di data latih negatif $vocab_count = count($vocab); //jumlah semua term di vocabulary $array_terms = $this->visitor_clean_space($stemmed_review); //kumpulan term yang diambil berasal dari masukan review visitor $pos_prior_prob = log($this->pos_prior_prob()); //log dari prior probability kelas positif $neg_prior_prob = log($this->neg_prior_prob()); //log dari prior probability kelas negatif $total_pos_likelihood_visitor = 0; $total_neg_likelihood_visitor = 0; foreach($array_terms as $term){ //loop untuk semua term di review visitor $pos_likelihood_visitor =0; $neg_likelihood_visitor =0; $found = false; for($i=0; $i < $vocab_count;$i++){ if($vocab[$i]["term"] == $term){ $pos_likelihood_visitor = $vocab[$i]["pos_likelihood"]; $neg_likelihood_visitor = $vocab[$i]["neg_likelihood"]; $found= true; break; } } if(!$found){ $pos_likelihood_visitor = $this->likelihood(0,$pos_terms_count,$vocab_count); $neg_likelihood_visitor = $this->likelihood(0,$neg_terms_count,$vocab_count); } $total_pos_likelihood_visitor += $pos_likelihood_visitor; $total_neg_likelihood_visitor += $neg_likelihood_visitor; } //posterior probability kelas positif dokumen C = log(prior probability) + total likelihood $pos_post_prob_visitor = $pos_prior_prob + $total_pos_likelihood_visitor; //posterior probability kelas negatif dokumen C = log(prior probability) + total likelihood $neg_post_prob_visitor = $neg_prior_prob + $total_neg_likelihood_visitor; //normalisasi log posterior probability $array_prob = $this->normalize_log($pos_post_prob_visitor,$neg_post_prob_visitor); $pos_post_prob_visitor = $array_prob["pos_prob"]; $neg_post_prob_visitor = $array_prob["neg_prob"]; //ambil kelas terbaik (kelas dengan posterior probability tertinggi) $best_class= $this->best_class($pos_post_prob_visitor,$neg_post_prob_visitor); //masukkan ke array results $array_results = array($pos_post_prob_visitor,$neg_post_prob_visitor,$best_class); return $array_results; } } ?><file_sep><?php $dashboard_active = ""; $train_active = ""; $akurasi_active = ""; $dataset_active = ""; $katadasar_active = ""; $stopwords_active = ""; $termtokenized_active = ""; $termfiltered_active = ""; $termstemmed_active = ""; if(isset($title)){ switch ($title) { case 'dashboard': $dashboard_active = "active-menu"; break; case 'train': $train_active = "active-menu"; break; case 'akurasi': $akurasi_active = "active-menu"; break; case 'dataset': $dataset_active = "active-menu"; break; case 'katadasar': $katadasar_active = "active-menu"; break; case 'stopwords': $stopwords_active = "active-menu"; break; case 'termtokenized': $termtokenized_active = "active-menu"; break; case 'termfiltered': $termfiltered_active = "active-menu"; break; case 'termstemmed': $termstemmed_active = "active-menu"; break; } } ?> <!-- HEADER--> <nav class="navbar navbar-default top-navbar" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><small>Sentiment Analysis</small></a> </div> <ul class="nav navbar-top-links navbar-right user-dropdown"> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false"> <i class="material-icons">perm_identity</i> <?php echo $this->session->userdata('name')?> <i class="material-icons">arrow_drop_down</i> </a> <ul class="dropdown-menu dropdown-user"> <li class="divider"></li> <li><a href="<?=site_url()?>auth/logout"><i class="material-icons">input</i> Logout</a> </li> </ul> <!-- /.dropdown --> </ul> </nav> <!-- AKHIR DARI HEADER--> <!-- SIDEBAR--> <nav class="navbar-default navbar-side" role="navigation"> <div class="sidebar-collapse"> <ul class="nav" id="main-menu"> <li> <a class="<?=$dashboard_active?>" href="<?=site_url()?>dashboard"><i class="material-icons">laptop</i> Dashboard</a> </li> <li> <a class="<?=$dataset_active?>" href="<?=site_url()?>dataset"><i class="material-icons">storage</i> Dataset</a> </li> <li> <a class="<?=$train_active?>" href="<?=site_url()?>train"><i class="material-icons">playlist_play</i> Latih Sistem</a> </li> <li> <a class="<?=$akurasi_active?>" href="<?=site_url()?>akurasi"><i class="material-icons">pie_chart</i> Hitung Akurasi</a> </li> <li> <a class="<?=$katadasar_active?>" href="<?=site_url()?>katadasar"><i class="material-icons">question_answer</i> Kata Dasar</a> </li> <li> <a class="<?=$stopwords_active?>" href="<?=site_url()?>stopwords"><i class="material-icons">feedback</i> Stop Words</a> </li> <li> <a href="#"><i class="material-icons">chat</i> Kumpulan Term<i class="material-icons arrow">arrow_drop_down</i></a> <ul aria-expanded="true" class="nav nav-second-level"> <li> <a class="<?=$termtokenized_active?>" href="<?=site_url()?>displayterm/displaytokenized">1. Setelah Tokenizing</a> </li> <li> <a class="<?=$termfiltered_active?>" href="<?=site_url()?>displayterm/displayfiltered">2. Setelah Filtering</a> </li> <li> <a class="<?=$termstemmed_active?>" href="<?=site_url()?>displayterm/displaystemmed">3. Setelah Stemming</a> </li> </ul> </li> <li> <a href="#myModal" data-toggle="modal"><i class="material-icons">help</i> Tentang</a> </li> </ul> </div> </nav> <!-- AKHIR DARI SIDEBAR--> <!-- MODAL TENTANG --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title text-center" id="labelmodaltentang"><strong>Sentiment Analysis for Movie Reviews in Bahasa</strong></h4> </div> <div class="modal-body text-center"> versi p.1 (prototype) <br> Copyright &copy 2017 Sentiment Analysis <br> All rights reserved </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button> </div> </div> </div> </div> <!--AKHIR DARI MODAL TENTANG--> <file_sep><?php class Akurasi extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('m_cruddataset'); $this->load->model('m_classifier'); $this->load->model('m_displaytable'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'akurasi'; $this->load->view('akurasi',$data); } public function insert_datauji(){ $this->m_classifier->insert_datauji(); } public function tabeltest(){ $query = $this->m_displaytable->displaytabeltest($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['judul_review'], $key['sentimen_review'], $key['pos_post_prob'], $key['neg_post_prob'], $key['sentimen_datauji'], $this->m_classifier->accuracy_badge($key['sentimen_review'],$key['sentimen_datauji']) ]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function displaytabeltest(){ $this->load->view('tabeltest'); } public function matrix_akurasi(){ $array_data_matrix = $this->m_classifier->matrix_akurasi(); echo json_encode($array_data_matrix); } } ?><file_sep><!DOCTYPE HTML> <html> <head> <title>Halaman Login</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> </head> <body class="body-color"> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-panel panel panel-default"> <div class="panel-heading text-center"> <h4 class="panel-title">Login Administrator</h4> </div> <div class="panel-body"> <form role="form" action ="<?=site_url()?>auth/login" method="POST"> <?php if($this->session->flashdata('message') != null) { echo '<div class="alert alert-'.$this->session->flashdata('type').'" role="alert">'; echo '<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>'; echo $this->session->flashdata('message') <> '' ? $this->session->flashdata('message') : ''; echo '</div>'; } ?> <div class="form-group has-feedback"> <span class="form-control-feedback"> <i class="material-icons">account_circle</i> </span> <input class="form-control" placeholder="Username" name="username" type="text" autofocus> </div> <div class="form-group has-feedback"> <span class="form-control-feedback"> <i class="material-icons">https</i> </span> <input class="form-control" placeholder="<PASSWORD>" name="password" type="<PASSWORD>" autofocus> </div> <br> <button type="submit" class="btn btn-lg btn-login btn-block">Login</button> </form> </div> </div> <!-- FOOTER--> <footer><p class="text-center copyright">&copyCopyright Sentiment Analysis.id <br> All right reserved.</a></p></footer> </div> </div> </div> <!--SCRIPTS--> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Katadasar extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_displaytable'); $this->load->model('m_crudkatadasar'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'katadasar'; $this->load->view('katadasar', $data); } public function kata(){ $query = $this->m_displaytable->displaykatadasar($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['kata_katadasar'], '<button data-target="#modalkatadasar" data-toggle="modal" class="btn btn-circle btn-default btn-edit" data-id="'.$key['id_katadasar'].'"><i class="material-icons">edit</i></button> <button data-target="#deletekatadasarmodal" data-toggle="modal" data-id="'.$key['id_katadasar'].'" class="btn btn-circle btn-danger btn-delete"><i class="material-icons">delete</i></button>' ]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function ambilkata(){ $id_katadasar = $this->input->post('id'); $data = $this->m_displaytable->fetchkatadasar($id_katadasar); echo json_encode($data); } public function inputkatadasar(){ $katabaru = $this->input->post('katadasarbaru'); $input_katadasar_baru = $this->m_crudkatadasar->inputkatadasar($katabaru); if($input_katadasar_baru){ $this->session->set_flashdata('notification','input_kd_success'); } else{ $this->session->set_flashdata('notification','input_kd_error'); } redirect('katadasar'); } public function editkatadasar(){ $kata = $this->input->post('katadasarbaru'); $idkatadasar = $this->input->post('id_katadasar'); $edit_katadasar = $this->m_crudkatadasar->editkatadasar($kata,$idkatadasar); if($edit_katadasar){ $this->session->set_flashdata('notification','edit_kd_success'); } else{ $this->session->set_flashdata('notification','edit_kd_error'); } redirect('katadasar'); } public function deletekatadasar(){ $idkatadasar = $this->input->post('id_katadasar'); $hapus_katadasar = $this->m_crudkatadasar->deletekatadasar($idkatadasar); if($hapus_katadasar){ $this->session->set_flashdata('notification','delete_kd_success'); } else{ $this->session->set_flashdata('notification','delete_kd_error'); } redirect('katadasar'); } } ?><file_sep> <!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="url" content="<?=base_url()?>" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" href="<?=base_url()?>assets/css/material-icons.css"> <link rel="stylesheet" href="<?=base_url()?>assets/css/visitor/visitor.css"> <link rel="stylesheet" href="<?=base_url()?>assets/css/visitor/font-awesome.min.css"> </head> <body id="top-page" data-spy="scroll" data-target=".navbar-fixed-top"> <!--NAVBAR--> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header page-scroll"> <button class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="#top-page">SENTIMENT ANALYSIS</a> </div> <div class="collapse navbar-collapse navbar-right sa-navbar" id="navbar-collapse"> <ul class="nav navbar-nav"> <li class="hidden"> <a class="page-scroll" href="#top-page"></a> </li> <li> <a class="page-scroll" href="#intro">Intro</a> </li> <li> <a class="page-scroll" href="#analisis">Analisis Sentimen</a> </li> <li> <a class="page-scroll" href="#about">Tentang</a> </li> </ul> <a class="btn btn-primary navbar-btn" href="https://github.com/hadisub/skripsi.git/fork" target="_blank"><i class="fa fa-github"></i> Fork di Github</a> </div> </div> </nav><!--AKHIR DARI NAVBAR --> <!--INTRO--> <div class="jumbotron sa-jumbotron text-center" id="jumbo"> <div class="container jumbo-vertical-center"> <h1>Sistem Analisis Sentimen <br> Review Film</h1> <p>Ini adalah versi publik dari sistem analisis sentimen review film. Sistem ini dapat memberi anda informasi tentang sentimen dari review film yang anda masukkan. Sentimen dari review anda dapat berupa sentimen positif atau negatif. </p> </div> <a class="btn btn-lg btn-primary page-scroll" href="#analisis">Masukkan Review Anda</a> </div> <div class="intro" id="intro"> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-4 intro-container"> <i class="icon material-icons">library_books</i> <div class="intro-wrapper"> <p class="intro-number" data-stop="<?php echo $total_traindata;?>"><?php echo $total_traindata;?></p> <p class="intro-text">Total Review Film</p> </div> </div> <div class="col-md-4 col-sm-4 intro-container"> <i class="icon material-icons">thumb_up</i> <div class="intro-wrapper"> <p class="intro-number" data-stop="<?php echo $pos_traindata;?>"><?php echo $neg_traindata;?></p> <p class="intro-text">Review Positif</p> </div> </div> <div class="col-md-4 col-sm-4 intro-container"> <i class="icon material-icons">thumb_down</i> <div class="intro-wrapper"> <p class="intro-number" data-stop="<?php echo $neg_traindata;?>"><?php echo $neg_traindata;?></p> <p class="intro-text">Review Negatif</p> </div> </div> </div> </div> </div> <!--ANALISIS SENTIMEN--> <div class="analisis" id="analisis"> <p class="analisis-title">ANALISIS SENTIMEN</p> <div class="container" style="width:80%;"> <form id="visitor-form"> <div class="form-group"> <textarea type="text" id="visitor-review" name="visitor-review" class="form-control textarea" rows="8" onkeyup="count_visitor_review(this);" spellcheck="false" placeholder="Ketik atau paste review di sini..."></textarea> <div class="text-right"> <span class="text-muted" id="count-visitor-review">0</span> <span class="text-muted">/7500 karakter</span> </div> </div> <button class="btn btn-lg btn-secondary" id="visitor-btn" type="submit">LIHAT SENTIMEN</button> </form> <div id="loader-wrapper"></div> <div id="analisis-wrapper"> <!--HASIL ANALISIS DIMUAT DI SINI--> </div> </div> </div> <!--TENTANG--> <div class="about" id="about"> <div class="container about-container"> <div class="rov"> <div class="col-sm-4 col=md-4"> <div class="about-title"> <h3>LIBRARIES</h3> </div> <div class="about-wrapper"> <p><a class="link" href="https://jquery.com">JQuery</a></p> <p><a class="link" href="http://imakewebthings.com/waypoints">Waypoints</a></p> <p><a class="link" href="http://gsgd.co.uk/sandbox/jquery/easing/">JQuery Easing</a></p> </div> </div> <div class="col-sm-4 col=md-4"> <div class="about-title"> <h3>TAUTAN</h3> </div> <div class="about-wrapper"> <a class="social-icon icon-twitter" href="https://twitter.com"><i class="fa fa-twitter"></i></a> <a class="social-icon icon-email" href="mailto:<EMAIL>"><i class="fa fa-envelope-o"></i></a> <a class="social-icon icon-facebook" href="https://facebook.com"><i class="fa fa-facebook"></i></a> <a class="social-icon icon-instagram" href="https://instagram.com"><i class="fa fa-instagram"></i></a> <a class="social-icon icon-github" href="https://github.com/hadisub" target="_blank"><i class="fa fa-github"></i></a> </div> </div> <div class="col-sm-4 col-md-4"> <div class="about-title"> <h3>TENTANG NAIVE BAYES</h3> </div> <div class="about-wrapper about-us"> <p>Sistem Analisis Sentimen Review Film menggunakan metode Naive Bayes untuk menghitung probabilitas review film yang diberikan. Deskripsi metode Naive Bayes lebih lengkap dapat dilihat di <a class="link-bootstrap"href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">tautan berikut.</a></p> </div> </div> </div> </div> </div> <footer class="footer" id="footer"> <p class="footer-text">&copy Copyright Sentiment Analysis. All rights reserved</br> Powered by <a class="link-bootstrap" href="http://getbootstrap.com">Bootstrap</a></p> </footer> <!--MODAL WARNING--> <div class="modal fade text-center" id="modal-error" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">ERROR</h4> </div> <div class="modal-body"> <p>Review harus diisi dan tidak boleh berisi lebih dari 7500 karakter.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button> </div> </div> </div> </div> <!--SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.js"></script> <script src="<?=base_url()?>assets/js/bootstrap.min.js"></script> <script src="<?=base_url()?>assets/js/visitor/jquery.easing.min.js"></script> <script src="<?=base_url()?>assets/js/visitor/scroll.js"></script> <script src="<?=base_url()?>assets/js/visitor/jquery.waypoints.js"></script> <script src="<?=base_url()?>assets/js/visitor/visitor-scripts.js"></script> <!-- CHARACTER COUNTERS UNTUK TEXTAREA REVIEW VISITOR --> <script src="<?=base_url()?>assets/js/countcharacters.js"></script> <!-- FORM VALIDATION--> <script src="<?=base_url()?>assets/js/validation/jquery.validate.js"></script> <script src="<?=base_url()?>assets/js/validation/additional-methods.min.js"></script> </body> </html> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Visitor extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_doc_extraction'); $this->load->model('m_classifier'); if($this->session->userdata('logged_in')){ redirect ('dashboard'); } } public function index(){ $data['total_traindata'] = $this->m_classifier->count_total_traindata(); $data['pos_traindata'] = $this->m_classifier->count_pos_traindata(); $data['neg_traindata'] = $this->m_classifier->count_neg_traindata(); $this->load->view('visitor/visitor',$data); } public function display_analisis(){ $this->load->view('visitor/visitor-analisis'); } public function process_visitor_review(){ $review = $_POST["isi_review"]; //proses ekstraksi $tokenized = $this->m_doc_extraction->tokenizing($review); $filtered = $this->m_doc_extraction->filtering($tokenized); $stemmed = $this->m_doc_extraction->stemming($filtered); //proses klasifikasi $analysis_results = $this->m_classifier->naive_bayes_visitor($stemmed); echo json_encode($analysis_results); } } ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_Displaytable extends CI_Model { public function fetchreview($id){ $this->db->where('id_review', $id); $this->db->from('sa_review'); return $this->db->get()->row_array(); } public function fetchkatadasar($id){ $this->db->where('id_katadasar', $id); $this->db->from('sa_katadasar'); return $this->db->get()->row_array(); } public function fetchstopwords($id){ $this->db->where('id_stopwords', $id); $this->db->from('sa_stopwords'); return $this->db->get()->row_array(); } public function displaytabeltrain($start, $length, $search_query){ $this->db->like('term', $search_query); $this->db->from('sa_vocabulary'); $this->db->order_by('term','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('term', $search_query); $this->db->from('sa_vocabulary'); $this->db->order_by('term','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_vocabulary'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaytabeltest($start, $length, $search_query){ $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA UJI'); $this->db->join('sa_datauji', 'sa_datauji.id_review = sa_review.id_review'); $this->db->order_by('judul_review','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->where('kategori_review','DATA UJI'); $this->db->join('sa_datauji', 'sa_datauji.id_review = sa_review.id_review'); $this->db->order_by('judul_review','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_review'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaydataset($start, $length, $search_query){ $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->order_by('judul_review','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->order_by('judul_review','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_review'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaykatadasar($start, $length, $search_query){ $this->db->like('kata_katadasar', $search_query); $this->db->from('sa_katadasar'); $this->db->order_by('kata_katadasar','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('kata_katadasar', $search_query); $this->db->from('sa_katadasar'); $this->db->order_by('kata_katadasar','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_katadasar'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaystopwords($start, $length, $search_query){ $this->db->like('kata_stopwords', $search_query); $this->db->from('sa_stopwords'); $this->db->order_by('kata_stopwords','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('kata_stopwords', $search_query); $this->db->from('sa_stopwords'); $this->db->order_by('kata_stopwords','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_stopwords'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaytermtokenized($start, $length, $search_query){ $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_review'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaytermfiltered($start, $length, $search_query){ $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_review'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } public function displaytermstemmed($start, $length, $search_query){ $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $totalfilter = $this->db->count_all_results(); $this->db->like('judul_review', $search_query); $this->db->from('sa_review'); $this->db->join('sa_bagofwords', 'sa_bagofwords.id_review = sa_review.id_review'); $this->db->order_by('sa_review.judul_review','ASC'); $this->db->limit($length, $start); $data = $this->db->get()->result_array(); $total = $this->db->count_all_results('sa_review'); return [ "data" => $data, "total" => $total, "result" => $totalfilter ]; } } ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Stopwords extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_displaytable'); $this->load->model('m_crudstopwords'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'stopwords'; $this->load->view('stopwords', $data); } public function kata(){ $query = $this->m_displaytable->displaystopwords($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['kata_stopwords'], '<button data-target="#modalstopwords" data-toggle="modal" class="btn btn-circle btn-default btn-edit" data-id="'.$key['id_stopwords'].'"><i class="material-icons">edit</i></button> <button data-target="#deletestopwordsmodal" data-toggle="modal" data-id="'.$key['id_stopwords'].'" class="btn btn-circle btn-danger btn-delete"><i class="material-icons">delete</i></button>' ]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function ambilkata(){ $id_stopwords = $this->input->post('id'); $data = $this->m_displaytable->fetchstopwords($id_stopwords); echo json_encode($data); } public function inputstopwords(){ $katabaru = $this->input->post('stopwordsbaru'); $input_stopwords_baru = $this->m_crudstopwords->inputstopwords($katabaru); if($input_stopwords_baru){ $this->session->set_flashdata('notification','input_sw_success'); } else{ $this->session->set_flashdata('notification','input_sw_error'); } redirect('stopwords'); } public function editstopwords(){ $kata = $this->input->post('stopwordsbaru'); $idstopwords = $this->input->post('id_stopwords'); $this->load->model('m_crudstopwords'); $edit_stopwords = $this->m_crudstopwords->editstopwords($kata,$idstopwords); if($edit_stopwords){ $this->session->set_flashdata('notification','edit_sw_success'); } else{ $this->session->set_flashdata('notification','edit_sw_error'); } redirect('stopwords'); } public function deletestopwords(){ $idstopwords = $this->input->post('id_stopwords'); $this->load->model('m_crudstopwords'); $hapus_stopwords = $this->m_crudstopwords->deletestopwords($idstopwords); if($hapus_stopwords){ $this->session->set_flashdata('notification','delete_sw_success'); } else{ $this->session->set_flashdata('notification','delete_sw_error'); } redirect('stopwords'); } } ?><file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="url" content="<?=base_url()?>" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/toastr.css"> </head> <body> <div id="wrapper"> <!-- SIDEBAR TOP --> <?php $this->load->view('template'); ?> <!-- AKHIR DARI SIDEBAR --> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header"> Dataset Review Film </h2> </div> </div> <!--BUTTON TAMBAH --> <div class="btn-fixed"> <button data-target="#modaldataset" data-toggle="modal" class="btn btn-primary btn-circle-lg btn-circle btn-circle-lg btn-add"><i class="material-icons material-icons-2x">note_add</i></button> </div> <!--TABEL--> <div class="row"> <div class="col-md-12 panel panel-default"> <div class="panel-heading text-center"> Tabel Dataset Review Film </div> <!-- Datatable --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>No.</th> <th width="25%">Judul</th> <th>Sentimen</th> <th>Kategori</th> <th width="30%">Isi Review</th> <th>Tindakan</th> </tr> </thead> </table> </div> </div> <!-- Akhir dari datatable --> </div> </div> <!-- FOOTER--> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis.id | All right reserved.</a></p></footer> </div> <!-- PAGE INNER --> </div> <!-- PAGE WRAPPER --> </div> <!-- MODAL FORM TAMBAH DAN EDIT REVIEW--> <div aria-hidden="true" aria-labelledby="modaldatasetlabel" role="dialog" tabindex="-1" id="modaldataset" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>dataset/inputdataset" method="post" id="formdataset"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" class="close" type="button">&times;</button> <h4 class="modal-title text-center"><span class="modal-action">Tambah</span> Data Review</h4> </div> <div class="modal-body"> <input type="hidden" name="id_review" id="id_review" value=""> <div class="form-group"> <label for="judulreview">Judul Review</label> <input type="text" class="form-control" id="judulreview" name="judulreview" placeholder="Masukkan judul review"> </div> <div class="form-group"> <label for="teksreview">Isi Review</label> <textarea id="teksreview" name="teksreview" class="form-control" rows="6" onkeyup="count_review(this);" placeholder="Masukkan atau paste review film di sini"></textarea> <div class="pull-right"> <span class="text-muted" id="countreviewchar">0</span> <span class="text-muted">/7500 karakter</span> </div> </div> <div class="form-group"> <label for="kategori">Kategori</label> <select class="form-control text-left" name="kategori"> <option value="DATA LATIH">DATA LATIH</option> <option value="DATA UJI">DATA UJI</option> </select> </div> <div class="form-group"> <label for="sentimenawal">Sentimen</label> <select class="form-control text-left" name="sentimenawal"> <option value="POSITIF">POSITIF</option> <option value="NEGATIF">NEGATIF</option> </select> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-success"> <i class = "material-icons">save</i> Simpan</button> </div> </div> </form> </div> </div> <!--AKHIR DARI MODAL FORM--> <!-- MODAL FORM HAPUS DATASET--> <div aria-hidden="true" aria-labelledby="modaldatasetlabel" role="dialog" tabindex="-1" id="deletereviewmodal" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>dataset/deletedataset" method="post"> <input type="hidden" name="id_review" id="id_review" value=""> <div class="modal-content"> <div class="modal-body"> <p class="text-center"><strong>PERINGATAN:</strong> <br> Review yang anda pilih akan terhapus dan tidak dapat dikembalikan lagi.<br> Apakah anda yakin untuk menghapus review ini?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-danger"> <i class = "material-icons">delete</i> Hapus</button> </div> </div> </form> </div> </div> <!--AKHIR DARI OF MODAL FORM--> <!--SCRIPTS--> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <script src="<?=base_url()?>assets/js/crud/dataset.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> <!-- CHARACTER COUNTERS UNTUK TEXTAREA REVIEW--> <script src="<?=base_url()?>assets/js/countcharacters.js"></script> <!-- FORM VALIDATION--> <script src="assets/js/validation/jquery.validate.js"></script> <script src="assets/js/validation/additional-methods.min.js"></script> <script src="assets/js/validation/formvalidation.js"></script> <!-- TOASTR NOTIFICATIONS--> <script src="<?=base_url()?>assets/js/toastr.js"></script> <?php $notification= $this->session->flashdata('notification'); if(isset($notification)){ if($notification == 'input_review_success'){ ?> <script> $(document).ready(function(){ toastr.success('Tambah review film berhasil.','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification == 'input_review_error'){ ?> <script> $(document).ready(function(){ toastr.error('Review film gagal tersimpan. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_review_success'){ ?> <script> $(document).ready(function(){ toastr.success('Edit review film berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_review_error'){ ?> <script> $(document).ready(function(){ toastr.error('Review film gagal diedit. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='delete_review_success'){ ?> <script> $(document).ready(function(){ toastr.success('Hapus review film berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification='delete_review_error'){ ?> <script> $(document).ready(function(){ toastr.error('Review film gagal dihapus. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } } ?> </body> </html><file_sep><?php class Dashboard extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('m_classifier'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'dashboard'; $data['total_traindata'] = $this->m_classifier->count_total_traindata(); $data['pos_traindata'] = $this->m_classifier->count_pos_traindata(); $data['neg_traindata'] = $this->m_classifier->count_neg_traindata(); $data['total_testdata'] = $this->m_classifier->count_total_testdata(); $data['testing'] = $this->m_classifier->naive_bayes_visitor('gal gadot'); $this->load->view('dashboard',$data); } } ?><file_sep>$(function(){ $.validator.setDefaults({ errorClass:"help-block", highlight: function(element){ $(element).closest(".form-group").addClass("has-error"); }, unhighlight: function(element){ $(element).closest(".form-group").removeClass("has-error"); } }); //DATASET $("#formdataset").validate({ rules:{ judulreview: { required: true, maxlength: 100, }, teksreview: { required: true, maxlength: 7500 } }, messages:{ judulreview:{ required: "Judul review tidak boleh kosong.", maxlength: "Judul review tidak boleh melebihi 100 karakter." }, teksreview: { required: "Isi review tidak boleh kosong.", maxlength: "Isi review tidak boleh melebihi 7500 karakter" } }, submitHandler: function(form){ form.submit(); } }); //KATA DASAR $("#formkatadasar").validate({ rules:{ katadasarbaru: { required: true, maxlength: 30, nowhitespace: true, lettersonly: true } }, messages:{ katadasarbaru: { required: "Kata dasar tidak boleh kosong.", maxlength: "Kata dasar tidak boleh melebihi 30 karakter." } }, submitHandler: function(form){ form.submit(); } }); //STOP WORDS $("#formstopwords").validate({ rules:{ stopwordsbaru: { required: true, maxlength: 30, nowhitespace: true, lettersonly: true } }, messages:{ stopwordsbaru: { required: "Stop words tidak boleh kosong.", maxlength: "Stop words tidak boleh melebihi 30 karakter." } }, submitHandler: function(form){ form.submit(); } }); });<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_Cruddataset extends CI_Model { public function inputdataset($judulreview,$isireview,$kategori,$sentimenawal){ $this->db->insert('sa_review',['judul_review'=>$judulreview, 'isi_review'=>$isireview,'kategori_review'=>$kategori,'sentimen_review'=>$sentimenawal]); return $this->db->insert_id(); } public function deletedataset($idreview){ $delete_review = $this->db->delete('sa_review',['id_review'=>$idreview]); return $delete_review; } public function editdataset($judulreview,$isireview,$kategori,$sentimenawal,$idreview){ $this->db->where('id_review',$idreview); $edit_review = $this->db->update('sa_review',['judul_review'=>$judulreview, 'isi_review'=>$isireview,'kategori_review'=>$kategori,'sentimen_review'=>$sentimenawal]); return $edit_review; } } ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_Authentication extends CI_Model { public function checklogin($username, $password){ $user = $this->db->get_where("sa_user", array("username"=>$username, "password"=>md5($password)))->row_array(); if (count($user)>0){ $logindata = array( 'id' => $user["id"], 'name' => $user["nama"], 'logged_in' => TRUE); $this->session->set_userdata($logindata); return true; } else{ return false; } } public function logout (){ $this->session->unset_userdata(array("username","id", 'logged_in')); } } ?><file_sep>var url = $("meta[name=url]").attr("content"); function loadtabel(){ $('#dataTables-example').dataTable({ "language": { "info": "Menampilkan halaman _PAGE_ dari _PAGES_", "sLengthMenu": "_MENU_ review per halaman", "sSearch": "Cari: ", "sNext": "Selanjutnya", "sPrevious": "Sebelumnya" }, "processing": true, "serverSide": true, "ajax": url + "train/tabeltrain" }); } $(document).ready(function () { $('#divtabeltraining').load(url+'train/displaytabeltrain', function(){ //LOAD DATATABLES loadtabel(); }); $('#trainbtn').click(function(){ $('#divtabeltraining').html(''); $('#divtabeltraining').addClass('loader'); //INSERT TERM OCCURENCES $.ajax({ url: url + "train/insert_train", success: function(){ $('#divtabeltraining').removeClass('loader'); }, error: function(){ $('#divtabeltraining').removeClass('loader'); alert('Tidak dapat memperbarui tabel'); } });   $('#divtabeltraining').load(url+'train/displaytabeltrain', function(){ //LOAD DATATABLES loadtabel(); }); }); }); <file_sep><?php class Train extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('m_displaytable'); $this->load->model('m_classifier'); $this->load->model('m_cruddataset'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function index(){ $data['title'] = 'train'; $this->load->view('train',$data); } public function insert_train(){ $this->m_classifier->insert_train(); } public function tabeltrain(){ $query = $this->m_displaytable->displaytabeltrain($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['term'], $key['pos_occ'], $key['neg_occ'], $key['pos_likelihood'], $key['neg_likelihood'] ]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function displaytabeltrain(){ $this->load->view('tabeltrain'); } } ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_Crudkatadasar extends CI_Model { public function inputkatadasar($katabaru){ $insert_katadasar_baru = $this->db->insert('sa_katadasar',['kata_katadasar'=>$katabaru]); return $insert_katadasar_baru; } public function deletekatadasar($idkatadasar){ $delete_katadasar = $this->db->delete('sa_katadasar',['id_katadasar'=>$idkatadasar]); return $delete_katadasar; } public function editkatadasar($katadasar,$idkatadasar){ $this->db->where('id_katadasar',$idkatadasar); $edit_katadasar = $this->db->update('sa_katadasar',['kata_katadasar'=>$katadasar]); return $edit_katadasar; } } ?><file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> </head> <body> <div id="wrapper"> <?php $this->load->view('template'); ?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header">Penghitungan Akurasi Sistem Analisis Sentimen</h2> </div> </div> <!--BUTTON AKURASI--> <div class="btn-fixed"> <button class="btn btn-primary btn-lg" id="akurasibtn"><i class="material-icons material-icons-1-5x">pie_chart</i> Hitung</button> </div> <!--TABEL MULAI DI SINI--> <div id="divtabeltest"> <!--TABEL DIMUAT DI SINI --> </div> <!--TABEL BERAKHIR DI SINI--> </div> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis | All right reserved.</a></p></footer> </div> </div> </div> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <script src="<?=base_url()?>assets/js/akurasi.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> </body> </html><file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> </head> <body> <div id="wrapper"> <?php $this->load->view('template');?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header">Latih Sistem</h2> </div> </div> <!--BUTTON TRAIN DATA --> <div class="btn-fixed"> <button class="btn btn-primary btn-lg" id="trainbtn"><i class="material-icons material-icons-1-5x">playlist_play</i> Latih</button> </div> <!-- TABEL DIMULAI DI SINI--> <div id="divtabeltraining"> <!--TABLE CONTENTS ARE LOADED HERE --> </div> <!--TABEL BERAKHIR DI SINI --> </div> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis | All right reserved.</a></p></footer> </div> </div> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/train.js"></script> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> </body> </html><file_sep><?php class M_Crudstopwords extends CI_Model { public function inputstopwords($katabaru){ $insert_stopwords_baru = $this->db->insert('sa_stopwords',['kata_stopwords'=>$katabaru]); return $insert_stopwords_baru; } public function deletestopwords($idstopwords){ $delete_stopwords = $this->db->delete('sa_stopwords',['id_stopwords'=>$idstopwords]); return $delete_stopwords; } public function editstopwords($stopwords,$idstopwords){ $this->db->where('id_stopwords',$idstopwords); $edit_stopwords = $this->db->update('sa_stopwords',['kata_stopwords'=>$stopwords]); return $edit_stopwords; } } ?><file_sep><?php class Displayterm extends CI_Controller{ function __construct() { parent::__construct(); $this->load->model('m_displaytable'); if(!$this->session->userdata('logged_in')){ redirect ('/'); } } public function displaytokenized(){ $data['title'] = 'termtokenized'; $this->load->view('termtokenized', $data); } public function displayfiltered(){ $data['title'] = 'termfiltered'; $this->load->view('termfiltered', $data); } public function displaystemmed(){ $data['title'] = 'termstemmed'; $this->load->view('termstemmed', $data); } //fungsi untuk menampilkan tabel public function tabeltokenized(){ $query = $this->m_displaytable->displaytermtokenized($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['judul_review'], $key['term_tokenized']]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function tabelfiltered(){ $query = $this->m_displaytable->displaytermtokenized($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['judul_review'], $key['term_filtered']]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } public function tabelstemmed(){ $query = $this->m_displaytable->displaytermstemmed($_GET['start'], $_GET['length'], $_GET['search']['value']); $no = $this->input->get('start')+1; $allData = []; foreach ($query['data'] as $key) { $allData[] = [ $no++, $key['judul_review'], $key['term_stemmed']]; } $data = [ "draw" => $_GET['draw'], "recordsTotal" => $query['total'], "recordsFiltered" => $query['result'], "data" => $allData ]; echo json_encode($data); } } ?><file_sep><!DOCTYPE html> <html> <head> <title>Sentiment Analysis</title> <meta charset="utf-8" /> <meta name="url" content="<?=base_url()?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="<?=base_url()?>assets/img/sa.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/styles.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/material-icons.css"> <link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/toastr.css"> </head> <body> <div id="wrapper"> <!-- SIDEBAR TOP --> <?php $this->load->view('template'); ?> <!-- AKHIR DARI SIDEBAR --> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 class="page-header"> Stop Words Review Film </h2> </div> </div> <!--BUTTON TAMBAH --> <div class="btn-fixed"> <button a href="#modalstopwords" data-toggle ="modal" class="btn btn-circle btn-circle-lg btn-primary btn-add text-right"><i class="material-icons material-icons-2x">playlist_add</i></button> </div> <div class="row"> <div class="col-md-12 panel panel-default"> <div class="panel-heading text-center"> Tabel Kumpulan Kata-Kata yang Dapat Dihilangkan (Stop Words) </div> <!-- Datatable --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>No.</th> <th>Kata</th> <th>Tindakan</th> </tr> </thead> </table> </div> </div> </div> <!--Akhir dari datatable --> </div> </div> <!-- FOOTER--> <footer><p class="text-center">Copyright &copy 2016 Sentiment Analysis | All right reserved.</a></p></footer> </div> </div> <!--PAGE INNER --> </div> <!--PAGE WRAPPER --> <!-- MODAL FORM TAMBAH DAN EDIT STOP WORDS--> <div aria-hidden="true" aria-labelledby="modalstopwordlabel" role="dialog" tabindex="-1" id="modalstopwords" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>stopwords/inputstopwords" method="post" id="formstopwords"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" class="close" type="button">&times;</button> <h4 class="modal-title text-center"><span class="modal-action">Tambah</span> Stop Words</h4> </div> <div class="modal-body"> <input type="hidden" name="id_stopwords" id="id_stopwords" value=""> <div class="form-group"> <label for="stopwordsbaru">Stop Words</label> <input type="text" class="form-control" id="stopwordsbaru" name="stopwordsbaru" onkeyup="count_stopwords(this);" placeholder="Masukkan stop words baru"> <div class="pull-right"> <span class="text-muted" id="countstopwordschar">0</span> <span class="text-muted">/30 karakter</span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-success"> <i class = "material-icons">save</i> Simpan</button> </div> </div> </form> </div> </div> <!--AKHIR DARI MODAL FORM--> <!-- MODAL FORM HAPUS STOP WORDS--> <div aria-hidden="true" aria-labelledby="modalstopwordslabel" role="dialog" tabindex="-1" id="deletestopwordsmodal" class="modal fade" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <form role="form" action="<?=site_url()?>stopwords/deletestopwords" method="post"> <input type="hidden" name="id_stopwords" id="id_stopwords" value=""> <div class="modal-content"> <div class="modal-body"> <p class="text-center"><strong>PERINGATAN:</strong> <br> Kata yang anda pilih akan terhapus dan tidak dapat dikembalikan lagi.<br> Apakah anda yakin untuk menghapus kata ini?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button> <button type="submit" class="btn btn-danger"> <i class = "material-icons">delete</i> Ya</button> </div> </div> </form> </div> </div> <!--AKHIR DARI MODAL FORM--> <!-- SCRIPTS --> <script type="text/javascript" src="<?=base_url()?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?=base_url()?>assets/js/bootstrap.js"></script> <!-- DATA TABLE SCRIPTS --> <script src="<?=base_url()?>assets/js/dataTables/jquery.dataTables.js"></script> <script src="<?=base_url()?>assets/js/dataTables/dataTables.bootstrap.js"></script> <script src="<?=base_url()?>assets/js/crud/stopwords.js"></script> <!-- METIS MENU SCRIPTS--> <script src="<?=base_url()?>assets/js/jquery.metisMenu.js"></script> <!-- Custom Js --> <script src="<?=base_url()?>assets/js/custom-scripts.js"></script> <!-- CHARACTER COUNTERS FOR INPUT--> <script src="<?=base_url()?>assets/js/countcharacters.js"></script> <!-- FORM VALIDATION--> <script src="assets/js/validation/jquery.validate.js"></script> <script src="assets/js/validation/additional-methods.min.js"></script> <script src="assets/js/validation/formvalidation.js"></script> <!-- TOASTR NOTIFICATIONS--> <script src="<?=base_url()?>assets/js/toastr.js"></script> <?php $notification= $this->session->flashdata('notification'); if(isset($notification)){ if($notification == 'input_sw_success'){ ?> <script> $(document).ready(function(){ toastr.success('Tambah stop word baru berhasil.','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification == 'input_sw_error'){ ?> <script> $(document).ready(function(){ toastr.error('Stop word gagal tersimpan. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_sw_success'){ ?> <script> $(document).ready(function(){ toastr.success('Edit stop word berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='edit_sw_error'){ ?> <script> $(document).ready(function(){ toastr.error('Stop word gagal diedit. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification=='delete_sw_success'){ ?> <script> $(document).ready(function(){ toastr.success('Hapus stop word berhasil','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } else if($notification='delete_sw_error'){ ?> <script> $(document).ready(function(){ toastr.error('Stop word gagal dihapus. Silahkan coba kembali','',{closeButton: true, positionClass: "toast-top-center", timeOut:2000, showMethod:"fadeIn", hideMethod:"fadeOut"}); }); </script> <?php } } ?> </body> </html>
00acc0ad62c6580b2f4d1d9d5aa43da6f54c96e2
[ "JavaScript", "PHP" ]
30
PHP
hadisub/sentimentanalysis
b848b335b6240f45484239e7218bea84140e9593
74341b94a290d33fc0a990fbcd4f16e94418d681
refs/heads/master
<file_sep><?php $dbhost = "localhost"; $dbname = "pong"; // Database user name. $dbuser = ""; // Database password. $dbpass = ""; ?><file_sep>-- phpMyAdmin SQL Dump -- version 3.4.10.2 -- http://www.phpmyadmin.net -- -- Host: localhost:3306 -- Generation Time: Oct 04, 2013 at 09:25 PM -- Server version: 5.5.33 -- PHP Version: 5.2.6 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `pong` -- -- -------------------------------------------------------- -- -- Table structure for table `help` -- CREATE TABLE IF NOT EXISTS `help` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `onderwerp` tinytext NOT NULL, `uitleg` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='De help bij Pong.' AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `nieuws` -- CREATE TABLE IF NOT EXISTS `nieuws` ( `datum` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `item` text NOT NULL, PRIMARY KEY (`datum`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Nieuwsitems voor de pongsite.'; -- -------------------------------------------------------- -- -- Table structure for table `scores` -- CREATE TABLE IF NOT EXISTS `scores` ( `mens` text NOT NULL, `ai` text NOT NULL, `score` tinytext NOT NULL, `niveau` tinytext NOT NULL, `tijd` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`tijd`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='De scores van spelers.'; /*!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 $theElements = array(); $oldElements = array(); $thisElement = ""; function startElement($parser, $name, $attribs){ global $theElements, $oldElements, $thisElement; array_push($oldElements, $thisElement); $thisElement = $name; $theElements[$thisElement] = ""; } function endElement($parser, $name){ global $oldElements, $thisElement; $thisElement = array_pop($oldElements); } /* * XML CharacterData handler */ function characterData($parser, $text){ global $theElements, $thisElement; $theElements[$thisElement] .= $text; } function unknownXML($parser, $text){ echo "What is this? ( $text )<br/>\n"; } $xml_parser = xml_parser_create(); //specify the different XML handlers... xml_set_default_handler($xml_parser, "unknownXML"); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); $data = $HTTP_RAW_POST_DATA; if( !xml_parse($xml_parser, $data, true) ){ die( "XML error: " . xml_error_string( xml_get_error_code($xml_parser) ). " at line " . xml_get_current_line_number($xml_parser) ); } // save to database... require_once ("../ponfig.php"); require_once ("../../php_lib/db_functions.php"); $human = $theElements["HUMANNAME"]; $ai = $theElements["AINAME"]; $pong_result = $theElements["PONGRESULT"]; $difficulty = $theElements["DIFFICULTY"]; $table = "scores"; $db_connection = dbConnect($dbhost, $dbuser, $dbpass); selectDataBase($db_connection, $dbname); $cols = getColNames(getFields($table, $db_connection)); $query = "INSERT into $table values ( '$human', '$ai', '$pong_result', '$difficulty', NOW() )"; $succes = dbQuery($db_connection, $query); // return results header("Content-type: text/xml"); echo ("<xml><succes>"); if($succes){ echo ("Ja"); } else{ echo ("Nee"); } echo ("</succes></xml>"); xml_parser_free($xml_parser); ?><file_sep>Pong ==== Pong in ActionScript 2, one of my first ActionScript projects back in 2005. You can [play](http://www.ansuz.nl/pong/play/) the game at my [project website](http://www.ansuz.nl/pong/). ###Structure The project is divided into 3 parts: * [as2](https://github.com/wjwarren/pong/tree/master/as2) * [sql](https://github.com/wjwarren/pong/tree/master/sql/) * [website](https://github.com/wjwarren/pong/tree/master/website/) ####AS2 All AS2 code and *.fla files needed to build the *.swf binaries. ####SQL Contains the (My)SQL database schema. ####Website All HTML, PHP, CSS, SWF files and images nedeed to deploy the website. <file_sep><?php require_once ("../php_lib/template_parser.php"); require_once ("ponfig.php"); require_once ("../php_lib/db_functions.php"); //create the header $newpage = new Page("templates/home/home_head.tpl"); $newpage->output(); //create all the news items $db_connection = dbConnect($dbhost, $dbuser, $dbpass); selectDataBase($db_connection, $dbname); $db_query = "SELECT DATE_FORMAT(datum, '%e-%c-%Y'), item FROM nieuws ORDER BY datum DESC"; $result = dbQuery($db_connection, $db_query); while ($row = mysql_fetch_row($result)) { //$tags["datum"] = dbQuery($db_connection, "DATE_FORMAT($row[0], '%e-%c-%Y')"); $tags["datum"] = $row[0]; $tags["bericht"] = $row[1]; $newpage = new Page("templates/home/home_item.tpl"); $newpage->replace_tags($tags); $newpage->output(); } //create the footer $newpage = new Page("templates/home/home_foot.tpl"); $newpage->output(); ?><file_sep><?php require_once ("../../php_lib/template_parser.php"); require_once ("../ponfig.php"); require_once ("../../php_lib/db_functions.php"); //create the header $newpage = new Page("../templates/scores/scores_head.tpl"); $newpage->output(); //create all the scores $db_connection = dbConnect($dbhost, $dbuser, $dbpass); selectDataBase($db_connection, $dbname); $cols = array("tijd", "speler", "ai", "score", "niveau"); $sort_col = getSort($cols); $result_sort = getSortType(); $db_query = "SELECT * FROM scores ORDER BY " . $sort_col . " " . $result_sort; $result = dbQuery($db_connection, $db_query); while ($row = mysql_fetch_row($result)) { $tags["mens"] = $row[0]; $tags["ai"] = $row[1]; $tags["score"] = $row[2]; $tags["niveau"] = $row[3]; $newpage = new Page("../templates/scores/scores_row.tpl"); $newpage->replace_tags($tags); $newpage->output(); } //create the footer $newpage = new Page("../templates/scores/scores_foot.tpl"); $newpage->output(); ?>
fb3d07d9f15ad025a3ba0933c4ebf68f16af3fed
[ "Markdown", "SQL", "PHP" ]
6
PHP
wjwarren/pong
0e61ba2672b4128ef4e4c7d106f00f348b3919a8
60f33c8990a24fb436e3a1f7ed44f5746b83bbfe
refs/heads/master
<repo_name>adeskmr/CMPS-160<file_sep>/Adesh_Kumar_assingment_5/prog/main.js /** * Function called when the webpage loads. */ var gl; var canvas; var boolean = false; var scene; var shape_size; var RGB = []; //point color for next point, [R G B A] var tShader = null; var program; var objProgram;//MADE BOTH SHADER PROGRAMS GLOBAL var texture; var ModesEnum = Object.freeze({ "fan":1, "elements": 2 }) var MatrixEnum = Object.freeze({ "projection":1, "orthogonal": 2 }) function main() { // Retrieve <canvas> element canvas = document.getElementById('webgl'); // Get the rendering context for WebGL gl = getWebGLContext(canvas); if(!gl) { console.log('Failed to get rendering context'); return; } gl.clearColor(0, 0, .2, 1.0); gl.enable(gl.DEPTH_TEST); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); resize(canvas); tShader = createShader(gl, ASSIGN4_VSHADER_TEXTURE, ASSIGN4_FSHADER_TEXTURE); objProgram = createShader(gl, OBJ_VSHADER, OBJ_FSHADER);//CREATED ADDITIONAL SHADER PROGRAM scene = new Scene() scene.camera = new Camera(false) //false for orth //calls the eventFunction.js initEventHandelers(); tick(); } function resize(canvas) { console.log("size1"); // Lookup the size the browser is displaying the canvas. var displayWidth = window.innerWidth; var displayHeight = window.innerHeight; console.log(displayWidth) // Check if the canvas is not the same size. // Make the canvas the same size canvas.width = displayWidth; canvas.height = displayHeight; console.log("work") console.log('Resized canvas to ' + canvas.width + ', ' + canvas.height); } <file_sep>/Adesh_Kumar_Assignment_7/prog/geometries/square.js /** * Specifies a Square. A subclass of Geometry. * * @author "<NAME>" * @this {Square} */ class Square extends Geometry { /** * Constructor for Square. * * @constructor * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ constructor(size, centerX, centerY) { super(); this.generateSquareVerticesWithNormals(size, centerX, centerY); // this.modelMatrix.setScale(this.size, 1, this.size); // Recommendations: Remember that Square is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the square. * * @private * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ generateSquareVerticesWithNormals(size, centerX, centerY) { function vecs_of_flat_arr(arr, n) { let ret = []; for (let i = 0; i < arr.length / n; i++) { let vec = []; for (let j = 0; j < n; j++) { vec.push(arr[i * n + j]); } ret.push(vec); } return ret; } var squareVertex1 = new Vertex(); squareVertex1.points.push(centerX - size, centerY, centerX + size); squareVertex1.color.push(0.5, 0.5, 0.5, 1); squareVertex1.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex1); var squareVertex2 = new Vertex(); squareVertex2.points.push(centerX - size, centerY, centerX - size); squareVertex2.color.push(0.5, 0.5, 0.5, 1); squareVertex2.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex2); var squareVertex3 = new Vertex(); squareVertex3.points.push(centerX + size, centerY, centerX + size); squareVertex3.color.push(0.5, 0.5, 0.5, 1); squareVertex3.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex3); var squareVertex4 = new Vertex(); squareVertex4.points.push(centerX - size, centerY, centerX - size); squareVertex4.color.push(0.5, 0.5, 0.5, 1); squareVertex4.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex4); var squareVertex5 = new Vertex(); squareVertex5.points.push(centerX + size, centerY, centerX + size); squareVertex5.color.push(0.5, 0.5, 0.5, 1); squareVertex5.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex5); var squareVertex6 = new Vertex(); squareVertex6.points.push(centerX + size, centerY, centerX - size); squareVertex6.color.push(0.5, 0.5, 0.5, 1); squareVertex6.normal = new Vector3([0, 1, 0]); this.vertices.push(squareVertex6); } } <file_sep>/Adesh_Kumar_Assingment_2/prog/main.js /** * Function called when the webpage loads. */ var gl; var canvas; var boolean = false; var scene; var shape_size; function main() { // Retrieve <canvas> element canvas = document.getElementById('webgl'); // Get the rendering context for WebGL gl = getWebGLContext(canvas); scene = new Scene(gl); // Initialize shaders if (!initShaders(gl, ASSIGN1_VSHADER, ASSIGN1_FSHADER)) { console.log('Failed to intialize shaders.'); return; } //calls the eventFunction.js initEventHandelers(); //sets background to black gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear <canvas> gl.clear(gl.COLOR_BUFFER_BIT); } <file_sep>/Adesh_Kumar_Assingment_2/prog/scene/geometry.js /** * Specifies a geometric object. * * @author "<NAME>" * @this {Geometry} */ class Geometry { /** * Constructor for Geometry. * * @constructor */ constructor() { this.vertices = []; // Vertex objects. Each vertex has x-y-z. this.color = []; // The color of your geometric object } /** * Renders this Geometry within your webGL scene. */ render() { sendAttributeBufferToGLSL(new Float32Array(this.vertices), 3, 'a_Position') tellGLSLToDrawCurrentBuffer(this.vertices.length/3); // Recommendations: sendUniformVec4ToGLSL(), tellGLSLToDrawCurrentBuffer(), // and sendAttributeBufferToGLSL() are going to be useful here. } } <file_sep>/README.md # CMPS-160 <file_sep>/Assingment 3/Adesh_Kumar_Assingment_3/prog/shaders.js // Basic Vertex Shader that receives position and size for each vertex (point). var ASSIGN3_VSHADER = 'attribute vec4 a_Position;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'void main() {\n' + ' gl_Position = u_ModelMatrix * a_Position;\n' + '}\n'; // Basic Fragment Shader that receives a single one color (point). var ASSIGN3_FSHADER = 'precision mediump float;\n' + 'uniform vec4 RGB; \n' + 'void main() {\n' + ' gl_FragColor = RGB;\n' + '}\n'; <file_sep>/Adesh_Kumar_assingment_4/prog/scene/geometry.js /** * Specifies a geometric object. * * @author "<NAME>" * @this {Geometry} */ class Geometry { /** * Constructor for Geometry. * * @constructor */ constructor() { this.vertices = []; // Vertex objects. Each vertex has x-y-z. this.color = []; // The color of your geometric object this.uv = []; this.modelMatrix = new Matrix4(); // Model matrix applied to geometric object this.shader = null; // shading program you will be using to shade this geometry } /** * Renders this Geometry within your webGL scene. */ render() { sendAttributeBufferToGLSL(new Float32Array(this.vertices), 3, 'a_Position'); sendAttributeBufferToGLSL(new Float32Array(this.color), 3, 'RGB'); sendUniformMatToGLSL(this.modelMatrix, 'u_ModelMatrix'); tellGLSLToDrawCurrentBuffer(this.vertices.length/3); // Recommendations: sendUniformVec4ToGLSL(), tellGLSLToDrawCurrentBuffer(), // and sendAttributeBufferToGLSL() are going to be useful here. } /** * Responsible for updating the geometry's modelMatrix for animation. * Does nothing for non-animating geometry. */ updateAnimation() { return; // NOTE: This is just in place so you'll be able to call updateAnimation() // on geometry that don't animate. No need to change anything. } } <file_sep>/Adesh_Kumar_Assingment_2/README.txt Welcome to CMPS 160's assignment 2! This zip file contains the necessary starter code and structure for this assignment. First, lets start with some code reuse recommendations from assignment 1: 1. Reuse eventFunctions.js. Modify it as you see fit for this assignment. Incorperating Scene within eventFunctions.js is highly encouraged. 2. Reuse glslFunctions.js. Two new functions are introduced within this assignment: i. tellGLSLToDrawCurrentBuffer() for drawing the scene on the canvas ii. sendAttributeBufferToGLSL() for sending an array of attribute values to your shaders. Some "skeleton" code can be found in prog. Simply copy that code into your ASG1 file and place the modified ASG1 file in ASG2's prog. 3. Reuse htmlFunctions.js. You might want to include old code EXACTLY where it was in Assignment 1. Second, some code you'll probably need to rewrite: 1. main.js and it's main(). 2. shaders.js with updated shaders. 3. driver.html (NOTE: Might want to use your ASG1 driver.html as a reference) Third, code that has remained the same: 1. The entire lib folder. Last, some new .js files introduced within prog: 1. scene/scene.js: Responsible for managing your WebGL scene 2. scene/geometry.js: Represents a geometric object within you WebGL scene 3. scene/vertex.js: Represents a vertex within a geometric object 4. geometries/circle.js: Represents a circle geometry. 5. geometries/square.js: Represents a square geometry. 6. geometries/triangle.js: Represents a triangle geometry. These new .js files are meant to introduce you to the Scene-Geometry programming paradigm common in most graphics libraries. So let's take a quick look at both Scene and Geometry objects specified within scene.js and geometry.js. Scene: The Scene object's role is to manage the presence of geometry onscreen. What this means is: 1. Adding geometry onto your canvas 2. Clearing all geometry currently on your canvas Recommendations for this assignment: Setting Scene as a global variable is a good idea (considering you will need to interact with it within eventFunctions.js). Initializing it within main() is also a good idea. Geometry: The Geometry object's role is to represent a geometric object onscreen. A geometric object (at this point) is composed of vertices containing the x-y-z coordinates necessary for drawing the Geometry. Recommendations for this Assignment: Object oriented programming is your friend. Limit code reuse by using the "super" keyword. Also remember method overloading is a thing (This is more relevant for future assignments, but I felt it's nice to mention). Circle, Square, and Triangle are SUBCLASSES of Geometry. And with that, you're free to start. Good luck! <file_sep>/Adesh_Kumar _Assignment_6/prog/main.js /** * Function called when the webpage loads. */ var gl; var viewMatrix; var projMatrix; var shader; var scene; var canvas var perspectiveButton; var orthographicButton; var viewMode = "perspective"; var nearSlider; var farSlider; var zoomSlider; var red, green, blue; var catOBJ; var teapotOBJ; var catObject; var teapotObject; var addAnimatedObject = true; var pan = false; var useNormalShader = false; function main() { initEventHandelers(); // Get the rendering context for WebGL gl = getWebGLContext(canvas); if (!gl) { console.log('Failed to get the rendering context for WebGL'); return; } // shader = createShader(gl, VSHADER, FSHADER); // useShader(gl, shader); shader = createShader(gl, VSHADER6, FSHADER6); shaderN = createShader(gl, VSHADER6_N, FSHADER6_N); useShader(gl, shader); scene = new Scene(gl); perspectiveButton.onclick = function (ev) { // console.log("hi"); viewMode = "perspective"; } orthographicButton.onclick = function (ev) { viewMode = "orthographic"; } // Register the event handler to be called on key press document.onkeydown = function(ev){ keydown(ev); }; // Specify the color for clearing <canvas> gl.clearColor(0.2, 0.2, 0.2, 1.0); gl.enable(gl.DEPTH_TEST); // Clear <canvas>` gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); resize(gl.canvas); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); catObject = new LoadedOBJ(catOBJ.text, 2.5, Math.random(), Math.random(), Math.random()); teapotObject = new LoadedOBJ(teapotOBJ.text, 2.5, Math.random(), Math.random(), Math.random()); scene.addGeometry(catObject); scene.addGeometry(teapotObject); loadImage(); tick(); } <file_sep>/Assingment 3/Adesh_Kumar_Assingment_3/prog/geometries/animated/tiltedCube.js /** * Specifies a tilted cube which rotates. * * @author "<NAME>" * @this {TiltedCube} */ class TiltedCube extends Geometry { /** * Constructor for TiltedCube. * * @constructor * @returns {TiltedCube} Geometric object created */ constructor(size, centerX, centerY){ super(); this.size = size; this.centerX = centerX; this.centerY = centerY; this.angle = 0; this.generateCubeVertices(); // Recommendations: Might want to tilt your cube at 30 degrees relative to // the z-axis here. Pretty good tilt that lets us see that it's a cube. } /** * Generates the vertices of TiltedCube. Just a regular cube. * * @private * @param {Number} size The size of the tilted cube. */ generateCubeVertices(){ super.vertices = [this.centerX+this.size, this.centerY+this.size, this.centerX+this.size, this.centerX+this.size, this.centerY-this.size, this.centerX+this.size, this.centerX-this.size, this.centerY-this.size, this.centerX+this.size, this.centerX-this.size, this.centerY-this.size, this.centerX+this.size, this.centerX-this.size, this.centerY+this.size, this.centerX+this.size, this.centerX+this.size, this.centerY+this.size, this.centerX+this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX-this.size, this.centerY+this.size, this.centerX+this.size, this.centerX-this.size, this.centerY-this.size, this.centerX+this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY+this.size, this.centerX-this.size, this.centerX-this.size, this.centerY+this.size, this.centerX+this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY-this.size, this.centerX-this.size, this.centerX+this.size, this.centerY-this.size, this.centerX+this.size, this.centerX+this.size, this.centerY-this.size, this.centerX+this.size, this.centerX+this.size, this.centerY+this.size, this.centerX+this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY+this.size, this.centerX+this.size, this.centerX-this.size, this.centerY+this.size, this.centerX+this.size, this.centerX-this.size, this.centerY+this.size, this.centerX+this.size, this.centerX-this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY+this.size, this.centerX-this.size, this.centerX+this.size, this.centerY-this.size, this.centerX+this.size, this.centerX+this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX-this.size, this.centerX-this.size, this.centerY-this.size, this.centerX+this.size, this.centerX+this.size, this.centerY-this.size, this.centerX+this.size]; super.color = [red.value/255, green.value/255, blue.value/255, 1.0]; // Recommendations: Might want to generate your cube vertices so that their // x-y-z values are combinations of 1.0 and -1.0. Allows you to scale the // the cube to your liking better in the future. } /** * Updates the animation of the TiltedCube. Should make it rotate. */ updateAnimation() { var tranl_origin = new Matrix4(); var scale_tri = new Matrix4(); var cube = new Matrix4(); var tranl_back = new Matrix4(); var newMatrix = new Matrix4(); tranl_back.setTranslate(this.centerX, this.centerY, this.centerX); scale_tri.setRotate(this.angle, 0, 1, 0); cube.setRotate(30, 1, 0, 0); tranl_origin.setTranslate(-this.centerX, -this.centerY, -this.centerX); newMatrix = tranl_origin.multiply(newMatrix); newMatrix = scale_tri.multiply(newMatrix); newMatrix = cube.multiply(newMatrix); newMatrix = tranl_back.multiply(newMatrix); super.modelMatrix = newMatrix; this.angle+=.5; // Recommendations: While your cube will only need to be at the origin, I'd // recommend coding it so it spins in place when placed anywhere on your // canvas. Why? Because you might need to have more than one spinning cube // in different positions on a future assignment ;) // // Keep in mind that no rendering should be done here. updateAnimation()'s // purpose is to update the geometry's modelMatrix and any other variables // related to animation. It should be the case that after I call // updateAnimation() I should be able to call render() elsewhere and have my // geometry complete a frame of animation. } } <file_sep>/Adesh_Kumar_assingment_5/README.txt Welcome to CMPS 160's assignment 4! This zip file contains the necessary starter code and structure for this assignment. First, lets start with some code reuse recommendations from assignment 3: 1. Reuse eventFunctions.js. Modify it as you see fit for this assignment. 2. Reuse glslFunctions.js. Two new functions were introduced: i. create2DTexture() for creating a 2-Dimmensional WebGl texture. ii. send2DTextureToGLSL for sending a 2-Dimmensional WebGl texture to your shaders. Some "skeleton" code can be found in prog. Simply copy that code into your ASG3 file and place the modified ASG3 file in ASG4's prog. 3. Reuse htmlFunctions.js. 4. Reuse reuse all geometry you've constructed so far. 5. geometry.js and scene.js have some changes. Please look into them. You might want to include old code EXACTLY where it was in Assignment 3. Second, some code you'll probably need to rewrite: 1. main.js and it's main(). 2. shaders.js with updated shaders. 3. driver.html (NOTE: Might want to use your ASG3 driver.html as a reference) Third, code that has remained the same: 1. Most of lib. Fourth, a new folder: 1. external: External has some sample OBJ files and textures you can use. Might want to store your OBJ files and textures here. Last, some new .js files introduced within: lib 1. updated-cuon-utils.js: cuon-utils.js has been deprecated in an effort to introduce you guys to using multiple shaders. initShaders() is no longer included and has been replaced with createShader() and useShader(). createShader() creates a WebGL shading program you will want to store within your geometry. useShader() takes that program and allows you to use it when drawing. prog/geometries/animated 1. checkerCube.js: Specifies a tiltedCube which has a checkerboard texture applied to it. 2. texturedCube.js: Specifies a tiltedCube which has any power-of-two texture applied to it. Has different effects on each face. These new .js files are meant to move us into getting started with textured objects! Here are a few pointers when using textures: What is a power-of-two texture? A power-of-two texture is a texture whose dimmensions are 2^n x 2^n for some n >= 0. These textures will always play nice with WebGL. Can I use textures which are not power-of-two textures? Yes. But you must do so in a certain way. When creating the 2D Texture, you must pass gl.CLAMP_TO_EDGE for gl.TEXTURE_WRAP_S and gl.TEXTURE_WRAP_T (this means sending gl.CLAMP_TO_EDGE as wrapSParam and wrapTParam when calling create2DTexture()). This should be what you need to know for this assignment. Good Luck! <file_sep>/Adesh_Kumar_assingment_5/prog/scene/geometry.js /** * Specifies a geometric object. * * @author "<NAME>" * @this {Geometry} */ class Geometry { /** * Constructor for Geometry. * * @constructor */ constructor() { this.spin = 0; this.vertices = []; this.color = [1,1,1,1]; this.modelMatrix = new Matrix4(); this.shader = null; this.data = [] this.uv = [] this.colors = [] } flatData() { //We push all points array to data for (var i = 0; i < this.vertices.length; i++) { this.data.push(Array.prototype.slice.call(this.vertices[i].points.elements)) this.uv.push(Array.prototype.slice.call(this.vertices[i].uv)) this.colors.push(Array.prototype.slice.call(this.vertices[i].color)) } this.data = new Float32Array(this.data.flat()) this.uv = new Float32Array(this.uv.flat()) this.colors = new Float32Array(this.colors.flat()) } render() { useShader(gl, tShader); // sendTextureBufferToGLSL(this.uv_data, 2, "aTextureCoord"); sendAttributeBufferToGLSL(this.uv, 2, 'aTextureCoord', 2, 0); sendAttributeBufferToGLSL(this.data, 3, 'a_Position') sendUniformMatToGLSL(this.modelMatrix.elements, "u_ModelMatrix") console.log(this.modelMatrix.elements) send2DTextureToGLSL(this.texture, 0, 'u_Sampler') if(this instanceof StaticCube) { sendIndicesBufferToGLSL(this.indices) tellGLSLToDrawCurrentBuffer(36, ModesEnum.elements) } else { tellGLSLToDrawCurrentBuffer(this.vertices.length) } } /** * Responsible for updating the geometry's modelMatrix for animation. * Does nothing for non-animating geometry. */ updateAnimation() { return; } } <file_sep>/Assignment 1/Adesh_Kumar_Assignment_1/prog/main.js //<NAME> //<EMAIL> // main.js //CMPS160 /** * Function called when the webpage loads. */ var gl = null; var canvas = null; var boolean = false; var coords = null; var a_Position = null; var a_PointSize = null; // main.js function main() { // Retrieve <canvas> element canvas = document.getElementById('webgl'); // Get the rendering context for WebGL gl = getWebGLContext(canvas); // Initialize shaders if (!initShaders(gl, ASSIGN1_VSHADER, ASSIGN1_FSHADER)) { console.log('Failed to intialize shaders.'); return; } //calls the eventFunction.js initEventHandelers(); // Get the storage location of a_Position a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log('Failed to get the storage location of a_Position'); return; } //sets background to black gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear <canvas> gl.clear(gl.COLOR_BUFFER_BIT); // on mouse down and mouse drag the function click is called drawing the points canvas.onmousemove = function(ev){ if(onmousedrag){ click(ev, gl, canvas, a_Position);} } canvas.onmousedown = function(ev){ onmousedrag = true; click(ev, gl, canvas, a_Position);} canvas.onmouseup = function(ev){ onmousedrag = false; click(ev, gl, canvas, a_Position);} }<file_sep>/Adesh_Kumar_assingment_5/prog/geometries/StaticCube.js /** * Specifies a tilted cube which rotates. * * @author "<NAME>" * @this {TiltedCube} */ class StaticCube extends Geometry { /** * Constructor for TiltedCube. * * @constructor * @returns {TiltedCube} Geometric object created */ constructor(size, centerX, centerY, centerZ, height, textureName) { super() this.size = size this.centerX = centerX this.centerY = centerY this.centerZ = centerZ this.height = height this.indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23, // left ]; this.modelMatrix.setTranslate(this.centerX, this.centerY, this.centerZ) this.modelMatrix.scale(1,this.height,1) this.spin = 0 this.generateCubeVertices() this.generateUVCoordinates() let path = "./"+textureName create2DTexture(path, gl.LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, function (texture) { console.log('4') send2DTextureToGLSL(texture, 0, 'u_Sampler') }) this.flatData() } /** * Generates the vertices of TiltedCube. Just a regular cube. * * @private */ generateCubeVertices() { for (var i = 0; i < 24; i++) { this.vertices[i] = new Vertex() this.vertices[i].color = [Math.random(), Math.random(), Math.random()] } // Front face this.vertices[0].points.elements =[-this.size, -this.size, this.size] this.vertices[1].points.elements =[this.size, -this.size, this.size] this.vertices[2].points.elements =[this.size, this.size, this.size] this.vertices[3].points.elements =[-this.size, this.size, this.size] // Back face this.vertices[4].points.elements =[-this.size, -this.size, -this.size] this.vertices[5].points.elements =[-this.size, this.size, -this.size] this.vertices[6].points.elements =[ this.size, this.size, -this.size] this.vertices[7].points.elements =[ this.size, -this.size, -this.size] // Top face this.vertices[8].points.elements =[-this.size, this.size, -this.size] this.vertices[9].points.elements =[-this.size, this.size, this.size] this.vertices[10].points.elements =[ this.size, this.size, this.size] this.vertices[11].points.elements =[ this.size, this.size, -this.size] // Bottom face this.vertices[12].points.elements =[-this.size, -this.size, -this.size] this.vertices[13].points.elements =[ this.size, -this.size, -this.size] this.vertices[14].points.elements =[ this.size, -this.size, this.size] this.vertices[15].points.elements =[-this.size, -this.size, this.size] // Right face this.vertices[16].points.elements =[ this.size, -this.size, -this.size] this.vertices[17].points.elements =[ this.size, this.size, -this.size] this.vertices[18].points.elements =[ this.size, this.size, this.size] this.vertices[19].points.elements =[ this.size, -this.size, this.size] // Left face this.vertices[20].points.elements =[-this.size, -this.size, -this.size] this.vertices[21].points.elements =[-this.size, -this.size, this.size] this.vertices[22].points.elements =[-this.size, this.size, this.size] this.vertices[23].points.elements =[-this.size, this.size, -this.size] } generateUVCoordinates() { // Front this.vertices[0].uv = [0.0, 0.0] this.vertices[1].uv = [1.0, 0.0] this.vertices[2].uv = [1.0, 1.0] this.vertices[3].uv = [0.0, 1.0] // Back this.vertices[4].uv = [0.0, 0.0] this.vertices[5].uv = [1.0, 0.0] this.vertices[6].uv = [1.0, 1.0] this.vertices[7].uv = [0.0, 1.0] // Top this.vertices[8].uv = [0.0, 0.0] this.vertices[9].uv = [1.0, 0.0] this.vertices[10].uv = [1.0, 1.0] this.vertices[11].uv = [0.0, 1.0] // Bottom this.vertices[12].uv = [0.0, 0.0] this.vertices[13].uv = [1.0, 0.0] this.vertices[14].uv = [1.0, 1.0] this.vertices[15].uv = [0.0, 1.0] // Right this.vertices[16].uv = [0.0, 0.0] this.vertices[17].uv = [1.0, 0.0] this.vertices[18].uv = [1.0, 1.0] this.vertices[19].uv = [0.0, 1.0] // Left this.vertices[20].uv = [0.0, 0.0] this.vertices[21].uv = [1.0, 0.0] this.vertices[22].uv = [1.0, 1.0] this.vertices[23].uv = [0.0, 1.0] } } <file_sep>/Adesh_Kumar_Assingment_2/prog/geometries/square.js /** * Specifies a Square. A subclass of Geometry. * * @author "<NAME>" * @this {Square} */ class Square extends Geometry { /** * Constructor for Square. * * @constructor * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ constructor(size, centerX, centerY) { super(); console.log("square") this.generateSquareVertices(size, centerX, centerY); // Recommendations: Remember that Square is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the square. * * @private * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ generateSquareVertices(size, centerX, centerY) { super.vertices = [ centerX, centerY, 0, centerX, centerY + size, 0, centerX - size, centerY + size, 0, centerX, centerY, 0, centerX - size, centerY + size, 0, centerX - size, centerY, 0, ]; } } <file_sep>/Adesh_Kumar_assingment_4 2/prog/eventFunctions.js /** * Responsible for initializing buttons, sliders, radio buttons, etc. present * within your HTML document. */ var shape; var segs; var onmousedrag = false; var isRainbow = false; var image = new Image(); // Create an image object function initEventHandelers() { // on mouse down and mouse drag the function click is called drawing the points canvas.onmousemove = function(ev){ if(onmousedrag){ click(ev);} } canvas.onmousedown = function(ev){ onmousedrag = true; click(ev);} canvas.onmouseup = function(ev){ onmousedrag = false; } // get the button click for html clear button document.getElementById('clearButton').onclick = function () { clearCanvas() }; var red = document.getElementById("red"); var green = document.getElementById("green"); var blue = document.getElementById("blue"); var file = document.getElementById("obj"); file.oninput = function() { addObjectToScene(); }; var addpic = document.getElementById("pic"); image.oninput = function() { loadTexture(gl, n, texture, u_Sampler, image); }; var triButton = document.getElementById("tri"); triButton.onclick = function() { shape = 0; } var squButton = document.getElementById("squ"); squButton.onclick = function() { shape = 1; } var cirButton = document.getElementById("cir"); cirButton.onclick = function() { shape = 2; } var cubeButton = document.getElementById("cube"); cubeButton.onclick = function() { shape = 3; } var rainbowButton = document.getElementById("rainbowButton"); rainbowButton.onclick = function(input) { rainbowButtonPress(rainbowButton); } shape = 0; segs = 12; var sizeSlider = document.getElementById("sizeSlider"); var cir = document.getElementById("cirseg"); cir.oninput = function() { segs = this.value; } } function rainbowButtonPress(button){ console.log("Rainbow Button Press"); if(isRainbow){ isRainbow = false; button.innerHTML = "Select Rainbow"; } else{ isRainbow = true; button.innerHTML = "Select Solid Color" } } /** * Function called upon mouse click or mouse drag. Computes position of cursor, * pushes cursor position as GLSL coordinates, and draws. * * @param {Object} ev The event object containing the mouse's canvas position */ function click(ev) { var x = ev.clientX; // x coordinate of a mouse pointer var y = ev.clientY; // y coordinate of a mouse pointer x = ((x) - canvas.width / 2) / (canvas.width / 2); y = (canvas.height / 2 - (y)) / (canvas.height / 2); coords = "X: " + x + ", Y: " + y; //gets the x and y coordinate sendTextToHTML(coords, "coord"); //send the x and y coordinate to the html console.log("hello1") if(shape == 0){ tri = new FluctuatingTriangle(sizeSlider.value/200, x, y); //tri.setColor(RGB); scene.addGeometry(tri); } else if(shape == 1){ squ = new SpinningSquare(sizeSlider.value/100, x, y); //squ.setColor(RGB); scene.addGeometry(squ); } else if(shape == 2){ cir = new Circle(.2, segs, x, y); //cir.setColor(RGB); scene.addGeometry(cir); } else { cube = new TiltedCube(sizeSlider.value/100, x, y); //cir.setColor(RGB); scene.addGeometry(cube); } console.log("hello3") } /** * Clears the HTML canvas. */ function clearCanvas() { scene.clearGeometry(); } function addObjectToScene(){ ObjString = document.getElementById('obj').files[0]; var reader = new FileReader(); reader.onload = function(e) { scene.addGeometry(new LoadedOBJ(e.target.result)); } reader.readAsText(ObjString); } <file_sep>/Assignment 1/ASG1/README.txt Welcome to CMPS 160's assignment 1! This zip file contains the necessary starter code and structure for this assignment. Note that while the provided structure is mandatory, expanding upon the structure is HIGHLY encouraged. Good luck! <file_sep>/Adesh_Kumar_assingment_4 2/prog/geometries/triangle.js /** * Specifies a Triangle. A subclass of Geometry. * * @author "Your Name Here" * @this {Triangle} */ class Triangle extends Geometry { /** * Constructor for Triangle. * * @constructor * @param {Number} size The size of the triangle drawn * @param {Number} centerX The center x-position of the triangle * @param {Number} centerY The center y-position of the triangle */ constructor(size, centerX, centerY) { super(); console.log("tri") this.generateTriangleVertices(size, centerX, centerY); // Recommendations: Remember that Triangle is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the Triangle. * * @private * @param {Number} size The size of the triangle drawn * @param {Number} centerX The center x-position of the triangle * @param {Number} centerY The center y-position of the triangle */ generateTriangleVertices(size, centerX, centerY) { super.vertices = [ centerX - size, centerY + size, 0, centerX + size, centerY + size, 0, centerX, centerY - size, 0]; if(isRainbow){ super.color = [ red.value/255, Math.random(green.value/255), Math.random(blue.value/255), Math.random(red.value/255), green.value/255, Math.random(blue.value/255), Math.random(red.value/255), Math.random(green.value/255), blue.value/255]; } else { super.color = [ red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255 ]; } // Recommendations: Might want to call this within your Triangle constructor. // Keeps your code clean :) } } <file_sep>/Adesh_Kumar_assingment_4/prog/geometries/animated/checkerCube.js /** * A tilted cube that has a checkerboard texture applied to it. A subclass of * TiltedCube. * * @author "<NAME>" * @this {CheckerCube} */ class CheckerCube extends TiltedCube { /** * Constructor for CheckerCube * * @constructor * @returns {CheckerCube} */ constructor() { super(); this.generateUVCoordinates(); // Recomendations: Might want to call generateUVCoordinates here. } /** * Generates the texture coordinates of CheckerCube. * * @private */ generateUVCoordinates() { // // YOUR CODE HERE // // var cube = [0.0 ,0.0, 0.0, // triangle 1 : begin // 0.0, 0.0, 1.0, // 0.0, 1.0, 1.0, // triangle 1 : end // 1.0, 1.0, 0.0, // triangle 2 : begin // 0.0, 0.0, 0.0, // 0.0, 1.0, 0.0, // triangle 2 : end // 1.0, 0.0, 1.0, // 0.0, 0.0, 0.0, // 1.0, 0.0, 0.0, // 1.0, 1.0, 0.0, // 1.0, 0.0 ,0.0, // 0.0, 0.0, 0.0, // 0.0, 0.0, 0.0, // 0.0, 1.0, 1.0, // 0.0, 1.0, 0.0, // 1.0, 0.0, 1.0, // 0.0, 0.0, 1.0, // 0.0, 0.0, 0.0, // 0.0, 1.0, 1.0, // 0.0, 0.0, 1.0, // 1.0, 0.0, 1.0, // 1.0, 1.0, 1.0, // 1.0, 0.0, 0.0, // 1.0, 1.0, 0.0, // 1.0, 0.0, 0.0, // 1.0, 1.0, 1.0, // 1.0, 0.0, 1.0, // 1.0, 1.0, 1.0, // 1.0, 1.0, 0.0, // 0.0, 1.0, 0.0, // 1.0, 1.0, 1.0, // 0.0, 1.0, 0.0, // 0.0, 1.0, 1.0, // 1.0, 1.0, 1.0, // 0.0, 1.0, 1.0, // 1.0, 0.0, 1.0] // Recomendations: Remember uv coordinates are defined from 0.0 to 1.0. } /** * Renders CheckerCube. */ render() { send2DTextureToGLSL(val, textureUnit, uniformName) // Recomendations: This will be the first time render will need to be // overloaded. Why? Because this is a textured geometry, not a geometry // which relies on a color value. } } <file_sep>/Adesh_Kumar_assingment_5/prog/camera.js class Camera { constructor(orthogonal = false) { this.eye = new Vector3([0,0,0]) this.at = new Vector3([0,0,-1]) this.up = new Vector3([0,1,0]); this.side = new Vector3([1,0,0]) this.orthogonal = orthogonal //Setting intial position of the user this.forward(10) this.rotate(180) this.left(1) //Updating everything this.updateCamera() this.updateProjection() } forward(dist) { this.eye.elements[0] += this.at.elements[0]*dist; this.eye.elements[1] += this.at.elements[1]*dist; this.eye.elements[2] += this.at.elements[2]*dist; } backward(dist) { this.eye.elements[0] -= this.at.elements[0]*dist; this.eye.elements[1] -= this.at.elements[1]*dist; this.eye.elements[2] -= this.at.elements[2]*dist; } right(dist) { this.eye.elements[0] += this.side.elements[0]*dist; this.eye.elements[1] += this.side.elements[1]*dist; this.eye.elements[2] += this.side.elements[2]*dist; } left(dist) { this.eye.elements[0] -= this.side.elements[0]*dist; this.eye.elements[1] -= this.side.elements[1]*dist; this.eye.elements[2] -= this.side.elements[2]*dist; } rotate(angle) { let rotate = new Matrix4().setRotate(angle, 0, 1, 0) this.at = rotate.multiplyVector3(this.at) this.side = this.crossVec3(this.at, this.up) this.side = this.normalizeVec3(this.side) } updateCamera() { let v3 = this.addVec3(this.eye, this.at) scene.viewMatrix.setLookAt(this.eye.elements[0], this.eye.elements[1], this.eye.elements[2], v3.elements[0], v3.elements[1], v3.elements[2], this.up.elements[0], this.up.elements[1], this.up.elements[2]); } updateProjection() { if(this.orthogonal) { scene.projMatrix.setOrtho(-10.0, 10.0, -10.0, 10.0, near, far); } else { scene.projMatrix.setPerspective(fov, gl.canvas.width/gl.canvas.height, near, far); } //We update the shader sendUniformMatToGLSL(scene.projMatrix.elements, "u_ProjMatrix") } //Basic operations needed for the camera addVec3(v1, v2) { let v3 = new Vector3([v1.elements[0] + v2.elements[0], v1.elements[1] + v2.elements[1], v1.elements[2] + v2.elements[2]]) return v3 } crossVec3(v1, v2) { let v3 = new Vector3() v3.elements[0] = v1.elements[1] * v2.elements[2] - v1.elements[2] * v2.elements[1]; v3.elements[1] = v1.elements[2] * v2.elements[0] - v1.elements[0] * v2.elements[2]; v3.elements[2] = v1.elements[0] * v2.elements[1] - v1.elements[1] * v2.elements[0]; return v3 } normalizeVec3(v1) { let rls = 1 / Math.sqrt(v1.elements[0]*v1.elements[0] + v1.elements[1]*v1.elements[1] + v1.elements[2]*v1.elements[2]); v1.elements[0] *= rls; v1.elements[1] *= rls; v1.elements[2] *= rls; return v1 } } <file_sep>/Assignment 1/ASG1/prog/shaders.js // Basic Vertex Shader that receives position and size for each vertex (point). var ASSIGN1_VSHADER = 'attribute vec4 a_Position;\n' + 'void main() {\n' + ' gl_Position = a_Position;\n' + // Set the vertex coordinates of the point ' gl_PointSize = 10.0;\n' + // Set the point size '}\n'; // Basic Fragment Shader that receives a single one color (point). var ASSIGN1_FSHADER = 'void main() {\n' + ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + '}\n'; <file_sep>/Adesh_Kumar _Assignment_6/prog/geometries/animated/tiltedCube.js /** * Specifies a tilted cube which rotates. * * @author "<NAME>" * @this {TiltedCube} */ class TiltedCube extends Geometry { /** * Constructor for TiltedCube. * * @constructor * @returns {TiltedCube} Geometric object created */ constructor(size, centerX, centerY) { super(); this.currentAngle = 0.0; this.size = size; this.centerX = centerX; this.centerY = centerY; this.vertices = this.generateCubeVerticesWithNormals(); this.modelMatrix.translate(this.centerX, 0.0, this.centerY); this.modelMatrix.scale(1, this.size, 1); // Recommendations: Might want to tilt your cube at 30 degrees relative to // the z-axis here. Pretty good tilt that lets us see that it's a cube. } generateCubeVerticesWithNormals() { function vecs_of_flat_arr(arr, n) { let ret = []; for (let i = 0; i < arr.length / n; i++) { let vec = []; for (let j = 0; j < n; j++) { vec.push(arr[i * n + j]); } ret.push(vec); } return ret; } let cube_vertices = [ -1, -1, -1, // Left side -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, // Front side 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, // Right side 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, // Back side -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, // Top side 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, // Bottom side -1, -1, 1, -1, -1, -1, 1, -1, -1 ]; let cube_normals = [ -1, 0, 0, // Left side -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 1, // Front side 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, // Right side 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, // Back side 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, // Top side 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, // Bottom side 0, -1, 0, 0, -1, 0, 0, -1, 0 ]; cube_vertices = vecs_of_flat_arr(cube_vertices, 3); cube_normals = vecs_of_flat_arr(cube_normals, 3); let cube_trig_vertices = []; let cube_trig_normals = []; // loop to create vertices of triangles to draw for (let i = 0; i < cube_vertices.length / 4; i++) { cube_trig_vertices[6 * i + 0] = cube_vertices[4 * i + 0]; cube_trig_vertices[6 * i + 1] = cube_vertices[4 * i + 1]; cube_trig_vertices[6 * i + 2] = cube_vertices[4 * i + 2]; cube_trig_vertices[6 * i + 3] = cube_vertices[4 * i + 0]; cube_trig_vertices[6 * i + 4] = cube_vertices[4 * i + 2]; cube_trig_vertices[6 * i + 5] = cube_vertices[4 * i + 3]; } cube_vertices = cube_trig_vertices; // same loop for normals for (let i = 0; i < cube_normals.length / 4; i++) { cube_trig_normals[6 * i + 0] = cube_normals[4 * i + 0]; cube_trig_normals[6 * i + 1] = cube_normals[4 * i + 1]; cube_trig_normals[6 * i + 2] = cube_normals[4 * i + 2]; cube_trig_normals[6 * i + 3] = cube_normals[4 * i + 0]; cube_trig_normals[6 * i + 4] = cube_normals[4 * i + 2]; cube_trig_normals[6 * i + 5] = cube_normals[4 * i + 3]; } cube_normals = cube_trig_normals; let ret = []; //every 3 points I create a vertex and I do a vertices.push for (var i = 0; i < cube_vertices.length; i++) { var v = new Vertex(); let p = cube_vertices[i]; let n = cube_normals[i]; v.points = [p[0] * 0.05, p[1] * 0.05, p[2] * 0.05]; v.color = [red, green, blue, 1.0]; v.normal = new Vector3([n[0], n[1], n[2]]); ret.push(v); } return ret; // Recommendations: Might want to generate your cube vertices so that their // x-y-z values are combinations of 1.0 and -1.0. Allows you to scale the // the cube to your liking better in the future. } }<file_sep>/Adesh_Kumar_Assignment_7/prog/shaders.js var VSHADER6 = 'attribute vec4 a_Position;\n' + 'attribute vec4 a_Color;\n' + 'attribute vec4 u_Colorid;\n' + 'attribute vec4 a_Normal;\n' + 'uniform bool u_Clicked;\n' + 'varying vec4 v_Color;\n' + 'varying vec3 v_Normal;\n' + 'varying vec3 u_directionalVector;\n' + 'varying vec3 v_Position;\n' + 'attribute float a_PointSize;\n' + 'uniform mat4 u_ViewMatrix;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'uniform mat4 u_ProjMatrix;\n' + 'uniform mat4 u_NormalMatrix;\n' + 'void main() {\n' + 'v_Color = a_Color;\n' + ' gl_Position = u_ProjMatrix * u_ViewMatrix * u_ModelMatrix * a_Position;\n' + // Coordinates ' gl_PointSize = a_PointSize;\n' + // Set the point size ' v_Position = vec3(u_ModelMatrix * a_Position);\n' + ' v_Normal = normalize(vec3(u_NormalMatrix * a_Normal));\n' + ' if (u_Clicked) {\n' + // Draw in red if mouse is pressed ' v_Color = u_Colorid;\n' + ' } else {\n' + ' v_Color = a_Color;\n' + ' }\n' + '}\n'; var FSHADER6 = 'precision mediump float;\n' + 'uniform vec3 u_LightColor;\n' + // Light color 'uniform vec3 u_LightPosition;\n' + // Position of the light source 'uniform vec3 u_AmbientLight;\n' + // Ambient light color 'varying vec4 v_Color;\n' + // uniform変数 'varying vec3 v_Normal;\n' + 'varying vec3 v_Position;\n' + 'void main() {\n' + // Normalize the normal because it is interpolated and not 1.0 in length any more ' vec3 normal = normalize(v_Normal);\n' + // Calculate the light direction and make its length 1. ' vec3 lightDirection = normalize(u_LightPosition - v_Position);\n' + // The dot product of the light direction and the orientation of a surface (the normal) ' float nDotL = max(dot(lightDirection, normal), 0.0);\n' + // Calculate the final color from diffuse reflection and ambient reflection ' vec3 diffuse = u_LightColor * v_Color.rgb * nDotL;\n' + ' vec3 ambient = u_AmbientLight * v_Color.rgb;\n' + ' gl_FragColor = vec4(diffuse + ambient, v_Color.a);\n' + '}\n'; var VSHADER6_N = 'attribute vec4 a_Position;\n' + 'attribute vec4 a_Color;\n' + 'attribute vec4 a_Normal;\n' + 'varying vec4 v_Color;\n' + 'varying vec3 v_Normal;\n' + 'varying vec3 v_Position;\n' + 'attribute float a_PointSize;\n' + 'uniform mat4 u_ViewMatrix;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'uniform mat4 u_ProjMatrix;\n' + 'uniform mat4 u_NormalMatrix;\n' + 'void main() {\n' + 'v_Color = a_Color;\n' + ' gl_Position = u_ProjMatrix * u_ViewMatrix * u_ModelMatrix * a_Position;\n' + // Coordinates ' gl_PointSize = a_PointSize;\n' + // Set the point size ' v_Position = vec3(u_ModelMatrix * a_Position);\n' + ' v_Normal = normalize(vec3(u_NormalMatrix * a_Normal));\n' + ' v_Color = a_Color;\n' + '}\n'; var FSHADER6_N = 'precision mediump float;\n' + 'uniform vec3 u_LightColor;\n' + // Light color 'uniform vec3 u_LightPosition;\n' + // Position of the light source 'uniform vec3 u_AmbientLight;\n' + // Ambient light color 'varying vec4 v_Color;\n' + // uniform変数 'varying vec3 v_Normal;\n' + 'varying vec3 v_Position;\n' + 'void main() {\n' + // Normalize the normal because it is interpolated and not 1.0 in length any more ' vec3 normal = normalize(v_Normal);\n' + ' vec3 position = normalize(v_Position);\n' + // Calculate the light direction and make its length 1. ' vec3 lightPosition = normalize(u_LightPosition);\n' + ' vec3 lightDirection = normalize(lightPosition - v_Position);\n' + ' vec3 reflectVec = reflect(-lightPosition, normal);\n' + // The dot product of the light direction and the orientation of a surface (the normal) ' float nDotL = max(dot(lightPosition, normal), 0.0);\n' + // Calculate the final color from diffuse reflection and ambient reflection ' float specAngle = max(dot(reflectVec, position), 0.0);\n' + ' float specular = pow(specAngle, 2.0);\n' + ' vec3 diffuse = u_LightColor * v_Color.rgb * nDotL;\n' + ' vec3 ambient = u_AmbientLight * v_Color.rgb;\n' + ' gl_FragColor = vec4(diffuse + ambient + specular, v_Color.a);\n' + '}\n'; <file_sep>/Adesh_Kumar_assingment_4/prog/geometries/square.js /** * Specifies a Square. A subclass of Geometry. * * @author "Your Name Here" * @this {Square} */ class Square extends Geometry { /** * Constructor for Square. * * @constructor * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ constructor(size, centerX, centerY) { super(); console.log("square") this.generateSquareVertices(size, centerX, centerY); // Recommendations: Remember that Square is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the square. * * @private * @param {Number} size The size of the square drawn * @param {Number} centerX The center x-position of the square * @param {Number} centerY The center y-position of the square */ generateSquareVertices(size, centerX, centerY) { super.vertices = [centerX - size, centerY + size, 0, centerX + size, centerY - size, 0, centerX - size, centerY - size, 0, centerX - size, centerY + size, 0, centerX + size, centerY - size, 0, centerX + size, centerY + size, 0]; if(isRainbow){ super.color = [ red.value/255, Math.random(green.value/255), Math.random(blue.value/255), Math.random(red.value/255), green.value/255, Math.random(blue.value/255), red.value/255, Math.random(green.value/255), Math.random(blue.value/255), Math.random(red.value/255), green.value/255, Math.random(blue.value/255), red.value/255, Math.random(green.value/255), Math.random(blue.value/255), Math.random(red.value/255), Math.random(green.value/255), blue.value/255]; } else { super.color = [ red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255, red.value/255, green.value/255, blue.value/255 ]; } // Recommendations: Might want to call this within your Square constructor. // Keeps your code clean :) } } <file_sep>/Adesh_Kumar_assingment_4/prog/geometries/circle.js /** * Specifies a Circle. A subclass of Geometry. * * @author "Your Name Here" * @this {Circle} */ class Circle extends Geometry { /** * Constructor for Circle. * * @constructor * @param {Number} radius The radius of the circle being constructed * @param {Integer} segments The number of segments composing the circle * @param {Number} centerX The central x-position of the circle * @param {Number} centerY The central y-position of the circle */ constructor(radius, segments, centerX, centerY) { super(); this.generateCircleVertices(radius, segments, centerX, centerY); // Recommendations: Remember that Circle is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the Circle. * * @private * @param {Number} radius The radius of the circle being constructed * @param {Integer} segments The number of segments composing the circle * @param {Number} centerX The central x-position of the circle * @param {Number} centerY The central y-position of the circle */ generateCircleVertices(radius, segments, centerX, centerY) { // Recommendations: Might want to call this within your Circle constructor. // Keeps your code clean :) var point = []; console.log("circle") //Do the top half for(var i = 0; i < segments*2; ++i){ //center point point.push(centerX, centerY, 0); //outer point 1 point.push( radius * Math.cos(i * Math.PI / segments) + centerX, radius * Math.sin(i * Math.PI / segments) + centerY, 0 ); //outer point 2 point.push( radius * Math.cos((i+1) * Math.PI / segments) + centerX, radius * Math.sin((i+1) * Math.PI / segments) + centerY, 0 ); } super.vertices = point; var baseColors = [ [Math.random(red.value/255), Math.random(green.value/255), Math.random(blue.value/255)], [Math.random(red.value/255), Math.random(green.value/255), Math.random(blue.value/255)], [Math.random(red.value/255), Math.random(green.value/255), Math.random(blue.value/255)]]; for(var i = 0; i < this.vertices.length; ++i){ if(isRainbow){ this.color.push(baseColors[i%3][0]); this.color.push(baseColors[i%3][1]); this.color.push(baseColors[i%3][2]); } else{ this.color.push(red.value/255); this.color.push(green.value/255); this.color.push(blue.value/255); } } } } <file_sep>/Assignment 1/Adesh_Kumar_Assignment_1/README.txt CMPS 160's assignment 1! <NAME> <EMAIL> Fall 2018 CMPS 160 Professor <NAME> Files: Driver.html Lib cuon-utils.js load-files.js webgl-debug.js webgl-utils.js Prog eventFunctions.js glslFunctions.js main.js shaders.js htmlFunctions.js Comments: This assignment got the best of me. I unfortunately didn't understand how to proper update the latest point as that was my lack of understanding on how to do so. However, I was quick to understand how webGL and javascript communicate as well as get the sliders and buttons to work. This was very enjoyable and challenging, I love this stuff and can't wait to get more. But hopefully understand it better. <file_sep>/Assignment 1/ASG1/prog/htmlFunctions.js /** * Updates the text within an HTML element. * * @param {String} text String being sent to HTML element. * @param {String} htmlID The ID of an html element. */ function sendTextToHTML(text, htmlID) { // // YOUR CODE HERE // } <file_sep>/Adesh_Kumar_Assingment_2/prog/geometries/triangle.js /** * Specifies a Triangle. A subclass of Geometry. * * @author "<NAME>" * @this {Triangle} */ class Triangle extends Geometry { /** * Constructor for Triangle. * * @constructor * @param {Number} size The size of the triangle drawn * @param {Number} centerX The center x-position of the triangle * @param {Number} centerY The center y-position of the triangle */ constructor(size, centerX, centerY) { super(); console.log("tri") this.generateTriangleVertices(size, centerX, centerY); // Recommendations: Remember that Triangle is a subclass of Geometry. // "super" keyword can come in handy when minimizing code reuse. } /** * Generates the vertices of the Triangle. * * @private * @param {Number} size The size of the triangle drawn * @param {Number} centerX The center x-position of the triangle * @param {Number} centerY The center y-position of the triangle */ generateTriangleVertices(size, centerX, centerY) { super.vertices = [ centerX - size, centerY + size, 0, centerX + size, centerY + size, 0, centerX, centerY - size, 0]; } } <file_sep>/Adesh_Kumar _Assignment_6/prog/scene/camera.js class Camera { /** * Constructor for Camera. * * @constructor * @returns {Camera} Camera object created */ constructor(pos, center, up, fov, ar, near, far) { this.pos = new Vector3(pos); this.center = new Vector3(center); this.up = new Vector3(up); this.fov = fov; this.aspect_ratio = ar; this.near = near; this.far = far; this.viewMatrix = new Matrix4(); this.projMatrix = new Matrix4(); } move(speed, dir) { // Normalizing center vector var move = new Vector3(this.center.elements); move.normalize(); this.pos.elements[0] += move.elements[0] * speed * dir; this.pos.elements[1] += move.elements[1] * speed * dir; this.pos.elements[2] += move.elements[2] * speed * dir; } pan(speed, dir) { var m = new Vector3(this.center.elements); m.normalize(); var rotAngle = 90*dir; var rotMat = new Matrix4(); rotMat.setRotate(rotAngle, 0, 1, 0); m = rotMat.multiplyVector3(m); this.pos.elements[0] += m.elements[0] * speed; this.pos.elements[1] += m.elements[1] * speed; this.pos.elements[2] += m.elements[2] * speed; // this.pos.elements[0] += speed * dir; } rotate(angle) { // Rotate center by the given angle var rot = new Matrix4(); rot.setRotate(angle, 0, 1, 0); this.center = rot.multiplyVector3(this.center); } update() { this.fov = zoomSlider.value/1; this.near = nearSlider.value/1; this.far = farSlider.value/1; this.viewMatrix.setLookAt(this.pos.elements[0], this.pos.elements[1], this.pos.elements[2], this.center.elements[0] + this.pos.elements[0], this.center.elements[1] + this.pos.elements[1], this.center.elements[2] + this.pos.elements[2], this.up.elements[0], this.up.elements[1], this.up.elements[2]); if (viewMode == "perspective") { this.projMatrix.setPerspective(this.fov, this.aspect_ratio, this.near, this.far); } else{ this.projMatrix.setOrtho(-1.0, 1.0, -1.0, 1.0, this.near, this.far); } } }<file_sep>/Adesh_Kumar _Assignment_6/prog/imageSample.js /** * Samples the color of each pixel in an image. * * @param {Image} image The image whose color data is being sampled * @returns {Array} A 1-D array of RGBA values in row-major order */ function sampleImageColor(image) { var canvas = document.createElement('canvas'); canvas.height = image.height; canvas.width = image.width; console.log(canvas); var context = canvas.getContext('2d'); context.drawImage(image, 0, 0); var colorData = context.getImageData(0, 0, image.width, image.height).data; return colorData; } <file_sep>/Adesh_Kumar_Assignment_7/prog/eventFunctions.js /** * Responsible for initializing buttons, sliders, radio buttons, etc. present * within your HTML document. */ function initEventHandelers() { canvas = document.getElementById("myCanvas"); perspectiveButton = document.getElementById("perspective"); orthographicButton = document.getElementById("orthographic"); nearSlider = document.getElementById("near"); farSlider = document.getElementById("far"); zoomSlider = document.getElementById("zoom"); catOBJ = document.getElementById("catOBJ"); teapotOBJ = document.getElementById("teapotOBJ"); hud = document.getElementById('hud'); // canvas.onmousedown = function(ev) { // Mouse is pressed // alert("hello") // var x = ev.clientX; // x coordinate of a mouse pointer // var y = ev.clientY; // y coordinate of a mouse pointer // // var rect = ev.target.getBoundingClientRect(); // // if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) { // // // If pressed position is inside <canvas>, check if it is above object // // var x_in_canvas = x - rect.left, y_in_canvas = rect.bottom - y; // // console.log("x_in_canvas"); // // var result = check(x_in_canvas, y_in_canvas); // // // var picked = check(gl, n, x_in_canvas, y_in_canvas, u_Clicked, viewProjMatrix, u_MvpMatrix); // // if (picked) alert('The cube was selected! '); // // } // } } /** * Function called upon mouse click or mouse drag. Computes position of cursor, * pushes cursor position as GLSL coordinates, and draws. * * @param {Object} ev The event object containing the mouse's canvas position */ /** * Clears the HTML canvas. */ function addObjToScene() { var objectFile = document.getElementById("chooseObjectFile").files[0]; var textureFile = document.getElementById("chooseTextureFile").files[0]; var fileReader = new FileReader(); fileReader.onloadend = function() { var objString = fileReader.result; if (textureFile != undefined) { fileReader.onloadend = function() { var textureURL = fileReader.result; var texturedOBJ = new TexturedOBJ(objString); var callback = function (texture) { texturedOBJ.texture = texture; } create2DTexture(textureURL, gl.LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, callback); scene.addGeometry(texturedOBJ); } fileReader.readAsDataURL(textureFile); } else { var loadedOBJ = new LoadedOBJ(objString); scene.addGeometry(loadedOBJ); } } fileReader.readAsText(objectFile); } function initializeTerrain(heightData, colorData) { // center of the cube var centerX = 0; var centerY = 0.85; for (let i = 0; i < heightData.length; i += 4) { // decide the 3 components of the height starting from the grey shades var r = heightData[i] / 255; r = Math.round(r * 10) / 10; var g = heightData[i + 1] / 255; g = Math.round(g * 10) / 10; var b = heightData[i + 2] / 255; b = Math.round(b * 10) / 10; // each 16 pixels (64 elements of the array) you change row // the first time this if{} is calculated is when i == 0 if (i % 64 == 0) { centerX = 0.05 - 0.8; centerY = centerY - 0.1; // console.log(i); } // if the height is 0, for efficiency sake you don't want to draw a cube if (r == 0.0 && g == 0.0 && b == 0.0) { centerX = centerX + 0.1; // update x coordinate of the canvas } else { // otherwise you draw the cube // calculate height var height = Math.sqrt(r * r + g * g + b * b); height = Math.round(height * 10) / 10; // store the color data in the global variable, then // the cube class will use the colors to draw each vertex red = colorData[i] / 255; red = Math.round(red * 10) / 10; green = colorData[i + 1] / 255; green = Math.round(green * 10) / 10; blue = colorData[i + 2] / 255; blue = Math.round(blue * 10) / 10; scene.addGeometry(new TiltedCube(height, centerX, centerY)); scene.render(); // update x coordinate of the canvas centerX = centerX + 0.1; } } scene.addGeometry(new Square(0.8, 0, -0.085)); } function loadImage() { var img1 = new Image(); var img2 = new Image(); img1.crossOrigin = "Anonymous"; img2.crossOrigin = "Anonymous"; var heightData = []; var colorData = []; img1.onload = function () { heightData = sampleImageColor(img1); img2.onload = function () { colorData = sampleImageColor(img2); initializeTerrain(heightData, colorData); }; }; img1.src = "external/terrain/Height_terains.png"; img2.src = "external/terrain/color_terains.png"; } function keydown(ev) { switch(ev.keyCode){ case 74: // j was pressed scene.camera.rotate(10); break; case 76: // l was pressed scene.camera.rotate(-10); break; case 68: // d was pressed scene.camera.pan(0.05, -1); break; case 65: // a was pressed scene.camera.pan(0.05, 1); break; case 87: // w was pressed scene.camera.move(0.05, 1); break; case 83: // s was pressed scene.camera.move(0.05, -1); break; case 78: // n was pressed useNormalShader = !useNormalShader; break; default: return; // Prevent the unnecessary drawing } //draw(); } function onmouse(ev) { var x = ev.clientX; // x coordinate of a mouse pointer var y = ev.clientY; // y coordinate of a mouse pointer var rect = ev.target.getBoundingClientRect(); if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) { // If pressed position is inside <canvas>, check if it is above object var x_in_canvas = x - rect.left, y_in_canvas = rect.bottom - y; check(x_in_canvas, y_in_canvas); // var picked = check(gl, n, x_in_canvas, y_in_canvas, u_Clicked, viewProjMatrix, u_MvpMatrix); } } function resize(canvas) { console.log(canvas) // Lookup the size the browser is displaying the canvas. var displayWidth = canvas.clientWidth; var displayHeight = canvas.clientHeight; // Check if the canvas is not the same size. if (canvas.width != displayWidth || canvas.height != displayHeight) { // Make the canvas the same size canvas.width = displayWidth; canvas.height = displayHeight; } } function resizeHUD(canvas) { console.log(canvas) // Lookup the size the browser is displaying the canvas. var displayWidth = ctx.canvas.clientWidth; var displayHeight = ctx.canvas.clientHeight; // Check if the canvas is not the same size. if (ctx.canvas.width != displayWidth || ctx.canvas.height != displayHeight) { // Make the canvas the same size ctx.canvas.width = displayWidth; ctx.canvas.height = displayHeight; } } function draw2D(ctx) { // // Start drawingß var img = new Image(); var img1 = new Image(); img.onload = function() { ctx.drawImage(img, 10, 10); ctx.beginPath(); ctx.stroke(); } img1.onload = function() { ctx.drawImage(img1, canvas.width/4, canvas.height-200); ctx.beginPath(); ctx.stroke(); } img.src = 'color_terrains1.png'; img1.src = 'hands.png'; } function check(x, y) { var picked = false; sendUniformIntToGLSL(1, "u_Clicked") scene.render(); // draw(gl, n, currentAngle, viewProjMatrix, u_ModelMatrix); // Draw cube with red // Read pixel at the clicked position var pixels = new Uint8Array(4); // Array for storing the pixel value console.log(pixels); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels); if( pixels[3] == 254) { picked = true; alert('Congratulations, you have found all the teapots!'); } if( pixels[3] == 253) { picked = true; alert('You found the First teapot! Hint: turn around 1/3 '); } if( pixels[3] == 252) { picked = true; alert('You found the Second teapot! You have one more to find. 2/3 '); } sendUniformIntToGLSL(0, "u_Clicked") // draw(gl, n, currentAngle, viewProjMatrix, u_ModelMatrix); // Draw the cube scene.render(); } /** * Changes the size of the points drawn on HTML canvas. * * @param {float} size Real value representing the size of the point. */ //function changePointSize(size) {} /** * Changes the color of the points drawn on HTML canvas. * * @param {float} color Color value from 0.0 to 1.0. */ //function changePointColor(color) {} <file_sep>/Adesh_Kumar_Assignment_7/prog/main.js /** * Function called when the webpage loads. */ var gl; var viewMatrix; var projMatrix; var shader; var scene; var canvas var perspectiveButton; var orthographicButton; var viewMode = "perspective"; var nearSlider; var farSlider; var zoomSlider; var red, green, blue; var catOBJ; var teapotOBJ; var teapotOBJ1; var teapotOBJ2; var catObject; var teapotObject; var addAnimatedObject = true; var pan = false; var hud; var ctx; var useNormalShader = false; var yOBJ = -1; function main() { initEventHandelers(); // Get the rendering context for WebGL gl = getWebGLContext(canvas); ctx = hud.getContext('2d'); if (!gl || !ctx) { console.log('Failed to get rendering context'); return; } // shader = createShader(gl, VSHADER, FSHADER); // useShader(gl, shader); shader = createShader(gl, VSHADER6, FSHADER6); shaderN = createShader(gl, VSHADER6_N, FSHADER6_N); useShader(gl, shader); scene = new Scene(gl); // Register the event handler to be called on key press document.onkeydown = function(ev){ keydown(ev); }; canvas.onmousedown = function(ev) { onmouse(ev); }; // Specify the color for clearing <canvas> gl.clearColor(0.2, 0.2, 0.2, 1.0); gl.enable(gl.DEPTH_TEST); // Clear <canvas>` gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); resize(gl.canvas); resizeHUD(ctx.hud); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); teapotObject = new LoadedOBJ(teapotOBJ.text, 3, yOBJ, 4, 1, Math.random(), Math.random(), 254/255); teapotObject1 = new LoadedOBJ(teapotOBJ.text, -5, yOBJ, -1, Math.random(), 1, Math.random(), 253/255); teapotObject2 = new LoadedOBJ(teapotOBJ.text, 15, yOBJ, -7, Math.random(), Math.random(), 1, 252/255); scene.addGeometry(teapotObject); scene.addGeometry(teapotObject1); scene.addGeometry(teapotObject2); loadImage(); tick(); } <file_sep>/Adesh_Kumar_assingment_5/prog/shaders.js // Basic Vertex Shader that receives position and size for each vertex (point). var ASSIGN4_VSHADER = 'attribute vec4 a_Position;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'uniform mat4 u_ViewMatrix;\n' + 'uniform mat4 u_ProjMatrix;\n' + 'attribute vec4 RGB;\n' + 'varying vec4 v_RGB;\n' + // varying variable 'void main() {\n' + 'gl_Position = u_ProjMatrix * u_ViewMatrix * u_modelMatrix * a_Position;\n' + ' v_RGB = RGB;\n' + '}\n'; // Basic Fragment Shader that receives a single one color (point). var ASSIGN4_FSHADER = 'precision mediump float;\n' + 'varying vec4 v_RGB;\n' + 'void main() {\n' + ' gl_FragColor = v_RGB;\n' + '}\n'; //##### <NAME> MODIFIED FUNCTION!!! DOUBLE CHECK IF THERE ARE ANY DIFFERENCES IN PREVIOUS VERSION // Basic Vertex Shader that receives position and size for each vertex (point). var OBJ_VSHADER = 'attribute vec4 a_Position;\n' + 'attribute float a_ShapeSize;\n' + 'attribute vec4 a_Color;\n' + 'varying vec4 v_Color;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'void main() {\n' + ' gl_Position = u_ModelMatrix * a_Position;\n' + ' gl_PointSize = a_ShapeSize;\n' + ' v_Color = a_Color;\n' + '}\n'; // Basic Fragment Shader that receives a single one color (point). var OBJ_FSHADER = 'precision mediump float;\n' + 'varying vec4 v_Color;\n' + 'void main() {\n' + ' gl_FragColor = v_Color;\n' + '}\n'; var ASSIGN4_VSHADER_TEXTURE = 'attribute vec4 a_Position;\n' + 'uniform mat4 u_ModelMatrix;\n' + 'uniform mat4 u_ViewMatrix;\n' + 'uniform mat4 u_ProjMatrix;\n' + 'attribute vec2 aTextureCoord;\n' + 'varying vec2 vTextureCoord;\n' + 'void main() {\n' + 'gl_Position = u_ModelMatrix * a_Position;\n' + ' vTextureCoord = aTextureCoord;\n' + '}\n'; var ASSIGN4_FSHADER_TEXTURE = 'precision mediump float;\n' + 'uniform sampler2D u_Sampler;\n' + 'varying vec2 vTextureCoord;\n' + 'void main() {\n' + ' gl_FragColor = texture2D(u_Sampler, vTextureCoord);\n' + '}\n'; <file_sep>/Assingment 3/Adesh_Kumar_Assingment_3/README.txt Welcome to CMPS 160's assignment 3! This zip file contains the necessary starter code and structure for this assignment. First, lets start with some code reuse recommendations from assignment 2: 1. Reuse eventFunctions.js. Modify it as you see fit for this assignment. 2. Reuse glslFunctions.js. One new function was introduced within this assignment: i. sendUniformMat4ToGLSL() for drawing the scene on the canvas Some "skeleton" code can be found in prog. Simply copy that code into your ASG2 file and place the modified ASG2 file in ASG3's prog. 3. Reuse htmlFunctions.js. 4. Reuse circle.js, triangle.js, and square.js. 5. geometry.js and scene.js have some new methods. Please look into it. You might want to include old code EXACTLY where it was in Assignment 2. Second, some code you'll probably need to rewrite: 1. main.js and it's main(). 2. shaders.js with updated shaders. 3. driver.html (NOTE: Might want to use your ASG2 driver.html as a reference) Third, code that has remained the same: 1. Most of lib. Last, some new .js files introduced within: lib 1. cuon-matrix.js: Contains the matrix/vector library necessary for this assignment. Note that the file uses pre-ES6 objects, so the way the Matrix4, Vector4, etc. objects are formatted in this file is different. lib/obj-loading 1. loadedOBJ.js: A subclass of geometry you will be using to load OBJ files 2. webgl-obj-loader.js: Code necessary for reading obj files. You should not need to interact with it. prog 1. tick.js: Responsible for gathering the frames necessary for animating your scene. prog/geometries/animated 1. fluctuatingTriangle.js: Specifies a triangle which grows and shrinks in size. A subclass of Triangle. 2. randomCircle.js: Specifies a triangle which moves randomly across the screen. A subclass of Circle. 3. spinningSquare.js: Specifies a square which spins in place. A subclass of Square. 4. tiltedCube.js: Specifies a tilted cube which spins. These new .js files are meant to move us into the world of animation! This assignment will heavily rely on matrix transformations to animate your geometry on screen. Now, let's clarify randomCircle. "What does random movement mean?" - What you want it to mean. There is no set criteria for "random" movement. Just provide us with something that visually "looks" random. However, your circle should stay within the boundaries of the canvas (because of this, the movement of your circle might not be truly random). "Any suggestions?" - Yes. Checking whether your circle is in your canvas is tricky. In order to check if its within the bounds of your canvas (assuming your canvas is still 500x500) I recommend 2 things: 1. Change your Vertex.points from an array to a Vector4 object from cuon-matrix.js. 2. Apply your modelMatrix to each Vertex.points every animation frame and check if any x-y-z is out-of-bounds (i.e. > 1.0 or < -1.0). This is what I did. You may come up with a better solution (good for you!). This should be all you need to know for assignment 3. Good luck! <file_sep>/Adesh_Kumar_Assignment_7/lib/obj_loading/texturedOBJ.js class TexturedOBJ extends LoadedOBJ { render() { useShader(gl, textureShader); sendUniformMatToGLSL(this.modelMatrix, "u_ModelMatrix"); send2DTextureToGLSL(this.texture, 0, "u_Sampler"); sendVertexBufferToGLSL(this.vertices, 3, "a_Position"); sendTextureBufferToGLSL(this.vertices, 2, "a_TextureCoord"); tellGLSLToDrawCurrentBuffer(this.vertices.length); } } <file_sep>/Adesh_Kumar_Assingment_2/prog/glslFunctions.js /** * Sends data to an attribute variable using a buffer. * * @private * @param {Float32Array} data Data being sent to attribute variable * @param {Number} dataCount The amount of data to pass per vertex * @param {String} attribName The name of the attribute variable */ function sendAttributeBufferToGLSL(data, dataCount, attribName) { var attrib = gl.getAttribLocation(gl.program, attribName); if (attrib < 0) { console.log('Failed to get the storage location of ' + attribName); return; } var vBuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vBuf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.DYNAMIC_DRAW); gl.vertexAttribPointer(attrib, dataCount, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(attrib); // Recommendations: This piece of code should do these three things: // 1. Create a an attribute buffer // 2. Bind data to that buffer // 3. Enable the buffer for use // Some modifications can be made to this function to improve performance. Ask // a TA in lab if you're interested in these modifications. } /** * Draws the current buffer loaded. Buffer was loaded by sendAttributeBufferToGLSL. * * @param {Integer} pointCount The amount of vertices being drawn from the buffer. */ function tellGLSLToDrawCurrentBuffer(pointCount) { console.log(pointCount) gl.drawArrays(gl.TRIANGLES, 0, pointCount); // Recommendations: Should only be one line of code. } /** * Sends a float value to the specified uniform variable within GLSL shaders. * Prints an error message if unsuccessful. * * @param {float} val The float value being passed to uniform variable * @param {String} uniformName The name of the uniform variable */ function sendUniformFloatToGLSL(uniformName, val) { uniformName = gl.getUniformLocation(gl.program, uniformName); if (uniformName < 0) { console.log('Failed to get the storage location of' + 'uniformName'); return; } gl.uniform1f(uniformName, val); } // // YOUR CODE HERE // /** * Sends an JavaSript array (vector) to the specified uniform variable within * GLSL shaders. Array can be of length 2-4. * * @param {Array} val Array (vector) being passed to uniform variable * @param {String} uniformName The name of the uniform variable */ function sendUniformVec4ToGLSL(val, uniformName) { var unif = gl.getUniformLocation(gl.program, uniformName); if(unif < 0) { console.log('Failed to get the storage location of' + 'uniformName'); return; } if(val.length == 2){ gl.uniform4f(unif, val[0], val[1], 0, 1.0); } else if(val.length == 3){ gl.uniform4f(unif, val[0], val[1], val[2], 0, 1.0); } else if(val.length == 4){ gl.uniform4f(unif, val[0], val[1], val[2], val[3]); } } <file_sep>/Adesh_Kumar _Assignment_6/prog/scene/geometry.js /** * Specifies a geometric object. * * @author <NAME> * @this {Geometry} */ class Geometry { /** * Constructor for Geometry. * * @constructor */ constructor() { this.vertices = []; // Vertex objects. Each vertex has x-y-z. this.viewMatrix = new Matrix4(); // Model matrix applied to geometric object this.modelMatrix = new Matrix4(); this.shader = null; // shading program you will be using to shade this geometry this.texture = null; this.x = 0; } /** * Renders this Geometry within your webGL scene. */ // render() { // // this.normalMatrix.setInverseOf(this.modelMatrix); // // this.normalMatrix.transpose(); // // sendUniformMatToGLSL(this.normalMatrix, "u_NormalMatrix") // sendVertexBufferToGLSL(this.vertices, 3, "a_Position"); // sendColorBufferToGLSL(this.vertices, 4, "a_Color"); // light(); // sendUniformMatToGLSL(this.modelMatrix, "u_ModelMatrix"); // tellGLSLToDrawCurrentBuffer(this.vertices.length); // // Recommendations: sendUniformVec4ToGLSL(), tellGLSLToDrawCurrentBuffer(), // // and sendAttributeBufferToGLSL() are going to be useful here. // } render() { var u_LightColor = gl.getUniformLocation(gl.program, 'u_LightColor'); var u_LightPosition = gl.getUniformLocation(gl.program, 'u_LightPosition'); var u_AmbientLight = gl.getUniformLocation(gl.program, 'u_AmbientLight'); if (useNormalShader) { useShader(gl, shader); } else { useShader(gl, shaderN); gl.uniform3f(u_LightColor, 1.0, 1.0, 1.0); gl.uniform3f(u_LightPosition, 3*Math.sin(this.x), 4.0, 4.0); gl.uniform3f(u_AmbientLight, 0.2, 0.2, 0.2); } var normalMatrix = new Matrix4(); normalMatrix.setInverseOf(this.modelMatrix); normalMatrix.transpose(); sendUniformMatToGLSL(normalMatrix, "u_NormalMatrix"); sendVertexBufferToGLSL(this.vertices, 3, "a_Position"); sendColorBufferToGLSL(this.vertices, 4, "a_Color"); sendNormalBufferToGLSL(this.vertices, 3, "a_Normal"); sendUniformMatToGLSL(this.modelMatrix, "u_ModelMatrix"); tellGLSLToDrawCurrentBuffer(this.vertices.length); this.x+=0.1; // Recommendations: sendUniformVec4ToGLSL(), tellGLSLToDrawCurrentBuffer(), // and sendAttributeBufferToGLSL() are going to be useful here. } /** * Responsible for updating the geometry's modelMatrix for animation. * Does nothing for non-animating geometry. */ updateAnimation() { return; // NOTE: This is just in place so you'll be able to call updateAnimation() // on geometry that don't animate. No need to change anything. } } <file_sep>/Assignment 1/ASG1/prog/eventFunctions.js /** * Responsible for initializing buttons, sliders, radio buttons, etc. present * within your HTML document. */ function initEventHandelers() { // // YOUR CODE HERE // } /** * Function called upon mouse click or mouse drag. Computes position of cursor, * pushes cursor position as GLSL coordinates, and draws. * * @param {Object} ev The event object containing the mouse's canvas position */ function click(ev){ } /** * Renders the scene on the HTML canvas. */ function render() { // // YOUR CODE HERE // } /** * Clears the HTML canvas. */ function clearCanvas() { // // YOUR CODE HERE // } /** * Changes the size of the points drawn on HTML canvas. * * @param {float} size Real value representing the size of the point. */ function changePointSize(size) { // // YOUR CODE HERE // } /** * Changes the color of the points drawn on HTML canvas. * * @param {float} color Color value from 0.0 to 1.0. */ function changePointColor(color) { // // YOUR CODE HERE // }
20723565452ecd82a78d805463403b32e1481254
[ "JavaScript", "Text", "Markdown" ]
38
JavaScript
adeskmr/CMPS-160
869e0fdc13b3e5d914bbc704cb6d466888054c4f
61e0aa70a9f536f27e7f344a358402eeb69e60ed
refs/heads/master
<repo_name>daywednes/spellcheck<file_sep>/spellcheck.py ''' Created on Jul 2, 2012 @author: mdoan ''' import sys import re from collections import defaultdict import random import time def reduce_word(word): return re.sub(r'[aouie]+', r'_', re.sub(r'([a-z])\1+', r'\1', word.lower())) def make_word(w): w = re.sub(r'[aouie]', vowels_list[random.randint(0, 4)], w) wlist = [] for ch in w: if ch != '\'': if random.randint(0, 4) == 0: for _ in range(random.randint(1,4)): wlist.append(ch) else: wlist.append(ch) else: wlist.append(ch) for i in range(len(wlist)): if random.randint(0, 5) == 0: wlist[i] = wlist[i].upper() return ''.join(wlist) if __name__ == '__main__': if len(sys.argv) > 1: if not(len(sys.argv) > 2 and sys.argv[1] == '-g'): print('Syntax error\npython spellcheck.py\npython spellcheck.py -g 1000 [1000 words to be generated]') sys.exit(0) ''' init ''' DICT = map(lambda x: x.lower(), open('/usr/share/dict/words').read().split()) dict_set = set(DICT) inverted_dict = defaultdict(list) for word in DICT: inverted_dict[reduce_word(word)].append(word) vowels = set(['a', 'e', 'i', 'o', 'u']) vowels_list = ['a', 'e', 'i', 'o', 'u'] if len(sys.argv) > 2 and sys.argv[1] == '-g': num = int(sys.argv[2]) random.seed(int(time.time())) dict_len = len(DICT) for _ in range(num): w = DICT[random.randint(0, dict_len-1)] print(make_word(w)) else: try: while 1: word = raw_input('>') if word == "" or word == "\n": break if word in dict_set: print(word + ' -> '+ word) continue mlist = inverted_dict[reduce_word(word)] arr0 = map(lambda x: len(x), re.split(r'[^aoieu]+', word.lower())) found = False for item in mlist: arr1 = map(lambda x: len(x), re.split(r'[^aoieu]+', item)) if len(arr1) == len(arr0) and arr1 <= arr0: print(word + ' -> ' + item) found = True break if not found: print(word + ' -> NO SUGGESTION') except Exception: pass
4e5c0aada45a2f12b400a7ef61ebd7e87d04bd96
[ "Python" ]
1
Python
daywednes/spellcheck
e6506b2dc4f1d6fd0146529adc5f8974aa0fb5a7
358abdb5a20dd31507019b570302c555fac95308
refs/heads/master
<file_sep>target :UnitTestTests, :exclusive => true do pod 'Kiwi' end <file_sep># WSUnitTest A TDD project for practice// <file_sep>It is just a demo repo for my blog post here: [Use stub and mock in Kiwi](http://onevcat.com/2014/05/kiwi-mock-stub-test/). I replaced the OCMock with Kiwi to achieve the same result for the project of objc.io. You can visit [objc.io #1](http://www.objc.io/issue-1/) for further information.<file_sep>platform :ios, '7.0' pod 'MTDates' target :specs do link_with 'BDDExamplesSpecs' pod 'Specta' pod 'OCMockito' pod 'Expecta' pod 'Kiwi' end
0036c6affaf223b09d9b15474e7782f3aa298c9d
[ "Markdown", "Ruby" ]
4
Ruby
devSC/WSUnitTest
c66d9fb912d4101c1eb53bc1f3577aba68a4da3d
674f6ac00b0d3d38ba10e0a95628e8d7734eec36
refs/heads/master
<file_sep>"""SSW-810-A Ekaterina (katya) Bevinova HW12 """ import sqlite3 from flask import Flask, render_template app = Flask(__name__) @app.route('/instructors_table') def instructors_table(): DB_FILE = r"C:\sql\810_startup.db" query = "select CWID, Name, Dept, Course, count(Course) as Students from (select * from HW11_instructors left join HW11_grades on Instructor_CWID = CWID) group by Course order by CWID DESC " db = sqlite3.connect(DB_FILE) results = db.execute(query) data = [{'Cwid': cwid, 'Name': name, 'Dept': dept, 'Course': course, 'Students': students} for cwid, name, dept, course, students in results] db.close() return render_template('instructors_table.html', title='Stevens Repository', table_title="Number of students by course and instructor", instructors=data) app.run(debug=True) <file_sep>"""SSW-810-A Ekaterina (katya) Bevinova HW11 """ from prettytable import PrettyTable from HW08ebevinova import read_file import unittest import os from collections import defaultdict import sqlite3 class Student: "A class that stores all the information about students." pt_hdr = ['CWID', 'Name', 'Major', 'Completed Courses', 'Remaining Required', 'Remaining Electives'] def __init__(self, cwid, name, major): self.cwid = cwid self.name = name self.major = major self.courses = dict() #key is course, value is grade (we're not using defaultdict because we'll always have a value for the course) self.labels = ['cwid', 'name', 'major', 'courses'] def add_course(self, course, grade): """A function that assigns a value grade to the key course.""" self.courses[course] = grade def pt_row(self, maj): """"A function that creates rows with student's information.""" completed_courses, remaining_required, remaining_electives = maj.calculated_courses(self.courses) return [self.cwid, self.name, self.major, completed_courses, remaining_required, remaining_electives] class Majors: "A class that stores all the information about required and elective courses." pt_hdr = ['Dept', 'Required', 'Electives'] def __init__(self, dept): self.dept = dept self.required = set() self.electives = set() def add(self, flag, course): if flag == 'R': self.required.add(course) elif flag == 'E': self.electives.add(course) def calculated_courses(self, courses): """Return completed_courses, remaining_required, remaining_electives where courses is dict with key as a course and value as a grade""" remaining_required = self.required remaining_electives = self.electives completed_courses = set() for course, grade in courses.items(): if grade in ('A', 'A-', 'B+', 'B-', 'B', 'C', 'C-', 'C+'): completed_courses.add(course) remaining_required = self.required - completed_courses if self.electives.intersection(completed_courses): remaining_electives = None return completed_courses, remaining_required, remaining_electives def pt_row(self): return [self.dept, self.required, self.electives] class Instructor: """A class that stores all the information about instructors.""" pt_hdr = ['CWID', 'Name', 'Dept', 'Course', 'Students'] def __init__(self, cwid, name, department): self.cwid = cwid self.name = name self.department = department self.students = defaultdict(int) #defaultdict specifies only value type def add_course(self, course): self.students[course] += 1 def pt_row(self): """A function that creates rows with instructor's information.""" for course, num_students in self.students.items(): yield [self.cwid, self.name, self.department, course, num_students] class Repository: """A class that stores information about students and instructors and generates tables of students and instructors.""" def __init__(self, path, ptables =True): self.students = dict() #cwid is the key, Instance of class Student is the value self.instructors = dict() #cwid is they, Instance of class Instructor is the value self.grades = list() self.majors = dict() #major is the key, Instance of class Majors is the value self.reading_students(os.path.join(path, 'students.txt')) self.get_instructors(os.path.join(path, 'instructors.txt')) self.get_grades(os.path.join(path, 'grades.txt')) self.reading_majors(os.path.join(path, 'majors.txt')) if ptables: print("\nStudent Summary") self.student_table() print("\nInstructor Summary") self.instructor_table() print("\nMajors Summary") self.majors_table() def majors_table(self): pt = PrettyTable(field_names = Majors.pt_hdr) for dept in self.majors.values(): pt.add_row(dept.pt_row()) print (pt) def student_table(self): """A function that creates a table with student's information.""" pt = PrettyTable(field_names = Student.pt_hdr) for student in self.students.values(): pt.add_row(student.pt_row(self.majors[student.major])) print (pt) def instructor_table(self): """A function that creates a table with instructor's information that is extracted from External Database.""" DB_FILE = "C:\sql\810_startup.db" db = sqlite3.connect(DB_FILE) pt = PrettyTable(field_names = Instructor.pt_hdr) query = "select CWID, Name, Dept, Course, count(Course) as Students from (select * from HW11_instructors left join HW11_grades on Instructor_CWID = CWID) group by Course order by CWID DESC " for row in db.execute(query): pt.add_row(row) print (pt) db.close() def reading_majors(self, path): try: for dept, flag, course in read_file(path, 3, '\t', header=False): if dept not in self.majors: #if dept is not in majors (dict) then we add a new instance of it self.majors[dept] = Majors(dept) self.majors[dept].add(flag, course) #add flag, course to the major through every line except ValueError as e: print (e) def reading_students(self, path): """A function that assigns student's information (cwid, name, major) to his/her cwid.""" try: for cwid, name, major in read_file(path, 3, '\t', header=False): self.students[cwid] = Student(cwid, name, major) except ValueError as e: print(e) def get_instructors(self, path): """A function that assigns instructor's information (cwid, name, dept) to instructor's cwid.""" try: for cwid, name, dept in read_file(path, 3, sep = '\t', header=False): self.instructors[cwid] = Instructor(cwid, name, dept) except ValueError as e: print(e) def get_grades(self, path): """A function that adds courses and grades to students and instructors.""" try: for student_cwid, course, grade, instructor_cwid in read_file(path, 4, sep = '\t', header=False): if student_cwid in self.students: self.students[student_cwid].add_course(course, grade) else: print("unknown student") if instructor_cwid in self.instructors: self.instructors[instructor_cwid].add_course(course) else: print("instructor not found") except ValueError as e: print (e) def main(): path = (r'C:\Users\Kat\Documents\VSC-Python\810\Repository') stevens = Repository(path) if __name__ == '__main__': main()
477a459f5eb10e3dcd0391a065ca4d2c66a7271f
[ "Python" ]
2
Python
esbevinova/Repository
c3859b3f81407fe391596ff7844d7593039e3685
0be35cbee7ec447b35606275573a5ddfcd9bb860
refs/heads/master
<file_sep>var NNode = neataptic.Node; var Neat = neataptic.Neat; var Network = neataptic.Network; var methods = neataptic.methods; var architect = neataptic.architect; var BOARD_SIZE=4; var MUTATION_RATE=0.1; var ELITISM_PERCENT=0.1; var USE_TRAINED_POP=false; var PLAYER_AMOUNT=50 var START_HIDDEN_SIZE=16; var pop = []; /*for (var i = 0; i < batchSize; i++) { pop.push(randNet()); }*/ function randNet() { //return neataptic. var network = architect.Random(16, 10, 4); return network; } function currentBoard() { return game.grid.cells.reduce((a, b) => a.concat(b)).map(x => ( x ? 0.5 / x.value : 1)); } function stringBoard() { return game.grid.cells.map(a=>a.map(x => ( x ? x.value : 0)).join(",")).join(";"); } var runningNet = false; var runningLoop = -1; var stuck = false; var tNetCB=Math.sqrt; //drawGraph(network.graph(1000, 800), '.svg'); function testNetVisible(network,callback) { tNetCB=callback; window.clearInterval(runningLoop); game.restart(); runningNet = network; stuck = false; runningLoop = window.setInterval(tickVisible, 0); /*while(!game.over){ var choices=network.activate(currentBoard()); var max=Math.max(...choices); game.move([0,1,2,3].filter(x=>choices[x]===max)[0]); }*/ } function tryMove(way){ var before=stringBoard(); game.move(way); return before!==stringBoard(); } function tickVisible() { if (game.over || stuck) { runningNet = false; window.clearInterval(runningLoop); if(tNetCB){ tNetCB(); } } if (runningNet) { var choices = runningNet.activate(currentBoard()); var max = Math.max(...choices); var markedChoices = [0, 1, 2, 3].map(x => ({v: x, s: choices[x]})); markedChoices.sort(function(a, b) { return b.s - a.s; }); var moved = tryMove(markedChoices[0].v); if (!moved) { var moved = tryMove(markedChoices[1].v); if (!moved) { var moved = tryMove(markedChoices[2].v); if (!moved) { var moved = tryMove(markedChoices[3].v); if (!moved) { stuck = true; } } } } } } var runningNet = false; var runningLoop = -1; var stuck = false; //drawGraph(network.graph(1000, 800), '.svg'); function testNet(network) { // window.clearInterval(runningLoop); game.restart(); runningNet = network; stuck = false; // runningLoop=window.setInterval(tick,100); while (!(game.over || stuck)) { var choices = runningNet.activate(currentBoard()); var max = Math.max(...choices); var markedChoices = [0, 1, 2, 3].map(x => ({v: x, s: choices[x]})); markedChoices.sort(function(a, b) { return b.s - a.s; }); var moved = tryMove(markedChoices[0].v); if (!moved) { var moved = tryMove(markedChoices[1].v); if (!moved) { var moved = tryMove(markedChoices[2].v); if (!moved) { var moved = tryMove(markedChoices[3].v); if (!moved) { stuck = true; } } } } } return game.score; } function advancedTest(network, times) { var ave = 0; for (var i = 0; i < times; i++) { ave += testNet(network) / times; } return ave; } function tick() { if (game.over || stuck) { runningNet = false; window.clearInterval(runningLoop); } if (runningNet) { var choices = runningNet.activate(currentBoard()); var max = Math.max(...choices); var markedChoices = [0, 1, 2, 3].map(x => ({v: x, s: choices[x]})); markedChoices.sort(function(a, b) { return b.s - a.s; }); var moved = tryMove(markedChoices[0].v); if (!moved) { var moved = tryMove(markedChoices[1].v); if (!moved) { var moved = tryMove(markedChoices[2].v); if (!moved) { var moved = tryMove(markedChoices[3].v); if (!moved) { stuck = true; } } } } } } function findBests(population) { var markedPop = population.map(x => ({ n: x, s: advancedTest(x, 10) })); markedPop.sort(function(a, b) { return b.s - a.s; }); return markedPop; } function newGen(population) { var reserved = 10; var nextPop = findBests(population).slice(0, reserved).map(x => x.n); for (var i = 0; i < batchSize - reserved; i++) { var a = nextPop[Math.floor(Math.random() * reserved)]; var b = nextPop[Math.floor(Math.random() * reserved)]; nextPop.push(Network.crossOver(a, b)); if (Math.random() < 0.5) { nextPop[nextPop.length - 1].mutate(neataptic.methods.mutation.ALL); } } return nextPop; } function increment() { pop = newGen(pop); } function showBest(population) { var best = findBests(population)[0].n; game.actuator.clearMessage(); testNetVisible(best); } function evolve(times) { //game.actuator.uiOn = false; for (var i = 0; i < times; i++) { increment(); } //game.actuator.uiOn = true; showBest(pop); console.log(game.score); } /** Construct the genetic algorithm */ function initNeat(){ window.neat = new Neat( BOARD_SIZE*BOARD_SIZE, 4, function(network){return advancedTest(network, 10);}, { mutation: methods.mutation.ALL, popsize: PLAYER_AMOUNT, mutationRate: MUTATION_RATE, elitism: Math.round(ELITISM_PERCENT * PLAYER_AMOUNT), network: new architect.Random( BOARD_SIZE*BOARD_SIZE, START_HIDDEN_SIZE, 4 ) } ); //if(USE_TRAINED_POP) neat.population = population; } initNeat(); /** End the evaluation of the current generation */ /*function endEvaluation(){ console.log('Generation:', neat.generation, '- average score:', neat.getAverage()); neat.sort(); var newPopulation = []; // Elitism for(var i = 0; i < neat.elitism; i++){ newPopulation.push(neat.population[i]); } // Breed the next individuals for(var i = 0; i < neat.popsize - neat.elitism; i++){ newPopulation.push(neat.getOffspring()); } // Replace the old population with the new population neat.population = newPopulation; neat.mutate(); neat.generation++; }*/ /* window.onready=function(){ evolve(100); } */ /*function runFromString(str,cb) { testNetVisible(Network.fromJSON(JSON.parse(str)),cb); } function readTextFile(file, callback) { var rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4 && rawFile.status == "200") { callback(rawFile.responseText); } } rawFile.send(null); } //usage: function fromMade() { console.log(game.score); readTextFile("../op.json", function(text) { //var data = JSON.parse(text); runFromString(text,fromMade); }); } window.setTimeout(fromMade, 1000); */
865756cccb2b373c1d7c39de9569033d62617fa0
[ "JavaScript" ]
1
JavaScript
ckissane/neataptic-2048
f7d56e2bde799910bf270bff451dc921a8be7e9a
b2ad6b70ac0e4c9c1a7ae7b673a8222064dc2939
refs/heads/master
<repo_name>hurricanerix/react-boiler<file_sep>/scripts/dev-server.sh #!/bin/bash PATH=$(npm bin):$PATH SCRIPT=`basename $0` FLAG=$1 if [ "$FLAG" != "-r" ] && [ "$FLAG" != "" ]; then echo -e "$0 -- Start a dev server, and re-bundle files as needed." echo "usage: $0 [-r]" echo -e "\t-r\tServe files out of 'release' instead" exit 0 fi WATCH_CMD='scripts/bundle.sh' HTTP_TARGET='app/' if [ "$FLAG" == "-r" ]; then WATCH_CMD='scripts/build_release.sh' HTTP_TARGET='release/' fi # Notify start echo -n "$SCRIPT start: "; date; trap 'kill %1;' SIGINT watch "sh $WATCH_CMD" app/js/source app/css --ignoreDotFiles 2>&1 | \ sed -e 's/^/[watch] /' & \ http-server $HTTP_TARGET 2>&1 | sed -e 's/^/[http-server] /' # Done echo -n "$SCRIPT complete: "; date; echo; <file_sep>/scripts/build_release.sh #!/bin/bash PATH=$(npm bin):$PATH SCRIPT=`basename $0` # Notify start echo -n "$SCRIPT start: "; date; # Clean previous release rm -rf release mkdir release # Bundle JS/CSS sh scripts/bundle.sh # Minify JS into release directory uglify -s app/bundle.js -o release/bundle.js # Minify CSS into release directory cssshrink app/bundle.css > release/bundle.css # Copy HTML and images into release directory cp app/index.html release/index.html cp -r app/images/ release/images/ # Done echo -n "$SCRIPT complete: "; date; echo; <file_sep>/README.md # React App Boilerplate A React app to do something. # Dev Setup Run ```./scripts/setup.sh``` to download required tools and libraries. Next run ```./scripts/dev_server.sh``` to bundle the site and launch a HTTP server. Now you can view your changes by opening http://127.0.0.1:8080 in your browser of choice. # Releasing your App When you are ready to release, run ```./scripts/build_release.sh```, this will minifiy the bundled JS and CSS scripts, and copy all the required files into the directory ```release```. The ```release``` dir can then be deployed to your web server. <file_sep>/scripts/clean.sh #!/bin/bash SCRIPT=`basename $0` FLAG=$1 if [ "$FLAG" != "-n" ] && [ "$FLAG" != "" ]; then echo -e "$0 -- Removes all build, bundle and release files." echo "usage: $0 [-n]" echo -e "\t-n\tRemove 'node_modules' directory also." exit 0 fi # Notify start echo -n "$SCRIPT start: "; date; echo "removing 'release' directory" rm -rf release echo "removing 'app/js/build/' files" rm -rf app/js/build mkdir -p app/js/build echo "removing 'app/bundle.*' files" rm -f app/bundle.js rm -f app/bundle.css if [ "$FLAG" == "-n" ]; then # echo "removing 'node_modules' directory" rm -rf node_modules fi # Done echo -n "$SCRIPT complete: "; date; echo; <file_sep>/scripts/lint.sh #!/bin/bash PATH=$(npm bin):$PATH SCRIPT=`basename $0` echo -n "$SCRIPT start: "; date; eslint -c eslintrc.json app/js/source echo -n "$SCRIPT complete: "; date; echo; <file_sep>/scripts/bundle.sh #!/bin/bash PATH=$(npm bin):$PATH SCRIPT=`basename $0` echo -n "$SCRIPT start: "; date; echo "Transforming JS" babel --presets react,es2015 app/js/source -d app/js/build 2>&1 | sed -e 's/^/[babel] /' echo "Transforming JS complete" echo "Packaging JS" browserify app/js/build/app.js -o app/bundle.js 2>&1 | sed -e 's/^/[browserify] /' echo "Packaging JS complete" echo "Packaging CSS" cat app/css/*/* app/css/*.css | sed 's/..\/..\/images/images/g' > app/bundle.css echo "Packaging CSS complete" echo -n "$SCRIPT complete: "; date; echo; <file_sep>/scripts/setup.sh #!/bin/bash SCRIPT=`basename $0` # Notify start echo -n "$SCRIPT start: "; date; # JavaScript Libs npm install --save-dev react npm install --save-dev react-dom # Transformative Libs npm install --save-dev babel-cli npm install --save-dev babel-preset-react npm install --save-dev babel-preset-es2015 npm install --save-dev browserify npm install --save-dev grunt grunt-contrib-copy grunt-contrib-uglify grunt-contrib-concat grunt-contrib-clean npm install --save-dev uglify npm install --save-dev cssshrink # Dev Tools npm install --save-dev eslint npm install --save-dev watch npm install --save-dev http-server # Done echo -n "$SCRIPT complete: "; date; echo;
099bffd5ec023e7d118f8f729672cf37c0851aeb
[ "Markdown", "Shell" ]
7
Shell
hurricanerix/react-boiler
539e73959d20086b677a2b516b1facbce69374bc
c366aee7775fd99fbdaca25fd284f85f4f74c365
refs/heads/master
<repo_name>rikkimax/ogl_gen<file_sep>/man4/.svn/pristine/53/53c2fb136e5e0580eec23e07a54158b0ccf3bf40.svn-base <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>glBufferStorage - OpenGL 4 Reference Pages</title> <link rel="stylesheet" type="text/css" href="opengl-man.css"/> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"/> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ MathML: { extensions: ["content-mathml.js"] }, tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } }); </script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"/> </head> <body> <header/> <div class="refentry" id="glBufferStorage"> <div class="titlepage"/> <div class="refnamediv"> <h2>Name</h2> <p>glBufferStorage, glNamedBufferStorage — creates and initializes a buffer object's immutable data store</p> </div> <div class="refsynopsisdiv"> <h2>C Specification</h2> <div class="funcsynopsis"> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glBufferStorage</strong>(</code> </td> <td>GLenum <var class="pdparam">target</var>, </td> </tr> <tr> <td> </td> <td>GLsizeiptr <var class="pdparam">size</var>, </td> </tr> <tr> <td> </td> <td>const GLvoid * <var class="pdparam">data</var>, </td> </tr> <tr> <td> </td> <td>GLbitfield <var class="pdparam">flags</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glNamedBufferStorage</strong>(</code> </td> <td>GLuint <var class="pdparam">buffer</var>, </td> </tr> <tr> <td> </td> <td>GLsizei <var class="pdparam">size</var>, </td> </tr> <tr> <td> </td> <td>const void *<var class="pdparam">data</var>, </td> </tr> <tr> <td> </td> <td>GLbitfield <var class="pdparam">flags</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> </div> </div> <div class="refsect1" id="parameters"> <h2>Parameters</h2> <div class="variablelist"> <dl class="variablelist"> <dt> <span class="term"> <em class="parameter"> <code>target</code> </em> </span> </dt> <dd> <p> Specifies the target to which the buffer object is bound for <code class="function">glBufferStorage</code>, which must be one of the buffer binding targets in the following table: </p> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; " class="col1"/> <col style="text-align: left; " class="col2"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"> <strong>Buffer Binding Target</strong> </span> </th> <th style="text-align: left; border-bottom: 2px solid ; "> <span class="bold"> <strong>Purpose</strong> </span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ARRAY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Vertex attributes</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ATOMIC_COUNTER_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Atomic counter storage</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_COPY_READ_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Buffer copy source</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_COPY_WRITE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Buffer copy destination</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_DISPATCH_INDIRECT_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Indirect compute dispatch commands</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_DRAW_INDIRECT_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Indirect command arguments</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ELEMENT_ARRAY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Vertex array indices</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_PIXEL_PACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Pixel read target</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_PIXEL_UNPACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Texture data source</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_QUERY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Query result buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_SHADER_STORAGE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Read-write storage for shaders</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_TEXTURE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Texture data buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_TRANSFORM_FEEDBACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Transform feedback buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="constant">GL_UNIFORM_BUFFER</code> </td> <td style="text-align: left; ">Uniform block storage</td> </tr> </tbody> </table> </div> </dd> <dt> <span class="term"> <em class="parameter"> <code>buffer</code> </em> </span> </dt> <dd> <p>Specifies the name of the buffer object for <code class="function">glNamedBufferStorage</code> function.</p> </dd> <dt> <span class="term"> <em class="parameter"> <code>size</code> </em> </span> </dt> <dd> <p>Specifies the size in bytes of the buffer object's new data store.</p> </dd> <dt> <span class="term"> <em class="parameter"> <code>data</code> </em> </span> </dt> <dd> <p>Specifies a pointer to data that will be copied into the data store for initialization, or <code class="constant">NULL</code> if no data is to be copied.</p> </dd> <dt> <span class="term"> <em class="parameter"> <code>flags</code> </em> </span> </dt> <dd> <p>Specifies the intended usage of the buffer's data store. Must be a bitwise combination of the following flags. <code class="constant">GL_DYNAMIC_STORAGE_BIT</code>, <code class="constant">GL_MAP_READ_BIT</code> <code class="constant">GL_MAP_WRITE_BIT</code>, <code class="constant">GL_MAP_PERSISTENT_BIT</code>, <code class="constant">GL_MAP_COHERENT_BIT</code>, and <code class="constant">GL_CLIENT_STORAGE_BIT</code>.</p> </dd> </dl> </div> </div> <div class="refsect1" id="description"> <h2>Description</h2> <p><code class="function">glBufferStorage</code> and <code class="function">glNamedBufferStorage</code> create a new immutable data store. For <code class="function">glBufferStorage</code>, the buffer object currently bound to <em class="parameter"><code>target</code></em> will be initialized. For <code class="function">glNamedBufferStorage</code>, <em class="parameter"><code>buffer</code></em> is the name of the buffer object that will be configured. The size of the data store is specified by <em class="parameter"><code>size</code></em>. If an initial data is available, its address may be supplied in <em class="parameter"><code>data</code></em>. Otherwise, to create an uninitialized data store, <em class="parameter"><code>data</code></em> should be <code class="constant">NULL</code>.</p> <p>The <em class="parameter"><code>flags</code></em> parameters specifies the intended usage of the buffer's data store. It must be a bitwise combination of a subset of the following flags: </p> <div class="variablelist"> <dl class="variablelist"> <dt> <span class="term"> <code class="constant">GL_DYNAMIC_STORAGE_BIT</code> </span> </dt> <dd> <p>The contents of the data store may be updated after creation through calls to <a class="citerefentry" href="glBufferSubData.xhtml"><span class="citerefentry"><span class="refentrytitle">glBufferSubData</span></span></a>. If this bit is not set, the buffer content may not be directly updated by the client. The data argument may be used to specify the initial content of the buffer's data store regardless of the presence of the <code class="constant">GL_DYNAMIC_STORAGE_BIT</code>. Regardless of the presence of this bit, buffers may always be updated with server-side calls such as <a class="citerefentry" href="glCopyBufferSubData.xhtml"><span class="citerefentry"><span class="refentrytitle">glCopyBufferSubData</span></span></a> and <a class="citerefentry" href="glClearBufferSubData.xhtml"><span class="citerefentry"><span class="refentrytitle">glClearBufferSubData</span></span></a>. </p> </dd> <dt> <span class="term"> <code class="constant">GL_MAP_READ_BIT</code> </span> </dt> <dd> <p>The data store may be mapped by the client for read access and a pointer in the client's address space obtained that may be read from.</p> </dd> <dt> <span class="term"> <code class="constant">GL_MAP_WRITE_BIT</code> </span> </dt> <dd> <p>The data store may be mapped by the client for write access and a pointer in the client's address space obtained that may be written through.</p> </dd> <dt> <span class="term"> <code class="constant">GL_MAP_PERSISTENT_BIT</code> </span> </dt> <dd> <p>The client may request that the server read from or write to the buffer while it is mapped. The client's pointer to the data store remains valid so long as the data store is mapped, even during execution of drawing or dispatch commands.</p> </dd> <dt> <span class="term"> <code class="constant">GL_MAP_COHERENT_BIT</code> </span> </dt> <dd> <p>Shared access to buffers that are simultaneously mapped for client access and are used by the server will be coherent, so long as that mapping is performed using <a class="citerefentry" href="glMapBufferRange.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBufferRange</span></span></a>. That is, data written to the store by either the client or server will be immediately visible to the other with no further action taken by the application. In particular,</p> <div class="itemizedlist"> <ul style="list-style-type: disc; " class="itemizedlist"> <li class="listitem"> <p>If <code class="constant">GL_MAP_COHERENT_BIT</code> is not set and the client performs a write followed by a call to the <a class="citerefentry" href="glMemoryBarrier.xhtml"><span class="citerefentry"><span class="refentrytitle">glMemoryBarrier</span></span></a> command with the <code class="constant">GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT</code> set, then in subsequent commands the server will see the writes.</p> </li> <li class="listitem"> <p>If <code class="constant">GL_MAP_COHERENT_BIT</code> is set and the client performs a write, then in subsequent commands the server will see the writes.</p> </li> <li class="listitem"> <p>If <code class="constant">GL_MAP_COHERENT_BIT</code> is not set and the server performs a write, the application must call <a class="citerefentry" href="glMemoryBarrier.xhtml"><span class="citerefentry"><span class="refentrytitle">glMemoryBarrier</span></span></a> with the <code class="constant">GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT</code> set and then call <a class="citerefentry" href="glFenceSync.xhtml"><span class="citerefentry"><span class="refentrytitle">glFenceSync</span></span></a> with <code class="constant">GL_SYNC_GPU_COMMANDS_COMPLETE</code> (or <code class="function">glFinish</code>). Then the CPU will see the writes after the sync is complete.</p> </li> <li class="listitem"> <p>If <code class="constant">GL_MAP_COHERENT_BIT</code> is set and the server does a write, the app must call <code class="function">glFenceSync</code> with <code class="constant">GL_SYNC_GPU_COMMANDS_COMPLETE</code> (or <a class="citerefentry" href="glFinish.xhtml"><span class="citerefentry"><span class="refentrytitle">glFinish</span></span></a>). Then the CPU will see the writes after the sync is complete.</p> </li> </ul> </div> </dd> <dt> <span class="term"> <code class="constant">GL_CLIENT_STORAGE_BIT</code> </span> </dt> <dd> <p>When all other criteria for the buffer storage allocation are met, this bit may be used by an implementation to determine whether to use storage that is local to the server or to the client to serve as the backing store for the buffer.</p> </dd> </dl> </div> <p>The allowed combinations of flags are subject to certain restrictions. They are as follows: </p> <div class="itemizedlist"> <ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <p>If <em class="parameter"><code>flags</code></em> contains <code class="constant">GL_MAP_PERSISTENT_BIT</code>, it must also contain at least one of <code class="constant">GL_MAP_READ_BIT</code> or <code class="constant">GL_MAP_WRITE_BIT</code>.</p> </li> <li class="listitem"> <p>If <em class="parameter"><code>flags</code></em> contains <code class="constant">GL_MAP_COHERENT_BIT</code>, it must also contain <code class="constant">GL_MAP_PERSISTENT_BIT</code>.</p> </li> </ul> </div> </div> <div class="refsect1" id="notes"> <h2>Notes</h2> <p><code class="function">glBufferStorage</code> is available only if the GL version is 4.4 or greater.</p> <p><code class="function">glNamedBufferStorage</code> is available only if the GL version is 4.5 or greater.</p> <p>If <em class="parameter"><code>data</code></em> is <code class="constant">NULL</code>, a data store of the specified size is still created, but its contents remain uninitialized and thus undefined.</p> </div> <div class="refsect1" id="errors"> <h2>Errors</h2> <p><code class="constant">GL_INVALID_ENUM</code> is generated by <code class="function">glBufferStorage</code> if <em class="parameter"><code>target</code></em> is not one of the accepted buffer targets.</p> <p><code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glNamedBufferStorage</code> if buffer is not the name of an existing buffer object.</p> <p><code class="constant">GL_INVALID_VALUE</code> is generated if <em class="parameter"><code>size</code></em> is less than or equal to zero.</p> <p><code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glBufferStorage</code> if the reserved buffer object name 0 is bound to <em class="parameter"><code>target</code></em>.</p> <p><code class="constant">GL_OUT_OF_MEMORY</code> is generated if the GL is unable to create a data store with the properties requested in <em class="parameter"><code>flags</code></em>.</p> <p><code class="constant">GL_INVALID_VALUE</code> is generated if <em class="parameter"><code>flags</code></em> has any bits set other than those defined above.</p> <p><code class="constant">GL_INVALID_VALUE</code> error is generated if <em class="parameter"><code>flags</code></em> contains <code class="constant">GL_MAP_PERSISTENT_BIT</code> but does not contain at least one of <code class="constant">GL_MAP_READ_BIT</code> or <code class="constant">GL_MAP_WRITE_BIT</code>.</p> <p><code class="constant">GL_INVALID_VALUE</code> is generated if <em class="parameter"><code>flags</code></em> contains <code class="constant">GL_MAP_COHERENT_BIT</code>, but does not also contain <code class="constant">GL_MAP_PERSISTENT_BIT</code>.</p> <p><code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glBufferStorage</code> if the <code class="constant">GL_BUFFER_IMMUTABLE_STORAGE</code> flag of the buffer bound to <em class="parameter"><code>target</code></em> is <code class="constant">GL_TRUE</code>.</p> </div> <div class="refsect1" id="associatedgets"> <h2>Associated Gets</h2> <p> <a class="citerefentry" href="glGetBufferSubData.xhtml"><span class="citerefentry"><span class="refentrytitle">glGetBufferSubData</span></span></a> </p> <p><a class="citerefentry" href="glGetBufferParameter.xhtml"><span class="citerefentry"><span class="refentrytitle">glGetBufferParameter</span></span></a> with argument <code class="constant">GL_BUFFER_SIZE</code> or <code class="constant">GL_BUFFER_USAGE</code></p> </div> <div class="refsect1" id="versions"> <h2>Version Support</h2> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; "/> <col style="text-align: center; " class="firstvers"/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; " class="lastvers"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; "> </th> <th style="text-align: center; border-bottom: 2px solid ; " colspan="12"> <span class="bold"><strong>OpenGL Version</strong></span> </th> </tr> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>Function / Feature Name</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.4</strong></span> </th> <th style="text-align: center; border-bottom: 2px solid ; "> <span class="bold"><strong>4.5</strong></span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="function">glBufferStorage</code> </td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-bottom: 2px solid ; ">✔</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="function">glNamedBufferStorage</code> </td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; ">✔</td> </tr> </tbody> </table> </div> </div> <div class="refsect1" id="seealso"> <h2>See Also</h2> <p> <a class="citerefentry" href="glBindBuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glBindBuffer</span></span></a>, <a class="citerefentry" href="glBufferSubData.xhtml"><span class="citerefentry"><span class="refentrytitle">glBufferSubData</span></span></a>, <a class="citerefentry" href="glMapBuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBuffer</span></span></a>, <a class="citerefentry" href="glUnmapBuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glUnmapBuffer</span></span></a> </p> </div> <div class="refsect1" id="Copyright"> <h2>Copyright</h2> <p> Copyright <span class="trademark"/>© 2014 Khronos Group. This material may be distributed subject to the terms and conditions set forth in the Open Publication License, v 1.0, 8 June 1999. <a class="link" href="http://opencontent.org/openpub/" target="_top">http://opencontent.org/openpub/</a>. </p> </div> </div> <footer/> </body> </html> <file_sep>/man4/docbook4/Makefile #!gmake # # License Applicability. Except to the extent portions of this file are # made subject to an alternative license as permitted in the SGI Free # Software License B, Version 1.1 (the "License"), the contents of this # file are subject only to the provisions of the License. You may not use # this file except in compliance with the License. You may obtain a copy # of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 # Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: # # http://oss.sgi.com/projects/FreeB # # Note that, as provided in the License, the Software is distributed on an # "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS # DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND # CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A # PARTICULAR PURPOSE, AND NON-INFRINGEMENT. # # Original Code. The Original Code is: OpenGL Sample Implementation, # Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, # Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. # Copyright in any portions created by third parties is as indicated # elsewhere herein. All Rights Reserved. # # Additional Notice Provisions: The application programming interfaces # established by SGI in conjunction with the Original Code are The # OpenGL(R) Graphics System: A Specification (Version 1.2.1), released # April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version # 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X # Window System(R) (Version 1.3), released October 19, 1998. This software # was created using the OpenGL(R) version 1.2.1 Sample Implementation # published by SGI, but has not been independently verified as being # compliant with the OpenGL(R) version 1.2.1 Specification. COMMONPREF = standard include $(ROOT)/usr/include/make/commondefs SUBDIRS = \ xhtml \ $(NULL) default $(ALLTARGS): $(_FORCE) $(SUBDIRS_MAKERULE) distoss: $(MAKE) $(COMMONPREF)$@ $(SUBDIRS_MAKERULE) include $(COMMONRULES) DOCBOOK4DTD = http://www.oasis-open.org/docbook/xml/mathml/1.1CR1/dbmathml.dtd XMLLINT = xmllint --noout --xinclude --dtdvalid $(DOCBOOK4DTD) validate: $(XMLLINT) [a-t]*.xml <file_sep>/man4/.svn/pristine/23/231f0f51162c6c9c069abd4ca9f052cd168a261d.svn-base <html> <head> <link rel="stylesheet" type="text/css" href="style-index.css" /> <title>OpenGL 4.x Reference Pages</title> <?php include 'accord.js'; ?> </head> <body> <a href="indexflat.php">Use alternate (flat) index</a> <div id="navwrap"> <ul id="containerul"> <!-- Must wrap entire list for expand/contract --> <li class="Level1"> <a href="start.html" target="pagedisplay">Introduction</a> </li> <li class="Level1">API Entry Points <ul class="Level2"> <a name="a"></a> <li>a <ul class="Level3"> <li><a href="glActiveShaderProgram.xhtml" target="pagedisplay">glActiveShaderProgram</a></li> <li><a href="glActiveTexture.xhtml" target="pagedisplay">glActiveTexture</a></li> <li><a href="glAttachShader.xhtml" target="pagedisplay">glAttachShader</a></li> </ul> <!-- End Level3 --> </li> <a name="b"></a> <li>b <ul class="Level3"> <li><a href="glBeginConditionalRender.xhtml" target="pagedisplay">glBeginConditionalRender</a></li> <li><a href="glBeginQuery.xhtml" target="pagedisplay">glBeginQuery</a></li> <li><a href="glBeginQueryIndexed.xhtml" target="pagedisplay">glBeginQueryIndexed</a></li> <li><a href="glBeginTransformFeedback.xhtml" target="pagedisplay">glBeginTransformFeedback</a></li> <li><a href="glBindAttribLocation.xhtml" target="pagedisplay">glBindAttribLocation</a></li> <li><a href="glBindBuffer.xhtml" target="pagedisplay">glBindBuffer</a></li> <li><a href="glBindBufferBase.xhtml" target="pagedisplay">glBindBufferBase</a></li> <li><a href="glBindBufferRange.xhtml" target="pagedisplay">glBindBufferRange</a></li> <li><a href="glBindBuffersBase.xhtml" target="pagedisplay">glBindBuffersBase</a></li> <li><a href="glBindBuffersRange.xhtml" target="pagedisplay">glBindBuffersRange</a></li> <li><a href="glBindFragDataLocation.xhtml" target="pagedisplay">glBindFragDataLocation</a></li> <li><a href="glBindFragDataLocationIndexed.xhtml" target="pagedisplay">glBindFragDataLocationIndexed</a></li> <li><a href="glBindFramebuffer.xhtml" target="pagedisplay">glBindFramebuffer</a></li> <li><a href="glBindImageTexture.xhtml" target="pagedisplay">glBindImageTexture</a></li> <li><a href="glBindImageTextures.xhtml" target="pagedisplay">glBindImageTextures</a></li> <li><a href="glBindProgramPipeline.xhtml" target="pagedisplay">glBindProgramPipeline</a></li> <li><a href="glBindRenderbuffer.xhtml" target="pagedisplay">glBindRenderbuffer</a></li> <li><a href="glBindSampler.xhtml" target="pagedisplay">glBindSampler</a></li> <li><a href="glBindSamplers.xhtml" target="pagedisplay">glBindSamplers</a></li> <li><a href="glBindTexture.xhtml" target="pagedisplay">glBindTexture</a></li> <li><a href="glBindTextures.xhtml" target="pagedisplay">glBindTextures</a></li> <li><a href="glBindTextureUnit.xhtml" target="pagedisplay">glBindTextureUnit</a></li> <li><a href="glBindTransformFeedback.xhtml" target="pagedisplay">glBindTransformFeedback</a></li> <li><a href="glBindVertexArray.xhtml" target="pagedisplay">glBindVertexArray</a></li> <li><a href="glBindVertexBuffer.xhtml" target="pagedisplay">glBindVertexBuffer</a></li> <li><a href="glBindVertexBuffers.xhtml" target="pagedisplay">glBindVertexBuffers</a></li> <li><a href="glBlendColor.xhtml" target="pagedisplay">glBlendColor</a></li> <li><a href="glBlendEquation.xhtml" target="pagedisplay">glBlendEquation</a></li> <li><a href="glBlendEquation.xhtml" target="pagedisplay">glBlendEquationi</a></li> <li><a href="glBlendEquationSeparate.xhtml" target="pagedisplay">glBlendEquationSeparate</a></li> <li><a href="glBlendEquationSeparate.xhtml" target="pagedisplay">glBlendEquationSeparatei</a></li> <li><a href="glBlendFunc.xhtml" target="pagedisplay">glBlendFunc</a></li> <li><a href="glBlendFunc.xhtml" target="pagedisplay">glBlendFunci</a></li> <li><a href="glBlendFuncSeparate.xhtml" target="pagedisplay">glBlendFuncSeparate</a></li> <li><a href="glBlendFuncSeparate.xhtml" target="pagedisplay">glBlendFuncSeparatei</a></li> <li><a href="glBlitFramebuffer.xhtml" target="pagedisplay">glBlitFramebuffer</a></li> <li><a href="glBlitFramebuffer.xhtml" target="pagedisplay">glBlitNamedFramebuffer</a></li> <li><a href="glBufferData.xhtml" target="pagedisplay">glBufferData</a></li> <li><a href="glBufferStorage.xhtml" target="pagedisplay">glBufferStorage</a></li> <li><a href="glBufferSubData.xhtml" target="pagedisplay">glBufferSubData</a></li> </ul> <!-- End Level3 --> </li> <a name="c"></a> <li>c <ul class="Level3"> <li><a href="glCheckFramebufferStatus.xhtml" target="pagedisplay">glCheckFramebufferStatus</a></li> <li><a href="glCheckFramebufferStatus.xhtml" target="pagedisplay">glCheckNamedFramebufferStatus</a></li> <li><a href="glClampColor.xhtml" target="pagedisplay">glClampColor</a></li> <li><a href="glClear.xhtml" target="pagedisplay">glClear</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearBuffer</a></li> <li><a href="glClearBufferData.xhtml" target="pagedisplay">glClearBufferData</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearBufferfi</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearBufferfv</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearBufferiv</a></li> <li><a href="glClearBufferSubData.xhtml" target="pagedisplay">glClearBufferSubData</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearBufferuiv</a></li> <li><a href="glClearColor.xhtml" target="pagedisplay">glClearColor</a></li> <li><a href="glClearDepth.xhtml" target="pagedisplay">glClearDepth</a></li> <li><a href="glClearDepth.xhtml" target="pagedisplay">glClearDepthf</a></li> <li><a href="glClearBufferData.xhtml" target="pagedisplay">glClearNamedBufferData</a></li> <li><a href="glClearBufferSubData.xhtml" target="pagedisplay">glClearNamedBufferSubData</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearNamedFramebufferfi</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearNamedFramebufferfv</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearNamedFramebufferiv</a></li> <li><a href="glClearBuffer.xhtml" target="pagedisplay">glClearNamedFramebufferuiv</a></li> <li><a href="glClearStencil.xhtml" target="pagedisplay">glClearStencil</a></li> <li><a href="glClearTexImage.xhtml" target="pagedisplay">glClearTexImage</a></li> <li><a href="glClearTexSubImage.xhtml" target="pagedisplay">glClearTexSubImage</a></li> <li><a href="glClientWaitSync.xhtml" target="pagedisplay">glClientWaitSync</a></li> <li><a href="glClipControl.xhtml" target="pagedisplay">glClipControl</a></li> <li><a href="glColorMask.xhtml" target="pagedisplay">glColorMask</a></li> <li><a href="glColorMask.xhtml" target="pagedisplay">glColorMaski</a></li> <li><a href="glCompileShader.xhtml" target="pagedisplay">glCompileShader</a></li> <li><a href="glCompressedTexImage1D.xhtml" target="pagedisplay">glCompressedTexImage1D</a></li> <li><a href="glCompressedTexImage2D.xhtml" target="pagedisplay">glCompressedTexImage2D</a></li> <li><a href="glCompressedTexImage3D.xhtml" target="pagedisplay">glCompressedTexImage3D</a></li> <li><a href="glCompressedTexSubImage1D.xhtml" target="pagedisplay">glCompressedTexSubImage1D</a></li> <li><a href="glCompressedTexSubImage2D.xhtml" target="pagedisplay">glCompressedTexSubImage2D</a></li> <li><a href="glCompressedTexSubImage3D.xhtml" target="pagedisplay">glCompressedTexSubImage3D</a></li> <li><a href="glCompressedTexSubImage1D.xhtml" target="pagedisplay">glCompressedTextureSubImage1D</a></li> <li><a href="glCompressedTexSubImage2D.xhtml" target="pagedisplay">glCompressedTextureSubImage2D</a></li> <li><a href="glCompressedTexSubImage3D.xhtml" target="pagedisplay">glCompressedTextureSubImage3D</a></li> <li><a href="glCopyBufferSubData.xhtml" target="pagedisplay">glCopyBufferSubData</a></li> <li><a href="glCopyImageSubData.xhtml" target="pagedisplay">glCopyImageSubData</a></li> <li><a href="glCopyBufferSubData.xhtml" target="pagedisplay">glCopyNamedBufferSubData</a></li> <li><a href="glCopyTexImage1D.xhtml" target="pagedisplay">glCopyTexImage1D</a></li> <li><a href="glCopyTexImage2D.xhtml" target="pagedisplay">glCopyTexImage2D</a></li> <li><a href="glCopyTexSubImage1D.xhtml" target="pagedisplay">glCopyTexSubImage1D</a></li> <li><a href="glCopyTexSubImage2D.xhtml" target="pagedisplay">glCopyTexSubImage2D</a></li> <li><a href="glCopyTexSubImage3D.xhtml" target="pagedisplay">glCopyTexSubImage3D</a></li> <li><a href="glCopyTexSubImage1D.xhtml" target="pagedisplay">glCopyTextureSubImage1D</a></li> <li><a href="glCopyTexSubImage2D.xhtml" target="pagedisplay">glCopyTextureSubImage2D</a></li> <li><a href="glCopyTexSubImage3D.xhtml" target="pagedisplay">glCopyTextureSubImage3D</a></li> <li><a href="glCreateBuffers.xhtml" target="pagedisplay">glCreateBuffers</a></li> <li><a href="glCreateFramebuffers.xhtml" target="pagedisplay">glCreateFramebuffers</a></li> <li><a href="glCreateProgram.xhtml" target="pagedisplay">glCreateProgram</a></li> <li><a href="glCreateProgramPipelines.xhtml" target="pagedisplay">glCreateProgramPipelines</a></li> <li><a href="glCreateQueries.xhtml" target="pagedisplay">glCreateQueries</a></li> <li><a href="glCreateRenderbuffers.xhtml" target="pagedisplay">glCreateRenderbuffers</a></li> <li><a href="glCreateSamplers.xhtml" target="pagedisplay">glCreateSamplers</a></li> <li><a href="glCreateShader.xhtml" target="pagedisplay">glCreateShader</a></li> <li><a href="glCreateShaderProgram.xhtml" target="pagedisplay">glCreateShaderProgram</a></li> <li><a href="glCreateShaderProgram.xhtml" target="pagedisplay">glCreateShaderProgramv</a></li> <li><a href="glCreateTextures.xhtml" target="pagedisplay">glCreateTextures</a></li> <li><a href="glCreateTransformFeedbacks.xhtml" target="pagedisplay">glCreateTransformFeedbacks</a></li> <li><a href="glCreateVertexArrays.xhtml" target="pagedisplay">glCreateVertexArrays</a></li> <li><a href="glCullFace.xhtml" target="pagedisplay">glCullFace</a></li> </ul> <!-- End Level3 --> </li> <a name="d"></a> <li>d <ul class="Level3"> <li><a href="glDebugMessageCallback.xhtml" target="pagedisplay">glDebugMessageCallback</a></li> <li><a href="glDebugMessageControl.xhtml" target="pagedisplay">glDebugMessageControl</a></li> <li><a href="glDebugMessageInsert.xhtml" target="pagedisplay">glDebugMessageInsert</a></li> <li><a href="glDeleteBuffers.xhtml" target="pagedisplay">glDeleteBuffers</a></li> <li><a href="glDeleteFramebuffers.xhtml" target="pagedisplay">glDeleteFramebuffers</a></li> <li><a href="glDeleteProgram.xhtml" target="pagedisplay">glDeleteProgram</a></li> <li><a href="glDeleteProgramPipelines.xhtml" target="pagedisplay">glDeleteProgramPipelines</a></li> <li><a href="glDeleteQueries.xhtml" target="pagedisplay">glDeleteQueries</a></li> <li><a href="glDeleteRenderbuffers.xhtml" target="pagedisplay">glDeleteRenderbuffers</a></li> <li><a href="glDeleteSamplers.xhtml" target="pagedisplay">glDeleteSamplers</a></li> <li><a href="glDeleteShader.xhtml" target="pagedisplay">glDeleteShader</a></li> <li><a href="glDeleteSync.xhtml" target="pagedisplay">glDeleteSync</a></li> <li><a href="glDeleteTextures.xhtml" target="pagedisplay">glDeleteTextures</a></li> <li><a href="glDeleteTransformFeedbacks.xhtml" target="pagedisplay">glDeleteTransformFeedbacks</a></li> <li><a href="glDeleteVertexArrays.xhtml" target="pagedisplay">glDeleteVertexArrays</a></li> <li><a href="glDepthFunc.xhtml" target="pagedisplay">glDepthFunc</a></li> <li><a href="glDepthMask.xhtml" target="pagedisplay">glDepthMask</a></li> <li><a href="glDepthRange.xhtml" target="pagedisplay">glDepthRange</a></li> <li><a href="glDepthRangeArray.xhtml" target="pagedisplay">glDepthRangeArray</a></li> <li><a href="glDepthRangeArray.xhtml" target="pagedisplay">glDepthRangeArrayv</a></li> <li><a href="glDepthRange.xhtml" target="pagedisplay">glDepthRangef</a></li> <li><a href="glDepthRangeIndexed.xhtml" target="pagedisplay">glDepthRangeIndexed</a></li> <li><a href="glDetachShader.xhtml" target="pagedisplay">glDetachShader</a></li> <li><a href="glEnable.xhtml" target="pagedisplay">glDisable</a></li> <li><a href="glEnable.xhtml" target="pagedisplay">glDisablei</a></li> <li><a href="glEnableVertexAttribArray.xhtml" target="pagedisplay">glDisableVertexArrayAttrib</a></li> <li><a href="glEnableVertexAttribArray.xhtml" target="pagedisplay">glDisableVertexAttribArray</a></li> <li><a href="glDispatchCompute.xhtml" target="pagedisplay">glDispatchCompute</a></li> <li><a href="glDispatchComputeIndirect.xhtml" target="pagedisplay">glDispatchComputeIndirect</a></li> <li><a href="glDrawArrays.xhtml" target="pagedisplay">glDrawArrays</a></li> <li><a href="glDrawArraysIndirect.xhtml" target="pagedisplay">glDrawArraysIndirect</a></li> <li><a href="glDrawArraysInstanced.xhtml" target="pagedisplay">glDrawArraysInstanced</a></li> <li><a href="glDrawArraysInstancedBaseInstance.xhtml" target="pagedisplay">glDrawArraysInstancedBaseInstance</a></li> <li><a href="glDrawBuffer.xhtml" target="pagedisplay">glDrawBuffer</a></li> <li><a href="glDrawBuffers.xhtml" target="pagedisplay">glDrawBuffers</a></li> <li><a href="glDrawElements.xhtml" target="pagedisplay">glDrawElements</a></li> <li><a href="glDrawElementsBaseVertex.xhtml" target="pagedisplay">glDrawElementsBaseVertex</a></li> <li><a href="glDrawElementsIndirect.xhtml" target="pagedisplay">glDrawElementsIndirect</a></li> <li><a href="glDrawElementsInstanced.xhtml" target="pagedisplay">glDrawElementsInstanced</a></li> <li><a href="glDrawElementsInstancedBaseInstance.xhtml" target="pagedisplay">glDrawElementsInstancedBaseInstance</a></li> <li><a href="glDrawElementsInstancedBaseVertex.xhtml" target="pagedisplay">glDrawElementsInstancedBaseVertex</a></li> <li><a href="glDrawElementsInstancedBaseVertexBaseInstance.xhtml" target="pagedisplay">glDrawElementsInstancedBaseVertexBaseInstance</a></li> <li><a href="glDrawRangeElements.xhtml" target="pagedisplay">glDrawRangeElements</a></li> <li><a href="glDrawRangeElementsBaseVertex.xhtml" target="pagedisplay">glDrawRangeElementsBaseVertex</a></li> <li><a href="glDrawTransformFeedback.xhtml" target="pagedisplay">glDrawTransformFeedback</a></li> <li><a href="glDrawTransformFeedbackInstanced.xhtml" target="pagedisplay">glDrawTransformFeedbackInstanced</a></li> <li><a href="glDrawTransformFeedbackStream.xhtml" target="pagedisplay">glDrawTransformFeedbackStream</a></li> <li><a href="glDrawTransformFeedbackStreamInstanced.xhtml" target="pagedisplay">glDrawTransformFeedbackStreamInstanced</a></li> </ul> <!-- End Level3 --> </li> <a name="e"></a> <li>e <ul class="Level3"> <li><a href="glEnable.xhtml" target="pagedisplay">glEnable</a></li> <li><a href="glEnable.xhtml" target="pagedisplay">glEnablei</a></li> <li><a href="glEnableVertexAttribArray.xhtml" target="pagedisplay">glEnableVertexArrayAttrib</a></li> <li><a href="glEnableVertexAttribArray.xhtml" target="pagedisplay">glEnableVertexAttribArray</a></li> <li><a href="glBeginConditionalRender.xhtml" target="pagedisplay">glEndConditionalRender</a></li> <li><a href="glBeginQuery.xhtml" target="pagedisplay">glEndQuery</a></li> <li><a href="glBeginQueryIndexed.xhtml" target="pagedisplay">glEndQueryIndexed</a></li> <li><a href="glBeginTransformFeedback.xhtml" target="pagedisplay">glEndTransformFeedback</a></li> </ul> <!-- End Level3 --> </li> <a name="f"></a> <li>f <ul class="Level3"> <li><a href="glFenceSync.xhtml" target="pagedisplay">glFenceSync</a></li> <li><a href="glFinish.xhtml" target="pagedisplay">glFinish</a></li> <li><a href="glFlush.xhtml" target="pagedisplay">glFlush</a></li> <li><a href="glFlushMappedBufferRange.xhtml" target="pagedisplay">glFlushMappedBufferRange</a></li> <li><a href="glFlushMappedBufferRange.xhtml" target="pagedisplay">glFlushMappedNamedBufferRange</a></li> <li><a href="glFramebufferParameteri.xhtml" target="pagedisplay">glFramebufferParameteri</a></li> <li><a href="glFramebufferRenderbuffer.xhtml" target="pagedisplay">glFramebufferRenderbuffer</a></li> <li><a href="glFramebufferTexture.xhtml" target="pagedisplay">glFramebufferTexture</a></li> <li><a href="glFramebufferTexture.xhtml" target="pagedisplay">glFramebufferTexture1D</a></li> <li><a href="glFramebufferTexture.xhtml" target="pagedisplay">glFramebufferTexture2D</a></li> <li><a href="glFramebufferTexture.xhtml" target="pagedisplay">glFramebufferTexture3D</a></li> <li><a href="glFramebufferTextureLayer.xhtml" target="pagedisplay">glFramebufferTextureLayer</a></li> <li><a href="glFrontFace.xhtml" target="pagedisplay">glFrontFace</a></li> </ul> <!-- End Level3 --> </li> <a name="g"></a> <li>g <ul class="Level3"> <li><a href="glGenBuffers.xhtml" target="pagedisplay">glGenBuffers</a></li> <li><a href="glGenerateMipmap.xhtml" target="pagedisplay">glGenerateMipmap</a></li> <li><a href="glGenerateMipmap.xhtml" target="pagedisplay">glGenerateTextureMipmap</a></li> <li><a href="glGenFramebuffers.xhtml" target="pagedisplay">glGenFramebuffers</a></li> <li><a href="glGenProgramPipelines.xhtml" target="pagedisplay">glGenProgramPipelines</a></li> <li><a href="glGenQueries.xhtml" target="pagedisplay">glGenQueries</a></li> <li><a href="glGenRenderbuffers.xhtml" target="pagedisplay">glGenRenderbuffers</a></li> <li><a href="glGenSamplers.xhtml" target="pagedisplay">glGenSamplers</a></li> <li><a href="glGenTextures.xhtml" target="pagedisplay">glGenTextures</a></li> <li><a href="glGenTransformFeedbacks.xhtml" target="pagedisplay">glGenTransformFeedbacks</a></li> <li><a href="glGenVertexArrays.xhtml" target="pagedisplay">glGenVertexArrays</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGet</a></li> <li><a href="glGetActiveAtomicCounterBufferiv.xhtml" target="pagedisplay">glGetActiveAtomicCounterBufferiv</a></li> <li><a href="glGetActiveAttrib.xhtml" target="pagedisplay">glGetActiveAttrib</a></li> <li><a href="glGetActiveSubroutineName.xhtml" target="pagedisplay">glGetActiveSubroutineName</a></li> <li><a href="glGetActiveSubroutineUniform.xhtml" target="pagedisplay">glGetActiveSubroutineUniform</a></li> <li><a href="glGetActiveSubroutineUniform.xhtml" target="pagedisplay">glGetActiveSubroutineUniformiv</a></li> <li><a href="glGetActiveSubroutineUniformName.xhtml" target="pagedisplay">glGetActiveSubroutineUniformName</a></li> <li><a href="glGetActiveUniform.xhtml" target="pagedisplay">glGetActiveUniform</a></li> <li><a href="glGetActiveUniformBlock.xhtml" target="pagedisplay">glGetActiveUniformBlock</a></li> <li><a href="glGetActiveUniformBlock.xhtml" target="pagedisplay">glGetActiveUniformBlockiv</a></li> <li><a href="glGetActiveUniformBlockName.xhtml" target="pagedisplay">glGetActiveUniformBlockName</a></li> <li><a href="glGetActiveUniformName.xhtml" target="pagedisplay">glGetActiveUniformName</a></li> <li><a href="glGetActiveUniformsiv.xhtml" target="pagedisplay">glGetActiveUniformsiv</a></li> <li><a href="glGetAttachedShaders.xhtml" target="pagedisplay">glGetAttachedShaders</a></li> <li><a href="glGetAttribLocation.xhtml" target="pagedisplay">glGetAttribLocation</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetBooleani_v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetBooleanv</a></li> <li><a href="glGetBufferParameter.xhtml" target="pagedisplay">glGetBufferParameter</a></li> <li><a href="glGetBufferParameter.xhtml" target="pagedisplay">glGetBufferParameteri64v</a></li> <li><a href="glGetBufferParameter.xhtml" target="pagedisplay">glGetBufferParameteriv</a></li> <li><a href="glGetBufferPointerv.xhtml" target="pagedisplay">glGetBufferPointerv</a></li> <li><a href="glGetBufferSubData.xhtml" target="pagedisplay">glGetBufferSubData</a></li> <li><a href="glGetCompressedTexImage.xhtml" target="pagedisplay">glGetCompressedTexImage</a></li> <li><a href="glGetCompressedTexImage.xhtml" target="pagedisplay">glGetCompressedTextureImage</a></li> <li><a href="glGetCompressedTextureSubImage.xhtml" target="pagedisplay">glGetCompressedTextureSubImage</a></li> <li><a href="glGetDebugMessageLog.xhtml" target="pagedisplay">glGetDebugMessageLog</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetDoublei_v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetDoublev</a></li> <li><a href="glGetError.xhtml" target="pagedisplay">glGetError</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetFloati_v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetFloatv</a></li> <li><a href="glGetFragDataIndex.xhtml" target="pagedisplay">glGetFragDataIndex</a></li> <li><a href="glGetFragDataLocation.xhtml" target="pagedisplay">glGetFragDataLocation</a></li> <li><a href="glGetFramebufferAttachmentParameter.xhtml" target="pagedisplay">glGetFramebufferAttachmentParameter</a></li> <li><a href="glGetFramebufferAttachmentParameter.xhtml" target="pagedisplay">glGetFramebufferAttachmentParameteriv</a></li> <li><a href="glGetFramebufferParameter.xhtml" target="pagedisplay">glGetFramebufferParameter</a></li> <li><a href="glGetFramebufferParameter.xhtml" target="pagedisplay">glGetFramebufferParameteriv</a></li> <li><a href="glGetGraphicsResetStatus.xhtml" target="pagedisplay">glGetGraphicsResetStatus</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetInteger64i_v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetInteger64v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetIntegeri_v</a></li> <li><a href="glGet.xhtml" target="pagedisplay">glGetIntegerv</a></li> <li><a href="glGetInternalformat.xhtml" target="pagedisplay">glGetInternalformat</a></li> <li><a href="glGetInternalformat.xhtml" target="pagedisplay">glGetInternalformati64v</a></li> <li><a href="glGetInternalformat.xhtml" target="pagedisplay">glGetInternalformativ</a></li> <li><a href="glGetMultisample.xhtml" target="pagedisplay">glGetMultisample</a></li> <li><a href="glGetMultisample.xhtml" target="pagedisplay">glGetMultisamplefv</a></li> <li><a href="glGetBufferParameter.xhtml" target="pagedisplay">glGetNamedBufferParameteri64v</a></li> <li><a href="glGetBufferParameter.xhtml" target="pagedisplay">glGetNamedBufferParameteriv</a></li> <li><a href="glGetBufferPointerv.xhtml" target="pagedisplay">glGetNamedBufferPointerv</a></li> <li><a href="glGetBufferSubData.xhtml" target="pagedisplay">glGetNamedBufferSubData</a></li> <li><a href="glGetFramebufferAttachmentParameter.xhtml" target="pagedisplay">glGetNamedFramebufferAttachmentParameteriv</a></li> <li><a href="glGetFramebufferParameter.xhtml" target="pagedisplay">glGetNamedFramebufferParameteriv</a></li> <li><a href="glGetRenderbufferParameter.xhtml" target="pagedisplay">glGetNamedRenderbufferParameteriv</a></li> <li><a href="glGetCompressedTexImage.xhtml" target="pagedisplay">glGetnCompressedTexImage</a></li> <li><a href="glGetTexImage.xhtml" target="pagedisplay">glGetnTexImage</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetnUniformdv</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetnUniformfv</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetnUniformiv</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetnUniformuiv</a></li> <li><a href="glGetObjectLabel.xhtml" target="pagedisplay">glGetObjectLabel</a></li> <li><a href="glGetObjectPtrLabel.xhtml" target="pagedisplay">glGetObjectPtrLabel</a></li> <li><a href="glGetPointerv.xhtml" target="pagedisplay">glGetPointerv</a></li> <li><a href="glGetProgram.xhtml" target="pagedisplay">glGetProgram</a></li> <li><a href="glGetProgramBinary.xhtml" target="pagedisplay">glGetProgramBinary</a></li> <li><a href="glGetProgramInfoLog.xhtml" target="pagedisplay">glGetProgramInfoLog</a></li> <li><a href="glGetProgramInterface.xhtml" target="pagedisplay">glGetProgramInterface</a></li> <li><a href="glGetProgramInterface.xhtml" target="pagedisplay">glGetProgramInterfaceiv</a></li> <li><a href="glGetProgram.xhtml" target="pagedisplay">glGetProgramiv</a></li> <li><a href="glGetProgramPipeline.xhtml" target="pagedisplay">glGetProgramPipeline</a></li> <li><a href="glGetProgramPipelineInfoLog.xhtml" target="pagedisplay">glGetProgramPipelineInfoLog</a></li> <li><a href="glGetProgramPipeline.xhtml" target="pagedisplay">glGetProgramPipelineiv</a></li> <li><a href="glGetProgramResource.xhtml" target="pagedisplay">glGetProgramResource</a></li> <li><a href="glGetProgramResourceIndex.xhtml" target="pagedisplay">glGetProgramResourceIndex</a></li> <li><a href="glGetProgramResource.xhtml" target="pagedisplay">glGetProgramResourceiv</a></li> <li><a href="glGetProgramResourceLocation.xhtml" target="pagedisplay">glGetProgramResourceLocation</a></li> <li><a href="glGetProgramResourceLocationIndex.xhtml" target="pagedisplay">glGetProgramResourceLocationIndex</a></li> <li><a href="glGetProgramResourceName.xhtml" target="pagedisplay">glGetProgramResourceName</a></li> <li><a href="glGetProgramStage.xhtml" target="pagedisplay">glGetProgramStage</a></li> <li><a href="glGetProgramStage.xhtml" target="pagedisplay">glGetProgramStageiv</a></li> <li><a href="glGetQueryIndexed.xhtml" target="pagedisplay">glGetQueryIndexed</a></li> <li><a href="glGetQueryIndexed.xhtml" target="pagedisplay">glGetQueryIndexediv</a></li> <li><a href="glGetQueryiv.xhtml" target="pagedisplay">glGetQueryiv</a></li> <li><a href="glGetQueryObject.xhtml" target="pagedisplay">glGetQueryObject</a></li> <li><a href="glGetQueryObject.xhtml" target="pagedisplay">glGetQueryObjecti64v</a></li> <li><a href="glGetQueryObject.xhtml" target="pagedisplay">glGetQueryObjectiv</a></li> <li><a href="glGetQueryObject.xhtml" target="pagedisplay">glGetQueryObjectui64v</a></li> <li><a href="glGetQueryObject.xhtml" target="pagedisplay">glGetQueryObjectuiv</a></li> <li><a href="glGetRenderbufferParameter.xhtml" target="pagedisplay">glGetRenderbufferParameter</a></li> <li><a href="glGetRenderbufferParameter.xhtml" target="pagedisplay">glGetRenderbufferParameteriv</a></li> <li><a href="glGetSamplerParameter.xhtml" target="pagedisplay">glGetSamplerParameter</a></li> <li><a href="glGetSamplerParameter.xhtml" target="pagedisplay">glGetSamplerParameterfv</a></li> <li><a href="glGetSamplerParameter.xhtml" target="pagedisplay">glGetSamplerParameterIiv</a></li> <li><a href="glGetSamplerParameter.xhtml" target="pagedisplay">glGetSamplerParameterIuiv</a></li> <li><a href="glGetSamplerParameter.xhtml" target="pagedisplay">glGetSamplerParameteriv</a></li> <li><a href="glGetShader.xhtml" target="pagedisplay">glGetShader</a></li> <li><a href="glGetShaderInfoLog.xhtml" target="pagedisplay">glGetShaderInfoLog</a></li> <li><a href="glGetShader.xhtml" target="pagedisplay">glGetShaderiv</a></li> <li><a href="glGetShaderPrecisionFormat.xhtml" target="pagedisplay">glGetShaderPrecisionFormat</a></li> <li><a href="glGetShaderSource.xhtml" target="pagedisplay">glGetShaderSource</a></li> <li><a href="glGetString.xhtml" target="pagedisplay">glGetString</a></li> <li><a href="glGetString.xhtml" target="pagedisplay">glGetStringi</a></li> <li><a href="glGetSubroutineIndex.xhtml" target="pagedisplay">glGetSubroutineIndex</a></li> <li><a href="glGetSubroutineUniformLocation.xhtml" target="pagedisplay">glGetSubroutineUniformLocation</a></li> <li><a href="glGetSync.xhtml" target="pagedisplay">glGetSync</a></li> <li><a href="glGetSync.xhtml" target="pagedisplay">glGetSynciv</a></li> <li><a href="glGetTexImage.xhtml" target="pagedisplay">glGetTexImage</a></li> <li><a href="glGetTexLevelParameter.xhtml" target="pagedisplay">glGetTexLevelParameter</a></li> <li><a href="glGetTexLevelParameter.xhtml" target="pagedisplay">glGetTexLevelParameterfv</a></li> <li><a href="glGetTexLevelParameter.xhtml" target="pagedisplay">glGetTexLevelParameteriv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTexParameter</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTexParameterfv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTexParameterIiv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTexParameterIuiv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTexParameteriv</a></li> <li><a href="glGetTexImage.xhtml" target="pagedisplay">glGetTextureImage</a></li> <li><a href="glGetTexLevelParameter.xhtml" target="pagedisplay">glGetTextureLevelParameterfv</a></li> <li><a href="glGetTexLevelParameter.xhtml" target="pagedisplay">glGetTextureLevelParameteriv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTextureParameterfv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTextureParameterIiv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTextureParameterIuiv</a></li> <li><a href="glGetTexParameter.xhtml" target="pagedisplay">glGetTextureParameteriv</a></li> <li><a href="glGetTextureSubImage.xhtml" target="pagedisplay">glGetTextureSubImage</a></li> <li><a href="glGetTransformFeedback.xhtml" target="pagedisplay">glGetTransformFeedback</a></li> <li><a href="glGetTransformFeedback.xhtml" target="pagedisplay">glGetTransformFeedbacki64_v</a></li> <li><a href="glGetTransformFeedback.xhtml" target="pagedisplay">glGetTransformFeedbacki_v</a></li> <li><a href="glGetTransformFeedback.xhtml" target="pagedisplay">glGetTransformFeedbackiv</a></li> <li><a href="glGetTransformFeedbackVarying.xhtml" target="pagedisplay">glGetTransformFeedbackVarying</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetUniform</a></li> <li><a href="glGetUniformBlockIndex.xhtml" target="pagedisplay">glGetUniformBlockIndex</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetUniformdv</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetUniformfv</a></li> <li><a href="glGetUniformIndices.xhtml" target="pagedisplay">glGetUniformIndices</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetUniformiv</a></li> <li><a href="glGetUniformLocation.xhtml" target="pagedisplay">glGetUniformLocation</a></li> <li><a href="glGetUniformSubroutine.xhtml" target="pagedisplay">glGetUniformSubroutine</a></li> <li><a href="glGetUniformSubroutine.xhtml" target="pagedisplay">glGetUniformSubroutineuiv</a></li> <li><a href="glGetUniform.xhtml" target="pagedisplay">glGetUniformuiv</a></li> <li><a href="glGetVertexArrayIndexed.xhtml" target="pagedisplay">glGetVertexArrayIndexed</a></li> <li><a href="glGetVertexArrayIndexed.xhtml" target="pagedisplay">glGetVertexArrayIndexed64iv</a></li> <li><a href="glGetVertexArrayIndexed.xhtml" target="pagedisplay">glGetVertexArrayIndexediv</a></li> <li><a href="glGetVertexArrayiv.xhtml" target="pagedisplay">glGetVertexArrayiv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttrib</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribdv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribfv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribIiv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribIuiv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribiv</a></li> <li><a href="glGetVertexAttrib.xhtml" target="pagedisplay">glGetVertexAttribLdv</a></li> <li><a href="glGetVertexAttribPointerv.xhtml" target="pagedisplay">glGetVertexAttribPointerv</a></li> </ul> <!-- End Level3 --> </li> <a name="h"></a> <li>h <ul class="Level3"> <li><a href="glHint.xhtml" target="pagedisplay">glHint</a></li> </ul> <!-- End Level3 --> </li> <a name="i"></a> <li>i <ul class="Level3"> <li><a href="glInvalidateBufferData.xhtml" target="pagedisplay">glInvalidateBufferData</a></li> <li><a href="glInvalidateBufferSubData.xhtml" target="pagedisplay">glInvalidateBufferSubData</a></li> <li><a href="glInvalidateFramebuffer.xhtml" target="pagedisplay">glInvalidateFramebuffer</a></li> <li><a href="glInvalidateFramebuffer.xhtml" target="pagedisplay">glInvalidateNamedFramebufferData</a></li> <li><a href="glInvalidateSubFramebuffer.xhtml" target="pagedisplay">glInvalidateNamedFramebufferSubData</a></li> <li><a href="glInvalidateSubFramebuffer.xhtml" target="pagedisplay">glInvalidateSubFramebuffer</a></li> <li><a href="glInvalidateTexImage.xhtml" target="pagedisplay">glInvalidateTexImage</a></li> <li><a href="glInvalidateTexSubImage.xhtml" target="pagedisplay">glInvalidateTexSubImage</a></li> <li><a href="glIsBuffer.xhtml" target="pagedisplay">glIsBuffer</a></li> <li><a href="glIsEnabled.xhtml" target="pagedisplay">glIsEnabled</a></li> <li><a href="glIsEnabled.xhtml" target="pagedisplay">glIsEnabledi</a></li> <li><a href="glIsFramebuffer.xhtml" target="pagedisplay">glIsFramebuffer</a></li> <li><a href="glIsProgram.xhtml" target="pagedisplay">glIsProgram</a></li> <li><a href="glIsProgramPipeline.xhtml" target="pagedisplay">glIsProgramPipeline</a></li> <li><a href="glIsQuery.xhtml" target="pagedisplay">glIsQuery</a></li> <li><a href="glIsRenderbuffer.xhtml" target="pagedisplay">glIsRenderbuffer</a></li> <li><a href="glIsSampler.xhtml" target="pagedisplay">glIsSampler</a></li> <li><a href="glIsShader.xhtml" target="pagedisplay">glIsShader</a></li> <li><a href="glIsSync.xhtml" target="pagedisplay">glIsSync</a></li> <li><a href="glIsTexture.xhtml" target="pagedisplay">glIsTexture</a></li> <li><a href="glIsTransformFeedback.xhtml" target="pagedisplay">glIsTransformFeedback</a></li> <li><a href="glIsVertexArray.xhtml" target="pagedisplay">glIsVertexArray</a></li> </ul> <!-- End Level3 --> </li> <a name="l"></a> <li>l <ul class="Level3"> <li><a href="glLineWidth.xhtml" target="pagedisplay">glLineWidth</a></li> <li><a href="glLinkProgram.xhtml" target="pagedisplay">glLinkProgram</a></li> <li><a href="glLogicOp.xhtml" target="pagedisplay">glLogicOp</a></li> </ul> <!-- End Level3 --> </li> <a name="m"></a> <li>m <ul class="Level3"> <li><a href="glMapBuffer.xhtml" target="pagedisplay">glMapBuffer</a></li> <li><a href="glMapBufferRange.xhtml" target="pagedisplay">glMapBufferRange</a></li> <li><a href="glMapBuffer.xhtml" target="pagedisplay">glMapNamedBuffer</a></li> <li><a href="glMapBufferRange.xhtml" target="pagedisplay">glMapNamedBufferRange</a></li> <li><a href="glMemoryBarrier.xhtml" target="pagedisplay">glMemoryBarrier</a></li> <li><a href="glMemoryBarrier.xhtml" target="pagedisplay">glMemoryBarrierByRegion</a></li> <li><a href="glMinSampleShading.xhtml" target="pagedisplay">glMinSampleShading</a></li> <li><a href="glMultiDrawArrays.xhtml" target="pagedisplay">glMultiDrawArrays</a></li> <li><a href="glMultiDrawArraysIndirect.xhtml" target="pagedisplay">glMultiDrawArraysIndirect</a></li> <li><a href="glMultiDrawElements.xhtml" target="pagedisplay">glMultiDrawElements</a></li> <li><a href="glMultiDrawElementsBaseVertex.xhtml" target="pagedisplay">glMultiDrawElementsBaseVertex</a></li> <li><a href="glMultiDrawElementsIndirect.xhtml" target="pagedisplay">glMultiDrawElementsIndirect</a></li> </ul> <!-- End Level3 --> </li> <a name="n"></a> <li>n <ul class="Level3"> <li><a href="glBufferData.xhtml" target="pagedisplay">glNamedBufferData</a></li> <li><a href="glBufferStorage.xhtml" target="pagedisplay">glNamedBufferStorage</a></li> <li><a href="glBufferSubData.xhtml" target="pagedisplay">glNamedBufferSubData</a></li> <li><a href="glDrawBuffer.xhtml" target="pagedisplay">glNamedFramebufferDrawBuffer</a></li> <li><a href="glDrawBuffers.xhtml" target="pagedisplay">glNamedFramebufferDrawBuffers</a></li> <li><a href="glFramebufferParameteri.xhtml" target="pagedisplay">glNamedFramebufferParameteri</a></li> <li><a href="glReadBuffer.xhtml" target="pagedisplay">glNamedFramebufferReadBuffer</a></li> <li><a href="glFramebufferRenderbuffer.xhtml" target="pagedisplay">glNamedFramebufferRenderbuffer</a></li> <li><a href="glFramebufferTexture.xhtml" target="pagedisplay">glNamedFramebufferTexture</a></li> <li><a href="glFramebufferTextureLayer.xhtml" target="pagedisplay">glNamedFramebufferTextureLayer</a></li> <li><a href="glRenderbufferStorage.xhtml" target="pagedisplay">glNamedRenderbufferStorage</a></li> <li><a href="glRenderbufferStorageMultisample.xhtml" target="pagedisplay">glNamedRenderbufferStorageMultisample</a></li> </ul> <!-- End Level3 --> </li> <a name="o"></a> <li>o <ul class="Level3"> <li><a href="glObjectLabel.xhtml" target="pagedisplay">glObjectLabel</a></li> <li><a href="glObjectPtrLabel.xhtml" target="pagedisplay">glObjectPtrLabel</a></li> </ul> <!-- End Level3 --> </li> <a name="p"></a> <li>p <ul class="Level3"> <li><a href="glPatchParameter.xhtml" target="pagedisplay">glPatchParameter</a></li> <li><a href="glPatchParameter.xhtml" target="pagedisplay">glPatchParameterfv</a></li> <li><a href="glPatchParameter.xhtml" target="pagedisplay">glPatchParameteri</a></li> <li><a href="glPauseTransformFeedback.xhtml" target="pagedisplay">glPauseTransformFeedback</a></li> <li><a href="glPixelStore.xhtml" target="pagedisplay">glPixelStore</a></li> <li><a href="glPixelStore.xhtml" target="pagedisplay">glPixelStoref</a></li> <li><a href="glPixelStore.xhtml" target="pagedisplay">glPixelStorei</a></li> <li><a href="glPointParameter.xhtml" target="pagedisplay">glPointParameter</a></li> <li><a href="glPointParameter.xhtml" target="pagedisplay">glPointParameterf</a></li> <li><a href="glPointParameter.xhtml" target="pagedisplay">glPointParameterfv</a></li> <li><a href="glPointParameter.xhtml" target="pagedisplay">glPointParameteri</a></li> <li><a href="glPointParameter.xhtml" target="pagedisplay">glPointParameteriv</a></li> <li><a href="glPointSize.xhtml" target="pagedisplay">glPointSize</a></li> <li><a href="glPolygonMode.xhtml" target="pagedisplay">glPolygonMode</a></li> <li><a href="glPolygonOffset.xhtml" target="pagedisplay">glPolygonOffset</a></li> <li><a href="glPopDebugGroup.xhtml" target="pagedisplay">glPopDebugGroup</a></li> <li><a href="glPrimitiveRestartIndex.xhtml" target="pagedisplay">glPrimitiveRestartIndex</a></li> <li><a href="glProgramBinary.xhtml" target="pagedisplay">glProgramBinary</a></li> <li><a href="glProgramParameter.xhtml" target="pagedisplay">glProgramParameter</a></li> <li><a href="glProgramParameter.xhtml" target="pagedisplay">glProgramParameteri</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1f</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1i</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1iv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1ui</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform1uiv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2f</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2i</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2iv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2ui</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform2uiv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3f</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3i</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3iv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3ui</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform3uiv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4f</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4i</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4iv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4ui</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniform4uiv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix2fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix2x3fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix2x4fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix3fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix3x2fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix3x4fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix4fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix4x2fv</a></li> <li><a href="glProgramUniform.xhtml" target="pagedisplay">glProgramUniformMatrix4x3fv</a></li> <li><a href="glProvokingVertex.xhtml" target="pagedisplay">glProvokingVertex</a></li> <li><a href="glPushDebugGroup.xhtml" target="pagedisplay">glPushDebugGroup</a></li> </ul> <!-- End Level3 --> </li> <a name="q"></a> <li>q <ul class="Level3"> <li><a href="glQueryCounter.xhtml" target="pagedisplay">glQueryCounter</a></li> </ul> <!-- End Level3 --> </li> <a name="r"></a> <li>r <ul class="Level3"> <li><a href="glReadBuffer.xhtml" target="pagedisplay">glReadBuffer</a></li> <li><a href="glReadPixels.xhtml" target="pagedisplay">glReadnPixels</a></li> <li><a href="glReadPixels.xhtml" target="pagedisplay">glReadPixels</a></li> <li><a href="glReleaseShaderCompiler.xhtml" target="pagedisplay">glReleaseShaderCompiler</a></li> <li><a href="removedTypes.xhtml" target="pagedisplay">removedTypes</a></li> <li><a href="glRenderbufferStorage.xhtml" target="pagedisplay">glRenderbufferStorage</a></li> <li><a href="glRenderbufferStorageMultisample.xhtml" target="pagedisplay">glRenderbufferStorageMultisample</a></li> <li><a href="glResumeTransformFeedback.xhtml" target="pagedisplay">glResumeTransformFeedback</a></li> </ul> <!-- End Level3 --> </li> <a name="s"></a> <li>s <ul class="Level3"> <li><a href="glSampleCoverage.xhtml" target="pagedisplay">glSampleCoverage</a></li> <li><a href="glSampleMaski.xhtml" target="pagedisplay">glSampleMaski</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameter</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameterf</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameterfv</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameteri</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameterIiv</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameterIuiv</a></li> <li><a href="glSamplerParameter.xhtml" target="pagedisplay">glSamplerParameteriv</a></li> <li><a href="glScissor.xhtml" target="pagedisplay">glScissor</a></li> <li><a href="glScissorArray.xhtml" target="pagedisplay">glScissorArray</a></li> <li><a href="glScissorArray.xhtml" target="pagedisplay">glScissorArrayv</a></li> <li><a href="glScissorIndexed.xhtml" target="pagedisplay">glScissorIndexed</a></li> <li><a href="glScissorIndexed.xhtml" target="pagedisplay">glScissorIndexedv</a></li> <li><a href="glShaderBinary.xhtml" target="pagedisplay">glShaderBinary</a></li> <li><a href="glShaderSource.xhtml" target="pagedisplay">glShaderSource</a></li> <li><a href="glShaderStorageBlockBinding.xhtml" target="pagedisplay">glShaderStorageBlockBinding</a></li> <li><a href="glStencilFunc.xhtml" target="pagedisplay">glStencilFunc</a></li> <li><a href="glStencilFuncSeparate.xhtml" target="pagedisplay">glStencilFuncSeparate</a></li> <li><a href="glStencilMask.xhtml" target="pagedisplay">glStencilMask</a></li> <li><a href="glStencilMaskSeparate.xhtml" target="pagedisplay">glStencilMaskSeparate</a></li> <li><a href="glStencilOp.xhtml" target="pagedisplay">glStencilOp</a></li> <li><a href="glStencilOpSeparate.xhtml" target="pagedisplay">glStencilOpSeparate</a></li> </ul> <!-- End Level3 --> </li> <a name="t"></a> <li>t <ul class="Level3"> <li><a href="glTexBuffer.xhtml" target="pagedisplay">glTexBuffer</a></li> <li><a href="glTexBufferRange.xhtml" target="pagedisplay">glTexBufferRange</a></li> <li><a href="glTexImage1D.xhtml" target="pagedisplay">glTexImage1D</a></li> <li><a href="glTexImage2D.xhtml" target="pagedisplay">glTexImage2D</a></li> <li><a href="glTexImage2DMultisample.xhtml" target="pagedisplay">glTexImage2DMultisample</a></li> <li><a href="glTexImage3D.xhtml" target="pagedisplay">glTexImage3D</a></li> <li><a href="glTexImage3DMultisample.xhtml" target="pagedisplay">glTexImage3DMultisample</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameter</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameterf</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameterfv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameteri</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameterIiv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameterIuiv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTexParameteriv</a></li> <li><a href="glTexStorage1D.xhtml" target="pagedisplay">glTexStorage1D</a></li> <li><a href="glTexStorage2D.xhtml" target="pagedisplay">glTexStorage2D</a></li> <li><a href="glTexStorage2DMultisample.xhtml" target="pagedisplay">glTexStorage2DMultisample</a></li> <li><a href="glTexStorage3D.xhtml" target="pagedisplay">glTexStorage3D</a></li> <li><a href="glTexStorage3DMultisample.xhtml" target="pagedisplay">glTexStorage3DMultisample</a></li> <li><a href="glTexSubImage1D.xhtml" target="pagedisplay">glTexSubImage1D</a></li> <li><a href="glTexSubImage2D.xhtml" target="pagedisplay">glTexSubImage2D</a></li> <li><a href="glTexSubImage3D.xhtml" target="pagedisplay">glTexSubImage3D</a></li> <li><a href="glTextureBarrier.xhtml" target="pagedisplay">glTextureBarrier</a></li> <li><a href="glTexBuffer.xhtml" target="pagedisplay">glTextureBuffer</a></li> <li><a href="glTexBufferRange.xhtml" target="pagedisplay">glTextureBufferRange</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameterf</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameterfv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameteri</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameterIiv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameterIuiv</a></li> <li><a href="glTexParameter.xhtml" target="pagedisplay">glTextureParameteriv</a></li> <li><a href="glTexStorage1D.xhtml" target="pagedisplay">glTextureStorage1D</a></li> <li><a href="glTexStorage2D.xhtml" target="pagedisplay">glTextureStorage2D</a></li> <li><a href="glTexStorage2DMultisample.xhtml" target="pagedisplay">glTextureStorage2DMultisample</a></li> <li><a href="glTexStorage3D.xhtml" target="pagedisplay">glTextureStorage3D</a></li> <li><a href="glTexStorage3DMultisample.xhtml" target="pagedisplay">glTextureStorage3DMultisample</a></li> <li><a href="glTexSubImage1D.xhtml" target="pagedisplay">glTextureSubImage1D</a></li> <li><a href="glTexSubImage2D.xhtml" target="pagedisplay">glTextureSubImage2D</a></li> <li><a href="glTexSubImage3D.xhtml" target="pagedisplay">glTextureSubImage3D</a></li> <li><a href="glTextureView.xhtml" target="pagedisplay">glTextureView</a></li> <li><a href="glTransformFeedbackBufferBase.xhtml" target="pagedisplay">glTransformFeedbackBufferBase</a></li> <li><a href="glTransformFeedbackBufferRange.xhtml" target="pagedisplay">glTransformFeedbackBufferRange</a></li> <li><a href="glTransformFeedbackVaryings.xhtml" target="pagedisplay">glTransformFeedbackVaryings</a></li> </ul> <!-- End Level3 --> </li> <a name="u"></a> <li>u <ul class="Level3"> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1f</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1i</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1iv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1ui</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform1uiv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2f</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2i</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2iv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2ui</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform2uiv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3f</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3i</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3iv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3ui</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform3uiv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4f</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4i</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4iv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4ui</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniform4uiv</a></li> <li><a href="glUniformBlockBinding.xhtml" target="pagedisplay">glUniformBlockBinding</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix2fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix2x3fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix2x4fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix3fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix3x2fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix3x4fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix4fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix4x2fv</a></li> <li><a href="glUniform.xhtml" target="pagedisplay">glUniformMatrix4x3fv</a></li> <li><a href="glUniformSubroutines.xhtml" target="pagedisplay">glUniformSubroutines</a></li> <li><a href="glUniformSubroutines.xhtml" target="pagedisplay">glUniformSubroutinesuiv</a></li> <li><a href="glUnmapBuffer.xhtml" target="pagedisplay">glUnmapBuffer</a></li> <li><a href="glUnmapBuffer.xhtml" target="pagedisplay">glUnmapNamedBuffer</a></li> <li><a href="glUseProgram.xhtml" target="pagedisplay">glUseProgram</a></li> <li><a href="glUseProgramStages.xhtml" target="pagedisplay">glUseProgramStages</a></li> </ul> <!-- End Level3 --> </li> <a name="v"></a> <li>v <ul class="Level3"> <li><a href="glValidateProgram.xhtml" target="pagedisplay">glValidateProgram</a></li> <li><a href="glValidateProgramPipeline.xhtml" target="pagedisplay">glValidateProgramPipeline</a></li> <li><a href="glVertexAttribBinding.xhtml" target="pagedisplay">glVertexArrayAttribBinding</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexArrayAttribFormat</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexArrayAttribIFormat</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexArrayAttribLFormat</a></li> <li><a href="glVertexBindingDivisor.xhtml" target="pagedisplay">glVertexArrayBindingDivisor</a></li> <li><a href="glVertexArrayElementBuffer.xhtml" target="pagedisplay">glVertexArrayElementBuffer</a></li> <li><a href="glBindVertexBuffer.xhtml" target="pagedisplay">glVertexArrayVertexBuffer</a></li> <li><a href="glBindVertexBuffers.xhtml" target="pagedisplay">glVertexArrayVertexBuffers</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1f</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1fv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1s</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib1sv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2f</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2fv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2s</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib2sv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3f</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3fv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3s</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib3sv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4bv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4f</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4fv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4iv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nbv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Niv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nsv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nub</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nubv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nuiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4Nusv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4s</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4sv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4ubv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4uiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttrib4usv</a></li> <li><a href="glVertexAttribBinding.xhtml" target="pagedisplay">glVertexAttribBinding</a></li> <li><a href="glVertexAttribDivisor.xhtml" target="pagedisplay">glVertexAttribDivisor</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexAttribFormat</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI1i</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI1iv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI1ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI1uiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI2i</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI2iv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI2ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI2uiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI3i</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI3iv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI3ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI3uiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4bv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4i</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4iv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4sv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4ubv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4uiv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribI4usv</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexAttribIFormat</a></li> <li><a href="glVertexAttribPointer.xhtml" target="pagedisplay">glVertexAttribIPointer</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL1d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL1dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL2d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL2dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL3d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL3dv</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL4d</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribL4dv</a></li> <li><a href="glVertexAttribFormat.xhtml" target="pagedisplay">glVertexAttribLFormat</a></li> <li><a href="glVertexAttribPointer.xhtml" target="pagedisplay">glVertexAttribLPointer</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribP1ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribP2ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribP3ui</a></li> <li><a href="glVertexAttrib.xhtml" target="pagedisplay">glVertexAttribP4ui</a></li> <li><a href="glVertexAttribPointer.xhtml" target="pagedisplay">glVertexAttribPointer</a></li> <li><a href="glVertexBindingDivisor.xhtml" target="pagedisplay">glVertexBindingDivisor</a></li> <li><a href="glViewport.xhtml" target="pagedisplay">glViewport</a></li> <li><a href="glViewportArray.xhtml" target="pagedisplay">glViewportArray</a></li> <li><a href="glViewportArray.xhtml" target="pagedisplay">glViewportArrayv</a></li> <li><a href="glViewportIndexed.xhtml" target="pagedisplay">glViewportIndexed</a></li> <li><a href="glViewportIndexed.xhtml" target="pagedisplay">glViewportIndexedf</a></li> <li><a href="glViewportIndexed.xhtml" target="pagedisplay">glViewportIndexedfv</a></li> </ul> <!-- End Level3 --> </li> <a name="w"></a> <li>w <ul class="Level3"> <li><a href="glWaitSync.xhtml" target="pagedisplay">glWaitSync</a></li> </ul> <!-- End Level3 --> </li> </ul> <!-- End Level2 --> </li> <!-- End Level1 --> <li class="Level1">GLSL Functions <ul class="Level2"> <a name="a"></a> <li>a <ul class="Level3"> <li><a href="abs.xhtml" target="pagedisplay">abs</a></li> <li><a href="acos.xhtml" target="pagedisplay">acos</a></li> <li><a href="acosh.xhtml" target="pagedisplay">acosh</a></li> <li><a href="all.xhtml" target="pagedisplay">all</a></li> <li><a href="any.xhtml" target="pagedisplay">any</a></li> <li><a href="asin.xhtml" target="pagedisplay">asin</a></li> <li><a href="asinh.xhtml" target="pagedisplay">asinh</a></li> <li><a href="atan.xhtml" target="pagedisplay">atan</a></li> <li><a href="atanh.xhtml" target="pagedisplay">atanh</a></li> <li><a href="atomicAdd.xhtml" target="pagedisplay">atomicAdd</a></li> <li><a href="atomicAnd.xhtml" target="pagedisplay">atomicAnd</a></li> <li><a href="atomicCompSwap.xhtml" target="pagedisplay">atomicCompSwap</a></li> <li><a href="atomicCounter.xhtml" target="pagedisplay">atomicCounter</a></li> <li><a href="atomicCounterDecrement.xhtml" target="pagedisplay">atomicCounterDecrement</a></li> <li><a href="atomicCounterIncrement.xhtml" target="pagedisplay">atomicCounterIncrement</a></li> <li><a href="atomicExchange.xhtml" target="pagedisplay">atomicExchange</a></li> <li><a href="atomicMax.xhtml" target="pagedisplay">atomicMax</a></li> <li><a href="atomicMin.xhtml" target="pagedisplay">atomicMin</a></li> <li><a href="atomicOr.xhtml" target="pagedisplay">atomicOr</a></li> <li><a href="atomicXor.xhtml" target="pagedisplay">atomicXor</a></li> </ul> <!-- End Level3 --> </li> <a name="b"></a> <li>b <ul class="Level3"> <li><a href="barrier.xhtml" target="pagedisplay">barrier</a></li> <li><a href="bitCount.xhtml" target="pagedisplay">bitCount</a></li> <li><a href="bitfieldExtract.xhtml" target="pagedisplay">bitfieldExtract</a></li> <li><a href="bitfieldInsert.xhtml" target="pagedisplay">bitfieldInsert</a></li> <li><a href="bitfieldReverse.xhtml" target="pagedisplay">bitfieldReverse</a></li> </ul> <!-- End Level3 --> </li> <a name="c"></a> <li>c <ul class="Level3"> <li><a href="ceil.xhtml" target="pagedisplay">ceil</a></li> <li><a href="clamp.xhtml" target="pagedisplay">clamp</a></li> <li><a href="cos.xhtml" target="pagedisplay">cos</a></li> <li><a href="cosh.xhtml" target="pagedisplay">cosh</a></li> <li><a href="cross.xhtml" target="pagedisplay">cross</a></li> </ul> <!-- End Level3 --> </li> <a name="d"></a> <li>d <ul class="Level3"> <li><a href="degrees.xhtml" target="pagedisplay">degrees</a></li> <li><a href="determinant.xhtml" target="pagedisplay">determinant</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdx</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdxCoarse</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdxFine</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdy</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdyCoarse</a></li> <li><a href="dFdx.xhtml" target="pagedisplay">dFdyFine</a></li> <li><a href="distance.xhtml" target="pagedisplay">distance</a></li> <li><a href="dot.xhtml" target="pagedisplay">dot</a></li> </ul> <!-- End Level3 --> </li> <a name="e"></a> <li>e <ul class="Level3"> <li><a href="EmitStreamVertex.xhtml" target="pagedisplay">EmitStreamVertex</a></li> <li><a href="EmitVertex.xhtml" target="pagedisplay">EmitVertex</a></li> <li><a href="EndPrimitive.xhtml" target="pagedisplay">EndPrimitive</a></li> <li><a href="EndStreamPrimitive.xhtml" target="pagedisplay">EndStreamPrimitive</a></li> <li><a href="equal.xhtml" target="pagedisplay">equal</a></li> <li><a href="exp.xhtml" target="pagedisplay">exp</a></li> <li><a href="exp2.xhtml" target="pagedisplay">exp2</a></li> </ul> <!-- End Level3 --> </li> <a name="f"></a> <li>f <ul class="Level3"> <li><a href="faceforward.xhtml" target="pagedisplay">faceforward</a></li> <li><a href="findLSB.xhtml" target="pagedisplay">findLSB</a></li> <li><a href="findMSB.xhtml" target="pagedisplay">findMSB</a></li> <li><a href="floatBitsToInt.xhtml" target="pagedisplay">floatBitsToInt</a></li> <li><a href="floatBitsToInt.xhtml" target="pagedisplay">floatBitsToUint</a></li> <li><a href="floor.xhtml" target="pagedisplay">floor</a></li> <li><a href="fma.xhtml" target="pagedisplay">fma</a></li> <li><a href="fract.xhtml" target="pagedisplay">fract</a></li> <li><a href="frexp.xhtml" target="pagedisplay">frexp</a></li> <li><a href="fwidth.xhtml" target="pagedisplay">fwidth</a></li> <li><a href="fwidth.xhtml" target="pagedisplay">fwidthCoarse</a></li> <li><a href="fwidth.xhtml" target="pagedisplay">fwidthFine</a></li> </ul> <!-- End Level3 --> </li> <a name="g"></a> <li>g <ul class="Level3"> <li><a href="gl_ClipDistance.xhtml" target="pagedisplay">gl_ClipDistance</a></li> <li><a href="gl_CullDistance.xhtml" target="pagedisplay">gl_CullDistance</a></li> <li><a href="gl_FragCoord.xhtml" target="pagedisplay">gl_FragCoord</a></li> <li><a href="gl_FragDepth.xhtml" target="pagedisplay">gl_FragDepth</a></li> <li><a href="gl_FrontFacing.xhtml" target="pagedisplay">gl_FrontFacing</a></li> <li><a href="gl_GlobalInvocationID.xhtml" target="pagedisplay">gl_GlobalInvocationID</a></li> <li><a href="gl_HelperInvocation.xhtml" target="pagedisplay">gl_HelperInvocation</a></li> <li><a href="gl_InstanceID.xhtml" target="pagedisplay">gl_InstanceID</a></li> <li><a href="gl_InvocationID.xhtml" target="pagedisplay">gl_InvocationID</a></li> <li><a href="gl_Layer.xhtml" target="pagedisplay">gl_Layer</a></li> <li><a href="gl_LocalInvocationID.xhtml" target="pagedisplay">gl_LocalInvocationID</a></li> <li><a href="gl_LocalInvocationIndex.xhtml" target="pagedisplay">gl_LocalInvocationIndex</a></li> <li><a href="gl_NumSamples.xhtml" target="pagedisplay">gl_NumSamples</a></li> <li><a href="gl_NumWorkGroups.xhtml" target="pagedisplay">gl_NumWorkGroups</a></li> <li><a href="gl_PatchVerticesIn.xhtml" target="pagedisplay">gl_PatchVerticesIn</a></li> <li><a href="gl_PointCoord.xhtml" target="pagedisplay">gl_PointCoord</a></li> <li><a href="gl_PointSize.xhtml" target="pagedisplay">gl_PointSize</a></li> <li><a href="gl_Position.xhtml" target="pagedisplay">gl_Position</a></li> <li><a href="gl_PrimitiveID.xhtml" target="pagedisplay">gl_PrimitiveID</a></li> <li><a href="gl_PrimitiveIDIn.xhtml" target="pagedisplay">gl_PrimitiveIDIn</a></li> <li><a href="gl_SampleID.xhtml" target="pagedisplay">gl_SampleID</a></li> <li><a href="gl_SampleMask.xhtml" target="pagedisplay">gl_SampleMask</a></li> <li><a href="gl_SampleMaskIn.xhtml" target="pagedisplay">gl_SampleMaskIn</a></li> <li><a href="gl_SamplePosition.xhtml" target="pagedisplay">gl_SamplePosition</a></li> <li><a href="gl_TessCoord.xhtml" target="pagedisplay">gl_TessCoord</a></li> <li><a href="gl_TessLevelInner.xhtml" target="pagedisplay">gl_TessLevelInner</a></li> <li><a href="gl_TessLevelOuter.xhtml" target="pagedisplay">gl_TessLevelOuter</a></li> <li><a href="gl_VertexID.xhtml" target="pagedisplay">gl_VertexID</a></li> <li><a href="gl_ViewportIndex.xhtml" target="pagedisplay">gl_ViewportIndex</a></li> <li><a href="gl_WorkGroupID.xhtml" target="pagedisplay">gl_WorkGroupID</a></li> <li><a href="gl_WorkGroupSize.xhtml" target="pagedisplay">gl_WorkGroupSize</a></li> <li><a href="greaterThan.xhtml" target="pagedisplay">greaterThan</a></li> <li><a href="greaterThanEqual.xhtml" target="pagedisplay">greaterThanEqual</a></li> <li><a href="groupMemoryBarrier.xhtml" target="pagedisplay">groupMemoryBarrier</a></li> </ul> <!-- End Level3 --> </li> <a name="i"></a> <li>i <ul class="Level3"> <li><a href="imageAtomicAdd.xhtml" target="pagedisplay">imageAtomicAdd</a></li> <li><a href="imageAtomicAnd.xhtml" target="pagedisplay">imageAtomicAnd</a></li> <li><a href="imageAtomicCompSwap.xhtml" target="pagedisplay">imageAtomicCompSwap</a></li> <li><a href="imageAtomicExchange.xhtml" target="pagedisplay">imageAtomicExchange</a></li> <li><a href="imageAtomicMax.xhtml" target="pagedisplay">imageAtomicMax</a></li> <li><a href="imageAtomicMin.xhtml" target="pagedisplay">imageAtomicMin</a></li> <li><a href="imageAtomicOr.xhtml" target="pagedisplay">imageAtomicOr</a></li> <li><a href="imageAtomicXor.xhtml" target="pagedisplay">imageAtomicXor</a></li> <li><a href="imageLoad.xhtml" target="pagedisplay">imageLoad</a></li> <li><a href="imageSamples.xhtml" target="pagedisplay">imageSamples</a></li> <li><a href="imageSize.xhtml" target="pagedisplay">imageSize</a></li> <li><a href="imageStore.xhtml" target="pagedisplay">imageStore</a></li> <li><a href="umulExtended.xhtml" target="pagedisplay">imulExtended</a></li> <li><a href="intBitsToFloat.xhtml" target="pagedisplay">intBitsToFloat</a></li> <li><a href="interpolateAtCentroid.xhtml" target="pagedisplay">interpolateAtCentroid</a></li> <li><a href="interpolateAtOffset.xhtml" target="pagedisplay">interpolateAtOffset</a></li> <li><a href="interpolateAtSample.xhtml" target="pagedisplay">interpolateAtSample</a></li> <li><a href="inverse.xhtml" target="pagedisplay">inverse</a></li> <li><a href="inversesqrt.xhtml" target="pagedisplay">inversesqrt</a></li> <li><a href="isinf.xhtml" target="pagedisplay">isinf</a></li> <li><a href="isnan.xhtml" target="pagedisplay">isnan</a></li> </ul> <!-- End Level3 --> </li> <a name="l"></a> <li>l <ul class="Level3"> <li><a href="ldexp.xhtml" target="pagedisplay">ldexp</a></li> <li><a href="length.xhtml" target="pagedisplay">length</a></li> <li><a href="lessThan.xhtml" target="pagedisplay">lessThan</a></li> <li><a href="lessThanEqual.xhtml" target="pagedisplay">lessThanEqual</a></li> <li><a href="log.xhtml" target="pagedisplay">log</a></li> <li><a href="log2.xhtml" target="pagedisplay">log2</a></li> </ul> <!-- End Level3 --> </li> <a name="m"></a> <li>m <ul class="Level3"> <li><a href="matrixCompMult.xhtml" target="pagedisplay">matrixCompMult</a></li> <li><a href="max.xhtml" target="pagedisplay">max</a></li> <li><a href="memoryBarrier.xhtml" target="pagedisplay">memoryBarrier</a></li> <li><a href="memoryBarrierAtomicCounter.xhtml" target="pagedisplay">memoryBarrierAtomicCounter</a></li> <li><a href="memoryBarrierBuffer.xhtml" target="pagedisplay">memoryBarrierBuffer</a></li> <li><a href="memoryBarrierImage.xhtml" target="pagedisplay">memoryBarrierImage</a></li> <li><a href="memoryBarrierShared.xhtml" target="pagedisplay">memoryBarrierShared</a></li> <li><a href="min.xhtml" target="pagedisplay">min</a></li> <li><a href="mix.xhtml" target="pagedisplay">mix</a></li> <li><a href="mod.xhtml" target="pagedisplay">mod</a></li> <li><a href="modf.xhtml" target="pagedisplay">modf</a></li> </ul> <!-- End Level3 --> </li> <a name="n"></a> <li>n <ul class="Level3"> <li><a href="noise.xhtml" target="pagedisplay">noise</a></li> <li><a href="noise.xhtml" target="pagedisplay">noise1</a></li> <li><a href="noise.xhtml" target="pagedisplay">noise2</a></li> <li><a href="noise.xhtml" target="pagedisplay">noise3</a></li> <li><a href="noise.xhtml" target="pagedisplay">noise4</a></li> <li><a href="normalize.xhtml" target="pagedisplay">normalize</a></li> <li><a href="not.xhtml" target="pagedisplay">not</a></li> <li><a href="notEqual.xhtml" target="pagedisplay">notEqual</a></li> </ul> <!-- End Level3 --> </li> <a name="o"></a> <li>o <ul class="Level3"> <li><a href="outerProduct.xhtml" target="pagedisplay">outerProduct</a></li> </ul> <!-- End Level3 --> </li> <a name="p"></a> <li>p <ul class="Level3"> <li><a href="packDouble2x32.xhtml" target="pagedisplay">packDouble2x32</a></li> <li><a href="packHalf2x16.xhtml" target="pagedisplay">packHalf2x16</a></li> <li><a href="packUnorm.xhtml" target="pagedisplay">packSnorm2x16</a></li> <li><a href="packUnorm.xhtml" target="pagedisplay">packSnorm4x8</a></li> <li><a href="packUnorm.xhtml" target="pagedisplay">packUnorm</a></li> <li><a href="packUnorm.xhtml" target="pagedisplay">packUnorm2x16</a></li> <li><a href="packUnorm.xhtml" target="pagedisplay">packUnorm4x8</a></li> <li><a href="pow.xhtml" target="pagedisplay">pow</a></li> </ul> <!-- End Level3 --> </li> <a name="r"></a> <li>r <ul class="Level3"> <li><a href="radians.xhtml" target="pagedisplay">radians</a></li> <li><a href="reflect.xhtml" target="pagedisplay">reflect</a></li> <li><a href="refract.xhtml" target="pagedisplay">refract</a></li> <li><a href="round.xhtml" target="pagedisplay">round</a></li> <li><a href="roundEven.xhtml" target="pagedisplay">roundEven</a></li> </ul> <!-- End Level3 --> </li> <a name="s"></a> <li>s <ul class="Level3"> <li><a href="sign.xhtml" target="pagedisplay">sign</a></li> <li><a href="sin.xhtml" target="pagedisplay">sin</a></li> <li><a href="sinh.xhtml" target="pagedisplay">sinh</a></li> <li><a href="smoothstep.xhtml" target="pagedisplay">smoothstep</a></li> <li><a href="sqrt.xhtml" target="pagedisplay">sqrt</a></li> <li><a href="step.xhtml" target="pagedisplay">step</a></li> </ul> <!-- End Level3 --> </li> <a name="t"></a> <li>t <ul class="Level3"> <li><a href="tan.xhtml" target="pagedisplay">tan</a></li> <li><a href="tanh.xhtml" target="pagedisplay">tanh</a></li> <li><a href="texelFetch.xhtml" target="pagedisplay">texelFetch</a></li> <li><a href="texelFetchOffset.xhtml" target="pagedisplay">texelFetchOffset</a></li> <li><a href="texture.xhtml" target="pagedisplay">texture</a></li> <li><a href="textureGather.xhtml" target="pagedisplay">textureGather</a></li> <li><a href="textureGatherOffset.xhtml" target="pagedisplay">textureGatherOffset</a></li> <li><a href="textureGatherOffsets.xhtml" target="pagedisplay">textureGatherOffsets</a></li> <li><a href="textureGrad.xhtml" target="pagedisplay">textureGrad</a></li> <li><a href="textureGradOffset.xhtml" target="pagedisplay">textureGradOffset</a></li> <li><a href="textureLod.xhtml" target="pagedisplay">textureLod</a></li> <li><a href="textureLodOffset.xhtml" target="pagedisplay">textureLodOffset</a></li> <li><a href="textureOffset.xhtml" target="pagedisplay">textureOffset</a></li> <li><a href="textureProj.xhtml" target="pagedisplay">textureProj</a></li> <li><a href="textureProjGrad.xhtml" target="pagedisplay">textureProjGrad</a></li> <li><a href="textureProjGradOffset.xhtml" target="pagedisplay">textureProjGradOffset</a></li> <li><a href="textureProjLod.xhtml" target="pagedisplay">textureProjLod</a></li> <li><a href="textureProjLodOffset.xhtml" target="pagedisplay">textureProjLodOffset</a></li> <li><a href="textureProjOffset.xhtml" target="pagedisplay">textureProjOffset</a></li> <li><a href="textureQueryLevels.xhtml" target="pagedisplay">textureQueryLevels</a></li> <li><a href="textureQueryLod.xhtml" target="pagedisplay">textureQueryLod</a></li> <li><a href="textureSamples.xhtml" target="pagedisplay">textureSamples</a></li> <li><a href="textureSize.xhtml" target="pagedisplay">textureSize</a></li> <li><a href="transpose.xhtml" target="pagedisplay">transpose</a></li> <li><a href="trunc.xhtml" target="pagedisplay">trunc</a></li> </ul> <!-- End Level3 --> </li> <a name="u"></a> <li>u <ul class="Level3"> <li><a href="uaddCarry.xhtml" target="pagedisplay">uaddCarry</a></li> <li><a href="intBitsToFloat.xhtml" target="pagedisplay">uintBitsToFloat</a></li> <li><a href="umulExtended.xhtml" target="pagedisplay">umulExtended</a></li> <li><a href="unpackDouble2x32.xhtml" target="pagedisplay">unpackDouble2x32</a></li> <li><a href="unpackHalf2x16.xhtml" target="pagedisplay">unpackHalf2x16</a></li> <li><a href="unpackUnorm.xhtml" target="pagedisplay">unpackSnorm2x16</a></li> <li><a href="unpackUnorm.xhtml" target="pagedisplay">unpackSnorm4x8</a></li> <li><a href="unpackUnorm.xhtml" target="pagedisplay">unpackUnorm</a></li> <li><a href="unpackUnorm.xhtml" target="pagedisplay">unpackUnorm2x16</a></li> <li><a href="unpackUnorm.xhtml" target="pagedisplay">unpackUnorm4x8</a></li> <li><a href="usubBorrow.xhtml" target="pagedisplay">usubBorrow</a></li> </ul> <!-- End Level3 --> </li> </ul> <!-- End Level2 --> </li> <!-- End Level1 --> </div> <!-- End containerurl --> <script type="text/javascript">initiate();</script> </body> </html> <file_sep>/README.md # OpenGL binding generator (with docs) ## How to use: ```sh dub run ogl_gen -- --gen-d=<filename> --gen-d-module=<package.module> --load-core-4.5 --load-core-3 --load-core-2 --load-spec ``` Add ``--gen-d-wrapperName=<name>`` if you want it wrapped in a struct. Add ``--gen-d-static`` if you want a static binding, otherwise it will be dynamic.<file_sep>/man4/.svn/pristine/22/222826bb23cde4095edd26431c99fa2fe926920e.svn-base #!/bin/sh set -x cp opengl-man.css *.html *.xhtml $HOME/public/man5/xhtml/ <file_sep>/man4/conv.sh #!/bin/sh # Usage: conv.sh srcfile-name # System copy @ rev 7660 xsl=/usr/share/xml/docbook/stylesheet/docbook5/db4-upgrade.xsl # Sourceforge HEAD copy @ rev 9783 xsl=rev9783.db4-upgrade.xsl # Updated with patch from docbook-apps xsl=db4-upgrade.xsl echo "Using XSL $xsl" for arg in $* ; do src=$arg if test ! -f $file ; then echo "No such source file $src, skipping" continue fi dst=`basename $src` if test -f $dst ; then echo "Destination file $dst already exists, skipping" continue fi cp DOCTYPE.txt $dst sed -e 's/&/AMPER/g' < $src | \ xsltproc $xsl - | \ sed -e 's/AMPER/\&/g' \ >> $dst done <file_sep>/man4/valid #!/bin/sh DB5RNG=http://docbook.org/xml/5.0/rng/docbook.rng # or /usr/share/xml/docbook/schema/rng/5.0/docbook.rng xmllint --noout --xinclude --relaxng $DB5RNG $* <file_sep>/man2/fo/Makefile #!gmake # XSLT processor - other possibilities like Saxon exist XSLT = xsltproc # Location of locally customized stylesheet, which imports # the Docbook modular stylesheets, and the specific # stylesheet to convert Docbook+MathML => XSL-FO. # At present, the XSL-FO stylesheets do *not* handle MathML. # Getting math output is a significant toolchain issue. DB2XHTML = /usr/share/sgml/docbook/xsl-stylesheets/fo/docbook.xsl # Path to the APache FOP processor # Download the current version 0.92beta from # http://xmlgraphics.apache.org/fop/ FOP = /path/to/fop-0.92beta/fop .SUFFIXES: .gl .xml .html .xhtml .ck.xhtml .tex .pdf .3G .tar .tar.gz .PHONY: man html pdf tex %.fo: ../%.xml $(XSLT) --xinclude -o $@ $(DB2XHTML) $< %.pdf: %.fo $(FOP) -fo $< -pdf $@ # ARB Ecosystem man pages ARBFO = \ glBlendEquationSeparate.fo \ glStencilFuncSeparate.fo \ glStencilMaskSeparate.fo \ glStencilOpSeparate.fo # SuperBible GL 1.5 man pages SUPERBIBLEFO = \ glBeginQuery.fo \ glBindBuffer.fo \ glBufferData.fo \ glBufferSubData.fo \ glDeleteBuffers.fo \ glDeleteQueries.fo \ glGenBuffers.fo \ glGenQueries.fo \ glGetBufferParameteriv.fo \ glGetBufferPointerv.fo \ glGetBufferSubData.fo \ glGetQueryiv.fo \ glGetQueryObject.fo \ glIsBuffer.fo \ glIsQuery.fo \ glMapBuffer.fo # 3Dlabs GL 2.0 man pages 3DLABSFO = \ glAttachShader.fo \ glBindAttribLocation.fo \ glCompileShader.fo \ glCreateProgram.fo \ glCreateShader.fo \ glDeleteProgram.fo \ glDeleteShader.fo \ glDetachShader.fo \ glDrawBuffers.fo \ glEnableVertexAttribArray.fo \ glGetActiveAttrib.fo \ glGetActiveUniform.fo \ glGetAttachedShaders.fo \ glGetAttribLocation.fo \ glGetProgramInfoLog.fo \ glGetProgram.fo \ glGetShaderInfoLog.fo \ glGetShaderSource.fo \ glGetShader.fo \ glGetUniformLocation.fo \ glGetUniform.fo \ glGetVertexAttribPointerv.fo \ glGetVertexAttrib.fo \ glIsProgram.fo \ glIsShader.fo \ glLinkProgram.fo \ glShaderSource.fo \ glUniform.fo \ glUseProgram.fo \ glValidateProgram.fo \ glVertexAttribPointer.fo \ glVertexAttrib.fo # SGI OpenGL 1.4 man pages SGIGLFO = \ glAccum.fo \ glActiveTexture.fo \ glAlphaFunc.fo \ glAreTexturesResident.fo \ glArrayElement.fo \ glBegin.fo \ glBindTexture.fo \ glBitmap.fo \ glBlendColor.fo \ glBlendEquation.fo \ glBlendFuncSeparate.fo \ glBlendFunc.fo \ glCallLists.fo \ glCallList.fo \ glClearAccum.fo \ glClearColor.fo \ glClearDepth.fo \ glClearIndex.fo \ glClearStencil.fo \ glClear.fo \ glClientActiveTexture.fo \ glClipPlane.fo \ glColorMask.fo \ glColorMaterial.fo \ glColorPointer.fo \ glColorSubTable.fo \ glColorTableParameter.fo \ glColorTable.fo \ glColor.fo \ glCompressedTexImage1D.fo \ glCompressedTexImage2D.fo \ glCompressedTexImage3D.fo \ glCompressedTexSubImage1D.fo \ glCompressedTexSubImage2D.fo \ glCompressedTexSubImage3D.fo \ glConvolutionFilter1D.fo \ glConvolutionFilter2D.fo \ glConvolutionParameter.fo \ glCopyColorSubTable.fo \ glCopyColorTable.fo \ glCopyConvolutionFilter1D.fo \ glCopyConvolutionFilter2D.fo \ glCopyPixels.fo \ glCopyTexImage1D.fo \ glCopyTexImage2D.fo \ glCopyTexSubImage1D.fo \ glCopyTexSubImage2D.fo \ glCopyTexSubImage3D.fo \ glCullFace.fo \ glDeleteLists.fo \ glDeleteTextures.fo \ glDepthFunc.fo \ glDepthMask.fo \ glDepthRange.fo \ glDrawArrays.fo \ glDrawBuffer.fo \ glDrawElements.fo \ glDrawPixels.fo \ glDrawRangeElements.fo \ glEdgeFlagPointer.fo \ glEdgeFlag.fo \ glEnableClientState.fo \ glEnable.fo \ glEvalCoord.fo \ glEvalMesh.fo \ glEvalPoint.fo \ glFeedbackBuffer.fo \ glFinish.fo \ glFlush.fo \ glFogCoordPointer.fo \ glFogCoord.fo \ glFog.fo \ glFrontFace.fo \ glFrustum.fo \ glGenLists.fo \ glGenTextures.fo \ glGetClipPlane.fo \ glGetColorTableParameter.fo \ glGetColorTable.fo \ glGetCompressedTexImage.fo \ glGetConvolutionFilter.fo \ glGetConvolutionParameter.fo \ glGetError.fo \ glGetHistogramParameter.fo \ glGetHistogram.fo \ glGetLight.fo \ glGetMap.fo \ glGetMaterial.fo \ glGetMinmaxParameter.fo \ glGetMinmax.fo \ glGetPixelMap.fo \ glGetPointerv.fo \ glGetPolygonStipple.fo \ glGetSeparableFilter.fo \ glGetString.fo \ glGetTexEnv.fo \ glGetTexGen.fo \ glGetTexImage.fo \ glGetTexLevelParameter.fo \ glGetTexParameter.fo \ glGet.fo \ glHint.fo \ glHistogram.fo \ glIndexMask.fo \ glIndexPointer.fo \ glIndex.fo \ glInitNames.fo \ glInterleavedArrays.fo \ glIsEnabled.fo \ glIsList.fo \ glIsTexture.fo \ glLightModel.fo \ glLight.fo \ glLineStipple.fo \ glLineWidth.fo \ glListBase.fo \ glLoadIdentity.fo \ glLoadMatrix.fo \ glLoadName.fo \ glLoadTransposeMatrix.fo \ glLogicOp.fo \ glMap1.fo \ glMap2.fo \ glMapGrid.fo \ glMaterial.fo \ glMatrixMode.fo \ glMinmax.fo \ glMultiDrawArrays.fo \ glMultiDrawElements.fo \ glMultiTexCoord.fo \ glMultMatrix.fo \ glMultTransposeMatrix.fo \ glNewList.fo \ glNormalPointer.fo \ glNormal.fo \ glOrtho.fo \ glPassThrough.fo \ glPixelMap.fo \ glPixelStore.fo \ glPixelTransfer.fo \ glPixelZoom.fo \ glPointParameter.fo \ glPointSize.fo \ glPolygonMode.fo \ glPolygonOffset.fo \ glPolygonStipple.fo \ glPrioritizeTextures.fo \ glPushAttrib.fo \ glPushClientAttrib.fo \ glPushMatrix.fo \ glPushName.fo \ glRasterPos.fo \ glReadBuffer.fo \ glReadPixels.fo \ glRect.fo \ glRenderMode.fo \ glResetHistogram.fo \ glResetMinmax.fo \ glRotate.fo \ glSampleCoverage.fo \ glScale.fo \ glScissor.fo \ glSecondaryColorPointer.fo \ glSecondaryColor.fo \ glSelectBuffer.fo \ glSeparableFilter2D.fo \ glShadeModel.fo \ glStencilFunc.fo \ glStencilMask.fo \ glStencilOp.fo \ glTexCoordPointer.fo \ glTexCoord.fo \ glTexEnv.fo \ glTexGen.fo \ glTexImage1D.fo \ glTexImage2D.fo \ glTexImage3D.fo \ glTexParameter.fo \ glTexSubImage1D.fo \ glTexSubImage2D.fo \ glTexSubImage3D.fo \ glTranslate.fo \ glVertexPointer.fo \ glVertex.fo \ glViewport.fo \ glWindowPos.fo # SGI GLU 1.3 man pages SGIGLUFO = \ gluBeginCurve.fo \ gluBeginPolygon.fo \ gluBeginSurface.fo \ gluBeginTrim.fo \ gluBuild1DMipmapLevels.fo \ gluBuild1DMipmaps.fo \ gluBuild2DMipmapLevels.fo \ gluBuild2DMipmaps.fo \ gluBuild3DMipmapLevels.fo \ gluBuild3DMipmaps.fo \ gluCheckExtension.fo \ gluCylinder.fo \ gluDeleteNurbsRenderer.fo \ gluDeleteQuadric.fo \ gluDeleteTess.fo \ gluDisk.fo \ gluErrorString.fo \ gluGetNurbsProperty.fo \ gluGetString.fo \ gluGetTessProperty.fo \ gluLoadSamplingMatrices.fo \ gluLookAt.fo \ gluNewNurbsRenderer.fo \ gluNewQuadric.fo \ gluNewTess.fo \ gluNextContour.fo \ gluNurbsCallbackDataEXT.fo \ gluNurbsCallbackData.fo \ gluNurbsCallback.fo \ gluNurbsCurve.fo \ gluNurbsProperty.fo \ gluNurbsSurface.fo \ gluOrtho2D.fo \ gluPartialDisk.fo \ gluPerspective.fo \ gluPickMatrix.fo \ gluProject.fo \ gluPwlCurve.fo \ gluQuadricCallback.fo \ gluQuadricDrawStyle.fo \ gluQuadricNormals.fo \ gluQuadricOrientation.fo \ gluQuadricTexture.fo \ gluScaleImage.fo \ gluSphere.fo \ gluTessBeginContour.fo \ gluTessBeginPolygon.fo \ gluTessCallback.fo \ gluTessEndPolygon.fo \ gluTessNormal.fo \ gluTessProperty.fo \ gluTessVertex.fo \ gluUnProject4.fo \ gluUnProject.fo # SGI GLX 1.4 man pages SGIGLXFO = \ glXChooseFBConfig.fo \ glXChooseVisual.fo \ glXCopyContext.fo \ glXCreateContext.fo \ glXCreateGLXPixmap.fo \ glXCreateNewContext.fo \ glXCreatePbuffer.fo \ glXCreatePixmap.fo \ glXCreateWindow.fo \ glXDestroyContext.fo \ glXDestroyGLXPixmap.fo \ glXDestroyPbuffer.fo \ glXDestroyPixmap.fo \ glXDestroyWindow.fo \ glXFreeContextEXT.fo \ glXGetClientString.fo \ glXGetConfig.fo \ glXGetContextIDEXT.fo \ glXGetCurrentContext.fo \ glXGetCurrentDisplay.fo \ glXGetCurrentDrawable.fo \ glXGetCurrentReadDrawable.fo \ glXGetFBConfigAttrib.fo \ glXGetFBConfigs.fo \ glXGetProcAddress.fo \ glXGetSelectedEvent.fo \ glXGetVisualFromFBConfig.fo \ glXImportContextEXT.fo \ glXIntro.fo \ glXIsDirect.fo \ glXMakeContextCurrent.fo \ glXMakeCurrent.fo \ glXQueryContextInfoEXT.fo \ glXQueryContext.fo \ glXQueryExtensionsString.fo \ glXQueryExtension.fo \ glXQueryServerString.fo \ glXQueryVersion.fo \ glXSelectEvent.fo \ glXSwapBuffers.fo \ glXUseXFont.fo \ glXWaitGL.fo \ glXWaitX.fo # XML man page source and XSL-FO / PDF targets GLFO = $(SGIGLFO) $(3DLABSFO) $(SUPERBIBLEFO) $(ARBFO) GLUFO = $(SGIGLUFO) GLXFO = $(SGIGLXFO) FO = $(GLFO) $(GLUFO) $(GLXFO) PDF = $(FO:.fo=.pdf) default: $(PDF) clean: $(RM) $(TEX_FILES) *.log *.aux *.toc *.dvi *.out clobber: clean $(RM) $(FO) $(PDF) $(PDF_FILES) <file_sep>/man4/copyfiles #!/bin/sh set -x cp *.php $HOME/public/man5 cp xhtml/*.* $HOME/public/man5/xhtml/ <file_sep>/man4/html/glBlitFramebuffer.xhtml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>glBlitFramebuffer - OpenGL 4 Reference Pages</title> <link rel="stylesheet" type="text/css" href="opengl-man.css"/> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"/> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ MathML: { extensions: ["content-mathml.js"] }, tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } }); </script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"/> </head> <body> <header/> <div class="refentry" id="glBlitFramebuffer"> <div class="titlepage"/> <div class="refnamediv"> <h2>Name</h2> <p>glBlitFramebuffer, glBlitNamedFramebuffer — copy a block of pixels from one framebuffer object to another</p> </div> <div class="refsynopsisdiv"> <h2>C Specification</h2> <div class="funcsynopsis"> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glBlitFramebuffer</strong>(</code> </td> <td>GLint <var class="pdparam">srcX0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcY0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcX1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcY1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstX0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstY0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstX1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstY1</var>, </td> </tr> <tr> <td> </td> <td>GLbitfield <var class="pdparam">mask</var>, </td> </tr> <tr> <td> </td> <td>GLenum <var class="pdparam">filter</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glBlitNamedFramebuffer</strong>(</code> </td> <td>GLuint <var class="pdparam">readFramebuffer</var>, </td> </tr> <tr> <td> </td> <td>GLuint <var class="pdparam">drawFramebuffer</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcX0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcY0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcX1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">srcY1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstX0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstY0</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstX1</var>, </td> </tr> <tr> <td> </td> <td>GLint <var class="pdparam">dstY1</var>, </td> </tr> <tr> <td> </td> <td>GLbitfield <var class="pdparam">mask</var>, </td> </tr> <tr> <td> </td> <td>GLenum <var class="pdparam">filter</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> </div> </div> <div class="refsect1" id="parameters"> <h2>Parameters</h2> <div class="variablelist"> <dl class="variablelist"> <dt> <span class="term"> <em class="parameter"> <code>readFramebuffer</code> </em> </span> </dt> <dd> <p> Specifies the name of the source framebuffer object for <code class="function">glBlitNamedFramebuffer</code>. </p> </dd> <dt> <span class="term"> <em class="parameter"> <code>drawFramebuffer</code> </em> </span> </dt> <dd> <p> Specifies the name of the destination framebuffer object for <code class="function">glBlitNamedFramebuffer</code>. </p> </dd> <dt> <span class="term"><em class="parameter"><code>srcX0</code></em>, </span> <span class="term"><em class="parameter"><code>srcY0</code></em>, </span> <span class="term"><em class="parameter"><code>srcX1</code></em>, </span> <span class="term"> <em class="parameter"> <code>srcY1</code> </em> </span> </dt> <dd> <p> Specify the bounds of the source rectangle within the read buffer of the read framebuffer. </p> </dd> <dt> <span class="term"><em class="parameter"><code>dstX0</code></em>, </span> <span class="term"><em class="parameter"><code>dstY0</code></em>, </span> <span class="term"><em class="parameter"><code>dstX1</code></em>, </span> <span class="term"> <em class="parameter"> <code>dstY1</code> </em> </span> </dt> <dd> <p> Specify the bounds of the destination rectangle within the write buffer of the write framebuffer. </p> </dd> <dt> <span class="term"> <em class="parameter"> <code>mask</code> </em> </span> </dt> <dd> <p> The bitwise OR of the flags indicating which buffers are to be copied. The allowed flags are <code class="constant">GL_COLOR_BUFFER_BIT</code>, <code class="constant">GL_DEPTH_BUFFER_BIT</code> and <code class="constant">GL_STENCIL_BUFFER_BIT</code>. </p> </dd> <dt> <span class="term"> <em class="parameter"> <code>filter</code> </em> </span> </dt> <dd> <p> Specifies the interpolation to be applied if the image is stretched. Must be <code class="constant">GL_NEAREST</code> or <code class="constant">GL_LINEAR</code>. </p> </dd> </dl> </div> </div> <div class="refsect1" id="description"> <h2>Description</h2> <p> <code class="function">glBlitFramebuffer</code> and <code class="function">glBlitNamedFramebuffer</code> transfer a rectangle of pixel values from one region of a read framebuffer to another region of a draw framebuffer. </p> <p> For <code class="function">glBlitFramebuffer</code>, the read and draw framebuffers are those bound to the <code class="constant">GL_READ_FRAMEBUFFER</code> and <code class="constant">GL_DRAW_FRAMEBUFFER</code> targets respectively. </p> <p> For <code class="function">glBlitNamedFramebuffer</code>, <em class="parameter"><code>readFramebuffer</code></em> and <em class="parameter"><code>drawFramebuffer</code></em> are the names of the read read and draw framebuffer objects respectively. If <em class="parameter"><code>readFramebuffer</code></em> or <em class="parameter"><code>drawFramebuffer</code></em> is zero, then the default read or draw framebuffer respectively is used. </p> <p> <em class="parameter"><code>mask</code></em> is the bitwise OR of a number of values indicating which buffers are to be copied. The values are <code class="constant">GL_COLOR_BUFFER_BIT</code>, <code class="constant">GL_DEPTH_BUFFER_BIT</code>, and <code class="constant">GL_STENCIL_BUFFER_BIT</code>. The pixels corresponding to these buffers are copied from the source rectangle bounded by the locations (<em class="parameter"><code>srcX0</code></em>, <em class="parameter"><code>srcY0</code></em>) and (<em class="parameter"><code>srcX1</code></em>, <em class="parameter"><code>srcY1</code></em>) to the destination rectangle bounded by the locations (<em class="parameter"><code>dstX0</code></em>, <em class="parameter"><code>dstY0</code></em>) and (<em class="parameter"><code>dstX1</code></em>, <em class="parameter"><code>dstY1</code></em>). The lower bounds of the rectangle are inclusive, while the upper bounds are exclusive. </p> <p> The actual region taken from the read framebuffer is limited to the intersection of the source buffers being transferred, which may include the color buffer selected by the read buffer, the depth buffer, and/or the stencil buffer depending on mask. The actual region written to the draw framebuffer is limited to the intersection of the destination buffers being written, which may include multiple draw buffers, the depth buffer, and/or the stencil buffer depending on mask. Whether or not the source or destination regions are altered due to these limits, the scaling and offset applied to pixels being transferred is performed as though no such limits were present. </p> <p> If the sizes of the source and destination rectangles are not equal, <em class="parameter"><code>filter</code></em> specifies the interpolation method that will be applied to resize the source image , and must be <code class="constant">GL_NEAREST</code> or <code class="constant">GL_LINEAR</code>. <code class="constant">GL_LINEAR</code> is only a valid interpolation method for the color buffer. If <em class="parameter"><code>filter</code></em> is not <code class="constant">GL_NEAREST</code> and <em class="parameter"><code>mask</code></em> includes <code class="constant">GL_DEPTH_BUFFER_BIT</code> or <code class="constant">GL_STENCIL_BUFFER_BIT</code>, no data is transferred and a <code class="constant">GL_INVALID_OPERATION</code> error is generated. </p> <p> If <em class="parameter"><code>filter</code></em> is <code class="constant">GL_LINEAR</code> and the source rectangle would require sampling outside the bounds of the source framebuffer, values are read as if the <code class="constant">GL_CLAMP_TO_EDGE</code> texture wrapping mode were applied. </p> <p> When the color buffer is transferred, values are taken from the read buffer of the specified read framebuffer and written to each of the draw buffers of the specified draw framebuffer. </p> <p> If the source and destination rectangles overlap or are the same, and the read and draw buffers are the same, the result of the operation is undefined. </p> </div> <div class="refsect1" id="errors"> <h2>Errors</h2> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">BlitNamedFramebuffer</code> if <em class="parameter"><code>readFramebuffer</code></em> or <em class="parameter"><code>drawFramebuffer</code></em> is not zero or the name of an existing framebuffer object. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if <em class="parameter"><code>mask</code></em> contains any of the <code class="constant">GL_DEPTH_BUFFER_BIT</code> or <code class="constant">GL_STENCIL_BUFFER_BIT</code> and <em class="parameter"><code>filter</code></em> is not <code class="constant">GL_NEAREST</code>. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if <em class="parameter"><code>mask</code></em> contains <code class="constant">GL_COLOR_BUFFER_BIT</code> and any of the following conditions hold: </p> <div class="itemizedlist"> <ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <p> The read buffer contains fixed-point or floating-point values and any draw buffer contains neither fixed-point nor floating-point values. </p> </li> <li class="listitem"> <p> The read buffer contains unsigned integer values and any draw buffer does not contain unsigned integer values. </p> </li> <li class="listitem"> <p> The read buffer contains signed integer values and any draw buffer does not contain signed integer values. </p> </li> </ul> </div> <p> </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if <em class="parameter"><code>mask</code></em> contains <code class="constant">GL_DEPTH_BUFFER_BIT</code> or <code class="constant">GL_STENCIL_BUFFER_BIT</code> and the source and destination depth and stencil formats do not match. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if <em class="parameter"><code>filter</code></em> is <code class="constant">GL_LINEAR</code> and the read buffer contains integer data. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if the effective value of <code class="constant">GL_SAMPLES</code> for the read and draw framebuffers is not identical. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if the value of <code class="constant">GL_SAMPLE_BUFFERS</code> for both read and draw buffers is greater than zero and the dimensions of the source and destination rectangles is not identical. </p> <p> <code class="constant">GL_INVALID_FRAMEBUFFER_OPERATION</code> is generated if the specified read and draw framebuffers are not framebuffer complete. </p> </div> <div class="refsect1" id="versions"> <h2>Version Support</h2> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; "/> <col style="text-align: center; " class="firstvers"/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; " class="lastvers"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; "> </th> <th style="text-align: center; border-bottom: 2px solid ; " colspan="12"> <span class="bold"><strong>OpenGL Version</strong></span> </th> </tr> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>Function / Feature Name</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.4</strong></span> </th> <th style="text-align: center; border-bottom: 2px solid ; "> <span class="bold"><strong>4.5</strong></span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="function">glBlitFramebuffer</code> </td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-bottom: 2px solid ; ">✔</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="function">glBlitNamedFramebuffer</code> </td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; ">✔</td> </tr> </tbody> </table> </div> </div> <div class="refsect1" id="seealso"> <h2>See Also</h2> <p> <a class="citerefentry" href="glReadPixels.xhtml"><span class="citerefentry"><span class="refentrytitle">glReadPixels</span></span></a> <a class="citerefentry" href="glCheckFramebufferStatus.xhtml"><span class="citerefentry"><span class="refentrytitle">glCheckFramebufferStatus</span></span></a>, <a class="citerefentry" href="glGenFramebuffers.xhtml"><span class="citerefentry"><span class="refentrytitle">glGenFramebuffers</span></span></a> <a class="citerefentry" href="glBindFramebuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glBindFramebuffer</span></span></a> <a class="citerefentry" href="glDeleteFramebuffers.xhtml"><span class="citerefentry"><span class="refentrytitle">glDeleteFramebuffers</span></span></a> </p> </div> <div class="refsect1" id="Copyright"> <h2>Copyright</h2> <p> Copyright <span class="trademark"/>© 2010-2014 Khronos Group. This material may be distributed subject to the terms and conditions set forth in the Open Publication License, v 1.0, 8 June 1999. <a class="link" href="http://opencontent.org/openpub/" target="_top">http://opencontent.org/openpub/</a>. </p> </div> </div> <footer/> </body> </html> <file_sep>/man4/docbook4/xhtml/makeindex.py #!/usr/bin/python3 # # Copyright (c) 2013 The Khronos Group Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and/or associated documentation files (the # "Materials"), to deal in the Materials without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Materials, and to # permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. import io, os, re, string, sys; if __name__ == '__main__': if (len(sys.argv) != 4): print('Usage:', sys.argv[0], ' gendir srcdir indexfile', file=sys.stderr) exit(1) else: gendir = sys.argv[1] srcdir = sys.argv[2] outfilename = sys.argv[3] # print(' gendir = ', gendir, ' srcdir = ', srcdir, 'outfilename = ', outfilename) else: print('Unknown invocation mode', file=sys.stderr) exit(1) # Docbook source and generated HTML file extensions srcext = '.xml' genext = '.xml' # Global flag indicating whether to strip 'gl' prefix before alphabetizing glPrefix = 1 # List of generated files files = os.listdir(gendir) # Add [file, alias] to dictionary[key] def addkey(dict, file, key, alias): if (key in dict.keys()): value = dict[key] print('Key', key, '-> [', file, ',', alias, '] already exists in dictionary as [', value[0], ',', value[1], ']') else: dict[key] = [file, key] # print('Adding key', key, 'to dictionary as [', file, ',', alias, ']') # Create list of entry point names to be indexed. # Unlike the old Perl script, this proceeds as follows: # - Each .xhtml page with a parent .xml page gets an # index entry for its base name. # - Additionally, each <function> tag inside a <funcdef> # in the parent page gets an aliased index entry. # - Each .xhtml page *without* a parent is reported but # not indexed. # - Each collision in index terms is reported. # - Index terms are keys in a dictionary whose entries # are [ pagename, alias ] where pagename is the # base name of the indexed page and alias is 1 if # this index isn't the same as pagename. pageIndex = {} for file in files: # print('Processing file', file) (entrypoint,ext) = os.path.splitext(file) if (ext == genext): parent = srcdir + '/' + entrypoint + srcext if (os.path.exists(parent)): addkey(pageIndex, file, entrypoint, 0) # Search parent file for <function> tags inside <funcdef> tags # This doesn't search for <varname> inside <fieldsynopsis>, because # those aren't on the same line and it's hard. fp = open(parent) for line in fp.readlines(): # Look for <function> tag contents and add as aliases # Don't add the same key twice for m in re.finditer(r"<funcdef>.*<function>(.*)</function>.*</funcdef>", line): funcname = m.group(1) if (funcname != entrypoint): addkey(pageIndex, file, funcname, 1) fp.close() else: print('No parent page for', file, ', will not be indexed') # Determine which letters are in the table of contents. # This may require stripping the 'gl' prefix from each key containing it, # depending on the global flag glPrefix. # toc is a dictionary of key letters # Sort key for sorting a list of strings # This cheats a bit by ignoring the gl prefix def sortKey(key): if (glPrefix and len(key) > 2 and key[0:2] == 'gl'): return key[2:] else: return key # Return the keys in a dictionary sorted by name def sortedKeys(dict): list = [key for key in dict.keys()] list.sort(key = sortKey) return list # Keys is the sorted list of page indexes keys = sortedKeys(pageIndex) # print('Sorted list of page indexes:\n', keys) toc = {} for key in keys: if (glPrefix and len(key) > 2 and key[0:2] == 'gl'): c = key[2] else: c = key[0] toc[c] = 1 # Letters is the sorted list of letter prefixes for keys. letters = sortedKeys(toc) # print('Sorted list of index letters:\n', letters) # Some utility functions for generating the navigation table def printHeader(fp): print('<html>', '<head>', ' <link rel="stylesheet" type="text/css" href="opengl-man.css" />', ' <title>OpenGL Documentation</title>', '</head>', '<body>', '<a name="top"></a>', '<center><h1>OpenGL 4 Reference Pages</h1></center>', '<br/><br/>\n', sep='\n', file=fp) def printFooter(fp): print('</body>\n</html>\n', file=fp) # Add a nav table entry. key = link name, # keyval = [file for link target, alias] def addTable(key, keyval, fp): file = keyval[0] alias = keyval[1] # (strippedname,ext) = os.path.splitext(file) print(' <tr><td><a target="pagedisp" href="', file, '">', key, '</a></td></tr>', sep='', file=fp) def beginTable(letter, fp): print(' <a name="' + letter + '"></a><br/><br/>', ' <table width="200" class="sample">', ' <th>' + letter + '</th>', sep='\n', file=fp) def endTable(opentable, fp): if (opentable == 0): return print(' <tr><td align="right"><a href="#top">Top</a></td></tr>', ' </table>', sep='\n', file=fp) # Generate the navigation tables fp = open(outfilename, 'w') printHeader(fp) # First the letter index print('<center>\n<div id="container">', file=fp) for letter in letters: print(' <b><a href="#', letter, '" style="text-decoration:none">', letter, '</a></b> &nbsp;', sep='', file=fp) print('</div>\n</center>', file=fp) # Print links for sorted keys in each letter section curletter = '' opentable = 0 for key in keys: if (glPrefix and len(key) > 2 and key[0:2] == 'gl'): c = key[2] else: c = key[0] if (c != curletter): endTable(opentable, fp) # Start a new subtable for this letter beginTable(c, fp) opentable = 1 curletter = c addTable(key, pageIndex[key], fp) endTable(opentable, fp) printFooter(fp) fp.close() <file_sep>/man4/docbook4/xhtml/Makefile #!gmake # XSLT processor - other possibilities like Saxon exist XSLT = xsltproc --nonet SED = sed # Location of locally customized stylesheet, which imports # the Docbook modular stylesheets, and specifically the # stylesheet to convert Docbook+MathML => XHTML+MathML DB2XHTML = opengl-man.xsl PREPROCESSOR = preproc.sed .SUFFIXES: .gl .xml .html .xhtml .ck.xhtml .tex .pdf .3G .tar .tar.gz .PHONY: man html pdf tex %.xml: ../%.xml $(DB2XHTML) $(PREPROCESSOR) $(XSLT) --xinclude -o $@ $(DB2XHTML) $< $(SED) -i -f $(PREPROCESSOR) $@ GL_ARB_draw_indirect_entries = \ glDrawArraysIndirect.xml \ glDrawElementsIndirect.xml GL_ARB_shader_subroutine_entries = \ glGetActiveSubroutineName.xml \ glGetActiveSubroutineUniform.xml \ glGetActiveSubroutineUniformName.xml \ glGetProgramStage.xml \ glGetSubroutineIndex.xml \ glGetSubroutineUniformLocation.xml \ glGetUniformSubroutine.xml \ glUniformSubroutines.xml GL_ARB_tessellation_shader_entries = \ glPatchParameter.xml GL_ARB_transform_feedback2_entries = \ glBindTransformFeedback.xml \ glDeleteTransformFeedbacks.xml \ glGenTransformFeedbacks.xml \ glIsTransformFeedback.xml \ glPauseTransformFeedback.xml \ glResumeTransformFeedback.xml \ glDrawTransformFeedback.xml GL_ARB_transform_feedback3_entries = \ glDrawTransformFeedbackStream.xml \ glBeginQueryIndexed.xml \ glGetQueryIndexed.xml GL_ARB_viewport_array_entries = \ glDepthRangeArray.xml \ glDepthRangeIndexed.xml \ glScissorArray.xml \ glScissorIndexed.xml \ glViewportArray.xml \ glViewportIndexed.xml GL_ARB_get_program_binary_entries = \ glGetProgramBinary.xml \ glProgramBinary.xml \ glProgramParameter.xml GL_ARB_ES2_compatibility_entries = \ glReleaseShaderCompiler.xml \ glShaderBinary.xml \ glGetShaderPrecisionFormat.xml GL_ARB_separate_shader_objects_entries = \ glUseProgramStages.xml \ glActiveShaderProgram.xml \ glCreateShaderProgram.xml \ glBindProgramPipeline.xml \ glGenProgramPipelines.xml \ glDeleteProgramPipelines.xml \ glIsProgramPipeline.xml \ glGetProgramPipeline.xml \ glValidateProgramPipeline.xml \ glGetProgramPipelineInfoLog.xml \ glProgramUniform.xml GL_ARB_sample_shading_entries = \ glMinSampleShading.xml GL_ARB_base_instance_entries = \ glDrawArraysInstancedBaseInstance.xml \ glDrawElementsInstancedBaseInstance.xml \ glDrawElementsInstancedBaseVertexBaseInstance.xml GL_EXT_texture_storage_entries = \ glTexStorage1D.xml \ glTexStorage2D.xml \ glTexStorage3D.xml GL_ARB_internal_format_query_entries = \ glGetInternalformat.xml GL_ARB_transform_feedback_instanced_entries = \ glDrawTransformFeedbackInstanced.xml \ glDrawTransformFeedbackStreamInstanced.xml GL_ARB_shader_atomic_counters_entries = \ glGetActiveAtomicCounterBufferiv.xml GL_ARB_shader_image_load_store_entries = \ glBindImageTexture.xml \ glMemoryBarrier.xml # START OF OPENGL 4.3 EXTENSIONS # GL_ARB_arrays_of_arrays has no new entry points GL_ARB_arrays_of_arrays_entries = GL_ARB_multi_draw_indirect_entries = \ glMultiDrawArraysIndirect.xml \ glMultiDrawElementsIndirect.xml # ES3_compatibility does not have any new entry points GL_ARB_ES3_compatibility_enries = GL_ARB_clear_buffer_object_entries = \ glClearBufferData.xml \ glClearBufferSubData.xml GL_ARB_compute_shader_entries = \ glDispatchCompute.xml \ glDispatchComputeIndirect.xml GL_ARB_copy_image_entries = \ glCopyImageSubData.xml GL_ARB_debug_group_entries = \ glPushDebugGroup.xml \ glPopDebugGroup.xml GL_ARB_debug_label_entries = \ glObjectLabel.xml \ glObjectPtrLabel.xml \ glGetObjectLabel.xml \ glGetObjectPtrLabel.xml # GL_ARB_debug_output2 has no new entry points GL_ARB_debug_output2_entries = GL_ARB_debug_output_entries = \ glDebugMessageControl.xml \ glDebugMessageInsert.xml \ glDebugMessageCallback.xml \ glGetDebugMessageLog.xml # Add glGetPointerv to glGet.xml # GL_ARB_explicit_uniform_location has no new entry points GL_ARB_explicit_uniform_location_entries = # GL_ARB_fragment_layer_viewport has no new entry points GL_ARB_fragment_layer_viewport_entries = GL_ARB_framebuffer_no_attachments_entries = \ glFramebufferParameteri.xml \ glGetFramebufferParameter.xml # GL_ARB_internalformat_query2 adds glGetInternalFormati64v to glGetInternalFormativ GL_ARB_internalformat_query2_entries = GL_ARB_invalidate_subdata_entries = \ glInvalidateTexSubImage.xml \ glInvalidateTexImage.xml \ glInvalidateBufferSubData.xml \ glInvalidateBufferData.xml \ glInvalidateFramebuffer.xml \ glInvalidateSubFramebuffer.xml GL_ARB_program_interface_query_entries = \ glGetProgramInterface.xml \ glGetProgramResourceIndex.xml \ glGetProgramResourceName.xml \ glGetProgramResource.xml \ glGetProgramResourceLocation.xml \ glGetProgramResourceLocationIndex.xml # GL_ARB_robust_buffer_access_behavior does not define any new entry points GL_ARB_robust_buffer_access_behavior_entries = # GL_ARB_shader_image_size does not define any new entry points GL_ARB_shader_image_size_entries = GL_ARB_shader_storage_buffer_object_entries = \ glShaderStorageBlockBinding.xml # GL_ARB_stencil_texturing does not define any new entry points GL_ARB_stencil_texturing_entries = GL_ARB_texture_buffer_range_entries = \ glTexBufferRange.xml # GL_ARB_texture_query_levels does not define any new entry points GL_ARB_texture_query_levels = GL_ARB_texture_storage_multisample_entries = \ glTexStorage2DMultisample.xml \ glTexStorage3DMultisample.xml GL_ARB_texture_view_entries = \ glTextureView.xml GL_ARB_vertex_attrib_binding_entries = \ glVertexAttribBinding.xml \ glVertexAttribFormat.xml \ glVertexBindingDivisor.xml \ glBindVertexBuffer.xml GL_ARB_buffer_storage_entries = \ glBufferStorage.xml GL_ARB_clear_texture_entries = \ glClearTexImage.xml \ glClearTexSubImage.xml GL_ARB_multi_bind_entries = \ glBindBuffersBase.xml \ glBindBuffersRange.xml \ glBindTextures.xml \ glBindImageTextures.xml \ glBindSamplers.xml \ glBindVertexBuffers.xml MODIFIEDFORGL4XML = \ glClearDepth.xml \ glCreateShader.xml \ glDepthRange.xml \ glDrawArrays.xml \ glGetVertexAttrib.xml \ glVertexAttrib.xml \ glVertexAttribPointer.xml GL4XML = \ $(GL_ARB_draw_indirect_entries) \ $(GL_ARB_shader_subroutine_entries) \ $(GL_ARB_tessellation_shader_entries) \ $(GL_ARB_transform_feedback2_entries) \ $(GL_ARB_transform_feedback3_entries) \ $(GL_ARB_sample_shading_entries) GL41XML = \ $(GL_ARB_viewport_array_entries) \ $(GL_ARB_get_program_binary_entries) \ $(GL_ARB_ES2_compatibility_entries) \ $(GL_ARB_separate_shader_objects_entries) GL42XML = \ $(GL_ARB_base_instance_entries) \ $(GL_EXT_texture_storage_entries) \ $(GL_ARB_internal_format_query_entries) \ $(GL_ARB_transform_feedback_instanced_entries) \ $(GL_ARB_shader_atomic_counters_entries) \ $(GL_ARB_shader_image_load_store_entries) \ removedTypes.xml GL43XML = \ $(GL_ARB_multi_draw_indirect_entries) \ $(GL_ARB_ES3_compatibility_enries) \ $(GL_ARB_clear_buffer_object_entries) \ $(GL_ARB_compute_shader_entries) \ $(GL_ARB_copy_image_entries) \ $(GL_ARB_invalidate_subdata_entries) \ $(GL_ARB_texture_buffer_range_entries) \ $(GL_ARB_texture_storage_multisample_entries) \ $(GL_ARB_vertex_attrib_binding_entries) \ $(GL_ARB_shader_storage_buffer_object_entries) \ $(GL_ARB_debug_group_entries) \ $(GL_ARB_debug_label_entries) \ $(GL_ARB_framebuffer_no_attachments_entries) \ $(GL_ARB_program_interface_query_entries) \ $(GL_ARB_debug_output_entries) \ $(GL_ARB_texture_view_entries) GL44XML = \ $(GL_ARB_buffer_storage_entries) \ $(GL_ARB_clear_texture_entries) \ $(GL_ARB_multi_bind_entries) UNMODIFIEDXML = \ glActiveTexture.xml \ glAttachShader.xml \ glBeginConditionalRender.xml \ glBeginQuery.xml \ glBeginTransformFeedback.xml \ glBindAttribLocation.xml \ glBindBuffer.xml \ glBindBufferBase.xml \ glBindBufferRange.xml \ glBindFragDataLocation.xml \ glBindFragDataLocationIndexed.xml \ glBindFramebuffer.xml \ glBindRenderbuffer.xml \ glBindSampler.xml \ glBindTexture.xml \ glBindVertexArray.xml \ glBlendColor.xml \ glBlendEquation.xml \ glBlendEquationSeparate.xml \ glBlendFunc.xml \ glBlendFuncSeparate.xml \ glBlitFramebuffer.xml \ glBufferData.xml \ glBufferSubData.xml \ glCheckFramebufferStatus.xml \ glClampColor.xml \ glClear.xml \ glClearColor.xml \ glClearBuffer.xml \ glClearStencil.xml \ glClientWaitSync.xml \ glColorMask.xml \ glCompileShader.xml \ glCompressedTexImage1D.xml \ glCompressedTexImage2D.xml \ glCompressedTexImage3D.xml \ glCompressedTexSubImage1D.xml \ glCompressedTexSubImage2D.xml \ glCompressedTexSubImage3D.xml \ glCopyBufferSubData.xml \ glCopyTexImage1D.xml \ glCopyTexImage2D.xml \ glCopyTexSubImage1D.xml \ glCopyTexSubImage2D.xml \ glCopyTexSubImage3D.xml \ glCreateProgram.xml \ glCreateShader.xml \ glCullFace.xml \ glDeleteBuffers.xml \ glDeleteFramebuffers.xml \ glDeleteProgram.xml \ glDeleteQueries.xml \ glDeleteRenderbuffers.xml \ glDeleteSamplers.xml \ glDeleteShader.xml \ glDeleteSync.xml \ glDeleteTextures.xml \ glDeleteVertexArrays.xml \ glDepthFunc.xml \ glDepthMask.xml \ glDetachShader.xml \ glDrawArrays.xml \ glDrawArraysInstanced.xml \ glDrawBuffer.xml \ glDrawBuffers.xml \ glDrawElements.xml \ glDrawElementsBaseVertex.xml \ glDrawElementsInstanced.xml \ glDrawElementsInstancedBaseVertex.xml \ glDrawRangeElements.xml \ glDrawRangeElementsBaseVertex.xml \ glEnable.xml \ glEnableVertexAttribArray.xml \ glFenceSync.xml \ glFinish.xml \ glFlush.xml \ glFlushMappedBufferRange.xml \ glFramebufferRenderbuffer.xml \ glFramebufferTexture.xml \ glFramebufferTextureLayer.xml \ glFrontFace.xml \ glGenBuffers.xml \ glGenerateMipmap.xml \ glGenFramebuffers.xml \ glGenQueries.xml \ glGenRenderbuffers.xml \ glGenSamplers.xml \ glGenTextures.xml \ glGenVertexArrays.xml \ glGet.xml \ glGetActiveAttrib.xml \ glGetActiveUniform.xml \ glGetActiveUniformBlock.xml \ glGetActiveUniformBlockName.xml \ glGetActiveUniformName.xml \ glGetActiveUniformsiv.xml \ glGetAttachedShaders.xml \ glGetAttribLocation.xml \ glGetBufferParameter.xml \ glGetBufferPointerv.xml \ glGetBufferSubData.xml \ glGetCompressedTexImage.xml \ glGetError.xml \ glGetFragDataIndex.xml \ glGetFragDataLocation.xml \ glGetFramebufferAttachmentParameter.xml \ glGetMultisample.xml \ glGetProgram.xml \ glGetProgramInfoLog.xml \ glGetQueryObject.xml \ glGetQueryiv.xml \ glGetRenderbufferParameter.xml \ glGetSamplerParameter.xml \ glGetShader.xml \ glGetShaderInfoLog.xml \ glGetShaderSource.xml \ glGetString.xml \ glGetSync.xml \ glGetTexImage.xml \ glGetTexLevelParameter.xml \ glGetTexParameter.xml \ glGetTransformFeedbackVarying.xml \ glGetUniform.xml \ glGetUniformBlockIndex.xml \ glGetUniformIndices.xml \ glGetUniformLocation.xml \ glGetVertexAttribPointerv.xml \ glHint.xml \ glIsBuffer.xml \ glIsEnabled.xml \ glIsFramebuffer.xml \ glIsProgram.xml \ glIsRenderbuffer.xml \ glIsQuery.xml \ glIsSampler.xml \ glIsShader.xml \ glIsSync.xml \ glIsTexture.xml \ glIsVertexArray.xml \ glLineWidth.xml \ glLinkProgram.xml \ glLogicOp.xml \ glMapBuffer.xml \ glMapBufferRange.xml \ glMultiDrawArrays.xml \ glMultiDrawElements.xml \ glMultiDrawElementsBaseVertex.xml \ glPixelStore.xml \ glPointParameter.xml \ glPointSize.xml \ glPolygonMode.xml \ glPolygonOffset.xml \ glPrimitiveRestartIndex.xml \ glProvokingVertex.xml \ glQueryCounter.xml \ glReadBuffer.xml \ glReadPixels.xml \ glRenderbufferStorage.xml \ glRenderbufferStorageMultisample.xml \ glSampleCoverage.xml \ glSampleMaski.xml \ glSamplerParameter.xml \ glScissor.xml \ glShaderSource.xml \ glStencilFunc.xml \ glStencilFuncSeparate.xml \ glStencilMask.xml \ glStencilMaskSeparate.xml \ glStencilOp.xml \ glStencilOpSeparate.xml \ glTexBuffer.xml \ glTexImage1D.xml \ glTexImage2D.xml \ glTexImage2DMultisample.xml \ glTexImage3D.xml \ glTexImage3DMultisample.xml \ glTexParameter.xml \ glTexSubImage1D.xml \ glTexSubImage2D.xml \ glTexSubImage3D.xml \ glTransformFeedbackVaryings.xml \ glUniform.xml \ glUniformBlockBinding.xml \ glUseProgram.xml \ glValidateProgram.xml \ glVertexAttribDivisor.xml \ glViewport.xml \ glWaitSync.xml MODIFIEDXML = \ XML = $(GL4XML) $(GL41XML) $(GL42XML) $(GL43XML) $(GL44XML) $(MODIFIEDFORGL4XML) $(UNMODIFIEDXML) default: $(XML) index.html glTexImage1D.xml \ glTexImage2D.xml \ glTexImage3D.xml \ glTexStorage1D.xml \ glTexStorage2D.xml \ glTexStorage3D.xml \ : ../internalformattable.xml ../baseformattable.xml ../compressedformattable.xml glTexBuffer.xml glTexBufferRange.xml: ../texboformattable.xml index.html: Makefile makeindex.py $(XML) ./makeindex.py . .. $@ clean clobber: clean $(RM) $(XML) index.html <file_sep>/man4/.svn/pristine/82/820984d2b96b108bb2402a317aaec70a16c33e58.svn-base #!/usr/bin/python3 # # Copyright (c) 2013-2014 The Khronos Group Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and/or associated documentation files (the # "Materials"), to deal in the Materials without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Materials, and to # permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. import io, os, re, string, sys; if __name__ == '__main__': if (len(sys.argv) != 5): print('Usage:', sys.argv[0], ' gendir srcdir accordfilename flatfilename', file=sys.stderr) exit(1) else: gendir = sys.argv[1] srcdir = sys.argv[2] accordfilename = sys.argv[3] flatfilename = sys.argv[4] # print(' gendir = ', gendir, ' srcdir = ', srcdir, 'accordfilename = ', accordfilename, 'flatfilename = ', flatfilename) else: print('Unknown invocation mode', file=sys.stderr) exit(1) # Various levels of indentation in generated HTML ind1 = ' ' ind2 = ind1 + ind1 ind3 = ind2 + ind1 ind4 = ind2 + ind2 # Symbolic names notAlias = False isAlias = True # Page title pageTitle = 'OpenGL 4.x Reference Pages' # Docbook source and generated HTML file extensions srcext = '.xml' genext = '.xhtml' # List of generated files files = os.listdir(gendir) # Feature - class representing a command or function to be indexed, used # as dictionary values keyed by the feature name to be indexed. # # Members # file - name of file containing the feature # feature - feature name for the index (basis for the dictionary key). # alias - True if this is an alias of another feature in the file. # Usually if alias is False, feature is the basename of file. # apiCommand - True if this is an API command, or should be grouped # like one class Feature: def __init__(self, file = None, feature = None, alias = False, apiCommand = None): self.file = file self.feature = feature self.alias = alias self.apiCommand = apiCommand def makeKey(self): # Return dictionary / sort key based on the feature name if (self.apiCommand and self.feature[0:2] == 'gl'): return self.feature[2:] else: return self.feature # Add dictionary entry for specified Feature. # The key used is the feature name, with the leading 'gl' stripped # off if this is an API command def addkey(dict, feature): key = feature.makeKey() if (key in dict.keys()): print('Key', key, ' already exists in dictionary!') else: dict[key] = feature # Create list of entry point names to be indexed. # Unlike the old Perl script, this proceeds as follows: # - Each .xhtml page with a parent .xml page gets an # index entry for its base name. # - Additionally, each <function> tag inside a <funcdef> # in the parent page gets an aliased index entry. # - Each .xhtml page *without* a parent is reported but # not indexed. # - Each collision in index terms is reported. # - Index terms are keys in a dictionary whose entries # are [ pagename, alias, glPrefix ] where pagename is # the base name of the indexed page and alias is True # if this index isn't the same as pagename. # - API keys have their glPrefix value set to True, # GLSL keys to False. There is a simplistic way of # telling the files apart based on the file name: # # * Everything starting with 'gl[A-Z]' is API # * 'removedTypes.*' is API (more may be added) # * Everything else is GLSL def isGLfile(entrypoint): if (re.match('^gl[A-Z]', entrypoint) or entrypoint == 'removedTypes'): return True else: return False # Dictionary of all keys mapped to Feature values refIndex = {} for file in files: # print('Processing file', file) (entrypoint,ext) = os.path.splitext(file) if (ext == genext): parent = srcdir + '/' + entrypoint + srcext # Determine if this is an API or GLSL page apiCommand = isGLfile(entrypoint) if (os.path.exists(parent)): addkey(refIndex, Feature(file, entrypoint, False, apiCommand)) # Search parent file for <function> tags inside <funcdef> tags # This doesn't search for <varname> inside <fieldsynopsis>, because # those aren't on the same line and it's hard. fp = open(parent) for line in fp.readlines(): # Look for <function> tag contents and add as aliases # Don't add the same key twice for m in re.finditer(r"<funcdef>.*<function>(.*)</function>.*</funcdef>", line): funcname = m.group(1) if (funcname != entrypoint): addkey(refIndex, Feature(file, funcname, True, apiCommand)) fp.close() else: print('No parent page for', file, ', will not be indexed') # Some utility functions for generating the navigation table # Opencl_tofc.html uses style.css instead of style-index.css # flatMenu - if True, don't include accordion JavaScript, # generating a flat (expanded) menu. # letters - if not None, include per-letter links to within # the indices for each letter in the list. # altMenu - if not None, the name of the alternate index to # link to. def printHeader(fp, flatMenu = False, letters = None, altMenu = None): if (flatMenu): scriptInclude = ' <!-- Don\'t include accord.js -->' else: scriptInclude = ' <?php include \'accord.js\'; ?>' print('<html>', '<head>', ' <link rel="stylesheet" type="text/css" href="style-index.css" />', ' <title>' + pageTitle + '</title>', scriptInclude, '</head>', '<body>', sep='\n', file=fp) if (altMenu): if (flatMenu): altLabel = '(accordion-style)' else: altLabel = '(flat)' print(' <a href="' + altMenu + '">' + 'Use alternate ' + altLabel + ' index' + '</a>', file=fp) if (letters): print(' <center>\n<div id="container">', file=fp) for letter in letters: print(' <b><a href="#' + letter + '" style="text-decoration:none">' + letter + '</a></b> &nbsp;', file=fp) print(' </div>\n</center>', file=fp) print(' <div id="navwrap">', ' <ul id="containerul"> <!-- Must wrap entire list for expand/contract -->', ' <li class="Level1">', ' <a href="start.html" target="pagedisplay">Introduction</a>', ' </li>', sep='\n', file=fp) def printFooter(fp, flatMenu = False): print(' </div> <!-- End containerurl -->', file=fp) if (not flatMenu): print(' <script type="text/javascript">initiate();</script>', file=fp) print('</body>', '</html>', sep='\n', file=fp) # Add a nav table entry. key = link name, feature = Feature info for key def addMenuLink(key, feature, fp): file = feature.file linkname = feature.feature print(ind4 + '<li><a href="' + file + '" target="pagedisplay">' + linkname + '</a></li>', sep='\n', file=fp) # Begin index section for a letter, include an anchor to link to def beginLetterSection(letter, fp): print(ind2 + '<a name="' + letter + '"></a>', ind2 + '<li>' + letter, ind3 + '<ul class="Level3">', sep='\n', file=fp) # End index section for a letter def endLetterSection(opentable, fp): if (opentable == 0): return print(ind3 + '</ul> <!-- End Level3 -->', ind2 + '</li>', sep='\n', file=fp) # Return the keys in a dictionary sorted by name. # Select only keys matching whichKeys (see genDict below) def sortedKeys(dict, whichKeys): list = [] for key in dict.keys(): if (whichKeys == 'all' or (whichKeys == 'api' and dict[key].apiCommand) or (whichKeys == 'glsl' and not dict[key].apiCommand)): list.append(key) list.sort(key=str.lower) return list # Generate accordion menu for this dictionary, titled as specified. # # If whichKeys is 'all', generate index for all features # If whichKeys is 'api', generate index only for API features # If whichKeys is 'glsl', generate index only for GLSL features # # fp is the file to write to def genDict(dict, title, whichKeys, fp): print(ind1 + '<li class="Level1">' + title, ind2 + '<ul class="Level2">', sep='\n', file=fp) # Print links for sorted keys in each letter section curletter = '' opentable = 0 # Determine which letters are in the table of contents for this # dictionary. If glPrefix is set, strip the 'gl' prefix from each # key containing it first. # Generatesorted list of page indexes. Select keys matching whichKeys. keys = sortedKeys(dict, whichKeys) # print('@ Sorted list of page indexes:\n', keys) for key in keys: # Character starting this key c = str.lower(key[0]) if (c != curletter): endLetterSection(opentable, fp) # Start a new subtable for this letter beginLetterSection(c, fp) opentable = 1 curletter = c addMenuLink(key, dict[key], fp) endLetterSection(opentable, fp) print(ind2 + '</ul> <!-- End Level2 -->', ind1 + '</li> <!-- End Level1 -->', sep='\n', file=fp) ###################################################################### # Generate the accordion menu, with separate API and GLSL sections fp = open(accordfilename, 'w') printHeader(fp, flatMenu = False, altMenu = flatfilename) genDict(refIndex, 'API Entry Points', 'api', fp) genDict(refIndex, 'GLSL Functions', 'glsl', fp) printFooter(fp, flatMenu = False) fp.close() ###################################################################### # Generate the non-accordion menu, with combined API and GLSL sections fp = open(flatfilename, 'w') # Set containing all index letters indices = { key[0].lower() for key in refIndex.keys() } letters = [c for c in indices] letters.sort() printHeader(fp, flatMenu = True, letters = letters, altMenu = accordfilename) genDict(refIndex, 'API and GLSL Index', 'all', fp) printFooter(fp, flatMenu = True) fp.close() <file_sep>/man2/.svn/pristine/e9/e9964432f58277a0716c4cabe3b3ee6cc3171522.svn-base #!gmake # XSLT processor - other possibilities like Saxon exist XSLT = xsltproc --nonet SED = sed # Location of locally customized stylesheet, which imports # the Docbook modular stylesheets, and specifically the # stylesheet to convert Docbook+MathML => XHTML+MathML DB2XHTML = opengl-man.xsl .SUFFIXES: .gl .xml .html .xhtml .ck.xhtml .tex .pdf .3G .tar .tar.gz .PHONY: man html pdf tex %.xml: ../%.xml opengl-man.xsl $(XSLT) --xinclude -o $@.tmp $(DB2XHTML) $< $(SED) 's/<?xml-stylesheet/<!-- saved from url=(0013)about:internet -->\n<?xml-stylesheet/g' $@.tmp | \ $(SED) 's#http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd#xhtml1-transitional.dtd#g' > $@ $(RM) $@.tmp # ARB Ecosystem man pages ARBXML = \ glBlendEquationSeparate.xml \ glStencilFuncSeparate.xml \ glStencilMaskSeparate.xml \ glStencilOpSeparate.xml # SuperBible GL 1.5 man pages SUPERBIBLEXML = \ glBeginQuery.xml \ glBindBuffer.xml \ glBufferData.xml \ glBufferSubData.xml \ glDeleteBuffers.xml \ glDeleteQueries.xml \ glGenBuffers.xml \ glGenQueries.xml \ glGetBufferParameteriv.xml \ glGetBufferPointerv.xml \ glGetBufferSubData.xml \ glGetQueryiv.xml \ glGetQueryObject.xml \ glIsBuffer.xml \ glIsQuery.xml \ glMapBuffer.xml # 3Dlabs GL 2.0 man pages 3DLABSXML = \ glAttachShader.xml \ glBindAttribLocation.xml \ glCompileShader.xml \ glCreateProgram.xml \ glCreateShader.xml \ glDeleteProgram.xml \ glDeleteShader.xml \ glDetachShader.xml \ glDrawBuffers.xml \ glEnableVertexAttribArray.xml \ glGetActiveAttrib.xml \ glGetActiveUniform.xml \ glGetAttachedShaders.xml \ glGetAttribLocation.xml \ glGetProgram.xml \ glGetProgramInfoLog.xml \ glGetShader.xml \ glGetShaderInfoLog.xml \ glGetShaderSource.xml \ glGetUniform.xml \ glGetUniformLocation.xml \ glGetVertexAttrib.xml \ glGetVertexAttribPointerv.xml \ glIsProgram.xml \ glIsShader.xml \ glLinkProgram.xml \ glShaderSource.xml \ glUniform.xml \ glUseProgram.xml \ glValidateProgram.xml \ glVertexAttrib.xml \ glVertexAttribPointer.xml # SGI OpenGL 1.4 man pages SGIGLXML = \ glAccum.xml \ glActiveTexture.xml \ glAlphaFunc.xml \ glAreTexturesResident.xml \ glArrayElement.xml \ glBegin.xml \ glBindTexture.xml \ glBitmap.xml \ glBlendColor.xml \ glBlendEquation.xml \ glBlendFuncSeparate.xml \ glBlendFunc.xml \ glCallLists.xml \ glCallList.xml \ glClearAccum.xml \ glClearColor.xml \ glClearDepth.xml \ glClearIndex.xml \ glClearStencil.xml \ glClear.xml \ glClientActiveTexture.xml \ glClipPlane.xml \ glColorMask.xml \ glColorMaterial.xml \ glColorPointer.xml \ glColorSubTable.xml \ glColorTableParameter.xml \ glColorTable.xml \ glColor.xml \ glCompressedTexImage1D.xml \ glCompressedTexImage2D.xml \ glCompressedTexImage3D.xml \ glCompressedTexSubImage1D.xml \ glCompressedTexSubImage2D.xml \ glCompressedTexSubImage3D.xml \ glConvolutionFilter1D.xml \ glConvolutionFilter2D.xml \ glConvolutionParameter.xml \ glCopyColorSubTable.xml \ glCopyColorTable.xml \ glCopyConvolutionFilter1D.xml \ glCopyConvolutionFilter2D.xml \ glCopyPixels.xml \ glCopyTexImage1D.xml \ glCopyTexImage2D.xml \ glCopyTexSubImage1D.xml \ glCopyTexSubImage2D.xml \ glCopyTexSubImage3D.xml \ glCullFace.xml \ glDeleteLists.xml \ glDeleteTextures.xml \ glDepthFunc.xml \ glDepthMask.xml \ glDepthRange.xml \ glDrawArrays.xml \ glDrawBuffer.xml \ glDrawElements.xml \ glDrawPixels.xml \ glDrawRangeElements.xml \ glEdgeFlagPointer.xml \ glEdgeFlag.xml \ glEnableClientState.xml \ glEnable.xml \ glEvalCoord.xml \ glEvalMesh.xml \ glEvalPoint.xml \ glFeedbackBuffer.xml \ glFinish.xml \ glFlush.xml \ glFogCoordPointer.xml \ glFogCoord.xml \ glFog.xml \ glFrontFace.xml \ glFrustum.xml \ glGenLists.xml \ glGenTextures.xml \ glGetClipPlane.xml \ glGetColorTableParameter.xml \ glGetColorTable.xml \ glGetCompressedTexImage.xml \ glGetConvolutionFilter.xml \ glGetConvolutionParameter.xml \ glGetError.xml \ glGetHistogramParameter.xml \ glGetHistogram.xml \ glGetLight.xml \ glGetMap.xml \ glGetMaterial.xml \ glGetMinmaxParameter.xml \ glGetMinmax.xml \ glGetPixelMap.xml \ glGetPointerv.xml \ glGetPolygonStipple.xml \ glGetSeparableFilter.xml \ glGetString.xml \ glGetTexEnv.xml \ glGetTexGen.xml \ glGetTexImage.xml \ glGetTexLevelParameter.xml \ glGetTexParameter.xml \ glGet.xml \ glHint.xml \ glHistogram.xml \ glIndexMask.xml \ glIndexPointer.xml \ glIndex.xml \ glInitNames.xml \ glInterleavedArrays.xml \ glIsEnabled.xml \ glIsList.xml \ glIsTexture.xml \ glLightModel.xml \ glLight.xml \ glLineStipple.xml \ glLineWidth.xml \ glListBase.xml \ glLoadIdentity.xml \ glLoadMatrix.xml \ glLoadName.xml \ glLoadTransposeMatrix.xml \ glLogicOp.xml \ glMap1.xml \ glMap2.xml \ glMapGrid.xml \ glMaterial.xml \ glMatrixMode.xml \ glMinmax.xml \ glMultiDrawArrays.xml \ glMultiDrawElements.xml \ glMultiTexCoord.xml \ glMultMatrix.xml \ glMultTransposeMatrix.xml \ glNewList.xml \ glNormalPointer.xml \ glNormal.xml \ glOrtho.xml \ glPassThrough.xml \ glPixelMap.xml \ glPixelStore.xml \ glPixelTransfer.xml \ glPixelZoom.xml \ glPointParameter.xml \ glPointSize.xml \ glPolygonMode.xml \ glPolygonOffset.xml \ glPolygonStipple.xml \ glPrioritizeTextures.xml \ glPushAttrib.xml \ glPushClientAttrib.xml \ glPushMatrix.xml \ glPushName.xml \ glRasterPos.xml \ glReadBuffer.xml \ glReadPixels.xml \ glRect.xml \ glRenderMode.xml \ glResetHistogram.xml \ glResetMinmax.xml \ glRotate.xml \ glSampleCoverage.xml \ glScale.xml \ glScissor.xml \ glSecondaryColorPointer.xml \ glSecondaryColor.xml \ glSelectBuffer.xml \ glSeparableFilter2D.xml \ glShadeModel.xml \ glStencilFunc.xml \ glStencilMask.xml \ glStencilOp.xml \ glTexCoordPointer.xml \ glTexCoord.xml \ glTexEnv.xml \ glTexGen.xml \ glTexImage1D.xml \ glTexImage2D.xml \ glTexImage3D.xml \ glTexParameter.xml \ glTexSubImage1D.xml \ glTexSubImage2D.xml \ glTexSubImage3D.xml \ glTranslate.xml \ glVertexPointer.xml \ glVertex.xml \ glViewport.xml \ glWindowPos.xml # SGI GLU 1.3 man pages SGIGLUXML = \ gluBeginCurve.xml \ gluBeginPolygon.xml \ gluBeginSurface.xml \ gluBeginTrim.xml \ gluBuild1DMipmapLevels.xml \ gluBuild1DMipmaps.xml \ gluBuild2DMipmapLevels.xml \ gluBuild2DMipmaps.xml \ gluBuild3DMipmapLevels.xml \ gluBuild3DMipmaps.xml \ gluCheckExtension.xml \ gluCylinder.xml \ gluDeleteNurbsRenderer.xml \ gluDeleteQuadric.xml \ gluDeleteTess.xml \ gluDisk.xml \ gluErrorString.xml \ gluGetNurbsProperty.xml \ gluGetString.xml \ gluGetTessProperty.xml \ gluLoadSamplingMatrices.xml \ gluLookAt.xml \ gluNewNurbsRenderer.xml \ gluNewQuadric.xml \ gluNewTess.xml \ gluNextContour.xml \ gluNurbsCallbackDataEXT.xml \ gluNurbsCallbackData.xml \ gluNurbsCallback.xml \ gluNurbsCurve.xml \ gluNurbsProperty.xml \ gluNurbsSurface.xml \ gluOrtho2D.xml \ gluPartialDisk.xml \ gluPerspective.xml \ gluPickMatrix.xml \ gluProject.xml \ gluPwlCurve.xml \ gluQuadricCallback.xml \ gluQuadricDrawStyle.xml \ gluQuadricNormals.xml \ gluQuadricOrientation.xml \ gluQuadricTexture.xml \ gluScaleImage.xml \ gluSphere.xml \ gluTessBeginContour.xml \ gluTessBeginPolygon.xml \ gluTessCallback.xml \ gluTessEndPolygon.xml \ gluTessNormal.xml \ gluTessProperty.xml \ gluTessVertex.xml \ gluUnProject4.xml \ gluUnProject.xml # SGI GLX 1.4 man pages SGIGLXXML = \ glXChooseFBConfig.xml \ glXChooseVisual.xml \ glXCopyContext.xml \ glXCreateContext.xml \ glXCreateGLXPixmap.xml \ glXCreateNewContext.xml \ glXCreatePbuffer.xml \ glXCreatePixmap.xml \ glXCreateWindow.xml \ glXDestroyContext.xml \ glXDestroyGLXPixmap.xml \ glXDestroyPbuffer.xml \ glXDestroyPixmap.xml \ glXDestroyWindow.xml \ glXFreeContextEXT.xml \ glXGetClientString.xml \ glXGetConfig.xml \ glXGetContextIDEXT.xml \ glXGetCurrentContext.xml \ glXGetCurrentDisplay.xml \ glXGetCurrentDrawable.xml \ glXGetCurrentReadDrawable.xml \ glXGetFBConfigAttrib.xml \ glXGetFBConfigs.xml \ glXGetProcAddress.xml \ glXGetSelectedEvent.xml \ glXGetVisualFromFBConfig.xml \ glXImportContextEXT.xml \ glXIntro.xml \ glXIsDirect.xml \ glXMakeContextCurrent.xml \ glXMakeCurrent.xml \ glXQueryContextInfoEXT.xml \ glXQueryContext.xml \ glXQueryDrawable.xml \ glXQueryExtensionsString.xml \ glXQueryExtension.xml \ glXQueryServerString.xml \ glXQueryVersion.xml \ glXSelectEvent.xml \ glXSwapBuffers.xml \ glXUseXFont.xml \ glXWaitGL.xml \ glXWaitX.xml # XML man page source and XHTML targets GLXML = $(SGIGLXML) $(3DLABSXML) $(SUPERBIBLEXML) $(ARBXML) GLUXML = $(SGIGLUXML) GLXXML = $(SGIGLXXML) XML = $(GLXML) $(GLUXML) $(GLXXML) default: $(XML) clean: $(RM) $(TEX_FILES) *.log *.aux *.toc *.dvi *.out clobber: clean $(RM) $(XML) $(PDF_FILES) <file_sep>/man4/.svn/pristine/36/36e30a03b4c94fb4b18cdc62ab01c689d7be0ce9.svn-base <html> <head> <title>OpenGL SDK</title> <?php include("/home/virtual/opengl.org/var/www/html/sdk/inc/sdk_head.txt"); ?> </head> <body> <?php include("/home/virtual/opengl.org/var/www/html/sdk/inc/sdk_body_start.txt"); ?> <?php include("/home/virtual/opengl.org/var/www/html/sdk/inc/sdk_footer.txt"); ?> </body> </html> <file_sep>/man4/jvalid #!/bin/sh DB5RNC=/usr/share/xml/docbook/schema/rng/5.0/docbookxi.rnc jing -c $DB5RNC $* <file_sep>/man4/.svn/pristine/39/39763dd9f49ef4e461e8bf28abf0340ea4db7c84.svn-base <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>glUnmapBuffer - OpenGL 4 Reference Pages</title> <link rel="stylesheet" type="text/css" href="opengl-man.css"/> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"/> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ MathML: { extensions: ["content-mathml.js"] }, tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } }); </script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"/> </head> <body> <header/> <div class="refentry" id="glUnmapBuffer"> <div class="titlepage"/> <div class="refnamediv"> <h2>Name</h2> <p>glUnmapBuffer, glUnmapNamedBuffer — release the mapping of a buffer object's data store into the client's address space</p> </div> <div class="refsynopsisdiv"> <h2>C Specification</h2> <div class="funcsynopsis"> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">GLboolean <strong class="fsfunc">glUnmapBuffer</strong>(</code> </td> <td>GLenum <var class="pdparam">target</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">GLboolean <strong class="fsfunc">glUnmapNamedBuffer</strong>(</code> </td> <td>GLuint <var class="pdparam">buffer</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> </div> </div> <div class="refsect1" id="parameters"> <h2>Parameters</h2> <div class="variablelist"> <dl class="variablelist"> <dt> <span class="term"> <em class="parameter"> <code>target</code> </em> </span> </dt> <dd> <p> Specifies the target to which the buffer object is bound for <code class="function">glUnmapBuffer</code>, which must be one of the buffer binding targets in the following table: </p> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; " class="col1"/> <col style="text-align: left; " class="col2"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"> <strong>Buffer Binding Target</strong> </span> </th> <th style="text-align: left; border-bottom: 2px solid ; "> <span class="bold"> <strong>Purpose</strong> </span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ARRAY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Vertex attributes</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ATOMIC_COUNTER_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Atomic counter storage</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_COPY_READ_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Buffer copy source</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_COPY_WRITE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Buffer copy destination</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_DISPATCH_INDIRECT_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Indirect compute dispatch commands</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_DRAW_INDIRECT_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Indirect command arguments</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_ELEMENT_ARRAY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Vertex array indices</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_PIXEL_PACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Pixel read target</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_PIXEL_UNPACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Texture data source</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_QUERY_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Query result buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_SHADER_STORAGE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Read-write storage for shaders</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_TEXTURE_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Texture data buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="constant">GL_TRANSFORM_FEEDBACK_BUFFER</code> </td> <td style="text-align: left; border-bottom: 2px solid ; ">Transform feedback buffer</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="constant">GL_UNIFORM_BUFFER</code> </td> <td style="text-align: left; ">Uniform block storage</td> </tr> </tbody> </table> </div> </dd> <dt> <span class="term"> <em class="parameter"> <code>buffer</code> </em> </span> </dt> <dd> <p> Specifies the name of the buffer object for <code class="function">glUnmapNamedBuffer</code>. </p> </dd> </dl> </div> </div> <div class="refsect1" id="description"> <h2>Description</h2> <p> <code class="function">glUnmapBuffer</code> and <code class="function">glUnmapNamedBuffer</code> unmap (release) any mapping of a specified buffer object into the client's address space (see <a class="citerefentry" href="glMapBufferRange.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBufferRange</span></span></a> and <a class="citerefentry" href="glMapBuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBuffer</span></span></a>). </p> <p> If a mapping is not unmapped before the corresponding buffer object's data store is used by the GL, an error will be generated by any GL command that attempts to dereference the buffer object's data store, unless the buffer was successfully mapped with <code class="constant">GL_MAP_PERSISTENT_BIT</code> (see <a class="citerefentry" href="glMapBufferRange.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBufferRange</span></span></a>). When a data store is unmapped, the mapped pointer becomes invalid. </p> <p> <code class="function">glUnmapBuffer</code> returns <code class="constant">GL_TRUE</code> unless the data store contents have become corrupt during the time the data store was mapped. This can occur for system-specific reasons that affect the availability of graphics memory, such as screen mode changes. In such situations, <code class="constant">GL_FALSE</code> is returned and the data store contents are undefined. An application must detect this rare condition and reinitialize the data store. </p> <p> A buffer object's mapped data store is automatically unmapped when the buffer object is deleted or its data store is recreated with <a class="citerefentry" href="glBufferData.xhtml"><span class="citerefentry"><span class="refentrytitle">glBufferData</span></span></a>). </p> </div> <div class="refsect1" id="notes"> <h2>Notes</h2> <p> If an error is generated, <code class="function">glUnmapBuffer</code> returns <code class="constant">GL_FALSE</code>. </p> <p> The <code class="constant">GL_ATOMIC_COUNTER_BUFFER</code> target is accepted only if the GL version is 4.2 or greater. </p> <p> The <code class="constant">GL_DISPATCH_INDIRECT_BUFFER</code> and <code class="constant">GL_SHADER_STORAGE_BUFFER</code> targets are available only if the GL version is 4.3 or greater. </p> <p> The <code class="constant">GL_QUERY_BUFFER</code> target is available only if the GL version is 4.4 or greater. </p> </div> <div class="refsect1" id="errors"> <h2>Errors</h2> <p> <code class="constant">GL_INVALID_ENUM</code> is generated by <code class="function">glUnmapBuffer</code> if <em class="parameter"><code>target</code></em> is not one of the buffer binding targets listed above. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glUnmapBuffer</code> if zero is bound to <em class="parameter"><code>target</code></em>. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glUnmapNamedBuffer</code> if <em class="parameter"><code>buffer</code></em> is not the name of an existing buffer object. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if the buffer object is not in a mapped state. </p> </div> <div class="refsect1" id="associatedgets"> <h2>Associated Gets</h2> <p> <a class="citerefentry" href="glGetBufferParameter.xhtml"><span class="citerefentry"><span class="refentrytitle">glGetBufferParameter</span></span></a> with argument <code class="constant">GL_BUFFER_MAPPED</code>. </p> </div> <div class="refsect1" id="versions"> <h2>Version Support</h2> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; "/> <col style="text-align: center; " class="firstvers"/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; " class="lastvers"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; "> </th> <th style="text-align: center; border-bottom: 2px solid ; " colspan="12"> <span class="bold"><strong>OpenGL Version</strong></span> </th> </tr> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>Function / Feature Name</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.4</strong></span> </th> <th style="text-align: center; border-bottom: 2px solid ; "> <span class="bold"><strong>4.5</strong></span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="function">glUnmapBuffer</code> </td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-bottom: 2px solid ; ">✔</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="function">glUnmapNamedBuffer</code> </td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; ">✔</td> </tr> </tbody> </table> </div> </div> <div class="refsect1" id="seealso"> <h2>See Also</h2> <p> <a class="citerefentry" href="glBufferData.xhtml"><span class="citerefentry"><span class="refentrytitle">glBufferData</span></span></a>, <a class="citerefentry" href="glDeleteBuffers.xhtml"><span class="citerefentry"><span class="refentrytitle">glDeleteBuffers</span></span></a>, <a class="citerefentry" href="glMapBuffer.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBuffer</span></span></a>, <a class="citerefentry" href="glMapBufferRange.xhtml"><span class="citerefentry"><span class="refentrytitle">glMapBufferRange</span></span></a> </p> </div> <div class="refsect1" id="Copyright"> <h2>Copyright</h2> <p> Copyright <span class="trademark"/>© 2005 Addison-Wesley. Copyright <span class="trademark"/>© 2010-2014 Khronos Group. This material may be distributed subject to the terms and conditions set forth in the Open Publication License, v 1.0, 8 June 1999. <a class="link" href="http://opencontent.org/openpub/" target="_top">http://opencontent.org/openpub/</a>. </p> </div> </div> <footer/> </body> </html> <file_sep>/man4/.svn/pristine/b1/b11c2384df4a86acf4eecfd28c47638a702a4ed7.svn-base <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>glGenerateMipmap - OpenGL 4 Reference Pages</title> <link rel="stylesheet" type="text/css" href="opengl-man.css"/> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"/> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ MathML: { extensions: ["content-mathml.js"] }, tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } }); </script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"/> </head> <body> <header/> <div class="refentry" id="glGenerateMipmap"> <div class="titlepage"/> <div class="refnamediv"> <h2>Name</h2> <p>glGenerateMipmap, glGenerateTextureMipmap — generate mipmaps for a specified texture object</p> </div> <div class="refsynopsisdiv"> <h2>C Specification</h2> <div class="funcsynopsis"> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glGenerateMipmap</strong>(</code> </td> <td>GLenum <var class="pdparam">target</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> <table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table"> <tr> <td> <code class="funcdef">void <strong class="fsfunc">glGenerateTextureMipmap</strong>(</code> </td> <td>GLuint <var class="pdparam">texture</var><code>)</code>;</td> </tr> </table> <div class="funcprototype-spacer"> </div> </div> </div> <div class="refsect1" id="parameters"> <h2>Parameters</h2> <div class="variablelist"> <dl class="variablelist"> <dt> <span class="term"> <em class="parameter"> <code>target</code> </em> </span> </dt> <dd> <p> Specifies the target to which the texture object is bound for <code class="function">glGenerateMipmap</code>. Must be one of <code class="constant">GL_TEXTURE_1D</code>, <code class="constant">GL_TEXTURE_2D</code>, <code class="constant">GL_TEXTURE_3D</code>, <code class="constant">GL_TEXTURE_1D_ARRAY</code>, <code class="constant">GL_TEXTURE_2D_ARRAY</code>, <code class="constant">GL_TEXTURE_CUBE_MAP</code>, or <code class="constant">GL_TEXTURE_CUBE_MAP_ARRAY</code>. </p> </dd> <dt> <span class="term"> <em class="parameter"> <code>texture</code> </em> </span> </dt> <dd> <p> Specifies the texture object name for <code class="function">glGenerateTextureMipmap</code>. </p> </dd> </dl> </div> </div> <div class="refsect1" id="description"> <h2>Description</h2> <p> <code class="function">glGenerateMipmap</code> and <code class="function">glGenerateTextureMipmap</code> generates mipmaps for the specified texture object. For <code class="function">glGenerateMipmap</code>, the texture object is that bound to to <em class="parameter"><code>target</code></em>. For <code class="function">glGenerateTextureMipmap</code>, <em class="parameter"><code>texture</code></em> is the name of the texture object. </p> <p> For cube map and cube map array textures, the texture object must be cube complete or cube array complete respectively. </p> <p> Mipmap generation replaces texel image levels $level_{base} + 1$ through $q$ with images derived from the $level_{base}$ image, regardless of their previous contents. All other mimap images, including the $level_{base}+1$ image, are left unchanged by this computation. </p> <p> The internal formats of the derived mipmap images all match those of the $level_{base}$ image. The contents of the derived images are computed by repeated, filtered reduction of the $level_{base} + 1$ image. For one- and two-dimensional array and cube map array textures, each layer is filtered independently. </p> </div> <div class="refsect1" id="notes"> <h2>Notes</h2> <p> Cube map array textures are accepted only if the GL version is 4.0 or higher. </p> </div> <div class="refsect1" id="errors"> <h2>Errors</h2> <p> <code class="constant">GL_INVALID_ENUM</code> is generated by <code class="function">glGenerateMipmap</code> if <em class="parameter"><code>target</code></em> is not one of the accepted texture targets. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated by <code class="function">glGenerateTextureMipmap</code> if <em class="parameter"><code>texture</code></em> is not the name of an existing texture object. </p> <p> <code class="constant">GL_INVALID_OPERATION</code> is generated if <em class="parameter"><code>target</code></em> is <code class="constant">GL_TEXTURE_CUBE_MAP</code> or <code class="constant">GL_TEXTURE_CUBE_MAP_ARRAY</code>, and the specified texture object is not cube complete or cube array complete, respectively. </p> </div> <div class="refsect1" id="versions"> <h2>Version Support</h2> <div class="informaltable"> <table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; "> <colgroup> <col style="text-align: left; "/> <col style="text-align: center; " class="firstvers"/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; "/> <col style="text-align: center; " class="lastvers"/> </colgroup> <thead> <tr> <th style="text-align: left; border-right: 2px solid ; "> </th> <th style="text-align: center; border-bottom: 2px solid ; " colspan="12"> <span class="bold"><strong>OpenGL Version</strong></span> </th> </tr> <tr> <th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>Function / Feature Name</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>2.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>3.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.0</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.1</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.2</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.3</strong></span> </th> <th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; "> <span class="bold"><strong>4.4</strong></span> </th> <th style="text-align: center; border-bottom: 2px solid ; "> <span class="bold"><strong>4.5</strong></span> </th> </tr> </thead> <tbody> <tr> <td style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; "> <code class="function">glGenerateMipmap</code> </td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">✔</td> <td style="text-align: center; border-bottom: 2px solid ; ">✔</td> </tr> <tr> <td style="text-align: left; border-right: 2px solid ; "> <code class="function">glGenerateTextureMipmap</code> </td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; border-right: 2px solid ; ">-</td> <td style="text-align: center; ">✔</td> </tr> </tbody> </table> </div> </div> <div class="refsect1" id="seealso"> <h2>See Also</h2> <p> <a class="citerefentry" href="glTexImage2D.xhtml"><span class="citerefentry"><span class="refentrytitle">glTexImage2D</span></span></a>, <a class="citerefentry" href="glBindTexture.xhtml"><span class="citerefentry"><span class="refentrytitle">glBindTexture</span></span></a>, <a class="citerefentry" href="glGenTextures.xhtml"><span class="citerefentry"><span class="refentrytitle">glGenTextures</span></span></a> </p> </div> <div class="refsect1" id="Copyright"> <h2>Copyright</h2> <p> Copyright <span class="trademark"/>© 2010-2014 Khronos Group. This material may be distributed subject to the terms and conditions set forth in the Open Publication License, v 1.0, 8 June 1999. <a class="link" href="http://opencontent.org/openpub/" target="_top">http://opencontent.org/openpub/</a>. </p> </div> </div> <footer/> </body> </html> <file_sep>/man4/docbook4/valid #!/bin/sh xmllint --noout --xinclude --dtdvalid http://www.oasis-open.org/docbook/xml/mathml/1.1CR1/dbmathml.dtd $* <file_sep>/man4/.svn/pristine/d6/d61f91246733f96931a53049194b8dd6a0fb32bc.svn-base # Copyright (c) 2013 The Khronos Group Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and/or associated documentation files (the # "Materials"), to deal in the Materials without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Materials, and to # permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. LDIRT := $(wildcard gl*.xml) COMMONPREF = standard include $(ROOT)/usr/include/make/commondefs SUBDIRS = \ html \ $(NULL) default $(ALLTARGS): $(_FORCE) $(SUBDIRS_MAKERULE) distoss: $(MAKE) $(COMMONPREF)$@ $(SUBDIRS_MAKERULE) include $(COMMONRULES) XIFILES = baseformattable.xml \ compressedformattable.xml \ internalformattable.xml \ texboformattable.xml \ apifunchead.xml \ apiversion.xml \ funchead.xml \ varhead.xml \ version.xml # Docbook 5 Relax-NG with XInclude schema URLs and local filenames DB5XIRNCURL = http://docbook.org/xml/5.0/rng/docbookxi.rnc DB5XIRNC = /usr/share/xml/docbook/schema/rng/5.0/docbookxi.rnc XML = $(filter-out $(XIFILES),$(wildcard *.xml)) validate: jing -c $(DB5XIRNC) $(XML)
33ff3bea8ebe7cbef6059b5de1f25d63faca48c9
[ "HTML", "Markdown", "Makefile", "Python", "PHP", "Shell" ]
20
HTML
rikkimax/ogl_gen
57a06d6aef003759a3c039b1c629953b077cd9e0
6ee75cfaf0549b7a52649533ff826da7748e89e4
refs/heads/master
<file_sep>'use strict' let BinaryTree = require('./binary_tree').BinaryTree; let Node = require('./binary_tree').Node; class MinimalTree extends BinaryTree{ create(arr){ this.root = this.recurseCreate(arr, 0, arr.length - 1); } recurseCreate(arr, begin, end){ if( end < begin ){ return null; } let pivot = Math.floor((begin + end) / 2); let r = new Node(arr[pivot]); r.left = this.recurseCreate(arr, begin, pivot - 1); r.right = this.recurseCreate(arr, pivot + 1, end); return r; } } module.exports = MinimalTree;<file_sep> import { expect } from 'chai'; import * as funcs from './string_compression'; for (let key in funcs) { let func = funcs[key]; describe('String compression: ' + key, function() { [ ['aaaaa', 'a5'], ['aabcccccaaa', 'a2b1c5a3'] ].forEach(args => { it(`must compress string '${args[0]}' to '${args[1]}'`, function() { expect(func(args[0])).to.equal(args[1]); }); }); [ ['a', 'a'], ['abcd', 'abcd'], ['aa', 'aa'], ['', ''] ].forEach(args => { it(`must not compress string '${args[0]}'`, function() { expect(func(args[0])).to.be.equal(args[1]); }); }); }); }<file_sep>'use strict' let List = require('./linkedlist'); let LinkedList = List.LinkedList; class Intersect{ constructor(list1, list2){ this.list1 = list1; this.list2 = list2; } findIntersection(){ let node1 = this.list1.head; let size1 = 0; let node2 = this.list2.head; let size2 = 0; while( node1.next ){ node1 = node1.next; size1++; } while( node2.next ){ node2 = node2.next; size2++; } if( node1 != node2 ){ return null; } let sizeDifference = Math.abs(size1 - size2); node1 = this.list1.head; node2 = this.list2.head; let c = 0; if( size1 < size2 ){ while( c < sizeDifference ){ node2 = node2.next; c++; } }else{ while( c < sizeDifference ){ node1 = node1.next; c++; } } while( node1 != node2 ){ node1 = node1.next; node2 = node2.next; } return node1; } } module.exports = Intersect;<file_sep>'use strict' let List = require('./linkedlist'); let LinkedList = List.LinkedList; class Loop{ constructor(list){ this.list = list; } detect(){ let visitedNodes = new Set(); let node = this.list.head; let result = null; while( node ){ if( visitedNodes.has(node.next) ){ result = node; break; } visitedNodes.add(node); node = node.next; } return result; } } module.exports = Loop;<file_sep>'use strict' class Queue{ constructor(){ this.first = null; this.last = null; } add(value){ let newNode = new QueueNode(value); if( this.last ){ this.last.next = newNode; } this.last = newNode; if( !this.first ){ this.first = this.last; } } remove(){ let result = null; if( this.first ){ result = this.first.value; this.first = this.first.next; if( this.first == null ){ this.last = null; } } return result; } peek(){ let result = null; if( this.first ){ result = this.first.value; } return result; } empty(){ return this.first == this.last; } toArray(){ let result = []; let node = this.first; while( node ){ result.push(node.value); node = node.next; } return result; } } class QueueNode{ constructor(value){ this.value = value; this.next = null; } } module.exports = Queue;<file_sep>'use strict' import { LinkedList } from './linkedlist' class RemoveDuplicates{ constructor(list){ this.list = list; } remove(){ let node = this.list.head; while( node ){ let previous = node; let current = node.next; while( current ){ if( node.value === current.value ){ previous.next = current.next; } previous = current; current = current.next; } node = node.next; } } } module.exports = RemoveDuplicates;<file_sep>'use strict' let chai = require('chai'); let BinaryTree = require('./binary_tree').BinaryTree; let Node = require('./binary_tree').Node; let ListOfDepths = require('./list_of_depths'); chai.should(); describe('List of Depths', () => { let listOfDepths; let tree; beforeEach(() => { tree = new BinaryTree(); listOfDepths = new ListOfDepths(); }) it('should have 0 lists when tree is empty', () => { let r = listOfDepths.create(tree); r.length.should.equal(0); }); it('should have 1 lists when tree has only root', () => { tree.root = new Node(1); let r = listOfDepths.create(tree); r.length.should.equal(1); r[0][0].value.should.equal(1); }); it('should have 2 lists when tree has 2 nodes', () => { tree.root = new Node(1); tree.root.left = new Node(2); let r = listOfDepths.create(tree); r.length.should.equal(2); r[0][0].value.should.equal(1); r[1][0].value.should.equal(2); }); it('should have 2 lists when tree has 3 nodes', () => { tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); let r = listOfDepths.create(tree); r.length.should.equal(2); r[0][0].value.should.equal(1); r[1][0].value.should.equal(2); r[1][1].value.should.equal(3); }); it('should have 4 lists with complex tree', () => { let root = new Node(1); let n2 = new Node(2); let n3 = new Node(3); let n4 = new Node(4); let n5 = new Node(5); let n6 = new Node(6); let n7 = new Node(7); tree.root = root; root.left = n2; root.right = n3; n2.left = n4; n2.right = n5; n3.right = n6; n6.left = n7; let r = listOfDepths.create(tree); r.length.should.equal(4); r[0][0].value.should.equal(1); r[1][0].value.should.equal(2); r[1][1].value.should.equal(3); r[2][0].value.should.equal(4); r[2][1].value.should.equal(5); r[2][2].value.should.equal(6); r[3][0].value.should.equal(7); }); });<file_sep>'use strict' let chai = require('chai'); let BinaryTree = require('./binary_tree').BinaryTree; let Node = require('./binary_tree').Node; let BalanceChecker = require('./check_balanced'); chai.should(); describe('Check Balanced', () => { let checker; let tree; beforeEach(() => { tree = new BinaryTree(); checker = new BalanceChecker(tree); }) it('should be balanced when tree is empty', () => { checker.check().should.be.true; }); it('should be balanced tree has only root', () => { tree.root = new Node(1); checker.check().should.be.true; }); it('should be balanced when tree has 2 nodes', () => { tree.root = new Node(1); tree.root.left = new Node(2); checker.check().should.be.true; }); it('should not be balanced tree has 3 nodes in line', () => { tree.root = new Node(1); tree.root.left = new Node(2); tree.root.left.right = new Node(3); checker.check().should.be.false; }); it('should be balanced with complex complete tree', () => { let root = new Node(1); let n2 = new Node(2); let n3 = new Node(3); let n4 = new Node(4); let n5 = new Node(5); let n6 = new Node(6); let n7 = new Node(7); tree.root = root; root.left = n2; root.right = n3; n2.left = n4; n2.right = n5; n3.right = n6; n3.right = n7; checker.check().should.be.true; }); it('should not be balanced with complex unbalanced tree', () => { let root = new Node(1); let n2 = new Node(2); let n3 = new Node(3); let n4 = new Node(4); let n5 = new Node(5); let n6 = new Node(6); let n7 = new Node(7); tree.root = root; root.left = n2; root.right = n3; n2.left = n4; n2.right = n5; n3.left = n6; n6.left = n7; checker.check().should.be.false; }); });<file_sep>'use strict' let chai = require('chai'); let Stack = require('./stack').Stack; chai.should(); describe('Stack', () => { let stack; beforeEach( () => { stack = new Stack(); }); it('created stack should not be null', () => { stack.should.not.be.null; }); it('should have 2 itens', () => { stack.push(1); stack.push(2); stack.empty().should.be.false; stack.toArray().should.deep.equal([2, 1]); }); it('should be filled and then empty', () => { stack.push(1); stack.push(2); let firstPop = stack.pop(); let secondPop = stack.pop(); stack.empty().should.be.true; firstPop.should.equal(2); secondPop.should.equal(1); }); it('should peek item', () => { stack.push(1); stack.push(2); stack.peek().should.be.equal(2); stack.empty().should.be.false; stack.toArray().should.deep.equal([2, 1]); }); });<file_sep>'use strict' let chai = require('chai'); let SortStack = require('./sort_stack'); chai.should(); describe('Sort stack', () => { it('should order itens added in reverse order', () => { let stack = new SortStack(); for(let i = 0; i < 10; i++){ stack.push(i); } let previous = 10; while( !stack.empty() ){ stack.pop().should.be.equal(--previous) } }); });<file_sep>'use strict' let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; class KthFinder{ constructor(list){ this.list = list; } find(k){ let result = new LinkedList(); let count = 0; let node = this.list.head; while( node ){ if( ++count >= k ){ result.appendToTail(node.value) } node = node.next; } return count >= k ? result : null; } } module.exports = KthFinder; <file_sep>'use strict' class Stack{ constructor(){ this.top = null; } pop(){ let result = null; if( this.top ){ result = this.top.value; this.top = this.top.next; } return result; } push(value){ let newNode = new StackNode(value); newNode.next = this.top; this.top = newNode; } peek(){ let result = null; if( this.top ){ result = this.top.value; } return result; } empty(){ return this.top == null; } toArray(){ let result = []; let node = this.top; while( node != null ){ result.push(node.value); node = node.next; } return result; } } class StackNode{ constructor(value){ this.value = value; this.next = null; } } module.exports = {Stack, StackNode};<file_sep>'use strict' let chai = require('chai'); let SetOfStacks = require('./set_of_stacks'); chai.should(); describe('Set of stacks', () => { it('should return null when no element has been added', () => { let set = new SetOfStacks(3); }); it('should return 9 to 1 3 by 3', () => { let set = new SetOfStacks(3); for(let i = 0; i < 10; i++){ set.push(i); } for(let i = 9; i >= 0; i--){ let popped = set.pop(); popped.should.be.equal(i); } }); it('popAt without insertion after', () => { let set = new SetOfStacks(3); for(let i = 0; i < 10; i++){ set.push(i); } set.popAt(1).should.be.equal(5); for(let i = 9; i >= 0; i--){ if( i === 5 ) continue; let popped = set.pop(); popped.should.be.equal(i); } }); it('popAt with insertion after', () => { let set = new SetOfStacks(2); set.push(0); set.push(1); set.push(2); set.popAt(1); set.push(3); set.push(4); set.push(5); for(let i = 5; i >= 0; i--){ if( i === 2 ) continue; let popped = set.pop(); popped.should.be.equal(i); } }); });<file_sep>'use strict' let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; class Palindrome{ constructor(list){ this.list = list; } check(){ let other = this.reverse(this.list); let node1 = this.list.head; let node2 = other.head; while( node1 ){ if( node1.value !== node2.value ){ return false; } node1 = node1.next; node2 = node2.next; } return true; } reverse(list){ let result = new LinkedList(); this.reverseNodes(list.head, result); return result; } reverseNodes(node, result){ if( node ){ this.reverseNodes(node.next, result); result.appendToTail(node.value); } } } module.exports = Palindrome;<file_sep>'use strict' let chai = require('chai'); let expect = chai.expect; let BuildOrder = require('./build_order'); chai.should(); describe('Build order', () => { it('should have a result equivalent to the book', () =>{ let projects = ['a', 'b', 'c', 'd', 'e', 'f']; let dependencies = [{'a':'d'}, {'f':'b'}, {'b':'d'}, {'f':'a'}, {'d':'c'}]; let buildOrder = new BuildOrder(projects, dependencies); buildOrder.graph.should.not.be.null; buildOrder.graph.nodes.length.should.equal(6); buildOrder.find().should.deep.equal(['f', 'e', 'a', 'b', 'd', 'c']); }); it('should return null when can not find a sequence due to circular dependency', () => { let projects = ['a', 'b', 'c']; let dependencies = [{'b':'a'}, {'c':'b'}, {'a':'c'}]; let buildOrder = new BuildOrder(projects, dependencies); buildOrder.graph.should.not.be.null; buildOrder.graph.nodes.length.should.equal(3); expect(buildOrder.find()).to.be.null; }); });<file_sep>'use strict' let chai = require('chai'); let expect = chai.expect; let Intersect = require('./intersect'); let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; chai.should(); describe('Intersect', () => { let list1, list2; let intersect; beforeEach(() => { list1 = new LinkedList(); list2 = new LinkedList(); intersect = new Intersect(list1, list2); }); it('must not find intersection', () => { list1.appendToTail(1); list1.appendToTail(2); list1.appendToTail(3); list2.appendToTail(4); list2.appendToTail(5); list2.appendToTail(6); let result = intersect.findIntersection(); expect(result).to.be.null; }); it('must find intersection in the middle', () => { let list3 = new LinkedList(); let intersectionNode = new Node(3); list3.appendNodeToTail(intersectionNode); list3.appendToTail(5); list3.appendToTail(6); list1.head = list3.head; list1.appendToHead(2); list1.appendToHead(1); list2.head = list3.head; list2.appendToHead(8); list2.appendToHead(7); let result = intersect.findIntersection(); result = result && intersectionNode == result; result.should.be.true; }); it('must find intersection in the tail', () => { let list3 = new LinkedList(); let intersectionNode = new Node(3); list3.appendNodeToTail(intersectionNode); list1.head = list3.head; list1.appendToHead(2); list1.appendToHead(1); list2.head = list3.head; list2.appendToHead(8); list2.appendToHead(7); let result = intersect.findIntersection(); result = result && intersectionNode == result; result.should.be.true; }); it('must find intersection in the head(aka same list)', () => { list1.appendToHead(2); list1.appendToHead(1); list1.appendToHead(1); list2.head = list1.head; let result = intersect.findIntersection(); result = result && list1.head == result; result.should.be.true; }); it('must find intersection in the middle of different size lists', () => { let list3 = new LinkedList(); let intersectionNode = new Node(3); list3.appendNodeToTail(intersectionNode); list3.appendToTail(4); list3.appendToTail(5); list1.head = list3.head; list1.appendToHead(1); list2.head = list3.head; list2.appendToHead(9); list2.appendToHead(8); list2.appendToHead(7); let result = intersect.findIntersection(); result = result && intersectionNode == result; result.should.be.true; }); });<file_sep>'use strict' let chai = require('chai'); let expect = chai.expect; let MinStack = require('./min_stack') chai.should(); describe("Min Stack", () => { let stack; beforeEach(() => { stack = new MinStack(); }); it("should return null on empty stack", () => { expect(stack.min()).to.be.null; }); it("should return 1 on [5, 1, 4, 3, 9] stack", () => { stack.push(9); stack.push(3); stack.push(4); stack.push(1); stack.push(5); stack.min().should.be.equal(1); }); it("should return 3 on [5, 1, 4, 3, 9] stack after 1 is popped", () => { stack.push(9); stack.push(3); stack.push(4); stack.push(1); stack.push(5); stack.pop(); stack.pop(); stack.min().should.be.equal(3); }); });<file_sep>'use strict' let chai = require('chai'); let expect = chai.expect; let AnimalShelter = require('./animal_shelter'); chai.should(); describe('Animal shelter', () => { let as; beforeEach( () => { as = new AnimalShelter(); }); it('should remove animals in order', () => { as.enqueue('dog', 1); as.enqueue('cat', 1); as.enqueue('dog', 2); as.enqueue('cat', 3); as.enqueue('cat', 5); let animal = as.dequeueAny(); animal.type.should.be.equal('dog'); animal.name.should.be.equal(1); animal = as.dequeueAny(); animal.type.should.be.equal('cat'); animal.name.should.be.equal(1); animal = as.dequeueAny(); animal.type.should.be.equal('dog'); animal.name.should.be.equal(2); animal = as.dequeueAny(); animal.type.should.be.equal('cat'); animal.name.should.be.equal(3); animal = as.dequeueAny(); animal.type.should.be.equal('cat'); animal.name.should.be.equal(5); }); it('should have only dogs', () => { as.enqueue('dog', 1); as.enqueue('dog', 2); as.enqueue('dog', 3); let animal = as.dequeueCat(); expect(animal).to.be.null; for(let i = 1; i <= 3 ; i++){ animal = as.dequeueAny(); animal.type.should.be.equal('dog'); animal.name.should.be.equal(i); } }); it('should have only cats', () => { as.enqueue('cat', 1); as.enqueue('cat', 2); as.enqueue('cat', 3); let animal = as.dequeueDog(); expect(animal).to.be.null; for(let i = 1; i <= 3 ; i++){ animal = as.dequeueAny(); animal.type.should.be.equal('cat'); animal.name.should.be.equal(i); } }); it('should first remove all dogs and then cats', () => { as.enqueue('cat', 1); as.enqueue('cat', 2); as.enqueue('cat', 3); as.enqueue('dog', 1); as.enqueue('dog', 2); as.enqueue('dog', 3); let animal = null; for(let i = 1; i <= 3 ; i++){ animal = as.dequeueDog(); animal.type.should.be.equal('dog'); animal.name.should.be.equal(i); } for(let i = 1; i <= 3 ; i++){ animal = as.dequeueAny(); animal.type.should.be.equal('cat'); animal.name.should.be.equal(i); } }); });<file_sep>'use strict' class MiddleNodeDeleter{ constructor(list){ this.list = list; } delete(value){ let node = this.searchNode(value); //necessary as we don't have direct access to nodes with the used list data structure if( node == null || node.next == null ){ return false; } node.value = node.next.value; node.next = node.next.next; return true; } searchNode(value){ let node = this.list.head; while( node ){ if( node.value === value ){ return node; } node = node.next; } return null; } } module.exports = MiddleNodeDeleter;<file_sep>'use strict' let Graph = require('./graph').Graph; let Node = require('./graph').Node; class BuildOrder { constructor(projects, dependencies){ this.graph = new Graph(); let nodes = {}; for(let p of projects){ let node = new Node(p); this.graph.addNode(node); nodes[p] = node; } for(let d of dependencies){ let dependency = Object.keys(d)[0]; let dependent = d[dependency]; nodes[dependent].addChildren(dependency); } } find(){ let independentNodes = this.graph.nodes.filter(n => n.children.length === 0 ); if( independentNodes.length === 0 ){ return null; } } } module.exports = BuildOrder;<file_sep>'use strict' let chai = require('chai'); let Palindrome = require('./palindrome'); let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; chai.should(); describe('Linked List Palindrome ', () => { let list; let palindrome; beforeEach(() => { list = new LinkedList(); palindrome = new Palindrome(list); }); it('not a palindrome', () =>{ list.appendToTail(6); list.appendToTail(1); list.appendToTail(7); list.appendToTail(7); list.appendToTail(3); list.appendToTail(2); list.appendToTail(1); palindrome.check().should.be.false; }); it('a palindrome', () =>{ list.appendToTail(6); list.appendToTail(1); list.appendToTail(7); list.appendToTail(5); list.appendToTail(7); list.appendToTail(1); list.appendToTail(6); palindrome.check().should.be.true; }); it('not a palindrome with even size', () =>{ list.appendToTail(6); list.appendToTail(1); list.appendToTail(7); list.appendToTail(3); list.appendToTail(2); list.appendToTail(1); palindrome.check().should.be.false; }); it('a palindrome with even size', () =>{ list.appendToTail(6); list.appendToTail(1); list.appendToTail(7); list.appendToTail(7); list.appendToTail(1); list.appendToTail(6); palindrome.check().should.be.true; }); });<file_sep>function zeroOrOneEdit(s1, s2){ if( Math.abs(s1.length - s2.length) > 1 ){ return false; } let smaller = s1.length < s2.length ? s1 : s2; let bigger = s1.length >= s2.length ? s1 : s2; let changeCount = 0; let offset = 0; for(let i = 0; i < smaller.length; i++){ if( smaller.charAt(i) !== bigger.charAt(i+offset) ){ changeCount++; if( smaller.length !== bigger.length ){ offset++; } } } return changeCount < 2; } console.log(zeroOrOneEdit('pale', 'ple')); console.log(zeroOrOneEdit('pales', 'pale')); console.log(zeroOrOneEdit('pale', 'bale')); console.log(zeroOrOneEdit('pale', 'bake'));<file_sep>'use strict' let Queue = require('./queue'); class AnimalShelter { constructor(){ this.catsQueue = new Queue(); this.dogsQueue = new Queue(); this.position = 0; } enqueue(type, name){ let a = new Animal(type, name, this.position++); if( a.type === 'cat'){ this.catsQueue.add(a); }else if( a.type === 'dog' ){ this.dogsQueue.add(a); }else{ throw 'Only dogs and cats allowed'; } } dequeueAny(){ let firstCat = this.catsQueue.peek(); let firstDog = this.dogsQueue.peek(); let result = null; if( firstDog == null || firstCat != null && firstCat.position < firstDog.position ){ result = this.catsQueue.remove(); }else{ result = this.dogsQueue.remove(); } return result; } dequeueDog(){ return this.dogsQueue.remove(); } dequeueCat(){ return this.catsQueue.remove(); } } class Animal{ constructor(type, name, position){ this.position = position; this.type = type; this.name = name; } } module.exports = AnimalShelter;<file_sep>'use strict' let chai = require('chai'); let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; let MiddleNodeDeleter = require('./delete_middle_node'); chai.should(); describe('Delete middle node', () => { let list; let deleter; beforeEach(() => { list = new LinkedList(); deleter = new MiddleNodeDeleter(list); }); it('', () =>{ list.appendToTail(1); list.appendToTail(2); list.appendToTail(3); list.appendToTail(4); list.appendToTail(5); deleter.delete(4); list.toArray().should.deep.equal([1, 2, 3, 5]); }); });<file_sep>'use strict' let chai = require('chai'); let Graph = require('./graph').Graph; let Node = require('./graph').Node; chai.should(); describe('Graph', () => { let graph; beforeEach(() =>{ graph = new Graph(); }); it('new graph should not be null', () => { graph.should.not.be.null; }); it('new graph should not have nodes', () => { graph.nodes.should.not.be.null; graph.nodes.should.be.empty; }); it('new node should not have children', () => { let node = new Node(1); node.children.should.not.be.null; node.children.should.be.empty; }); });<file_sep>'use strict' let chai = require('chai'); let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; let Partitioner = require('./partition'); chai.should(); function checkCondition(list, pivot){ let biggerThanPivot = false; let result = true; let node = list.head; while( node ){ if( node.value >= pivot ){ biggerThanPivot = true; } if( !biggerThanPivot && node.value >= pivot || biggerThanPivot && node.value < pivot){ result = false; break; } node = node.next; } return result; } describe('Partition list around ', () => { let list; let partitioner; beforeEach(() => { list = new LinkedList(); partitioner = new Partitioner(list); }); it('X smaller than smallest value in list', () =>{ let pivot = 0; list.appendToTail(1); list.appendToTail(2); list.appendToTail(3); list.appendToTail(4); list.appendToTail(5); partitioner.partition(pivot); checkCondition(list, pivot).should.be.true; }); it('X bigger than than biggest value in list', () =>{ let pivot = 6; list.appendToTail(1); list.appendToTail(2); list.appendToTail(3); list.appendToTail(4); list.appendToTail(5); partitioner.partition(pivot); checkCondition(list, pivot).should.be.true; }); it('X between values in list', () =>{ let pivot = 3; list.appendToTail(5); list.appendToTail(4); list.appendToTail(1); list.appendToTail(2); list.appendToTail(3); partitioner.partition(pivot); checkCondition(list, pivot).should.be.true; }); it('X twice in list', () =>{ let pivot = 3; list.appendToTail(5); list.appendToTail(4); list.appendToTail(1); list.appendToTail(3); list.appendToTail(2); list.appendToTail(3); partitioner.partition(pivot); checkCondition(list, pivot).should.be.true; }); it('book example ', () =>{ let pivot = 5; list.appendToTail(3); list.appendToTail(5); list.appendToTail(8); list.appendToTail(5); list.appendToTail(10); list.appendToTail(2); list.appendToTail(1); partitioner.partition(pivot); checkCondition(list, pivot).should.be.true; }); });<file_sep>'use strict' let chai = require('chai'); let Graph = require('./graph').Graph; let Node = require('./graph').Node; let RouteFinder = require('./route_between_nodes'); chai.should(); describe('Route between nodes', () => { let graph; let finder; beforeEach(() => { graph = new Graph(); finder = new RouteFinder(graph); }) it('should find a route', () => { let n1 = new Node(1); let n2 = new Node(2); let n3 = new Node(3); let n4 = new Node(4); let n5 = new Node(5); n1.addChildren(n2); n1.addChildren(n3); n2.addChildren(n4); n3.addChildren(n5); graph.addNode(n1); finder.hasRoute(n1, n5).should.be.true; }); it('should not find a route', () => { let n1 = new Node(1); let n2 = new Node(2); let n3 = new Node(3); let n4 = new Node(4); let n5 = new Node(5); n1.addChildren(n2); n2.addChildren(n4); n3.addChildren(n5); graph.addNode(n1); graph.addNode(n3); finder.hasRoute(n1, n5).should.be.false; }); });<file_sep>'use strict' let Stack = require('./stack').Stack; class QueueOfStacks{ constructor(){ this.mainStack = new Stack(); this.auxStack = new Stack(); } add(value){ this.fillMainStack(); this.mainStack.push(value); this.fillAuxStack(); } remove(){ return this.auxStack.pop(); } peek(){ return this.auxStack.peek(); } empty(){ return this.auxStack.empty(); } toArray(){ let result = []; while( !this.auxStack.empty() ){ let value = this.auxStack.pop(); result.push(value); this.mainStack.push(value) } this.fillAuxStack(); return result; } fillAuxStack(){ while( !this.mainStack.empty() ){ this.auxStack.push(this.mainStack.pop()); } } fillMainStack(){ while( !this.auxStack.empty() ){ this.mainStack.push(this.auxStack.pop()); } } } class QueueNode{ constructor(value){ this.value = value; this.next = null; } } module.exports = QueueOfStacks;<file_sep>'use strict' class RouteFinder{ constructor(graph){ this.graph = graph; } hasRoute(a, b){ let queue = []; a.visited = true; queue.push(a); while( queue.length ){ let n = queue.shift(); if( n == b ){ return true; } n.visited = true; for(let c of n.children){ if( !c.visited ){ c.visited = true; queue.push(c); } } } return false; } } module.exports = RouteFinder;<file_sep>'use strict' let chai = require('chai'); let expect = chai.expect; let BinaryTree = require('./binary_tree').BinaryTree; let Node = require('./binary_tree').Node; let Sucessor = require('./sucessor'); chai.should(); describe('Sucessor', () => { let tree; let sucessor; beforeEach(() => { tree = new BinaryTree(); sucessor = new Sucessor(tree); }); it('should be null with empty tree', () =>{ expect(sucessor.find(0)).to.be.null; }); it('should be null with single node', () =>{ tree.root = new Node(1); expect(sucessor.find(1)).to.be.null; }); it('should be null with unkown item', () =>{ let n1 = new Node(3); let n2 = new Node(2); let n3 = new Node(4); n1.left = n2; n1.right = n3; tree.root = n1; expect(sucessor.find(5)).to.be.null; }); it('should be smallest of the biggers when there is a right branch', () =>{ tree.root = buildComplexTree(); sucessor.find(4).should.equal(7); }); it('should be parent of parent when there is not right branch and node is reached from the right', () =>{ tree.root = buildComplexTree(); sucessor.find(13).should.equal(15); }); it('should be parent when there is not right branch and node is reached from the left', () =>{ tree.root = buildComplexTree(); sucessor.find(7).should.equal(8); }); }); /* 9 4 15 3 8 11 16 2 7 13 12 */ function buildComplexTree(){ let n9 = new Node(9); let n4 = new Node(4); let n15 = new Node(15); let n3 = new Node(3); let n8 = new Node(8); let n11 = new Node(11); let n16 = new Node(16); let n2 = new Node(2); let n7 = new Node(7); let n13 = new Node(13); let n12 = new Node(12); n9.left = n4; n4.parent = n9; n9.right = n15; n15.parent = n9; n4.left = n3; n3.parent = n4; n4.right = n8; n8.parent = n4; n15.left = n11; n11.parent = n15; n15.right = n16; n16.parent = n15; n3.left = n2; n2.parent = n3; n8.left = n7; n7.parent = n8; n11.right = n13; n13.parent = n11; n13.left = n12; n12.parent = n13; return n9; }<file_sep>'use strict' let chai = require('chai'); let List = require('./linkedlist'); let LinkedList = List.LinkedList; let Node = List.Node; chai.should(); describe('Linked List', () => { let list; beforeEach( () => { list = new LinkedList(); }); it('create a list', () => { list.should.not.be.null; }); it('appendToTail', () => { list.appendToTail('a'); list.appendToTail('b'); list.toArray().should.deep.equal(['a', 'b']); }); it('appendToTail', () => { list.appendToHead('a'); list.appendToHead('b'); list.toArray().should.deep.equal(['b', 'a']); }); describe('toArray', () =>{ it('should return empty array', () => { let r = list.toArray(); r.should.be.a('array'); r.should.be.empty; }); it('should return non empty array', () => { list.appendToTail('a'); list.appendToTail('b'); let r = list.toArray(); r.should.not.be.empty; r.should.deep.equal(['a', 'b']); }); }); });
f83be19eea40a491cedc3434f484d5d07c2c28da
[ "JavaScript" ]
31
JavaScript
ltrias/ctci
29ec0f03b0ddf3046f83885647f2bb0e10f74184
0e9763efad37e4c0a152bb0efb72befe3c80eaa0
refs/heads/master
<file_sep>import React from 'react' import profileimg from '../../assets/profile.jpg' import '../../scss/_profile.scss' import LogoFacebook from 'react-ionicons/lib/LogoFacebook' import LogoTwitter from 'react-ionicons/lib/LogoTwitter' import LogoGithub from 'react-ionicons/lib/LogoGithub' import LogoInstagram from 'react-ionicons/lib/LogoInstagram' import IosCloudDownloadOutline from 'react-ionicons/lib/IosCloudDownloadOutline' import IosArrowForward from 'react-ionicons/lib/IosArrowForward' const Profile = () => { return ( <div className="profile"> <div className="profile-img"> <img src={profileimg} alt="user" ></img> </div> <h1 className="myh1"><NAME></h1> <h2 className="myh2">Web Developer</h2> <div className="social"> <a target="_blank" href="https://dribbble.com/"><LogoFacebook color='orange' className="social-icon" fontSize="30px" /></a> <a target="_blank" href="https://twitter.com/"><LogoTwitter color='orange' className="social-icon" fontSize="30px" /></a> <a target="_blank" href="https://github.com/"><LogoGithub color='orange' className="social-icon" fontSize="30px" /></a> <a target="_blank" href="https://www.spotify.com/"><LogoInstagram color='orange' className="social-icon" fontSize="30px" /></a> </div> <div className="btns"> <button href="#" className="btn left" >Download C.V <IosCloudDownloadOutline color="white" className="icon" /></button> <button href="#" className="btn right">Contact Me <IosArrowForward color="white" className="icon" /></button> </div> </div> ) } export default Profile;<file_sep>import React from 'react' import '../../scss/_header.scss' import MdPerson from 'react-ionicons/lib/MdPerson' import IosPaper from 'react-ionicons/lib/MdPaper' import IosBrush from 'react-ionicons/lib/MdBrush' import IosChatbubbles from 'react-ionicons/lib/IosChatbubbles' export const Header = () => { return ( <header className="header"> <div className="top-menu"> <ul> <li className="active"> <a href="/" > <MdPerson color="white" /> <br /> <span className="link">About</span> </a> </li> <li> <a href="/resume"> <IosPaper color="white" /> <br /> <span className="link">Resume</span> </a> </li> <li> <a href="/"> <IosBrush color="white" /> <br /> <span className="link">Works</span> </a> </li> <li> <a href="/"> <IosChatbubbles color="white" /> <br /> <span className="link">Blog</span> </a> </li> </ul> </div> </header> ) } <file_sep>import React from 'react' import ChartWrapper4 from '../charts/ChartWrapper4' const Resume = () => { return ( <> <div className="section"> <h1 className="title">Experiences</h1> <div id="map-chart"> <ChartWrapper4 /> </div> </div> </> ) } export default Resume <file_sep>import React from 'react' import '../../scss/_about.scss' import MdWoman from 'react-ionicons/lib/MdWoman' import ChartWrapper from '../charts/ChartWrapper'; import ChartWrapper2 from '../charts/ChartWrapper2'; import ChartWrapper3 from '../charts/ChartWrapper3'; const About = () => { return ( <> <div className="section"> <h1 className="title">About Me</h1> <div className="section-flex"> <div className="about"> <p>After 3 years of academic education in IT and 3 years of self studying, I've learned coding and new technologies to make complex web applications and worked as contractor to make web applications for startup businesses and individual clients, now seeking a professional environment in which I can apply my web development skills and gain experience in a challenging and rewarding career.</p> </div> <div className="about-list"> <ul> <li><strong>age .....</strong><div className="float-right">25</div></li> <li><strong>gender .....</strong><div className="float-right"><MdWoman color="white" fontSize="25px" /></div></li> <li><strong>occupation .....</strong><div className="float-right">Web Developer</div></li> <li><strong>mobile .....</strong><div className="float-right">07-8282-222</div></li> <li><strong>email .....</strong><div className="float-right"><EMAIL></div></li> </ul> </div> </div> </div> <div className="section"> <h1 className="title">Skills</h1> <div className="section-flex"> <div className="section-flex" id="bubble-chart"> <ChartWrapper /> </div> <div className="section-flex" id="linked-chart"> <ChartWrapper2 /> </div> </div> </div> <div className="section"> <h1 className="title">Git</h1> <h2 className="myh2">Git Contribution In The Current year</h2> <div id="git-chart"> <ChartWrapper3 /> </div> </div> </> ) } export default About <file_sep>import React from 'react' import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import '../../scss/_landing.scss'; import { Header } from './Header'; import Profile from './Profile' import Resume from './Resume' import About from './About' export const LandingPage = () => { return ( <div className="landing"> <Header /> <div className="container"> <Profile /> <div className="pages"> <Router> <Switch> <Route exact path="/" component={About} /> <Route path="/resume" component={Resume} /> </Switch> </Router> </div> </div> </div> ) } <file_sep>import * as d3 from 'd3'; export default class BubbleChart { constructor(element) { var json = { 'children': [ { 'name': 'web design', 'value': 50 }, { 'name': 'UX / UI', 'value': 14 }, { 'name': 'dev ops', 'value': 3 }, { 'name': 'algorithm / data structure', 'value': 29 }, { 'name': 'unit testing', 'value': 10 }, { 'name': 'deployment', 'value': 29 }, { 'name': 'database structure', 'value': 23 } ] } var diameter = 400, color = d3.scaleOrdinal(d3.schemeSet2); var colorScale = d3.scaleLinear() .domain([0, d3.max(json.children, function (d) { return d.value; })]) .range(["rgb(46, 73, 123)", "rgb(71, 187, 94)"]); var bubble = d3.pack() .size([diameter, diameter]) .padding(1); var margin = { left: 0, right: 0, top: 0, bottom: 0 } var svg = d3.select('#bubble-chart').append('svg') .attr('viewBox', '0 0 ' + (diameter + margin.right) + ' ' + diameter) .attr('width', (diameter + margin.right)) .attr('height', diameter) .attr('class', 'chart-svg'); var root = d3.hierarchy(json) .sum(function (d) { return d.value; }) .sort(function (a, b) { return b.value - a.value; }); bubble(root); var node = svg.selectAll('.node') .data(root.children) .enter() .append('g').attr('class', 'node') .attr('transform', function (d) { return 'translate(' + d.x + ' ' + d.y + ')'; }) .append('g').attr('class', 'graph'); node.append("circle") .attr("r", function (d) { return d.r; }) .style("fill", function (d) { return color(d.data.name); }); node.append("text") .attr("dy", ".3em") .style("text-anchor", "middle") .text(function (d) { return d.data.name; }) .style("fill", "#ffffff") .style("font-size", '12px') .style("font-weight", '700'); // svg.append("g") // .attr("class", "legendOrdinal") // .attr("transform", "translate(600,40)"); } }
fdcb77b46f27e437ea4b369dc90a431a0bb7640b
[ "JavaScript" ]
6
JavaScript
aryankatebian/digital-insight
3991b4a8f20ba4fae75f66cc95f664207a275461
44f4d723aace053c2448579ee0842bf05d8cfb10
refs/heads/master
<file_sep>using FootbalStats.Repos; using HtmlAgilityPack; using Models; using ScrapySharp.Extensions; using ScrapySharp.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootbalStats.Scrapers { public class SoccerStatsScraper { public List<ForebetUrl> Urls; public SoccerStatsScraper() { Urls = new List<ForebetUrl>(); Urls.Add(new ForebetUrl("Premier League", "http://www.soccerstats.com/team_timing.asp?league=england&pmtype=sc10")); Urls.Add(new ForebetUrl("Championship", "http://www.soccerstats.com/team_timing.asp?league=england2&pmtype=sc10")); Urls.Add(new ForebetUrl("Primera Division", "http://www.soccerstats.com/team_timing.asp?league=spain&pmtype=sc10")); Urls.Add(new ForebetUrl("Segunda Division", "http://www.soccerstats.com/team_timing.asp?league=spain2&pmtype=sc10")); Urls.Add(new ForebetUrl("Bundesliga", "http://www.soccerstats.com/team_timing.asp?league=germany&pmtype=sc10")); Urls.Add(new ForebetUrl("Ligue 1", "http://www.soccerstats.com/team_timing.asp?league=france&pmtype=sc10")); Urls.Add(new ForebetUrl("Serie A", "http://www.soccerstats.com/team_timing.asp?league=italy&pmtype=sc10")); Urls.Add(new ForebetUrl("Serie B", "http://www.soccerstats.com/team_timing.asp?league=italy2&pmtype=sc10")); } public void Scrape() { ScrapingBrowser Browser = new ScrapingBrowser(); //Browser.AllowAutoRedirect = true; // Browser has settings you can access in setup //Browser.AllowMetaRedirect = true; foreach (var url in Urls) { WebPage PageResult = Browser.NavigateToPage(url.Uri); HtmlNode tableContainer = PageResult.Html.CssSelect(".tabbertabdefault").FirstOrDefault(); List<HtmlNode> rows = tableContainer.CssSelect("tr.trow2").ToList(); rows.AddRange(tableContainer.CssSelect("tr.trow8").ToList()); foreach (var row in rows) { var tds = row.ChildNodes.Where(x => x.Name == "td"); string team = tds.ElementAt<HtmlNode>(0).InnerText.Trim(); string do10 = tds.ElementAt<HtmlNode>(1).InnerText; string do20 = tds.ElementAt<HtmlNode>(2).InnerText; string do30 = tds.ElementAt<HtmlNode>(3).InnerText; string do40 = tds.ElementAt<HtmlNode>(4).InnerText; string do50 = tds.ElementAt<HtmlNode>(5).InnerText; string do60 = tds.ElementAt<HtmlNode>(6).InnerText; string do70 = tds.ElementAt<HtmlNode>(7).InnerText; string do80 = tds.ElementAt<HtmlNode>(8).InnerText; string do90 = tds.ElementAt<HtmlNode>(9).InnerText; SoccerStatGoalByMinute soccerStatGoalByMinute = ParseData(team, do10, do20, do30, do40, do50, do60, do70, do80, do90); AddSoccerStatGoalByMinute(soccerStatGoalByMinute); } } } private SoccerStatGoalByMinute ParseData(string team, string do10, string do20, string do30, string do40, string do50, string do60, string do70, string do80, string do90) { SoccerStatGoalByMinute entity = new SoccerStatGoalByMinute(); string removeNbsp = team.Substring(6); entity.Team = removeNbsp; entity.Do10Scored = GetScored(do10); entity.Do10Conceded = GetConceded(do10); entity.Do20Scored = GetScored(do20); entity.Do20Conceded = GetConceded(do20); entity.Do30Scored = GetScored(do30); entity.Do30Conceded = GetConceded(do30); entity.Do40Scored = GetScored(do40); entity.Do40Conceded = GetConceded(do40); entity.Do50Scored = GetScored(do50); entity.Do50Conceded = GetConceded(do50); entity.Do60Scored = GetScored(do60); entity.Do60Conceded = GetConceded(do60); entity.Do70Scored = GetScored(do70); entity.Do70Conceded = GetConceded(do70); entity.Do80Scored = GetScored(do80); entity.Do80Conceded = GetConceded(do80); entity.Do90Scored = GetScored(do90); entity.Do90Conceded = GetConceded(do90); return entity; } private void AddSoccerStatGoalByMinute(SoccerStatGoalByMinute entity) { SoccerStatGoalByMinuteRepository repo = new SoccerStatGoalByMinuteRepository(); repo.Add(entity); } private int GetScored(string str) { int scored = 0; string[] split = str.Trim().Split('-'); scored = int.Parse(split[0].Trim()); return scored; } private int GetConceded(string str) { int conceded = 0; string[] split = str.Trim().Split('-'); conceded = int.Parse(split[1].Trim()); return conceded; } } } <file_sep>using System.Collections.Generic; namespace Models { /// <summary> /// obsolete (not used right now) /// </summary> //public class Season : IEntity //{ // public Season() // { // Matches = new List<MatchResult>(); // } // public int Id { get; set; } // public League League { get; set; } // public string Name { get; set; } // public virtual IList<MatchResult> Matches { get; set; } //} } <file_sep>using System; namespace FootbalStats.Scrapers { public class ForebetUrl { public ForebetUrl(string league, string uri) { League = league; Uri = new Uri(uri); } public string League { get; set; } public Uri Uri { get; set; } } } <file_sep>using System.Text; namespace Models { public class SoccerStatGoalByMinute : IEntity { public int Id { get; set; } public string Team { get; set; } public int Do10Scored { get; set; } public int Do20Scored { get; set; } public int Do30Scored { get; set; } public int Do40Scored { get; set; } public int Do50Scored { get; set; } public int Do60Scored { get; set; } public int Do70Scored { get; set; } public int Do80Scored { get; set; } public int Do90Scored { get; set; } public int Do10Conceded { get; set; } public int Do20Conceded { get; set; } public int Do30Conceded { get; set; } public int Do40Conceded { get; set; } public int Do50Conceded { get; set; } public int Do60Conceded { get; set; } public int Do70Conceded { get; set; } public int Do80Conceded { get; set; } public int Do90Conceded { get; set; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine("|10|20|30|40|50|60|70|80|90|"); sb.Append("|"); if (Do10Scored < 10) sb.Append(" " + Do10Scored + "|"); else sb.Append(Do10Scored + "|"); if (Do20Scored < 10) sb.Append(" " + Do20Scored + "|"); else sb.Append(Do20Scored + "|"); if (Do30Scored < 10) sb.Append(" " + Do30Scored + "|"); else sb.Append(Do30Scored + "|"); if (Do40Scored < 10) sb.Append(" " + Do40Scored + "|"); else sb.Append(Do40Scored + "|"); if (Do50Scored < 10) sb.Append(" " + Do50Scored + "|"); else sb.Append(Do50Scored + "|"); if (Do60Scored < 10) sb.Append(" " + Do60Scored + "|"); else sb.Append(Do60Scored + "|"); if (Do70Scored < 10) sb.Append(" " + Do70Scored + "|"); else sb.Append(Do70Scored + "|"); if (Do80Scored < 10) sb.Append(" " + Do80Scored + "|"); else sb.Append(Do80Scored + "|"); if (Do90Scored < 10) sb.Append(" " + Do90Scored + "|"); else sb.Append(Do90Scored + "|"); sb.AppendLine(); return sb.ToString(); } } } <file_sep>using Models; using System.Collections.Generic; using System.Linq; using System; namespace Repos { public class LeagueRepository : IRepository<League> { MainDbContext _context; public LeagueRepository() { _context = new MainDbContext(); } public IEnumerable<League> List { get { return _context.Leagues; } } public void Add(League entity) { _context.Leagues.Add(entity); _context.SaveChanges(); } public void Delete(League entity) { _context.Leagues.Remove(entity); _context.SaveChanges(); } public void Update(League entity) { _context.Entry(entity).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } public League FindById(int Id) { var result = (from r in _context.Leagues where r.Id == Id select r).FirstOrDefault(); return result; } public League FindByName(string name) { var result = (from r in _context.Leagues where r.Name == name select r).FirstOrDefault(); return result; } } } <file_sep>using System; using System.Text; namespace Models { public class MatchResult : IEntity { public int Id { get; set; } //public Season Season { get; set; } public virtual League League { get; set; } public DateTime Date { get; set; } public int Percentage1 { get; set; } public int PercentageX { get; set; } public int Percentage2 { get; set; } public string Prediction { get; set; } public int ExactScore1 { get; set; } public int ExactScore2 { get; set; } public float AverageScore { get; set; } //public Team Team1 { get; set; } //TODO entity //public Team Team2 { get; set; } //TODO entity public string Team1 { get; set; } public string Team2 { get; set; } public int Team1Goals { get; set; } public int Team2Goals { get; set; } //public decimal HomeTeamCorners { get; set; } //public decimal AwayTeamCorners { get; set; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(Date.ToString("dd/MM/yyyy HH:mm")); sb.Append(" "); if (League != null) sb.Append("[" + League.Name + "]"); sb.Append(Team1); sb.Append(" - "); sb.Append(Team2); sb.Append(" "); sb.Append(ExactScore1); sb.Append(" - "); sb.Append(ExactScore2); return sb.ToString(); } } } <file_sep>using Models; using Repos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootbalStats { public class Analyzer { MatchRepository MatchRepo; List<MatchResult> Matches; public Analyzer() { MatchRepo = new MatchRepository(); Matches = MatchRepo.List.ToList(); } public Tuple<double, int, int> WeakTeamToScore(int goalDiff) { double percentage = 0; int totalClalified = 0; int correctlyClalified = 0; DateTime today = DateTime.Now; var finishedMatches = Matches.Where(m => m.Date < today); var predictedBothToScore = finishedMatches.Where(m => m.ExactScore1 != 0 && m.ExactScore2 != 0 && Math.Abs(m.ExactScore1 - m.ExactScore2) >= goalDiff); List<MatchResult> weakTeamScored = predictedBothToScore.Where(m => m.ExactScore1 < m.ExactScore2 && m.Team1Goals != 0).ToList(); weakTeamScored.AddRange(predictedBothToScore.Where(m => m.ExactScore2 < m.ExactScore1 && m.Team2Goals != 0).ToList()); double predictedBothToScoreCount = Convert.ToDouble(predictedBothToScore.Count()); double actuallyWeakTeamScoredCount = Convert.ToDouble(weakTeamScored.Count()); percentage = actuallyWeakTeamScoredCount / predictedBothToScoreCount; totalClalified = Convert.ToInt32(predictedBothToScoreCount); correctlyClalified = Convert.ToInt32(actuallyWeakTeamScoredCount); return new Tuple<double, int, int>(percentage, totalClalified, correctlyClalified); } public double WeakTeamToScoreByLeague(string leagueName) { LeagueRepository leagueRepo = new LeagueRepository(); League league = new League(); league = leagueRepo.FindByName(leagueName); double percentage = 0; DateTime today = DateTime.Now; var finishedMatches = league.Matches.Where(m => m.Date < today); var predictedBothToScore = finishedMatches.Where(m => m.ExactScore1 != 0 && m.ExactScore2 != 0); List<MatchResult> weakTeamScored = predictedBothToScore.Where(m => m.ExactScore1 < m.ExactScore2 && m.Team1Goals != 0).ToList(); weakTeamScored.AddRange(predictedBothToScore.Where(m => m.ExactScore2 < m.ExactScore1 && m.Team2Goals != 0).ToList()); double predictedBothToScoreCount = Convert.ToDouble(predictedBothToScore.Count()); double actuallyWeakTeamScoredCount = Convert.ToDouble(weakTeamScored.Count()); percentage = actuallyWeakTeamScoredCount / predictedBothToScoreCount; return percentage; } public Tuple<double, int, int> WeakTeamToScoreWithGoalDifferenceByLeague(int goalDiff, string leagueName) { double percentage = 0; int totalClalified = 0; int correctlyClalified = 0; LeagueRepository leagueRepo = new LeagueRepository(); League league = new League(); league = leagueRepo.FindByName(leagueName); DateTime today = DateTime.Now; var finishedMatches = league.Matches.Where(m => m.Date < today); var predictedBothToScore = finishedMatches.Where(m => m.ExactScore1 != 0 && m.ExactScore2 != 0 && Math.Abs(m.ExactScore1 - m.ExactScore2) >= goalDiff); List<MatchResult> weakTeamScored = predictedBothToScore.Where(m => m.ExactScore1 < m.ExactScore2 && m.Team1Goals != 0).ToList(); weakTeamScored.AddRange(predictedBothToScore.Where(m => m.ExactScore2 < m.ExactScore1 && m.Team2Goals != 0).ToList()); double predictedBothToScoreCount = Convert.ToDouble(predictedBothToScore.Count()); double actuallyWeakTeamScoredCount = Convert.ToDouble(weakTeamScored.Count()); percentage = actuallyWeakTeamScoredCount / predictedBothToScoreCount; totalClalified = predictedBothToScore.Count(); correctlyClalified = weakTeamScored.Count(); return new Tuple<double, int, int>(percentage, totalClalified, correctlyClalified); } public Tuple<double, int, int> WeakTeamToScoreByLeagueClean(string leagueName) { double percentage = 0; int successCount = 0; int failCount = 0; int total = 0; LeagueRepository leagueRepo = new LeagueRepository(); League league = new League(); league = leagueRepo.FindByName(leagueName); DateTime today = DateTime.Today; //weak team to score success //weak team 0 fail //success / (fail + success) var finishedMatches = league.Matches.Where(m => m.Date < today); var success = finishedMatches.Where(m => (m.Percentage1 < m.Percentage2 && m.Team1Goals != 0) || (m.Percentage2 < m.Percentage1 && m.Team2Goals != 0)); var fail = finishedMatches.Where(m => (m.Percentage1 < m.Percentage2 && m.Team1Goals == 0) || (m.Percentage2 < m.Percentage1 && m.Team2Goals == 0)); successCount = success.Count(); failCount = fail.Count(); total = successCount + failCount; percentage = Convert.ToDouble(successCount) / Convert.ToDouble(total); return new Tuple<double, int, int>(percentage, successCount, total); } } } <file_sep>using System.Collections.Generic; namespace Models { public class League : IEntity { public League() { //Seasons = new List<Season>(); Matches = new List<MatchResult>(); } public int Id { get; set; } public string Name { get; set; } //public virtual IList<Season> Seasons { get; set; } public virtual IList<MatchResult> Matches { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootbalStats.Algorithms { public static class LevenshteinDistance { /// <summary> /// Compute the distance between two strings. /// </summary> public static int Compute(string s, string t) { int n = s.Length; int m = t.Length; int[,] d = new int[n + 1, m + 1]; // Step 1 if (n == 0) { return m; } if (m == 0) { return n; } // Step 2 for (int i = 0; i <= n; d[i, 0] = i++) { } for (int j = 0; j <= m; d[0, j] = j++) { } // Step 3 for (int i = 1; i <= n; i++) { //Step 4 for (int j = 1; j <= m; j++) { // Step 5 int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; // Step 6 d[i, j] = Math.Min( Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // Step 7 return d[n, m]; } //public static double CalculateSimilarity(string source, string target) //{ // if ((source == null) || (target == null)) return 0.0; // if ((source.Length == 0) || (target.Length == 0)) return 0.0; // if (source == target) return 1.0; // int stepsToSame = ComputeV2(source, target); // return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length))); //} //public static int ComputeV2(string source, string target) //{ // // degenerate cases // if (source == target) return 0; // if (source.Length == 0) return target.Length; // if (target.Length == 0) return source.Length; // // create two work vectors of integer distances // int[] v0 = new int[target.Length + 1]; // int[] v1 = new int[target.Length + 1]; // // initialize v0 (the previous row of distances) // // this row is A[0][i]: edit distance for an empty s // // the distance is just the number of characters to delete from t // for (int i = 0; i < v0.Length; i++) // v0[i] = i; // for (int i = 0; i < source.Length; i++) // { // // calculate v1 (current row distances) from the previous row v0 // // first element of v1 is A[i+1][0] // // edit distance is delete (i+1) chars from s to match empty t // v1[0] = i + 1; // // use formula to fill in the rest of the row // for (int j = 0; j < target.Length; j++) // { // var cost = (source[i] == target[j]) ? 0 : 1; // v1[j + 1] = Math.Min(v1[j] + 1, Math.Min(v0[j + 1] + 1, v0[j] + cost)); // } // // copy v1 (current row) to v0 (previous row) for next iteration // for (int j = 0; j < v0.Length; j++) // v0[j] = v1[j]; // } // return v1[target.Length]; //} } } <file_sep>using Microsoft.VisualBasic.FileIO; using Models; using Repos; using System; using System.Collections.Generic; namespace FootbalStats.ImportExport { //public class CSVImporter //{ // private TextFieldParser parser; // public CSVImporter(string filePath) // { // parser = new TextFieldParser(filePath); // } // public void ImportSeason(string leagueName, string seasonName) // { // List<MatchResult> matches = new List<MatchResult>(); // using (parser) // { // parser.TextFieldType = FieldType.Delimited; // parser.SetDelimiters(","); // MatchResult match = new MatchResult(); // while (!parser.EndOfData) // { // string[] fields = parser.ReadFields(); // if (fields[1] != "Date") // { // match = new MatchResult(); // match.Date = DateTime.Parse(fields[1]); // match.HomeTeam = fields[2]; // match.AwayTeam = fields[3]; // if (!string.IsNullOrEmpty(fields[17])) match.HomeTeamCorners = Decimal.Parse(fields[17]); // if (!string.IsNullOrEmpty(fields[18])) match.AwayTeamCorners = Decimal.Parse(fields[18]); // if (!string.IsNullOrEmpty(fields[5])) match.FullTimeAwayTeamGoals = Decimal.Parse(fields[5]); // if (!string.IsNullOrEmpty(fields[4])) match.FullTimeHomeTeamGoals = Decimal.Parse(fields[4]); // matches.Add(match); // } // } // } // Season season = new Season(); // season.Name = seasonName; // season.Matches = matches; // LeagueRepository leagueRepo = new LeagueRepository(); // League league = leagueRepo.FindByName(leagueName); // if (league != null) // { // league.Seasons.Add(season); // leagueRepo.Update(league); // } // else // { // league = new League(); // league.Name = leagueName; // league.Seasons.Add(season); // leagueRepo.Add(league); // } // } //} } <file_sep>namespace FootbalStats.Migrations { using System; using System.Data.Entity.Migrations; public partial class SoccerStatGoalByMinute : DbMigration { public override void Up() { //CreateTable( // "dbo.Leagues", // c => new // { // Id = c.Int(nullable: false, identity: true), // Name = c.String(), // }) // .PrimaryKey(t => t.Id); //CreateTable( // "dbo.MatchResults", // c => new // { // Id = c.Int(nullable: false, identity: true), // Date = c.DateTime(nullable: false), // Percentage1 = c.Int(nullable: false), // PercentageX = c.Int(nullable: false), // Percentage2 = c.Int(nullable: false), // Prediction = c.String(), // ExactScore1 = c.Int(nullable: false), // ExactScore2 = c.Int(nullable: false), // AverageScore = c.Single(nullable: false), // Team1 = c.String(), // Team2 = c.String(), // Team1Goals = c.Int(nullable: false), // Team2Goals = c.Int(nullable: false), // League_Id = c.Int(), // }) // .PrimaryKey(t => t.Id) // .ForeignKey("dbo.Leagues", t => t.League_Id) // .Index(t => t.League_Id); CreateTable( "dbo.SoccerStatGoalByMinutes", c => new { Id = c.Int(nullable: false, identity: true), Team = c.String(), Do10Scored = c.Int(nullable: false), Do20Scored = c.Int(nullable: false), Do30Scored = c.Int(nullable: false), Do40Scored = c.Int(nullable: false), Do50Scored = c.Int(nullable: false), Do60Scored = c.Int(nullable: false), Do70Scored = c.Int(nullable: false), Do80Scored = c.Int(nullable: false), Do90Scored = c.Int(nullable: false), Do10Conceded = c.Int(nullable: false), Do20Conceded = c.Int(nullable: false), Do30Conceded = c.Int(nullable: false), Do40Conceded = c.Int(nullable: false), Do50Conceded = c.Int(nullable: false), Do60Conceded = c.Int(nullable: false), Do70Conceded = c.Int(nullable: false), Do80Conceded = c.Int(nullable: false), Do90Conceded = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.MatchResults", "League_Id", "dbo.Leagues"); DropIndex("dbo.MatchResults", new[] { "League_Id" }); DropTable("dbo.SoccerStatGoalByMinutes"); DropTable("dbo.MatchResults"); DropTable("dbo.Leagues"); } } } <file_sep>using Models; using System; using System.Collections.Generic; using System.Linq; namespace Repos { public class MatchRepository : IRepository<MatchResult> { MainDbContext _context; public MatchRepository() { _context = new MainDbContext(); } public IEnumerable<MatchResult> List { get { return _context.Matches; } } public void Add(MatchResult entity) { _context.Matches.Add(entity); _context.SaveChanges(); } public void Add(MatchResult match, string league) { var foundLeague = (from r in _context.Leagues where r.Name == league select r).FirstOrDefault(); match.League = foundLeague; _context.Matches.Add(match); _context.SaveChanges(); } public void Delete(MatchResult entity) { _context.Matches.Remove(entity); _context.SaveChanges(); } public void Update(MatchResult entity, string league) { MatchResult found = FindByDateAndTeams(entity.Date, entity.Team1, entity.Team2); if (CheckPropertyChange(ref found, entity)) { try { _context.Entry(found).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } catch (InvalidOperationException ex) { //fuck you } } if (LeagueChange(ref found, entity, league)) { try { _context.Entry(found).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } catch (InvalidOperationException ex) { //fuck you } } } public MatchResult FindById(int Id) { var result = (from r in _context.Matches where r.Id == Id select r).FirstOrDefault(); return result; } public MatchResult FindByDateAndTeams(DateTime date, string Team1, string Team2) { DateTime fromDate = date.AddDays(-30); DateTime toDate = date.AddDays(30); var result = _context.Matches.Where(m => m.Date < toDate && m.Date > fromDate && m.Team1 == Team1 && m.Team2 == Team2).FirstOrDefault(); return result; } private bool CheckPropertyChange(ref MatchResult found, MatchResult entity) { bool change = false; if (found.Date != entity.Date || found.Team1Goals != entity.Team1Goals || found.Team2Goals != entity.Team2Goals || found.Percentage1 != entity.Percentage1 || found.PercentageX != entity.PercentageX || found.Percentage2 != entity.Percentage2 || found.ExactScore1 != entity.ExactScore1 || found.ExactScore2 != entity.ExactScore2 || found.AverageScore != entity.AverageScore) { change = true; found.Date = entity.Date; found.Team1Goals = entity.Team1Goals; found.Team2Goals = entity.Team2Goals; found.Percentage1 = entity.Percentage1; found.PercentageX= entity.PercentageX; found.Percentage2 = entity.Percentage2; found.ExactScore1 = entity.ExactScore1; found.ExactScore2 = entity.ExactScore2; found.AverageScore= entity.AverageScore; } return change; } private bool LeagueChange(ref MatchResult found, MatchResult entity, string league) { bool change = false; if (found.League != null && entity.League != null && found.League.Name != entity.League.Name) { found.League = entity.League; change = true; } return change; } public void Update(MatchResult entity) { throw new NotImplementedException(); } } } <file_sep>using Models; using System.Data.Entity; namespace Repos { public class MainDbContext : DbContext { public MainDbContext() : base("FootballStats") { } public virtual IDbSet<MatchResult> Matches { get; set; } public virtual IDbSet<League> Leagues { get; set; } public virtual IDbSet<SoccerStatGoalByMinute> SoccerStatsGoalByMinute { get; set; } //public virtual IDbSet<Team> Teams { get; set; } //public virtual IDbSet<Season> Seasons { get; set; } } } <file_sep>using Fizzler.Systems.HtmlAgilityPack; using HtmlAgilityPack; using Models; using Repos; using ScrapySharp.Extensions; using ScrapySharp.Network; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace FootbalStats.Scrapers { public class ForebetScraper { public List<ForebetUrl> Urls; public ForebetScraper() { Urls = new List<ForebetUrl>(); Urls.Add(new ForebetUrl("Premier League", "https://www.forebet.com/en/football-tips-and-predictions-for-england/premier-league")); Urls.Add(new ForebetUrl("Championship", "https://www.forebet.com/en/football-tips-and-predictions-for-england/championship")); Urls.Add(new ForebetUrl("Primera Division", "https://www.forebet.com/en/football-tips-and-predictions-for-spain/primera-division")); Urls.Add(new ForebetUrl("Segunda Division", "https://www.forebet.com/en/football-tips-and-predictions-for-spain/segunda-division")); Urls.Add(new ForebetUrl("Bundesliga", "https://www.forebet.com/en/football-tips-and-predictions-for-germany/Bundesliga")); Urls.Add(new ForebetUrl("Ligue 1", "https://www.forebet.com/en/football-tips-and-predictions-for-france/ligue1")); Urls.Add(new ForebetUrl("Serie A", "https://www.forebet.com/en/football-tips-and-predictions-for-italy/serie-a")); Urls.Add(new ForebetUrl("Serie B", "https://www.forebet.com/en/football-tips-and-predictions-for-italy/serie-b")); } public void Scrape() { ScrapingBrowser Browser = new ScrapingBrowser(); //Browser.AllowAutoRedirect = true; // Browser has settings you can access in setup //Browser.AllowMetaRedirect = true; foreach (var url in Urls) { WebPage PageResult = Browser.NavigateToPage(url.Uri); List<HtmlNode> rows = PageResult.Html.CssSelect(".tr_0").ToList(); rows.AddRange(PageResult.Html.CssSelect(".tr_1").ToList()); foreach (var row in rows) { var tds = row.ChildNodes.Where(x => x.Name == "td"); //TEAMS string teams = string.Empty; try { teams = tds.ElementAt<HtmlNode>(0).ChildNodes.Where(x => x.Name == "a").FirstOrDefault().InnerHtml; } catch (Exception ex) { } //string teams = row.CssSelect(".tnms a").FirstOrDefault().InnerHtml; //DATE string date = string.Empty; try { date = tds.ElementAt<HtmlNode>(0).ChildNodes.Where(x => x.Name == "span").FirstOrDefault().InnerText; } catch (Exception ex) { } //string date = row.CssSelect(".tnms .date_bah").FirstOrDefault()?.InnerText; //PERCENTAGE 1 string percentage1 = string.Empty; try { percentage1 = tds.ElementAt<HtmlNode>(1)?.InnerText; } catch (Exception ex) { } //PERCENTAGE X string percentageX = string.Empty; try { percentageX = tds.ElementAt<HtmlNode>(2)?.InnerText; } catch (Exception ex) { } //PERCENTAGE 2 string percentage2 = string.Empty; try { percentage2 = tds.ElementAt<HtmlNode>(3)?.InnerText; } catch (Exception ex) { } //PREDICTION string prediction = string.Empty; try { prediction = tds.ElementAt<HtmlNode>(4)?.InnerText; } catch (Exception ex) { } //string prediction = row.CssSelect(".predict").FirstOrDefault()?.InnerText; //if (string.IsNullOrEmpty(prediction)) prediction = row.CssSelect(".predict_y").FirstOrDefault()?.InnerText; //if (string.IsNullOrEmpty(prediction)) prediction = row.CssSelect(".predict_no").FirstOrDefault()?.InnerText; //EXACT SCORE string exactScore = string.Empty; try { exactScore = tds.ElementAt<HtmlNode>(5)?.InnerText; } catch (Exception ex) { } //string exactScore = row.CssSelect(".scrpred").FirstOrDefault()?.InnerText; //AVERAGE SCORE string averageScore = string.Empty; try { averageScore = tds.ElementAt<HtmlNode>(6)?.InnerText; } catch (Exception ex) { } //TODO return commented code if needed //string finalScore = row.CssSelect(".lscr_td").FirstOrDefault()?.InnerText; string finalScore = string.Empty; try { if (tds.Count() == 12) { finalScore = tds.ElementAt<HtmlNode>(11)?.InnerText; } } catch (Exception ex) { } MatchResult match = ParseData(teams, date, percentage1, percentageX, percentage2, prediction, exactScore, averageScore, finalScore); AddOrUpdateMatch(match, url.League); } } } public MatchResult ParseData(string teams, string date, string percentage1, string percentageX, string percentage2, string prediction, string exactScore, string averageScore, string finalScore) { MatchResult match = new MatchResult(); match.Date = DateTime.ParseExact(date, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture).AddHours(3); int percentage_1 = int.TryParse(percentage1, out percentage_1) ? percentage_1 : 0; match.Percentage1 = percentage_1; int percentage_X = int.TryParse(percentageX, out percentage_X) ? percentage_X : 0; match.PercentageX = percentage_X; int percentage_2 = int.TryParse(percentage2, out percentage_2) ? percentage_2 : 0; match.Percentage2 = percentage_2; match.Prediction = prediction; int exactScore_1 = 0; int exactScore_2 = 0; if (!string.IsNullOrEmpty(exactScore)) { string[] exactResultPred = exactScore.Split('-'); int.TryParse(exactResultPred[0], out exactScore_1); int.TryParse(exactResultPred[1], out exactScore_2); match.ExactScore1 = exactScore_1; match.ExactScore2 = exactScore_2; } float averageScoreToFloat = float.TryParse(averageScore, out averageScoreToFloat) ? averageScoreToFloat : 0; match.AverageScore = averageScoreToFloat; string[] teamsSplit = teams.Split(new[] { "<br>" }, StringSplitOptions.None); match.Team1 = teamsSplit[0].Trim(); match.Team2 = teamsSplit[1].Trim(); int splitFinalScore1 = 0; int splitFinalScore2 = 0; if (!string.IsNullOrEmpty(finalScore)) { string[] split = finalScore.Trim().Split('('); string[] splitFinalScore = split[0].Split('-'); int.TryParse(splitFinalScore[0], out splitFinalScore1); int.TryParse(splitFinalScore[1], out splitFinalScore2); } match.Team1Goals = splitFinalScore1; match.Team2Goals = splitFinalScore2; return match; } public void AddOrUpdateMatch(MatchResult match, string league) { MatchRepository matchRepo = new MatchRepository(); MatchResult matchFound = matchRepo.FindByDateAndTeams(match.Date, match.Team1, match.Team2); if (matchFound == null) { matchRepo.Add(match, league); } else { matchRepo.Update(match, league); } } //NOT USED DEPRECATED public string GetHTMLFromUrl(ForebetUrl url) { string html = string.Empty; Uri urlAddress = url.Uri; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = null; if (response.CharacterSet == null) { readStream = new StreamReader(receiveStream); } else { readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); } html = readStream.ReadToEnd(); response.Close(); readStream.Close(); } return html; } //NOT USED DEPRECATED public void FizzlerTest(string htmllel) { var html = new HtmlDocument(); html.LoadHtml(@htmllel); // Fizzler for HtmlAgilityPack is implemented as the // QuerySelectorAll extension method on HtmlNode var document = html.DocumentNode; var body = document.QuerySelectorAll("body").FirstOrDefault(); var rows = body.QuerySelectorAll(".tr_0").ToList(); rows.AddRange(body.QuerySelectorAll(".tr_1").ToList()); foreach (var row in rows) { var tds = row.ChildNodes.Where(x => x.Name == "td"); var td1 = row.QuerySelectorAll(".tnms a").ToList(); //foreach (var td in tds) //{ // var teams = td.QuerySelectorAll("a").Where(x => x.Attributes.Where(a => a.Name == "class")); //} } } } } <file_sep>using System.Collections.Generic; using Models; using System; namespace Repos { public interface IRepository<T> where T : IEntity { IEnumerable<T> List { get; } void Add(T entity); void Delete(T entity); void Update(T entity); T FindById(int Id); //T FindByDateAndTeams(DateTime date, string Team1, string Team2); // THIS SHOULD BE DELETED } } <file_sep>using Models; using System.Collections.Generic; using System.Linq; namespace Repos { //public class SeasonRepository : IRepository<Season> //{ // MainDbContext _context; // public SeasonRepository() // { // _context = new MainDbContext(); // } // public IEnumerable<Season> List // { // get // { // return _context.Seasons; // } // } // public void Add(Season entity) // { // _context.Seasons.Add(entity); // _context.SaveChanges(); // } // public void Delete(Season entity) // { // _context.Seasons.Remove(entity); // _context.SaveChanges(); // } // public void Update(Season entity) // { // _context.Entry(entity).State = System.Data.Entity.EntityState.Modified; // _context.SaveChanges(); // } // public Season FindById(int Id) // { // var result = (from r in _context.Seasons where r.Id == Id select r).FirstOrDefault(); // return result; // } // public Season FindByName(string name) // { // var result = (from r in _context.Seasons where r.Name == name select r).FirstOrDefault(); // return result; // } //} } <file_sep>using Models; using Repos; using System; using System.Collections.Generic; using System.Linq; namespace FootbalStats.Repos { public class SoccerStatGoalByMinuteRepository : IRepository<SoccerStatGoalByMinute> { MainDbContext _context; public SoccerStatGoalByMinuteRepository() { _context = new MainDbContext(); } public IEnumerable<SoccerStatGoalByMinute> List { get { return _context.SoccerStatsGoalByMinute; } } public void Add(SoccerStatGoalByMinute entity) { _context.SoccerStatsGoalByMinute.Add(entity); _context.SaveChanges(); } public void Delete(SoccerStatGoalByMinute entity) { _context.SoccerStatsGoalByMinute.Remove(entity); _context.SaveChanges(); } public SoccerStatGoalByMinute FindById(int Id) { var result = (from r in _context.SoccerStatsGoalByMinute where r.Id == Id select r).FirstOrDefault(); return result; } public SoccerStatGoalByMinute FindByTeam(string team) { var result = (from r in _context.SoccerStatsGoalByMinute where r.Team == team select r).FirstOrDefault(); return result; } public void Update(SoccerStatGoalByMinute entity) { throw new NotImplementedException(); } } } <file_sep>using FootbalStats.Scrapers; using Models; using Repos; namespace FootbalStats { class Program { static void Main(string[] args) { //AddInitialLeagues(); //DO NOT RUN FIX UPDATE //SoccerStatsScraper soccerStatsScraper = new SoccerStatsScraper(); //soccerStatsScraper.Scrape(); ForebetScraper forebetScraper = new ForebetScraper(); forebetScraper.Scrape(); Reporter reporter = new Reporter(); //reporter.LeaguePercentageAnalyze(); // goal goal reporter.NextMatches(10); //+1 goal diff reporter.LeaguePercentageWithGoalDiffAnalyze(1); //reporter.GoalDifferenceAnalyze(1); //reporter.LeagiePercentageWeakTeamToNotScore(); //loti } public static void AddInitialLeagues() { string[] leagueNames = new string[] {"Premier League", "Championship", "Primera Division", "Segunda Division", "Bundesliga", "Ligue 1", "Serie A", "Serie B"}; var repo = new LeagueRepository(); //repo.Add(new League() { Name = "Serie B" }); foreach (var league in leagueNames) { repo.Add(new League() { Name = league }); } } } } <file_sep>namespace FootbalStats.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Leagues", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.MatchResults", c => new { Id = c.Int(nullable: false, identity: true), Date = c.DateTime(nullable: false), Percentage1 = c.Int(nullable: false), PercentageX = c.Int(nullable: false), Percentage2 = c.Int(nullable: false), Prediction = c.String(), ExactScore1 = c.Int(nullable: false), ExactScore2 = c.Int(nullable: false), AverageScore = c.Single(nullable: false), Team1 = c.String(), Team2 = c.String(), Team1Goals = c.Int(nullable: false), Team2Goals = c.Int(nullable: false), League_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Leagues", t => t.League_Id) .Index(t => t.League_Id); } public override void Down() { DropForeignKey("dbo.MatchResults", "League_Id", "dbo.Leagues"); DropIndex("dbo.MatchResults", new[] { "League_Id" }); DropTable("dbo.MatchResults"); DropTable("dbo.Leagues"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootbalStats.ImportExport { //TODO if needed public class ImportService { //THIS WAS IN PROGRAM.CS //CSVImporter importer = new CSVImporter(@"C:\Users\V45370\Desktop\Football CSVs\England\2016-2017\Championship.csv"); //importer.ImportSeason("Championship","2016-2017"); //LeagueRepository leagueRepo = new LeagueRepository(); //var championshipLeague = leagueRepo.FindByName("Championship"); //var thisSeason = championshipLeague.Seasons.FirstOrDefault(); //var newcastleMatches = thisSeason.Matches.Where(x => x.AwayTeam == "Newcastle" || x.HomeTeam == "Newcastle"); //var brightonMatches = thisSeason.Matches.Where(x => x.AwayTeam == "Brighton" || x.HomeTeam == "Brighton"); //decimal newCastleAverageCorners = 0; //decimal newCastleAverageGoals = 0; //foreach (var match in newcastleMatches) //{ // if(match.AwayTeam == "Newcastle") // { // newCastleAverageCorners += match.AwayTeamCorners; // newCastleAverageGoals += match.FullTimeAwayTeamGoals; // } // else // { // newCastleAverageCorners += match.HomeTeamCorners; // newCastleAverageGoals += match.FullTimeHomeTeamGoals; // } //} //newCastleAverageCorners /= newcastleMatches.Count(); //newCastleAverageGoals /= newcastleMatches.Count(); //decimal brightonAverageCorners = 0; //decimal brightonAverageGoals = 0; //foreach (var match in brightonMatches) //{ // if (match.AwayTeam == "Brighton") // { // brightonAverageCorners += match.AwayTeamCorners; // brightonAverageGoals += match.FullTimeAwayTeamGoals; // } // else // { // brightonAverageCorners += match.HomeTeamCorners; // brightonAverageGoals += match.FullTimeHomeTeamGoals; // } //} //brightonAverageCorners /= newcastleMatches.Count(); //brightonAverageGoals /= newcastleMatches.Count(); //Console.WriteLine("Newcastle average corners: {0}", newCastleAverageCorners); //Console.WriteLine("Newcastle average goals: {0}", newCastleAverageGoals); //Console.WriteLine("Brighton average corners: {0}", brightonAverageCorners); //Console.WriteLine("Brighton average goals: {0}", brightonAverageGoals); //Console.WriteLine("Newcastle:"); //foreach (var match in newcastleMatches.OrderBy(x=>x.Date)) //{ // if (match.AwayTeam == "Newcastle") // { // Console.WriteLine(match.FullTimeAwayTeamGoals); // } // else // { // Console.WriteLine(match.FullTimeHomeTeamGoals); // } //} //Console.WriteLine("Brighton:"); //foreach (var match in brightonMatches.OrderBy(x => x.Date)) //{ // if (match.AwayTeam == "Brighton") // { // Console.WriteLine(match.FullTimeAwayTeamGoals); // } // else // { // Console.WriteLine(match.FullTimeHomeTeamGoals); // } //} } } <file_sep>using Models; using Repos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootbalStats { public class Advisor { public Advisor() { } public List<MatchResult> WeakTeamToScoreByLeagueToday(string leagueName, int days) { LeagueRepository leagueRepo = new LeagueRepository(); League league = new League(); league = leagueRepo.FindByName(leagueName); DateTime today = DateTime.Today; var finishedMatches = league.Matches.Where(m => m.Date >= today && m.Date <= today.AddDays(days) ).OrderBy(m => m.Date); var predictedBothToScore = finishedMatches.Where(m => m.ExactScore1 != 0 && m.ExactScore2 != 0); List<MatchResult> weakTeamScored = predictedBothToScore.Where(m => m.ExactScore1 < m.ExactScore2).ToList(); weakTeamScored.AddRange(predictedBothToScore.Where(m => m.ExactScore2 < m.ExactScore1).ToList()); return weakTeamScored; } } }
a31bffe32cb09f18735eb8e253467fcb65e70bac
[ "C#" ]
21
C#
V45370/FootballStats
f221b45d3e4295c18110cdf941407a4007b71d98
2e90a4e0a97ce5bc5ee7512a2d3eccde06da4c10
refs/heads/master
<repo_name>xplenty/s3cp<file_sep>/lib/s3cp/s3mod.rb # Copyright (C) 2010-2012 <NAME> and Bizo Inc. / All rights reserved. # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. The ASF licenses this # file to you 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. require 's3cp/utils' op = OptionParser.new do |opts| opts.banner = "s3mod [path] [permission]" opts.separator "" opts.separator "where [permission] is one of:" opts.separator "" opts.separator " * private" opts.separator " * authenticated-read" opts.separator " * public-read" opts.separator " * public-read-write" opts.separator "" opts.on_tail("-h", "--help", "Show this message") do puts op exit end end op.parse!(ARGV) if ARGV.size < 2 puts op exit end def update_permissions(s3, bucket, key, permission) puts "Setting #{permission} on s3://#{bucket}/#{key}" s3.buckets[bucket].objects[key].acl = permission end source = ARGV[0] permission = S3CP.validate_acl(ARGV.last) S3CP.load_config() @s3 = S3CP.connect() bucket,key = S3CP.bucket_and_key(source) update_permissions(@s3, bucket, key, permission)
cdd9b54f89526d238a89ecb3240057a40d9f7193
[ "Ruby" ]
1
Ruby
xplenty/s3cp
9af30527e504e14b8ff802cbddc3c44902ba0890
4b6963ab13653c7abd99660a14a7896ccd496da6
refs/heads/master
<file_sep>//import react into the bundle import React from "react"; import ReactDOM from "react-dom"; //include bootstrap npm library into the bundle import "bootstrap"; //include your index.scss file into the bundle import "../styles/index.scss"; //import your own components import { Home } from "./component/home.js"; class TrafficLight extends React.Component { constructor() { super(); this.process = this.process.bind(this); this.state = { selectedcolorred: "light red", selectedcoloryellow: "light yellow", selectedcolorgreen: "light green" }; } process(e) { var val = e.target.getAttribute("value"); if (val == "redcolor") { this.setState(() => { return { selectedcolorred: "light red selected", selectedcoloryellow: "light yellow", selectedcolorgreen: "light green" }; }); } else if (val == "yellowcolor") { this.setState(() => { return { selectedcolorred: "light red", selectedcoloryellow: "light yellow selected", selectedcolorgreen: "light green" }; }); } else { this.setState(() => { return { selectedcolorred: "light red", selectedcoloryellow: "light yellow", selectedcolorgreen: "light green selected" }; }); } } render() { return ( <div> <div id="trafficTop" /> <div id="container"> <div className={this.state.selectedcolorred} value="redcolor" onClick={this.process} /> <div className={this.state.selectedcoloryellow} value="yellowcolor" onClick={this.process} /> <div className={this.state.selectedcolorgreen} value="greencolor" onClick={this.process} /> </div> </div> ); } } ReactDOM.render(<TrafficLight />, document.querySelector("#app"));
4850b5de49667fdd4df8cbec1089870f9f3a56ba
[ "JavaScript" ]
1
JavaScript
bharathichinnusamy/TrafficLightwithReact
198e61f222893c1006474475cc51a798ed0f0729
aafdd4a814f3dd6d2defe4b3f28c27fc19491ecd
refs/heads/master
<file_sep>var React = require('react'); var ReactDOM = require('react-dom'); var $ = require('jquery'); var SearchBar = React.createClass({ render: function () { return ( <div> <form> <img id='searchicon' src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/actions/search.png" alt='search'/> <input id='searchbar' type='text' placeholder='搜尋聊天室' /> </form> </div> ); } }); var Chat = React.createClass({ render: function() { console.log("Rendering Chat with props:", this.props.message); return ( <div id='chatbox'> <p id='chat'> {this.props.message.message} </p> </div> ); } }); var Messages = React.createClass({ render: function () { var Chats = this.props.messages.map(function(message) { return <Chat key={message._id} message={message}/> }, this); return ( <div id='messages'> {Chats} <form name="sendMessage"> <input id='inputMessage' name='message' type='text' placeholder='請輸入訊息。' onKeyDown={this.submit} /> </form> </div> ); }, submit: function(event){ //event.preventDefault(); var form = document.forms.sendMessage; var name = this.props.name; var msg = form.message.value; if(msg){ if(event.keyCode == 13){ this.addMessage({name: name, message: msg}); } //this.props.loadData({name: name}); //form.message.value = ""; } }, addMessage: function(newMessage){ $.ajax({ type: 'POST', url: '/api/messages', contentType: 'application/json', data: JSON.stringify(newMessage), success: function(data) { //var msg = data; // We're advised not to modify the state, it's immutable. So, make a copy. //var clientsModified = this.state.clients.concat(client); }.bind(this), error: function(xhr, status, err) { console.log("Error sending message:", err); } }); } }); var Talk = React.createClass({ getDefaultProps: function() { return { isSelected: false }; }, render: function() { var thistalkStyle = { position: 'relative', height: 100, background: 'white' }; if (this.props.isSelected) { thistalkStyle['background'] = '#DCDCDC'; } return( <div onClick={this.props.onClick} style={thistalkStyle}> <img id='friendProfile' src='newJay.png' alt='friendProfile' /> <p id="friendName"> {this.props.name} </p> </div> ); } }); var Talks = React.createClass({ getInitialState: function() { return { selectedTalk: null }; }, clickHandler: function(talk,idx) { this.setState({selectedTalk: idx}); this.props.loadData({'name':talk.name}); }, render: function () { var talks = this.props.data.map(function (talk, idx) { var is_selected = this.state.selectedTalk == idx; return <Talk key={idx} name={talk.name} onClick={this.clickHandler.bind(this, talk, idx)} isSelected={is_selected}/>; }.bind(this)); return ( <div id='talks'> <div id='talksContainer'> {talks} <img id='lineTool' src='lineTool.png' alt='lineTool'/> </div> </div> ); } }); var DialogueBox = React.createClass({ render: function () { return ( <div className="dialoguebox"> <Talks data={this.props.data} loadData={this.props.loadData} /> <Messages messages={this.props.messages} loadData={this.props.loadData} name={this.props.name} /> <SearchBar/> </div> ); }, }); var ClearFix = React.createClass({ render: function () { return ( <div className='clearfix'></div> ); } }); var Header = React.createClass({ render: function () { return ( <header> <div className='logo'> <h2>LINE@</h2> </div> <img id='photo' src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/PEO-octocat-0.svg/300px-PEO-octocat-0.svg.png" alt='photo' /> <div id='username'> <h3>Taylor</h3> </div> </header> ); } }); var Line = React.createClass({ getInitialState: function() { return { data: {friends:[]}, inifilter: {name:[]}, messages: [] }; }, getFriends: function() { var data = { friends : [ {name: 'Jack'}, {name: 'Rose'} ] }; this.setState({data: data}); }, componentWillMount: function(){ this.getFriends(); //this.loadData({}); }, render: function () { return ( <div> <Header /> <ClearFix /> <DialogueBox data={this.state.data.friends} messages={this.state.messages} name={this.state.inifilter.name} loadData={this.loadData}/> </div> ); }, loadData: function(filter) { $.ajax('/api/messages', {data: filter}).done(function(data) { this.setState({messages: data, inifilter: filter}); }.bind(this)); } }); ReactDOM.render( <Line/>,document.getElementById('app') ); <file_sep>var express = require('express') var bodyParser = require('body-parser'); var MongoClient = require('mongodb').MongoClient; var app = express(); var db; app.use(express.static('static')); app.get('/api/messages', function(req, res) { console.log("Query string:", req.query); var filter = {}; if (req.query.name) filter.name = req.query.name; db.collection("messages").find(filter).toArray(function(err, docs) { res.json(docs); }); }); app.use(bodyParser.json()); app.post('/api/messages', function(req, res) { console.log("Req body:", req.body); var newMessage = req.body; db.collection("messages").insertOne(newMessage, function(err, result) { var newId = result.insertedId; db.collection("messages").find({_id: newId}).next(function(err, doc) { res.json(doc); }); }); }); MongoClient.connect('mongodb://localhost/messagesdb', function(err, dbConnection) { db = dbConnection; var server = app.listen(3000, function() { var port = server.address().port; console.log("Started server at port", port); }); });
2d9bbf43cca63cd042c2fedc2ff2cd0133437f3a
[ "JavaScript" ]
2
JavaScript
Tayjiun/lineUI
9d3cdaf913439fb3d1ada7760cee165a7cfc25b9
9fb2940df79c8472ad1c108e44b6de85a63bd231
refs/heads/master
<file_sep>package bi.model; /** * Created by Patrick on 30.11.16. */ import java.util.ArrayList; import java.util.List; public class DataSet { private List<Attribute> attributes = new ArrayList<Attribute>(); private int length; public List<Attribute> getAttributes() { return this.attributes; } public void addAttribute(int pos, String name) { this.attributes.add(new Attribute(pos, name)); } public void addAttribute(Attribute attribute) { this.attributes.add(attribute); } public void setLength(int length) { this.length = length; } public int getLength() { return this.length; } public void setAttributeAsCl(int pos) { this.attributes.get(pos).setAsCl(); } } <file_sep>package bi; /** * Created by Patrick on 30.11.16. */ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import bi.model.Attribute; import bi.model.DataSet; public class DataSetWriter { private static final String SEPERATION_CHAR = ","; private String filename; private BufferedWriter writer; private DataSet dataset; public DataSetWriter(String filename, DataSet dataset) { this.filename = filename; this.dataset = dataset; } public void write() { try { writer = new BufferedWriter(new FileWriter(filename)); writeLine(true, 0); for (int i = 0; i < dataset.getLength(); i++) { writeLine(false, i); } } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Error writing file - " + e.getMessage()); } } public void writeLine(boolean header, int line){ StringBuilder builder = new StringBuilder(); boolean first = true; for (Attribute attribute : dataset.getAttributes()) { if (first) { first = false; } else { builder.append(SEPERATION_CHAR); } if(header){ builder.append(attribute.getName()); } else { //line builder.append(attribute.getValue(line)); } } try { writer.write(builder.toString()); writer.newLine(); writer.flush(); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Error writing file - " + e.getMessage()); } } }
a3eb448b6fb3c14c67a9b54cbb7fe76bd204b2c4
[ "Java" ]
2
Java
patrick089/BIWS16_Group1_Generate
b21999f4121b4b42a356485301fa7d33a9b878ec
1612f648b1893d7f6c5524565e147f340226918e
refs/heads/master
<repo_name>davidjwatts/sf_trucks<file_sep>/app/assets/javascripts/services/reviews-service.js foodTruckMap.factory("reviewService", ['Restangular', '$window', '_', '$http', '$q', function(Restangular, $window, _, $http, $q){ var _reviews = {}; var _allReviews = function(){ return Restangular.all("reviews").getList().then(function(data){ return data; }); }; var _groupReviews = function(reviews){ return _.groupBy(reviews, function(review){ return review.truck_name; }); }; _avgRating = function(name){ var sum = 0; var truck = _reviews[name]; var num_reviews = truck.length for(j = 0; j < num_reviews; j++){ sum += truck[j].rating; }; return sum/num_reviews; }; // public // var obj = {}; obj.getReviews = function(){ return $q(function(resolve, reject){ _allReviews().then(function(reviews){ _reviews = _groupReviews(reviews); resolve(_reviews); }); }); }; obj.addReviews = function(markers){ _.forEach(markers, function(marker){ _.forEach(marker.trucks, function(truck){ truck.reviews = _reviews[truck.name] if (!!truck.reviews){ truck.num_reviews = Object.keys(truck.reviews).length truck.avg_rating = _avgRating(truck.name) }; }); }); }; return obj; }]); <file_sep>/app/assets/javascripts/filters/distance-filter.js foodTruckMap.filter("distanceFilter", [function(){ return function(markers,coords, reverse){ return _.sortBy(markers, [function(marker){ var p1 = new google.maps.LatLng(marker.latitude, marker.longitude); var p2 = new google.maps.LatLng(coords.latitude, coords.longitude); return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2)); }]); }; }]); <file_sep>/config/routes.rb Rails.application.routes.draw do root 'angular#index' scope :api do scope :v1 do resources :reviews end end end <file_sep>/app/assets/javascripts/services/truck-service.js foodTruckMap.factory("markerService", ['_', '$http', '$q', function(_, $http, $q){ // ---------------------------------------- // Private // ---------------------------------------- var _markers = []; var _getPermits = function(){ return $http.get('https://data.sfgov.org/resource/6a9r-agq8.json') }; var _processPermits = function(data){ data = _.filter(data, function(o){return (o.latitude != 0 && o.status == "APPROVED" && "dayshours" in o)}); var markers = []; var groups = _groupByLocation(data); _addMarkers(groups, markers); return markers; }; // helper methods for _processPermits // var _groupByLocation = function(data){ return _.groupBy(data, function(truck){ var string = ""; string += truck.latitude.toString(); string += ","; string += truck.longitude.toString(); return string; }); }; var _addMarkers = function(groups, markers){ _.forEach(groups, function(location){ var marker = _createMarker(location); _addTrucks(marker, location); _consolidateTrucks(marker.trucks); markers.push(marker); }); }; var _createMarker = function(location){ var marker = {}; marker.id = location[0].objectid; marker.latitude = location[0].latitude; marker.longitude = location[0].longitude; marker.trucks = []; return marker; }; var _addTrucks = function(marker, location){ for (var i = 0; i < location.length; i++){ var truck = {}; truck.name = location[i].applicant; truck.food = location[i].fooditems; truck.hours = location[i].dayshours; marker.trucks.push(truck); }; }; var _consolidateTrucks = function(trucks){ if (trucks.length == 1 || !_duplicateNames(trucks)){ return; }; var temp; for (var i = 0; i < trucks.length - 1; i++){ for (var k = i + 1; k < trucks.length; k++){ if (trucks[i].name == trucks[k].name){ temp = trucks.splice(k, 1); trucks[i].hours += " | " + temp[0].hours; }; }; }; }; var _duplicateNames = function(trucks){ if (_.uniqBy(trucks, 'name').length == trucks.length){ return false; } else { return true; }; }; // ---------------------------------------- // Public // ---------------------------------------- var obj = {}; obj.getMarkers = function(){ return $q(function(resolve, reject){ _getPermits().then(function(response){ _markers = _processPermits(response.data); resolve(_markers); }); }); }; return obj; }]); <file_sep>/app/assets/javascripts/controllers/map-ctrl.js var SFCOORDS = { latitude: 37.753972, longitude: -122.431297 }; var dice; var rs; var scope; foodTruckMap.controller("mapCtrl", ["markerService", "reviewService", "uiGmapGoogleMapApi", "$scope", "_", "$window", "Restangular", function(markerService, reviewService, uiGmapGoogleMapApi, $scope, _, $window, Restangular){ $scope.formData = {}; // These are attributes for the google.maps object and while this looks quite // big, this seemed to be best practices in the examples I looked at. $scope.map = { center: angular.copy(SFCOORDS), zoom: 12, pan: true, markers: [], options: {icon: "https://maps.google.com/mapfiles/kml/paddle/ylw-circle-lv.png"}, clusterOptions: {minimumClusterSize: 5}, searchMarker: { coords: {}, id: -1, options: {}, selected: false }, markersEvents: { click: function(marker, eventName, model, arguments) { $scope.map.window.model = model; $scope.map.window.model.setFocus = $scope.setFocus $scope.map.window.show = true; } }, window: { show: false, closeClick: function(){ this.show = false; }, options: { pixelOffset: {width: 0, height: -10 } }, templateUrl: 'templates/window.html' }, searchbox: { template: 'searchbox.tpl.html', events: { places_changed: function(searchBox){ var location = searchBox.getPlaces()[0].geometry.location; var coords = { latitude: location.lat(), longitude: location.lng() }; $scope.map.searchMarker.coords = coords; $scope.map.searchMarker.selected = true; $scope.map.zoom = 14; $scope.map.refresh(coords); } } } }; $scope.review_form = false; $scope.reviewForm = function(){ $scope.review_form = true; } dice = $scope; $scope.setFocus = function(truck){ $window.console.log(truck); $window.console.log("setFocus firing"); $scope.focus_truck = truck; } // Brings in the processed data from the markers service markerService.getMarkers().then(function(markers){ $scope.map.markers = markers; $scope.attachReviews(); }); // Returns a boolean for whether the location search is active or not $scope.hasSearched = function(){ return $scope.map.searchMarker.selected; }; // Resets the location search to the center of SF and zooms out $scope.removeSearchMarker = function(){ $scope.map.window.show = false; delete $scope.map.searchMarker.coords $scope.map.zoom = 12; $scope.map.refresh(SFCOORDS); $scope.map.searchMarker.selected = false; }; // retrieves reviews and adds info to markers $scope.attachReviews = function(){ reviewService.getReviews().then(function(data){ reviewService.addReviews($scope.map.markers); }); }; }]); <file_sep>/app/controllers/reviews_controller.rb class ReviewsController < ApplicationController def index @reviews = Review.all respond_to do |format| format.json { render json: @reviews.to_json } end end def create @review = Review.new(review_params) respond_to do |format| if @review.save format.json { render json: @review } else format.json { render status: :unprocessable_entity } end end end def update @review = Review.find(params[:id]) respond_to do |format| if @review.update(review_params) format.json { render json: @review } else format.json { render status: :unprocessable_entity } end end end def review_params params.require(:review).permit(:truck_name, :body, :rating, :user_id) end end <file_sep>/public/templates/search-results.html <div class='list-group-item'> <div ng-repeat='truck in marker.trucks | filter:formData.query'> <h4><a href="#map" ng-click="map.markersEvents.click(marker, 'click', marker)">-{{truck.name}} | {{truck.avg_rating}}/5 ({{truck.num_reviews}} reviews)</a></h4> <p><a href='#reviews' ng-click="setFocus(truck)">Reviews</a></p> <p><strong>Food:</strong> {{truck.food}}</p> <p><strong>Hours:</strong> {{truck.hours}}</p> </div> </div> <file_sep>/README.md # Food Truck City ## Introduction This web application is intended to fulfill the requirements of the ClearVoice coding challenge as part of an application for hire. ## Deployment The app has been deployed on Heroku and can be used here: [Food Truck City](https://food-truck-city.herokuapp.com/) Please excuse a possible delay on first loading as the app may need to be loaded in the servers, since this is a free account, and they put the app to sleep after not being pinged for a certain number of hours. ## Basic Usage Upon the page loading, the map contains yellow icons for every food truck location registered in San Francisco. You can zoom and drag the map and select individual icons, which brings up a window displaying information for each food truck registered there. The search bar above the map can be used to query Google Places for a general location or address. The map will then drop a pin and center at the location specific, and zoom in. The list of food trucks on the right will represent the 10 closest permit locations, which also can be clicked on to open the information window. You can deselect your chosen location by clicking on the link above the list. Regardless of specifying a location, you can search for trucks via keyword match anywhere in their description by entering a query in the search box to the right of the map. A query will remain an active filter if a location search is conducted or deselected. So searching by location and query work separately or in conjunction, and in either order. ## Dependencies * Ruby * Bundler * Rails * PostgreSQL JS: * AngularJS * Lodash * angular-google-maps * angular-simple-logger CSS: * Bootstrap ## Description of Problem and Solution The prompt: "Create a service that tells the user what types of food trucks might be found near a specific location on a map. Use the data available on [DataSF:Food Trucks](https://data.sfgov.org/Economy-and-Community/Mobile-Food-Facility-Permit/rqzj-sfat)." The Approach I decided to use Google Maps (GMaps) API along with an Angular front-end served by a simple Rails back-end. The nature of the data suggested that I should use the GPS coordinates with each permit to create markers on the map, and that the data should be refreshed upon page load to provide up to date information. This combination, without any features requiring data persistence, precluded the need to make RESTful API calls back to the server after the home page is loaded. Despite being more capable in Rails than I am in Angular, and the desire for the app to use the full-stack to display my skills, I felt the problem simply didn't call for it. The result is a light and nimble app that only makes one API call on page load, and only consists of one page/view in angular. Based on the prompt, I thought the most essential feature was a map with labeled truck locations and the ability to search for a place or address and have that appear centered on the map. Secondarily, I wanted a list of the trucks that was searchable, clickable, and filtered by distance from the selected location (if applicable). Technical Solutions * Processing the Data The data is processed in a service that can return an array of objects, which can then be used as the reference for the GMaps markers directive and the window directive. In processing the JSON file retrieved from DataSF, several issues came up. One issue is that about 5% of the permits didn't offer coordinates and only had a string description of the place. Google's Geolocation api, which returns a location from a description, does not off a free plan for this number of requests. I decided to omit those permits. Another issue is that there are multiple permits per location, which may be from the same vendor or not. I approached this problem as modularly as I could. First I grouped the permits by location, since each location will yield one marker. Then I create a marker using the coordinates for each group. I then add an array to the marker which will contain information for each truck at that location, which also consolidates multiple permits from a single vendor at that location. The array of trucks in each marker contains the name, food description, and days/hours attributes of each separate vendor at that location. This information is used when rendering the window for that location. * Using Google Maps API with Angular The AngularUI group had created a module to streamline GMap API use, and I decided this would be a more efficient way to learn and implement GMap API. It offers various directives which do most of the work. The markers directive creates a marker for each element of a specified array. I used a separate single marker directive for the Google Places search a user can run. This refers to a solitary marker object that is reset when the user uses the "Remove my location" link. I also use a single window directive which would be populated with the information from the most recently clicked marker on the map. Future Features I was certainly pressed for time with this project, and much of the struggle was determining how to pair down the app's features so I could finish it in time. * To incorporate more of a back-end, I wanted to offer persisting user accounts that would feature a list of favorite trucks the user could add and refer to. * It would be nice to refine the location search more, which could be accomplished by limiting the closest trucks list to those within a certain radius, and the user could select the distance. * Along the same line, filtering the trucks list by days/times open, and then having a currently open link to filter by the current time. Also, I would like to add general food genres as a list of clickable search refinements. * Since we're all in AZ, it wouldn't be very fun to have the search location automatically set to the device's location on page load, but this makes a lot of sense for real users in SF. * I wanted to further process the descriptions to make them look nicer, for instance removing the colons in favor commas, and removing business terms from vendor name such as "LLC" and "Corporation". Problems Encountered I'm not very familiar with the deployment process, so I had a handful of issues with the asset pipeline, leading me to use some janky hacks to get the Heroku deployment to work. These issues included: * Using a CDN link to bootstrap in the main view template, instead of using the gem or a hard copy in the vendor assets folder. * Including both a hard copy of AngularJS in the vendor assets folder and using the Angular gem for rails. * Another issue I couldn't figure out in time is the "Mixed Content" warnings the Heroku deployment sends in the console upon page load. I couldn't find the non-SSL links anywhere in the assets being used. <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Review.delete_all Review.create(truck_name: "Roadside Rotisserie Corporation / Country Grill", body: "best ribs ever", rating: 5) Review.create(truck_name: "Roadside Rotisserie Corporation / Country Grill", body: "meh, had better", rating: 2) Review.create(truck_name: "Off the Grid Services, LLC", body: "I really wanted a hot dog, but this was okay", rating: 3) Review.create(truck_name: "M M Catering", body: "solid food truck experience", rating: 4)
5d18f6bbfcaa55e1c82f508809032271e63619ec
[ "JavaScript", "Ruby", "HTML", "Markdown" ]
9
JavaScript
davidjwatts/sf_trucks
f721d598b821a5ab1432f59d52c4219057c98515
e2f91818286bc015594f3a6561b240098c00e7d6
refs/heads/master
<file_sep>#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <stdlib.h> #define COUNTING_NUMBER 2000000 #define ID 0 int critical_section_variable = 0; int turn = 0; int flag[2] = {1,0}; int shmid1, shmid2, shmid3, shmid4; char *shmaddr1, *shmaddr2, *shmaddr3, *shmaddr4; int ret1, ret2, ret3, ret4; void lock(int self, int *flag, int *turn){ flag[self] = 1; *turn = (self+1)%2; printf("A lock turn : %d\n" , *turn); while(flag[*turn] && *turn == (self+1)%2); } void unlock(int self, int*flag) { printf("A : unlocking\n"); flag[self] = 0; } void getSharedMemory(int* shmid, key_t key) { *shmid = shmget((key_t)key, 1024, IPC_CREAT|0666); printf("A gSM shmid : %d\n", *shmid); if(*shmid == -1) { perror("A : shared memory access is failed.\n"); } } void attach(char* shmaddr, int* shmid) { shmaddr = shmat(*shmid, NULL , IPC_CREAT|0666); printf("A attach : %p\n)", shmaddr); if(shmaddr == "-1") { perror("A : attach failed\n"); } } void detach(char* shmaddr, int* ret) { *ret = shmdt(shmaddr); printf("A detach : %s\n", shmaddr); if( *ret == -1) { perror("A : detach failed\n"); } } /* void *func(int id) { int i; for( i = 0 ; i <COUNTING_NUMBER; i++) { lock(ID, flag, &turn); critical_section_variable++; printf("A : %d\n", critical_section_variable); unlock(ID , flag); } } */ int main(void) { int local_count = 0; int i; char *temp; for( i = 0 ; i < COUNTING_NUMBER; i++) { printf("A : %dth loop\n", i); // lock(ID, flag, &turn); shmid1 = shmget((key_t)1224, 1024, IPC_CREAT|0666); shmid2 = shmget((key_t)1246, 1024, IPC_CREAT|0666); shmid3 = shmget((key_t)1288, 1024, IPC_CREAT|0666); shmid4 = shmget((key_t)1296, 1024, IPC_CREAT|0666); // getSharedMemory(&shmid1, 1224); // getSharedMemory(&shmid2, 1246); // getSharedMemory(&shmid3, 1288); // getSharedMemory(&shmid4, 1296); printf("1\n"); shmaddr1 = shmat(shmid1, (void*)0, IPC_CREAT|0666); shmaddr2 = shmat(shmid2, (void*)0, IPC_CREAT|0666); shmaddr3 = shmat(shmid3, (void*)0, IPC_CREAT|0666); shmaddr4 = shmat(shmid4, (void*)0, IPC_CREAT|0666); printf("%s\n%s\n%s\n%s\n", shmaddr1, shmaddr2, shmaddr3, shmaddr4); // attach(shmaddr1, &shmid1); // attach(shmaddr2, &shmid2); // attach(shmaddr3, &shmid3); // attach(shmaddr3, &shmid4); printf("2"); // lock(ID , flag, &turn); flag[0] = atoi(shmaddr1); flag[1] = atoi(shmaddr2); turn = atoi(shmaddr3); critical_section_variable = atoi(shmaddr4); printf("3"); lock(ID, flag, &turn); printf("A : locking\n"); flag[ID] = 1; printf("A : flag[%d] %d \n",ID , flag[ID]); turn = (ID+1)%2; printf("A: locking turn : %d\n", turn); while(flag[turn] && turn == (ID+1)%2); printf("A : locking success"); sprintf(temp, "%d", flag[0]); strcpy(shmaddr1, temp); sprintf(temp , "%d", flag[1]); strcpy(shmaddr2, temp); sprintf(temp, "%d", turn); strcpy(shmaddr3, temp); critical_section_variable++; sprintf(temp, "%d", critical_section_variable); strcpy(shmaddr4, temp); // unlock(ID, flag); sprintf(temp, "%d", flag[0]); strcpy(shmaddr1, temp); local_count++; printf("4"); // strcpy(shmaddr1, (char*)flag[0]); // strcpy(shmaddr2, (char*)flag[1]); // strcpy(shmaddr3, (char*)turn); // strcpy(shmaddr4, (char*)critical_section_variable); printf("5"); ret1 = shmdt(shmaddr1); ret2 = shmdt(shmaddr2); ret3 = shmdt(shmaddr3); ret4 = shmdt(shmaddr4); // detach(shmaddr1, &ret1); // detach(shmaddr2, &ret2); // detach(shmaddr3, &ret3); // detach(shmaddr4, &ret4); //unlock(ID, flag); sleep(1); } return 0; } <file_sep>#include <stdio.h> #include <unistd.h> int main(void) { int i; for( i = 0 ; i < 12; ++i) { FILE* fp = fopen("text.txt", "w"); fprintf(fp, "%d\n" , i); printf("Child1 wrote %d.\n" , i); fclose(fp); sleep(1); } return 0; } <file_sep>#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <stdlib.h> #define COUNTING_NUMBER 2000000 #define ID 1 int critical_section_variable = 0; int turn = 0; int flag[2] = {1,1}; int shmid1, shmid2, shmid3, shmid4; char *shmaddr1, *shmaddr2, *shmaddr3, *shmaddr4; int ret1, ret2, ret3, ret4; void lock(int self, int *flag, int *turn){ printf("B : locking\n"); flag[self] = 1; printf("B : flag[%d] %d \n",self , flag[self]); *turn = (self+1)%2; printf("B: locking turn : %d\n", *turn); while(flag[*turn] && *turn == (self+1)%2); } void unlock(int self, int*flag) { printf("B : unlocking\n"); flag[self] = 0; } void getSharedMemory(int* shmid, key_t key) { *shmid = shmget((key_t)key, 1024, IPC_CREAT|0666); printf("B gSM : shmid %d\n", *shmid); if(*shmid == -1) { perror("B : shared memory access is failed.\n"); } } void attach(char* shmaddr, int* shmid) { shmaddr = shmat(*shmid, NULL , IPC_CREAT|0666); printf("B attach : %p\n", shmaddr); if(shmaddr == "-1") { perror("B : attach failed\n"); } } void detach(char* shmaddr, int* ret) { *ret = shmdt(shmaddr); if( *ret == -1) { perror("B : detach failed\n"); } } /* void *func(int ID) { int i; for( i = 0 ; i <COUNTING_NUMBER; i++) { lock(ID, flag, &turn); critical_section_variable++; printf("B : %d\n", critical_section_variable); unlock(ID , flag); } } */ int main(void) { int local_count = 0; int i; char* temp; for( i = 0 ; i < COUNTING_NUMBER ; i++) { sleep(1); printf("B : %dth loop\n", i); printf("flag[0] : %d \n",flag[0]); printf("flag[1] : %d \n", flag[1]); printf("B : locking success\n"); shmid1 = shmget((key_t)1224, 1024, IPC_CREAT|0666); shmid2 = shmget((key_t)1246, 1024, IPC_CREAT|0666); shmid3 = shmget((key_t)1288, 1024, IPC_CREAT|0666); shmid4 = shmget((key_t)1296, 1024, IPC_CREAT|0666); printf("B : getSharedMemory success\n"); shmaddr1 = shmat(shmid1, (void*)0 , IPC_CREAT|0666); shmaddr2 = shmat(shmid2, (void*)0 , IPC_CREAT|0666); shmaddr3 = shmat(shmid3, (void*)0 , IPC_CREAT|0666); shmaddr4 = shmat(shmid4, (void*)0 , IPC_CREAT|0666); printf("%s\n%s\n%s\n%s\n", shmaddr1, shmaddr2, shmaddr3, shmaddr4); printf("B : attach success\n"); printf("B flag[0] : %d\n", flag[0]); printf("B flag[1] : %d\n", flag[1]); printf("B *shmaddr1 : %p\n", shmaddr1); printf("HELLO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); flag[0] = atoi(shmaddr1); printf("B flag[0] : %d\n", flag[0]); flag[1] = atoi(shmaddr2); printf("B flag[1] : %d\n", flag[1]); turn = atoi(shmaddr3); printf("B turn : %d\n", turn); critical_section_variable = atoi(shmaddr4); printf("B critcal : %d\n", critical_section_variable); // lock(ID, flag, &turn); printf("B : locking\n"); flag[ID] = 1; printf("B : flag[%d] %d \n",ID , flag[ID]); turn = (ID+1)%2; printf("B: locking turn : %d\n", turn); while(flag[turn] && turn == (ID+1)%2); printf("Yop!!!!!!!!!!!!!!!!!!!!!!!!!\n"); sprintf(temp, "%d", flag[0]); strcpy(shmaddr1, temp); sprintf(temp, "%d", flag[1]); strcpy(shmaddr2, temp); sprintf(temp, "%d", turn); strcpy(shmaddr3, temp); printf("HPOOOOOOOOOOOOOOOO\n"); // unlock(ID, flag); flag[ID] = 0; sprintf(temp, "%d", flag[ID]); strcpy(shmaddr2, temp); printf("B : %d\n" , critical_section_variable); local_count++; printf("B : %d\n", local_count); // strcpy(shmaddr1, (char*)flag[0]); // strcpy(shmaddr2, (char*)flag[1]); // strcpy(shmaddr3, &turn); //` strcpy(shmaddr4, &critical_section_variable); ret1 = shmdt(shmaddr1); ret2 = shmdt(shmaddr2); ret3 = shmdt(shmaddr3); ret4 = shmdt(shmaddr4); // detach(shmaddr1, &ret1); // detach(shmaddr2, &ret2); // detach(shmaddr3, &ret3); // detach(shmaddr4, &ret4); //unlock(ID, flag); } return 0; } <file_sep>#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <unistd.h> struct msgbuf { long msgtype; char mtext[80]; }; int main(int argc, char **argv) { key_t key_id; int i = 0; struct msgbuf rsvbuf; int msgtype = 3; printf("Hello, this is B process. give me the data.\n"); while(1) { key_id = msgget((key_t)1234, IPC_CREAT|0666); if( key_id == -1) { perror("msgget error : "); return 0; } if(msgrcv( key_id, (void*)&rsvbuf, sizeof(struct msgbuf), msgtype, 0) == -1) { perror("msgrcv error : "); } else { printf("%s\n", rsvbuf.mtext); } } return 0; } <file_sep>#include "sched.h" void init_mystride_rq (struct mystride_rq *mystride_rq) { printk(KERN_INFO "***[MYSTRD] Mystride class is online \n"); mystride_rq->nr_running = 0; INIT_LIST_HEAD(&mystride_rq->queue); } void init_task_mystride(struct task_struct *p) { struct sched_mystride_entity *se = &p->mystride; p->sched_class = &mystride_sched_class; se->stride = 1000/(se->ticket); se->pass = se->stride; printk(KERN_INFO "***[MYSTRD] init_task_mystrd: ticket=%d,stride=%d,pass=%d,p->pid=%d\n", se->ticket, se->stride, se->pass, p->pid); } static void enqueue_task_mystride(struct rq *rq, struct task_struct *p, int flags) { struct mystride_rq *mystride_rq = &rq->mystride; struct sched_mystride_entity *task = &p->mystride; struct list_head *head = &mystride_rq->queue; struct list_head *pick = &task->run_list; struct sched_mystride_entity *next = container_of(head, struct sched_mystride_entity, run_list); int i = 0; if( mystride_rq->nr_running == 0 ) { list_add(pick, &mystride_rq->queue); mystride_rq->nr_running++; printk(KERN_INFO " ***[MYSTRD] enqueue | nr_running = %d\n", mystride_rq->nr_running); } else { head = head->next; next = container_of(head, struct sched_mystride_entity, run_list); //printk(KERN_INFO, "***[MYSTRD] enqueue for : next ticket 1111t = %d\n", next->ticket); for( i = 0 ; i < mystride_rq->nr_running; i++ ) { printk(KERN_INFO "***[MYSTRD] enqueue for\n"); if(next->pass >= task->pass ) break; head = head->next; next = container_of(head, struct sched_mystride_entity, run_list); //printk(KERN_INFO, "***[MYSTRD] enqueue for : next ticket 2222 = %d\n", next->ticket); } list_add_tail(&task->run_list, head); mystride_rq->nr_running++; printk(KERN_INFO "***[MYSTRD] enqueue: success cpu=%d,nr_running=%d,p->state=%lu,p->pid=%d\n", cpu_of(rq),mystride_rq->nr_running,p->state,p->pid); //pick = next->run_list.next; //next = container_of(pick, struct sched_mystride_entity, run_list); //TODO // make sure the new task is enqueueing in right position //printk(KERN_INFO "***[MYSTRD] enqueue: success cpu=%d,nr_running=%d,pid=%d\n", cpu_of(rq),mystride_rq->nr_running,p->pid); } } static void dequeue_task_mystride(struct rq *rq, struct task_struct *p, int flags) { struct mystride_rq *mystride_rq = &rq->mystride; //struct sched_mysched_entity *task = &p->mysched; //printk(KERN_INFO "***[MYSTRD] dequeue: start\n"); //TODO if(/*1. is queue empty?*/ mystride_rq->nr_running > 0) { printk(KERN_INFO "***[MYSTRD dequeue: start\n"); list_del_init(&p->mystride.run_list); mystride_rq->nr_running--; //2. dequeue the task from mysched_rq //3. decrement nr_running value of mysched_rq by 1 printk(KERN_INFO "\t***[MYSTRD] dequeue: success cpu=%d,nr_running=%d,p->state=%lu,p->pid=%d\n", cpu_of(rq),mystride_rq->nr_running,p->state, p->pid); if(/*4. Are current task and picked task same task?*/ rq->curr == p) { resched_curr(rq); } } else { } printk(KERN_INFO "***[MYSTRD] duqueue: end\n"); } static void update_curr_mystride(struct rq *rq){ struct task_struct *task = NULL; struct sched_mystride_entity *mystride = NULL; struct mystride_rq *mystride_rq = &rq->mystride; struct list_head *pick = mystride_rq->queue.next; struct task_struct *compare_struct = NULL; struct sched_mystride_entity *compare = NULL; struct list_head *compare_pick = NULL; int i = 0; mystride = container_of(pick, struct sched_mystride_entity, run_list); task = container_of(mystride, struct task_struct, mystride); compare_struct = task; //update the curr task's pass pick = mystride->run_list.next; compare = container_of(pick, struct sched_mystride_entity, run_list); compare_struct = container_of(compare, struct task_struct, mystride); compare_pick = compare->run_list.next; compare->pass += compare->stride; //task = container_of(next_se, struct task_struct, mystride); printk(KERN_INFO "***[MYSTRD] update_curr: update_curr starting!\n"); //make mystride_rq sorted by pass for( i = 0; i < mystride_rq->nr_running ; i++) { printk(KERN_INFO "/t/t***[MYSTRD] update_curr: curr->pid=%d,p->pid=%d,pass=%d\n", task->pid, compare_struct->pid, compare->pass); compare_pick = compare_pick->next; compare = container_of(compare_pick, struct sched_mystride_entity, run_list); compare_struct = container_of(compare, struct task_struct, mystride); } dequeue_task_mystride(rq, task, 0); enqueue_task_mystride(rq, task, 0); // if any task has smaller pass than curr task's pass resched_curr(rq) resched_curr(rq); printk(KERN_INFO "***[MYSTRD] update_curr: update_curr end!\n"); //TODO //update the curr task's pass and make mystride_rq sorted by pass // if any task has smaller pass than curr task's pass // resched_curr(rq) } static void check_preempt_curr_mystride(struct rq *rq, struct task_struct *p, int flags) { } struct task_struct *pick_next_task_mystride(struct rq *rq, struct task_struct *prev) { struct task_struct *next_p = NULL; struct sched_mystride_entity *next_se = NULL; struct mystride_rq *mystride_rq = &rq->mystride; struct list_head *pick = mystride_rq->queue.next; //printk(KERN_INFO "***[MYSTRD] pick_next_task: start\n"); //TODO if(/*1. is queue empty?*/ rq->mystride.nr_running == 0){ return NULL; } if(prev->sched_class != &mystride_sched_class) { printk(KERN_INFO "***[MYSTRD] pick_next_task: other class came in.. prev->pid=%d\n", prev->pid); put_prev_task(rq, prev); } printk(KERN_INFO "***[MYSTRD] pick_next_task: start\n"); next_se = container_of(pick, struct sched_mystride_entity, run_list); next_p = container_of(next_se, struct task_struct, mystride); //2. pick one sched_mysched_entity from mysched_rq and assign it to next_se() //3. find parent task_struct of picked sched_mysched_entity and assign it to next_p printk(KERN_INFO "\t***[MYSTRD] pick_next_task: cpu=%d,prev->pid=%d,next_p->pid=%d,nr_running=%d\n",cpu_of(rq),prev->pid,next_p->pid,mystride_rq->nr_running); printk(KERN_INFO "***[MYSTRD] pick_next_task: end\n"); return next_p; } static void put_prev_task_mystride(struct rq *rq, struct task_struct *p) { printk(KERN_INFO "***[MYSTRD] put_prev_task: do nothing, p->pid=%d\n", p->pid); } static int select_task_rq_mystride(struct task_struct *p, int cpu, int sd_flag, int flags) { return task_cpu(p); } static void set_curr_task_mystride(struct rq *rq) { } static void task_tick_mystride(struct rq *rq, struct task_struct *p, int queued) { printk(KERN_INFO"***[MYSTRD] task_tick\n"); update_curr_mystride(rq); } static void prio_changed_mystride(struct rq *rq, struct task_struct *p, int oldprio) { } /*This routine is called when a task migrates between classes*/ static void switched_to_mystride(struct rq *rq, struct task_struct *p) { resched_curr(rq); } const struct sched_class mystride_sched_class={ .next=&fair_sched_class, .enqueue_task=enqueue_task_mystride, .dequeue_task=dequeue_task_mystride, .check_preempt_curr=check_preempt_curr_mystride, .pick_next_task=pick_next_task_mystride, .put_prev_task=put_prev_task_mystride, #ifdef CONFIG_SMP .select_task_rq=select_task_rq_mystride, #endif .set_curr_task=set_curr_task_mystride, .task_tick=task_tick_mystride, .prio_changed=prio_changed_mystride, .switched_to=switched_to_mystride, .update_curr=update_curr_mystride, //rear %= 100; }; <file_sep>#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <stdlib.h> #define COUNTING_NUMBER 200000 #define ID 0 int *critical_section_variable; int *turn; int *flag; int shmid1, shmid2, shmid3; int *shmaddr1, *shmaddr2, *shmaddr3; int ret1, ret2, ret3; int main(void) { int local_count = 0; int i; shmid1 = shmget((key_t)1224, sizeof(int) * 2, IPC_CREAT|0666); shmid2 = shmget((key_t)1246, sizeof(int) * 1, IPC_CREAT|0666); shmid3 = shmget((key_t)1288, sizeof(int) * 1, IPC_CREAT|0666); shmaddr1 = (int*)shmat(shmid1, NULL, 0); shmaddr2 = (int*)shmat(shmid2, NULL, 0); shmaddr3 = (int*)shmat(shmid3, NULL, 0); flag = shmaddr1; turn = shmaddr2; critical_section_variable = shmaddr3; for(i=0; i<COUNTING_NUMBER; ++i){ flag[ID] = 1; *turn = (ID+1)%2; while(flag[*turn] && *turn == (ID+1)%2); shmaddr1 = flag; shmaddr2 = turn; (*critical_section_variable)++; local_count++; shmaddr2 = critical_section_variable; flag[ID] = 0; shmaddr1 = flag; } printf("thread num : %d ,local count %d\n", ID, local_count); printf("child finish!\n"); ret1 = shmdt(shmaddr1); ret2 = shmdt(shmaddr2); ret3 = shmdt(shmaddr3); sleep(1); return 0; } <file_sep>#include "sched.h" void init_mysched_rq (struct mysched_rq *mysched_rq) { printk(KERN_INFO "***[MYSCHED] Mysched class is online \n"); mysched_rq->nr_running = 0; INIT_LIST_HEAD(&mysched_rq->queue); } static void update_curr_mysched(struct rq *rq){} static void enqueue_task_mysched(struct rq *rq, struct task_struct *p, int flags) { struct mysched_rq *mysched_rq = &rq->mysched; struct sched_mysched_entity *task = &p->mysched; list_add_tail(&task->run_list, &mysched_rq->queue); mysched_rq->nr_running++; //TODO //1. enqueue the task in mysched_rq //2. increment nr_running value of mysched_rq by 1 printk(KERN_INFO "***[MYSCHED] enqueue: success cpu=%d,nr_running=%d,pid=%d\n", cpu_of(rq),mysched_rq->nr_running,p->pid); } static void dequeue_task_mysched(struct rq *rq, struct task_struct *p, int flags) { struct mysched_rq *mysched_rq = &rq->mysched; //struct sched_mysched_entity *task = &p->mysched; //TODO if(/*1. is queue empty?*/ mysched_rq->nr_running > 0) { list_del_init(&p->mysched.run_list); mysched_rq->nr_running--; //2. dequeue the task from mysched_rq //3. decrement nr_running value of mysched_rq by 1 printk(KERN_INFO "\t***[MYSCHED] dequeue: success cpu=%d,nr_running=%d,pid=%d\n", cpu_of(rq),mysched_rq->nr_running, p->pid); if(/*4. Are current task and picked task same task?*/ rq->curr == p) { resched_curr(rq); } } else { } } static void check_preempt_curr_mysched(struct rq *rq, struct task_struct *p, int flags) { } struct task_struct *pick_next_task_mysched(struct rq *rq, struct task_struct *prev) { struct task_struct *next_p = NULL; struct sched_mysched_entity *next_se = NULL; struct mysched_rq *mysched_rq = &rq->mysched; struct list_head *pick = mysched_rq->queue.next; //TODO if(/*1. is queue empty?*/ rq->mysched.nr_running == 0){ return NULL; } next_se = container_of(pick, struct sched_mysched_entity, run_list); next_p = container_of(next_se, struct task_struct, mysched); //2. pick one sched_mysched_entity from mysched_rq and assign it to next_se() //3. find parent task_struct of picked sched_mysched_entity and assign it to next_p printk(KERN_INFO "\t***[MYSCHED] pick_next_task: cpu=%d,prev->pid=%d,next_p->pid=%d,nr_running=%d\n",cpu_of(rq),prev->pid,next_p->pid,mysched_rq->nr_running); return next_p; } static void put_prev_task_mysched(struct rq *rq, struct task_struct *p) { } static int select_task_rq_mysched(struct task_struct *p, int cpu, int sd_flag, int flags) { return task_cpu(p); } static void set_curr_task_mysched(struct rq *rq) { } static void task_tick_mysched(struct rq *rq, struct task_struct *p, int queued) { } static void prio_changed_mysched(struct rq *rq, struct task_struct *p, int oldprio) { } /*This routine is called when a task migrates between classes*/ static void switched_to_mysched(struct rq *rq, struct task_struct *p) { resched_curr(rq); } const struct sched_class mysched_sched_class={ .next=&fair_sched_class, .enqueue_task=enqueue_task_mysched, .dequeue_task=dequeue_task_mysched, .check_preempt_curr=check_preempt_curr_mysched, .pick_next_task=pick_next_task_mysched, .put_prev_task=put_prev_task_mysched, #ifdef CONFIG_SMP .select_task_rq=select_task_rq_mysched, #endif .set_curr_task=set_curr_task_mysched, .task_tick=task_tick_mysched, .prio_changed=prio_changed_mysched, .switched_to=switched_to_mysched, .update_curr=update_curr_mysched, //rear %= 100; }; <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define ARGUMENT_NUMBER 20 //long long result = 0; long long reee[ARGUMENT_NUMBER]; void *ThreadFunc(void*n) { long long result = 0; long long i; long long number = *((long long *)n); printf("number = %lld\n", number); for ( i = 0 ; i < 25000000; i++) { //result에 number 더해서 저장. result += number; } // 결과갑 배열에 저장 reee[number] = result; } int main(void) { pthread_t threadID[ARGUMENT_NUMBER]; long long argument[ARGUMENT_NUMBER]; long long i; long long aaa = 0; //int status; for(i = 0 ; i < ARGUMENT_NUMBER; i++) { //thread 생성 argument[i] = i; pthread_create(&threadID[i], NULL, ThreadFunc, (void*)&argument[i]); } printf("Main Thread is waiting for Child Thread!\n"); for(i = 0 ; i < ARGUMENT_NUMBER; i++) { //thread 종료를 기다린다. pthread_join(threadID[i], NULL); } for ( i = 0; i <ARGUMENT_NUMBER; i++) { //각 쓰레드의 결과값들을 합친다. aaa += reee[i]; } //합친 값 출력 printf("result = %lld\n", aaa); return 0; } <file_sep>#include <stdio.h> #include <unistd.h> int main(void) { char gets[100], *string; int i; for(i=0; i<7; i++) { FILE* fp = fopen("text.txt", "r"); if((string = fgets(gets, 10, fp))!=NULL){ printf("%s", string); } fclose(fp); sleep(2); } return 0; } <file_sep>#include "sched.h" void init_myrr_rq(struct myrr_rq *myrr_rq) { printk(KERN_INFO "***[MYRR] Mysched class is online \n"); myrr_rq->nr_running = 0; INIT_LIST_HEAD(&myrr_rq->queue); } /*static void resched(struct rq *rq) { struct myrr_rq *myrr_rq = &rq->myrr; struct task_struct *curr = &rq->curr; struct sched_myrr_entity *myrr_ = &curr->myrr; }*/ static void enqueue_task_myrr(struct rq *rq, struct task_struct *p, int flags) { struct myrr_rq *myrr_rq = &rq->myrr; struct sched_myrr_entity *task = &p->myrr; list_add_tail(&task->run_list, &myrr_rq->queue); myrr_rq->nr_running++; //TODO //1. enqueue the task in mysched_rq //2. increment nr_running value of mysched_rq by 1 printk(KERN_INFO "***[MYRR] enqueue: success cpu=%d,nr_running=%d,pid=%d\n", cpu_of(rq),myrr_rq->nr_running,p->pid); } static void dequeue_task_myrr(struct rq *rq, struct task_struct *p, int flags) { struct myrr_rq *myrr_rq = &rq->myrr; //struct sched_mysched_entity *task = &p->mysched; //TODO if(/*1. is queue empty?*/ myrr_rq->nr_running > 0) { list_del_init(&p->myrr.run_list); myrr_rq->nr_running--; //2. dequeue the task from mysched_rq //3. decrement nr_running value of mysched_rq by 1 printk(KERN_INFO "\t***[MYRR] dequeue: success cpu=%d,nr_running=%d,pid=%d\n", cpu_of(rq),myrr_rq->nr_running, p->pid); if(/*4. Are current task and picked task same task?*/ rq->curr == p) { resched_curr(rq); } } else { } } static void check_preempt_curr_myrr(struct rq *rq, struct task_struct *p, int flags) { } struct task_struct *pick_next_task_myrr(struct rq *rq, struct task_struct *prev) { struct task_struct *next_p = NULL; struct sched_myrr_entity *next_se = NULL; struct myrr_rq *myrr_rq = &rq->myrr; struct list_head *pick = myrr_rq->queue.next; //TODO if(/*1. is queue empty?*/ rq->myrr.nr_running == 0){ return NULL; } next_se = container_of(pick, struct sched_myrr_entity, run_list); next_p = container_of(next_se, struct task_struct, myrr); //2. pick one sched_mysched_entity from mysched_rq and assign it to next_se() //3. find parent task_struct of picked sched_mysched_entity and assign it to next_p printk(KERN_INFO "\t***[MYRR] pick_next_task: cpu=%d,prev->pid=%d,next_p->pid=%d,nr_running=%d\n",cpu_of(rq),prev->pid,next_p->pid,myrr_rq->nr_running); return next_p; } static void update_curr_myrr(struct rq *rq){ //TODO struct task_struct *next_p = NULL; struct sched_myrr_entity *myrr_en = NULL; struct myrr_rq *myrr_rq = &rq->myrr; struct list_head *task = myrr_rq->queue.next; myrr_en = container_of(task, struct sched_myrr_entity, run_list); next_p = container_of(myrr_en, struct task_struct, myrr); //struct myrr_rq *myrr_rq = &rq->myrr; //struct task_struct *task = &myrr_rq->queue.next; //struct sched_myrr_entity *myrr_en = &task->myrr; //int shced_rr_timeslice = RR_TIMESLICE; myrr_en->update_num++; printk(KERN_INFO "\t***[MYRR] update_curr_myrr pid=%d update_num=%d\n", next_p->pid, myrr_en->update_num) if( myrr_en->update_num > 3) { myrr_en->update_num = 0; dequeue_task_myrr(rq, next_p, 0); enqueue_task_myrr(rq, next_p, 0); resched_curr(rq); //resched(rq); } //1. update update_num //2. if update_num > time slice // do something; // resched(rq); } static void task_tick_myrr(struct rq *rq, struct task_struct *p, int queued){ //TODO //1. call update_curr_myrr method update_curr_myrr(rq); } static void put_prev_task_myrr(struct rq *rq, struct task_struct *p) { printk(KERN_INFO"\tput_prev_task: do nothing, p->pid=%d\n", p->pid); } static int select_task_rq_myrr(struct task_struct *p, int cpu, int sd_flag, int flags) { return task_cpu(p); } static void set_curr_task_myrr(struct rq *rq) { } //static void task_tick_mysched(struct rq *rq, struct task_struct *p, int queued) { } static void prio_changed_myrr(struct rq *rq, struct task_struct *p, int oldprio) { } /*This routine is called when a task migrates between classes*/ static void switched_to_myrr(struct rq *rq, struct task_struct *p) { resched_curr(rq); } const struct sched_class myrr_sched_class={ .next=&fair_sched_class, .enqueue_task=enqueue_task_myrr, .dequeue_task=dequeue_task_myrr, .check_preempt_curr=check_preempt_curr_myrr, .pick_next_task=pick_next_task_myrr, .put_prev_task=put_prev_task_myrr, #ifdef CONFIG_SMP .select_task_rq=select_task_rq_myrr, #endif .set_curr_task=set_curr_task_myrr, .task_tick=task_tick_myrr, .prio_changed=prio_changed_myrr, .switched_to=switched_to_myrr, .update_curr=update_curr_myrr, //rear %= 100; }; <file_sep>#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> int main(void) { int shmid; void *shmaddr; int ret; printf("Hello, this is B process. give me the data.\n"); while(1) { sleep(1); //get shared memory id shmid = shmget((key_t)1234, 1024, IPC_CREAT|0666); if(shmid == -1) { perror("shared memory access is failed\n"); return 0; } //attach the shared memory shmaddr = shmat(shmid, (void*)0, IPC_CREAT|0666); if(shmaddr == (char*)-1) { perror("attach failed\n"); return 0; } //printf("%d\n", strlen((char*)shmaddr)); if(strlen((char*)shmaddr)>0) { printf("%s", (char*)shmaddr); } ret = shmdt(shmaddr); if(ret == -1) { perror("detach failed\n"); return 0; } //remove the shared memory ret = shmctl(shmid, IPC_RMID, 0); if(ret == -1) { perror("remove failed\n"); return 0; } } return 0; } <file_sep>all : main CC = gcc main : main.o gcc -o main main.o -pthread main.o : main.c gcc -c -o main.o main.c -pthread clean : rm *.o main <file_sep>#include <stdio.h> #include <unistd.h> int main(void){ pid_t pid1, pid2; int status1, status2; printf("Waiting for Child Processes.\n"); if((pid1=fork())==-1){ printf("fork failed.\n"); } else if( pid1 == 0 ) { execl("child1", NULL); } else{ pid2 = fork();} if(pid2==-1){ printf("fork failed.\n"); } else if( pid2 == 0 ){ execl("child2", NULL); } else{ waitpid(pid1, &status1, 0); waitpid(pid2, &status2, 0); } return 0; } <file_sep>#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <unistd.h> struct msgbuf { long msgtype; char mtext[80]; }; int main(void) { key_t key_id; int i = 0; struct msgbuf sndbuf; char puts[80]; printf("Hello this is A process. I'll give the data to B.\n"); while(1) { fgets(puts,80,stdin); key_id = msgget((key_t)1234, IPC_CREAT|0666); if (key_id == -1 ) { perror("msgget error : "); return 0; } sndbuf.msgtype = 3; strcpy(sndbuf.mtext, puts); if(msgsnd( key_id, (void*)&sndbuf, sizeof(struct msgbuf), IPC_NOWAIT) == -1) { perror("msgsnd error : "); } if(!strcmp(puts, "bye")) { printf("this message will be sent to b process..\n"); return 0; } } return 0; } <file_sep>#include <stdio.h> #include <semaphore.h> #include <pthread.h> #define COUNTING_NUMBER 100 int cur_writer = 0; int cur_count = 0; int rear = -1; int front = -1; //int cur_count = 0; sem_t wc; // writer count sem_t rc; // reader count int wcVal = 0; int rcVal = 0; void *writer(int* name) { int i; int count = 0; for(i=0; i<COUNTING_NUMBER;i++){ usleep(1000); sem_getvalue(&wc, &wcVal); // check if there is another writer if(wcVal == 2){ sem_wait(&wc); //critical section cur_writer = *name; count++; cur_count = count; printf("writer id : writer%d | cur_count : %d\n", cur_writer, cur_count); sem_post(&wc); } } } void *reader(int* name) { int i, data, dataCount; usleep(300); printf("reader%d in\n", *(int*)name); sem_wait(&rc); //critical section data = cur_writer; dataCount = cur_count; sem_post(&rc); printf("\t\treader - cur_writer : %d | cur_count : %d\n", data, dataCount); } int main(void) { int i; int w1 = 1; int w2 = 2; int r1 = 1; int r2 = 2; int r3 = 3; int r4 = 4; int r5 = 5; //do not share the semaphore with other processes sem_init(&rc, 1, 5); //share the semaphore with other processes sem_init(&wc, 0, 2); pthread_t writer1, writer2, reader1, reader2, reader3, reader4, reader5; //create writers pthread_create(&writer1, NULL, (void*)writer, &w1); pthread_create(&writer2, NULL, (void*)writer, &w2); //create readers pthread_create(&reader1, NULL, (void*)reader, &r1); pthread_create(&reader2, NULL, (void*)reader, &r2); pthread_create(&reader3, NULL, (void*)reader, &r3); pthread_create(&reader4, NULL, (void*)reader, &r4); pthread_create(&reader5, NULL, (void*)reader, &r5); pthread_join(writer1, NULL); pthread_join(writer2, NULL); pthread_join(reader1, NULL); pthread_join(reader2, NULL); pthread_join(reader3, NULL); pthread_join(reader4, NULL); pthread_join(reader5, NULL); sem_destroy(&rc); sem_destroy(&wc); return 0; } <file_sep>all : child1 child2 main CC = gcc child1 : child1.o gcc -o child1 child1.o child1.o : child1.c gcc -c -o child1.o child1.c child2 : child2.o gcc -o child2 child2.o child2.o : child2.c gcc -c -o child2.o child2.c main : main.o gcc -o main main.o main.o : main.c gcc -c -o main.o main.c clean: rm *.o main child1 child2 <file_sep>#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> int main(void) { int shmid; int i; void *shmaddr; int ret; char puts[200]; printf("Hello, this is A process. I'll give the data to B.\n"); while(1) { fgets(puts, 200, stdin); //make a shared memory shmid = shmget((key_t)1234, 1024, IPC_CREAT|0666); if(shmid < 0) { perror("shmget"); return 0; } //attach the shared memory shmaddr = shmat(shmid, (void*)0, IPC_CREAT|0666); if(shmaddr == (char*)-1) { perror("attach failed\n"); return 0; } strcpy((char*)shmaddr, puts); //detach the shared memory shmdt(shmaddr); if(ret == -1) { perror("detach failed\n"); return 0; } if(!strcmp(puts, "bye\n")) { printf("this message will be sent to b process..\n"); return 0; } sleep(1); } return 0; } <file_sep>#include <stdio.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/ipc.h> #define COUNTING_NUMBER 200000 int shmid1, shmid2, shmid3; int *shmaddr1, *shmaddr2, *shmaddr3; int main(void){ pid_t pid1, pid2; int status1, status2; shmid1 = shmget((key_t)1224, sizeof(int) * 2, IPC_CREAT|0666); // flag shmid2 = shmget((key_t)1246, sizeof(int) * 1, IPC_CREAT|0666); // turn shmid3 = shmget((key_t)1288, sizeof(int) * 1, IPC_CREAT|0666); // critical_variable int *init = (int*)shmat(shmid3, NULL, 0); int one = 0, two = 1; if((pid1=fork())==-1){ printf("fork failed.\n"); } else if( pid1 == 0 ) { execl("child1", NULL); } else{ pid2 = fork();} if(pid2==-1){ printf("fork failed.\n"); } else if( pid2 == 0 ){ execl("child2", NULL); } else{ waitpid(pid1, &status1, 0); waitpid(pid2, &status2, 0); printf("Actual Count: %d | Expected Count: %d\n", *init, COUNTING_NUMBER * 2); int chk1 = shmctl(shmid1,IPC_RMID, 0); int chk2 = shmctl(shmid2,IPC_RMID, 0); int chk3 = shmctl(shmid3,IPC_RMID, 0); } return 0; } <file_sep>#include "sched.h" void init_myprio_rq (struct myprio_rq *myprio_rq) { printk(KERN_INFO "***[MYPRIO] Myprio class is online \n"); myprio_rq->nr_running = 0; INIT_LIST_HEAD(&myprio_rq->queue); } void init_task_myprio(struct task_struct *p) { struct sched_myprio_entity *se = &p->myprio; //stride will be 10~1000(int) p->sched_class = &myprio_sched_class; if((se->stride % 100) < 50) se->aging = (se->stride)/100; else //round aging by stride se->aging = (se->stride)/100 + 1 ; //any task must be executed before 100 upadates se->pass = se->stride; } //not only update curr, but also aging the other tasks. static void update_curr_myprio(struct rq *rq) { struct myprio_rq *myprio_rq = &rq->myprio; struct list_head *myprio_queue = &myprio_rq->queue; struct sched_myprio_entity *se = NULL; struct task_struct *p = NULL; printk(KERN_INFO " ***[MYPRIO] update_curr: update_curr starting!\n"); ((rq->curr)->myprio).pass += ((rq->curr)->myprio).stride; int i=0; for(i;i<myprio_rq->nr_running;i++) { myprio_queue = myprio_queue->next; se = container_of(myprio_queue, struct sched_myprio_entity, run_list); p = container_of(se, struct task_struct, myprio); if(p->pid != (rq->curr)->pid) { //if se->pass be less than 0, set 0. if((se->pass - se->aging) < 0) se->pass = 0; se->pass -= se->aging; //decrease other tasks' pass by aging to increase priority } printk(KERN_INFO " ***[MYPRIO] update_curr: curr->pid=%d, p->pid=%d, pass=%u, stride=%u\n", (rq->curr)->pid ,p->pid, se->pass, se->stride); } //we don't change the order of rq because sorting every update is more difficult. //for every update, we must pick minimum-pass task. resched_curr(rq); printk(KERN_INFO " ***[MYPRIO] update_curr: update_curr end!\n"); } static void enqueue_task_myprio(struct rq *rq, struct task_struct *p, int flags) { struct myprio_rq *myprio_rq = &rq->myprio; struct list_head *myprio_queue = &myprio_rq->queue; struct sched_myprio_entity *mse = &p->myprio; struct list_head *mse_run_list = &mse->run_list; //just enqueue to last order list_add_tail(mse_run_list, myprio_queue); //increase nr_running and change state myprio_rq->nr_running++; printk(KERN_INFO "***[MYPRIO] enqueue: success cpu=%d, nr_running=%d, p->state=%lu, p->pid=%d, pass=%u, stride=%u\n", cpu_of(rq), myprio_rq->nr_running, p->state, p->pid, mse->pass, mse->stride); } static void dequeue_task_myprio(struct rq *rq, struct task_struct *p, int flags) { struct myprio_rq *myprio_rq = &rq->myprio; struct list_head *myprio_queue = &myprio_rq->queue; struct sched_myprio_entity *mse = &p->myprio; struct list_head *mse_run_list = &mse->run_list; //check whether queue is empty if(myprio_rq->nr_running != 0) { //delete the task and decrease nr_running list_del_init(mse_run_list); myprio_rq->nr_running--; printk(KERN_INFO "***[MYPRIO] dequeue: success cpu=%d, nr_running=%d, p->state=%lu, p->pid=%d, pass=%u, stride=%u\n", cpu_of(rq), myprio_rq->nr_running, p->state, p->pid, mse->pass, mse->stride); } else { } } static void check_preempt_curr_myprio(struct rq *rq, struct task_struct *p, int flags) {} struct task_struct *pick_next_task_myprio(struct rq *rq, struct task_struct *prev) { struct sched_myprio_entity *se = NULL; struct task_struct *next_p = NULL; struct sched_myprio_entity *next_se = NULL; struct myprio_rq *myprio_rq = &rq->myprio; struct list_head *myprio_queue = &myprio_rq->queue; if(myprio_rq->nr_running == 0) { return NULL; } if(prev->sched_class != &myprio_sched_class) { printk(KERN_INFO " ***[MYPRIO] pick_next_task: other class came in.. prev->pid=%d\n", prev->pid); put_prev_task(rq, prev); } //select the minimum-pass task in rq //if the minimum-pass tasks are more than 2, //select the one which has the least stride. int i; unsigned int minimum_pass; unsigned int minimum_stride; next_se = container_of(myprio_queue->next, struct sched_myprio_entity, run_list); next_p = container_of(next_se, struct task_struct, myprio); minimum_pass = next_se->pass; minimum_stride = next_se->stride; for(i = 0; i < myprio_rq->nr_running; i++) { myprio_queue = myprio_queue->next; se = container_of(myprio_queue, struct sched_myprio_entity, run_list); if(se->pass < minimum_pass) { minimum_pass = se->pass; minimum_stride = se->stride; next_se = se; } else if(se->pass == minimum_pass) hihellobye { if(se->stride < minimum_stride) { minimum_stride = se->stride; next_se = se; } } } next_p = container_of(next_se, struct task_struct, myprio); printk(KERN_INFO " ***[MYPRIO] pick_next_task: cpu=%d, prev->pid=%d, next_p->pid=%d, next_pass=%u, next_stride=%u, nr_running=%d\n", cpu_of(rq),prev->pid, next_p->pid, next_se->pass, next_se->stride, myprio_rq->nr_running); return next_p; } static void put_prev_task_myprio(struct rq *rq, struct task_struct *p) { printk(KERN_INFO " ***[MYPRIO] put_prev_task: do nothing, p->pid=%d\n", p->pid); } static int select_task_rq_myprio(struct task_struct *p, int cpu, int sd_flas, int flags) { return task_cpu(p); } static void set_curr_task_myprio(struct rq *rq) {} static void task_tick_myprio(struct rq *rq, struct task_struct *p, int queue) { update_curr_myprio(rq); } static void prio_changed_myprio(struct rq *rq, struct task_struct *p, int oldprio) {} static void switched_to_myprio(struct rq *rq, struct task_struct *p) { resched_curr(rq); } const struct sched_class myprio_sched_class={ .next=&mysched_sched_class, .enqueue_task=enqueue_task_myprio, .dequeue_task=dequeue_task_myprio, .check_preempt_curr=check_preempt_curr_myprio, .pick_next_task=pick_next_task_myprio, .put_prev_task=put_prev_task_myprio, #ifdef CONFIG_SMP .select_task_rq=select_task_rq_myprio, #endif .set_curr_task=set_curr_task_myprio, .task_tick=task_tick_myprio, .prio_changed=prio_changed_myprio, .switched_to=switched_to_myprio, .update_curr=update_curr_myprio, }; <file_sep>all : processB processA CC = gcc processB : processB.o gcc -o processB processB.o processB.o : processB.c gcc -c -o processB.o processB.c processA : processA.o gcc -o processA processA.o processA.o : processA.c gcc -c -o processA.o processA.c clean: rm *.o processA processB <file_sep>all : thread CC = gcc thread : thread.o gcc -o thread thread.o -pthread thread.o : thread.c gcc -c -o thread.o thread.c -pthread clean : rm *.o thread <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <atomic> #define COUNTING_NUMBER 2000000 using namespace std; int critical_section_variable = 0; std::atomic<int> turn; std::atomic<int> flag[2] = {{0},{0}}; void lock(int self) { flag[self].store(1); turn.store((self+1)%2); while(flag[turn].load() && turn.load() == (self+1)%2); } void unlock(int self) { flag[self].store(0); } void *func(void *s) { int* thread_num = (int*)s; int i; for(i=0;i<COUNTING_NUMBER; i++) { lock(*thread_num); critical_section_variable++; unlock(*thread_num); } } int main(void) { pthread_t p1, p2; int parameter[2] = {0,1}; pthread_create(&p1, NULL, func, (void*)&parameter[0]); pthread_create(&p2, NULL, func, (void*)&parameter[1]); pthread_join(p1, NULL); pthread_join(p2, NULL); printf("Actual Count: %d | Expected Count: %d\n", critical_section_variable, COUNTING_NUMBER*2); return 0; }
5b158147e3918d5c075f6da5378760be3686d957
[ "C", "Makefile", "C++" ]
22
C
hyedoii/OS
54a3443dbe420762e9b6166894e70bff530638e1
1062f4a2ade50440617523f6638b71adca684d3f
refs/heads/master
<file_sep>"""\ Tests for kt.testing test fixture composition. These tests use ``nose`` used for handling tests; something different will be needed to ensure we work with other test runners. """ import unittest import kt.testing import kt.testing.tests class FixtureUsingBaseClass(kt.testing.FixtureComponent): """Test fixture component derived from provided base class.""" def __init__(self, testcase): super(FixtureUsingBaseClass, self).__init__(testcase) testcase.record.append((self.test, 'derived init')) def setup(self): super(FixtureUsingBaseClass, self).setup() self.test.record.append((self.test, 'derived setup')) self.test.addCleanup( lambda: self.test.record.append((self.test, 'derived cleanup'))) def teardown(self): super(FixtureUsingBaseClass, self).teardown() self.test.record.append((self.test, 'derived teardown')) class IndependentFixture(object): """Test fixture component not using provided base class.""" def __init__(self, testcase, state=42): self.test = testcase testcase.record.append((self.test, 'independent init')) self.state = state def setup(self): self.test.record.append((self.test, 'independent setup')) self.test.addCleanup( lambda: self.test.record.append((self.test, 'independent cleanup'))) def teardown(self): self.test.record.append((self.test, 'independent teardown')) def complain(self, msg): self.test.record.append((self.test, 'independent complaint: %s' % msg)) raise AssertionError('using independent class: %s' % msg) class FixtureWithoutTeardown(object): def __init__(self, testcase): self.test = testcase testcase.record.append((self.test, 'teardownless init')) def setup(self): self.test.record.append((self.test, 'teardownless setup')) self.test.addCleanup( lambda: self.test.record.append((self.test, 'teardownless cleanup'))) def unwrap(tc): """Retrieve test object from unittest.TestCase-derived nose test.""" return tc.test class TestComposition(kt.testing.tests.Core): def check_composite_case(self, cls): assert issubclass(cls, kt.testing.CompositeFixture) assert issubclass(cls, unittest.TestCase) def test_simple_usage(self): self.check_simple_usage(object) def test_simple_usage_testcase(self): self.check_simple_usage(unittest.TestCase) def check_simple_usage(self, baseclass): class TC(baseclass): usingbase = kt.testing.compose(FixtureUsingBaseClass) independent = kt.testing.compose(IndependentFixture) record = [] def test_this(self): self.record.append((self, 'test_this')) def test_the_other(self): self.record.append((self, 'test_the_other')) self.check_composite_case(TC) # Rely on tests being sorted in alphabetical order by method name. tto, tt = self.loader.makeTest(TC) tto_tc = unwrap(tto) tt_tc = unwrap(tt) self.run_one_case(tto) tto_record = [msg for tc, msg in TC.record if tc is tto_tc] tt_record = [msg for tc, msg in TC.record if tc is tt_tc] assert tto_record == [ 'derived init', 'independent init', 'derived setup', 'independent setup', 'test_the_other', # # Note the intermixing of teardown and cleanups; the # teardowns for the fixture components are handled as # teardowns for the test itself. # 'independent teardown', 'independent cleanup', 'derived teardown', 'derived cleanup', ] # The fixture components have already been created for test_this # as well, but the setup methods haven't been called: assert tt_record == [ 'derived init', 'independent init', ] self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record if tc is tt_tc] assert tt_record == [ 'derived init', 'independent init', 'derived setup', 'independent setup', 'test_this', 'independent teardown', 'independent cleanup', 'derived teardown', 'derived cleanup', ] def test_inherited_fixture_components(self): self.check_inherited_fixture_components(object) def test_inherited_fixture_components_testcase(self): self.check_inherited_fixture_components(unittest.TestCase) def check_inherited_fixture_components(self, baseclass): class TCOne(baseclass): usingbase = kt.testing.compose(FixtureUsingBaseClass) class TCTwo(TCOne): independent = kt.testing.compose(IndependentFixture) record = [] def test_this(self): self.record.append((self, 'test_this')) self.check_composite_case(TCOne) self.check_composite_case(TCTwo) tt, = self.loader.makeTest(TCTwo) self.run_one_case(tt) tt_record = [msg for tc, msg in TCTwo.record] assert tt_record == [ 'derived init', 'independent init', 'derived setup', 'independent setup', 'test_this', 'independent teardown', 'independent cleanup', 'derived teardown', 'derived cleanup', ] def test_explicit_derived_metaclass_allowed(self): class DerivedMeta(kt.testing.CFMeta): pass self.check_explicit_metaclass_allowed(DerivedMeta) def test_explicit_metaclass_allowed(self): self.check_explicit_metaclass_allowed(kt.testing.CFMeta) def check_explicit_metaclass_allowed(self, meta): class TC(object): __metaclass__ = meta fixture = kt.testing.compose(IndependentFixture) record = [] def test_this(self): self.record.append((self, 'test_this')) self.check_composite_case(TC) tt, = self.loader.makeTest(TC) self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record] assert tt_record == [ 'independent init', 'independent setup', 'test_this', 'independent teardown', 'independent cleanup', ] def test_conflicting_metaclass_disallowed(self): class AltMeta(type): pass try: class TC(object): __metaclass__ = AltMeta kt.testing.compose(IndependentFixture) except ValueError as e: assert str(e) == ('competing metaclasses;' ' found: kt.testing.tests.composite.AltMeta,' ' need: kt.testing.CFMeta') else: # pragma: no cover raise AssertionError('expected ValueError') def test_metaclass_used_without_fixtures_allowed(self): self.check_explicit_metaclass_without_fixtures_allowed( kt.testing.CFMeta) def test_derived_metaclass_used_without_fixtures_allowed(self): class DerivedMeta(kt.testing.CFMeta): pass self.check_explicit_metaclass_without_fixtures_allowed(DerivedMeta) def check_explicit_metaclass_without_fixtures_allowed(self, meta): # Unlikely, but harmless. class TC(object): __metaclass__ = meta record = [] def test_this(self): self.record.append((self, 'test_this')) self.check_composite_case(TC) tt, = self.loader.makeTest(TC) self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record] assert tt_record == ['test_this'] def test_test_can_use_fixture_api(self): self.check_case_can_use_fixture_api(object) def test_test_can_use_fixture_api_testcase(self): self.check_case_can_use_fixture_api(unittest.TestCase) def check_case_can_use_fixture_api(self, base): class TC(base): fixture = kt.testing.compose(IndependentFixture) record = [] def test_this(self): self.record.append((self, 'test_this')) self.state = self.fixture.state self.fixture.complain('bleh') tt, = self.loader.makeTest(TC) result = self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record] assert unwrap(tt).state == unwrap(tt).fixture.state assert tt_record == [ 'independent init', 'independent setup', 'test_this', 'independent complaint: bleh', 'independent teardown', 'independent cleanup', ] (xtc, err), = result.failures assert xtc is tt assert err.startswith('Traceback (most recent call last):') assert 'using independent class: bleh' in err def test_fixture_components_get_args(self): self.check_fixture_components_construction_args(object) def test_fixture_components_get_args_testcase(self): self.check_fixture_components_construction_args(unittest.TestCase) def test_fixture_components_get_kwargs(self): self.check_fixture_components_construction_kwargs(object) def test_fixture_components_get_kwargs_testcase(self): self.check_fixture_components_construction_kwargs(unittest.TestCase) def check_fixture_components_construction_args(self, base): class TC(base): fixture = kt.testing.compose(IndependentFixture, 24) self.check_fixture_components_construction(TC) def check_fixture_components_construction_kwargs(self, base): class TC(base): fixture = kt.testing.compose(IndependentFixture, state=24) self.check_fixture_components_construction(TC) def check_fixture_components_construction(self, cls): class TC(cls): record = [] def test_this(self): self.state = self.fixture.state tt, = self.loader.makeTest(TC) self.run_one_case(tt) assert unwrap(tt).state == 24 # If the fixture component doesn't have a teardown method, it isn't # added to the cleanup list. def test_fixture_without_teardown(self): self.check_fixture_without_teardown(object) def test_fixture_without_teardown_testcase(self): self.check_fixture_without_teardown(unittest.TestCase) def check_fixture_without_teardown(self, base): class TC(base): fixture = kt.testing.compose(FixtureWithoutTeardown) record = [] def test_this(self): self.record.append((self, 'test_this')) tt, = self.loader.makeTest(TC) self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record] assert tt_record == [ 'teardownless init', 'teardownless setup', 'test_this', 'teardownless cleanup', ] # Overriding a fixture component property doesn't make the component # inaccessible; aliases for component properties work just fine. def test_component_property_alias(self): self.check_component_property_alias(object) def test_component_property_alias_testcase(self): self.check_component_property_alias(unittest.TestCase) def check_component_property_alias(self, base): class TCBase(base): fixture = kt.testing.compose(IndependentFixture, state='original') class TC(TCBase): orig = TCBase.fixture fixture = kt.testing.compose(IndependentFixture, state='override') record = [] def test_this(self): pass # pragma: no cover tt, = self.loader.makeTest(TC) tc = unwrap(tt) assert tc.orig.state == 'original' assert tc.fixture.state == 'override' def test_inherited_cooperative_setup(self): self.check_inherited_cooperative_setup(object) def test_inherited_cooperative_setup_testcase(self): self.check_inherited_cooperative_setup(unittest.TestCase) def check_inherited_cooperative_setup(self, base): """\ Co-operative setup is supported when appropriate bases are omitted. We do this because it's really important that our setUp method is invoked, so it should be drop-dead easy. """ class TCBase(base): # No fixture composition here. def setUp(self): super(TCBase, self).setUp() self.record.append((self, 'TCBase setup')) class TC(TCBase): fixture = kt.testing.compose(FixtureWithoutTeardown) record = [] def test_this(self): self.record.append((self, 'test_this')) tt, = self.loader.makeTest(TC) self.run_one_case(tt) tt_record = [msg for tc, msg in TC.record] assert tt_record == [ 'teardownless init', 'teardownless setup', 'TCBase setup', 'test_this', 'teardownless cleanup', ] <file_sep>"""\ Support for faking out ``requests`` for tests. Only requests specifically allowed will be permitted, with the responses provided. This does *not* intercede with other mechanisms for requesting resources by URL from Python (httplib, urllib, urllib2, etc.). """ from __future__ import absolute_import import json import mock import requests.structures RESPONSE_ENTITY_NOT_ALLOWED = 204, 205, 301, 302, 303, 304, 307, 308 class Requests(object): def __init__(self, test, body='', content_type='text/plain'): self.test = test self.body = body self.content_type = content_type def setup(self): self.requests = [] self.responses = {} p = mock.patch('requests.api.request', self.request) self.test.addCleanup(p.stop) p.start() p = mock.patch('requests.request', self.request) self.test.addCleanup(p.stop) p.start() def teardown(self): """The test failed if there were too many or too few requests.""" if self.responses: raise AssertionError('configured responses not consumed') def add_error(self, method, url, exception): assert isinstance(exception, Exception) key = method.upper(), url responses = self.responses.setdefault(key, []) responses.append(exception) def add_response(self, method, url, status=200, body=None, headers={}): headers = requests.structures.CaseInsensitiveDict(headers) key = method.upper(), url if status in RESPONSE_ENTITY_NOT_ALLOWED: if body: raise ValueError( 'cannot provide non-empty body for status == %s' % status) body = '' elif body is None: body = self.body headers['Content-Type'] = self.content_type responses = self.responses.setdefault(key, []) responses.append(Response(status, body, headers)) def request(self, method, url, *args, **kwargs): key = method.upper(), url if key not in self.responses: response = AssertionError('unexpected request: %s %s' % key) else: response = self.responses[key].pop(0) if not self.responses[key]: del self.responses[key] self.requests.append((method, url, response, args, kwargs)) if isinstance(response, Exception): raise response else: return response class Response(object): def __init__(self, status, text='', headers={}): headers = requests.structures.CaseInsensitiveDict(headers) if status in RESPONSE_ENTITY_NOT_ALLOWED: assert not text elif 'Content-Length' not in headers: headers['Content-Length'] = str(len(text)) self.status_code = status self.text = text self.headers = headers def json(self): return json.loads(self.text) <file_sep> [html] title = kt.testing coverage [report] precision = 1 [run] branch = True source = kt.testing <file_sep>#!/usr/bin/python import os import sys import setuptools packages = setuptools.find_packages('src') here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, 'README.rst')) as f: long_description = f.read() # Avoid turds left behind during refactorings from affecting new # test runs. # if 'nosetests' in sys.argv[1:]: here = os.path.dirname(os.path.abspath(__file__)) for path, dirs, files in os.walk(here): for fn in [fn for fn in files if fn.endswith('.pyc') or fn.endswith('.pyo')]: if not os.path.exists(fn[:-1]): fn = os.path.join(path, fn) print 'Removing', fn os.unlink(fn) tests_require = ['nose'] metadata = dict( name='kt.testing', version='0', description='Test support code featuring flexible harness composition', long_description=long_description, author='<NAME>, Jr.', author_email='<EMAIL>', url='https://github.com/keepertech/kt.testing', packages=packages, package_dir={'': 'src'}, namespace_packages=['kt'], install_requires=[ 'mock', 'requests', ], tests_require=tests_require, extras_require={ 'test': tests_require, }, test_suite='nose.collector', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing', ], ) if __name__ == '__main__': setuptools.setup(**metadata) <file_sep>"""\ Tests for kt.testing.requests. """ from __future__ import absolute_import import socket import unittest import requests import requests.api import kt.testing import kt.testing.requests import kt.testing.tests class TestRequestsMethods(kt.testing.tests.Core, unittest.TestCase): api = requests def check_successful_run(self, cls, count=1): t, = self.loader.makeTest(cls) result = self.run_one_case(t) tc = t.test assert result.errors == [] assert result.failures == [] assert len(tc.fixture.requests) == count return tc def test_requests_get(self): class TC(object): api = self.api fixture = kt.testing.compose(kt.testing.requests.Requests) def setUp(self): super(TC, self).setUp() self.fixture.add_response('get', 'http://localhost:8000/foo') self.fixture.add_error('get', 'http://localhost:8000/foo', socket.gaierror('unknown name')) def testit(self): r = self.api.get('http://localhost:8000/foo') assert r.status_code == 200 assert r.text == '' try: r = self.api.get('http://localhost:8000/foo') except socket.gaierror as e: assert str(e) == 'unknown name' else: # pragma: no cover raise AssertionError('expected AssertionError') self.check_successful_run(TC, count=2) def test_requests_delete(self): self.check_requests_method('delete') def test_requests_patch(self): self.check_requests_method('patch') def test_requests_post(self): self.check_requests_method('post') def test_requests_put(self): self.check_requests_method('put') def check_requests_method(self, request_method): class TC(object): api = self.api method = request_method fixture = kt.testing.compose(kt.testing.requests.Requests) def setUp(self): super(TC, self).setUp() self.fixture.add_response( self.method, 'http://localhost:8000/bar', body='{"answer":42}', headers={'Content-Type': 'application/json'}) def testit(self): m = getattr(self.api, self.method) r = m('http://localhost:8000/bar') assert r.status_code == 200 assert r.text == '{"answer":42}' assert r.json() == {'answer': 42} self.check_successful_run(TC) def test_empty_response_required(self): self.check_empty_response_required(204) self.check_empty_response_required(205) self.check_empty_response_required(301) self.check_empty_response_required(302) self.check_empty_response_required(303) self.check_empty_response_required(304) self.check_empty_response_required(307) self.check_empty_response_required(308) def check_empty_response_required(self, status): class TC(object): fixture = kt.testing.compose(kt.testing.requests.Requests) ran_testit = False def setUp(self): super(TC, self).setUp() self.fixture.add_response( 'get', 'http://localhost:8000/bar', body='non-empty', status=status) def testit(self): self.ran_testit = True # pragma: no cover t, = self.loader.makeTest(TC) result = self.run_one_case(t) tc = t.test (xt, err), = result.errors assert xt is t assert err.endswith( '\nValueError: cannot provide non-empty body for status == %s\n' % status) assert result.failures == [] assert not tc.fixture.requests assert not tc.ran_testit def test_empty_response_allowed(self): self.check_empty_response_allowed(200) self.check_empty_response_allowed(201) self.check_empty_response_allowed(204) self.check_empty_response_allowed(205) self.check_empty_response_allowed(301) self.check_empty_response_allowed(302) self.check_empty_response_allowed(303) self.check_empty_response_allowed(304) self.check_empty_response_allowed(307) self.check_empty_response_allowed(308) self.check_empty_response_allowed(400) self.check_empty_response_allowed(404) self.check_empty_response_allowed(500) def check_empty_response_allowed(self, status): class TC(object): api = self.api fixture = kt.testing.compose(kt.testing.requests.Requests) ran_testit = False def setUp(self): super(TC, self).setUp() self.fixture.add_response( 'get', 'http://localhost:8000/bar', body='', status=status) def testit(self): self.ran_testit = True r = self.api.get('http://localhost:8000/bar') assert r.status_code == status assert r.text == '' tc = self.check_successful_run(TC) assert tc.ran_testit def test_fails_without_matching_response(self): class TC(unittest.TestCase): fixture = kt.testing.compose(kt.testing.requests.Requests) def testit(self): pass # pragma: no cover tc, = self.loader.makeTest(TC) tc = tc.test tc.setUp() try: try: self.api.get('http://www.python.org/') except AssertionError as e: e = str(e) assert e == 'unexpected request: GET http://www.python.org/' else: # pragma: no cover raise AssertionError('expected AssertionError to be raised') finally: tc.tearDown() def test_multiple_responses(self): class TC(unittest.TestCase): fixture = kt.testing.compose(kt.testing.requests.Requests) def testit(self): pass # pragma: no cover tc, = self.loader.makeTest(TC) tc = tc.test tc.setUp() tc.fixture.add_response( 'get', 'http://www.keepertech.com/', body='first', headers={'content-length': '42'}) tc.fixture.add_response( 'get', 'http://www.keepertech.com/', body='second') # Responses for the same method/path are provided in the order # they are configured: try: r = self.api.get('http://www.keepertech.com/') assert r.status_code == 200 assert r.text == 'first' assert int(r.headers['Content-Length']) == 42 r = self.api.get('http://www.keepertech.com/') assert r.status_code == 200 assert r.text == 'second' finally: tc.tearDown() class TestRequestsAPIMethods(TestRequestsMethods): """Anything that uses requests.* should be able to use requests.api.*. Verify the requests.api.* functions are handled by the fixture. """ api = requests.api class TestWithoutInvokingRequests(kt.testing.tests.Core, unittest.TestCase): # These tests don't cause any of the mocked APIs in requests to be # invoked, so they don't need to be performed for both requests.* # and requests.api.* flavors. def test_fails_if_responses_not_consumed(self): class TC(unittest.TestCase): fixture = kt.testing.compose(kt.testing.requests.Requests) def test_it(self): pass t, = self.loader.makeTest(TC) tc = t.test result = tc.defaultTestResult() tc.setUp() tc.fixture.add_response('get', 'http://www.keepertech.com/') tc.test_it() tc.tearDown() # If the test runs without consuming all the responses, an error # is generated during teardown: tc._resultForDoCleanups = result assert result.errors == [] ok = tc.doCleanups() self.assertFalse(ok) (t, tb), = result.errors self.assertIn('configured responses not consumed', tb) <file_sep>============================================= ``kt.testing`` - Test harness support library ============================================= Applications that make use of large frameworks often need to mock or stub out portions of those APIs in ways that provide a consistent view on the resources that API exposes. A test fixture often wants to establish a particular state for the API at a higher level than that of individual API calls; this is especially the case if an API provides more than one way to do things. How the code under test uses the underlying API is less interesting than the information exposed by the API and the operations performed on it. There are a number of ways to approach these situations using tests based on ``unittest.TestCase`` (or similar) fixtures. Too often, these become tangled messes where test authors have to pay attention to implementation details of base and mix-in classes to avoid support for different APIs interfering with each other's internal state. This library approaches the problem by allowing APIs that support test control of other frameworks or libraries to be independent components. These *fixture components* can: - access the test object, - be involved in setup and teardown, - provide cleanup handlers, - provide APIs for tests to configure the behavior of the APIs they manage, and - provide additional assertion methods specific to what they do. These components can inject themselves into the APIs they manage in whatever ways are appropriate (using ``mock.patch``, for example). Release history --------------- 1.0.0 (2016-03-21) ~~~~~~~~~~~~~~~~~~ Initial public release of library initialy created for internal use at `Keeper Technology`_. Implementing fixture components ------------------------------- Fixture components are defined by a factory object, usually a class, and are expected to provide a slim API for the harness. Let's look at a simple but complete, usable example:: import logging class TestLoggingHandler(logging.StreamHandler): def __init__(self, stream, records): self.records = records super(TestLoggingHandler, self).__init__(stream) def handle(self, record): self.records.append(record) super(TestLoggingHandler, self).handle(record) class LoggingFixture(object): def __init__(self, test, name=None): self.test = test self.name = name def setup(self): sio = cStringIO.StringIO() self.output = sio.getvalue self.records = [] handler = TestLoggingHandler(sio, self.records) logger = logging.getLogger(self.name) logger.addHandler(handler) self.test.addCleanup(logger.removeHandler, handler) Using this from a test fixture is straightforward:: import unittest class TestMyThing(unittest.TestCase): logging = kt.testing.compose(LoggingFixture) def test_some_logging(self): logging.getLogger('my.package').error('not happy') record = self.logging.records[-1] self.assertEqual(record.getMessage(), 'not happy') self.assertEqual(record.levelname, 'ERROR') Fixture components may also provide a ``teardown`` method that takes no arguments (aside from self). These are called after the ``tearDown`` method of the test case is invoked, and do not require that method to be successful. (They are invoked as cleanup functions of the test case.) Constructor arguments for the fixture component can be provided with ``kt.testing.compose``, but note that the test case instance will always be passed as the first positional argument:: class TestMyThing(unittest.TestCase): logging = kt.testing.compose(LoggingFixture, name='my.package') def test_some_logging(self): logging.getLogger('your.package').error('not happy') with self.assertRaises(IndexError): self.logging.records[-1] Each instance of the test case class will get it's own instance of the fixture components, accessible via the properties defined using ``kt.testing.compose``. These instances will already be available when the ``__init__`` method of the test case is invoked. If the test class overrides the ``setUp`` method, it will need to ensure the superclass ``setUp`` is invoked so the ``setup`` method of the fixture components are invoked:: class TestSomeThing(unittest.TestCase): logging = kt.testing.compose(LoggingFixture, name='my.package') def setUp(self): super(TestSomeThing, self).setUp() # more stuff here Note that the ``setUp`` didn't invoke ``unittest.TestCase.setUp`` directly. Since ``kt.testing.compose`` can cause an additional mix-in class to be added, ``super`` is the way to go unless you're specifically using a base class that's known to have the right mix-in already mixed. Multiple fixtures and test inheritance -------------------------------------- Multiple fixture components of the same or different types can be added for a single test class:: class TestMyThing(unittest.TestCase): my = kt.testing.compose(LoggingFixture, name='my.package') your = kt.testing.compose(LoggingFixture, name='your.package') def test_different(self): self.assertIsNot(self.my, self.your) Base classes that use fixture components will be properly initialized, and properties can be aliased and overridden in ways that make sense:: class TestAnotherThing(TestMyThing): orig_my = TestMyThing.my my = kt.testing.compose(LoggingFixture, name='my.another') def test_different(self): self.assertIsNot(self.my, self.your) self.assertIsNot(self.orig_my, self.your) self.assertIsNot(self.orig_my, self.my) self.assertEqual(self.my.name, 'my.another') self.assertEqual(self.orig_my.name, 'my.package') self.assertEqual(self.your.name, 'your.package') ``kt.testing.requests`` - Intercession for ``requests`` ------------------------------------------------------- Many applications (and other libraries) use the ``requests`` package to retrieve resources identified by URL. It's often reasonable to use ``mock`` directly to handle requests for resources in tests, but sometimes a little more is warranted. The ``requests`` library provides multiple ways to trigger particular requests, and applications usually shouldn't care which is used to make a request. A fixture component for ``requests`` is provided:: class TestMyApplication(unittest.TestCase): requests = kt.testing.compose(kt.testing.requests.Requests) A default response entity can be provided via constructor arguments passed through ``compose``. The body and content-type can both be provided:: class TestMyApplication(unittest.TestCase): requests = kt.testing.compose( kt.testing.requests.Requests, body='{"success": true, "value": "let's have some json data"}', content_type='application/json', ) If the default response entity is not defined, an empty body of type text/plain is used. The fixture provides these methods for configuring responses for particular requests by URL: ``add_response(method, url, status=200, body=None, headers={})`` Provide a particular response for a given URL and request method. Other aspects of the request are not considered for identifying what response to provide. If the response status indicates an entity is allowed in the response and `body` is provided as ``None``, the default body and content-type will be returned. This will be an empty string unless some other value is provided to the fixture component constructor. If the status indicates no entity should be returned, an empty body will be used. The provided information will be used to create a response that is returned by the ``requests`` API. ``add_error(method, url, exception)`` Provide an exception that should be raised when a particular resource is requested. This can be used to simulate errors such as a non-responsive server or DNS resolution failure. Only the URL and request method are considered for identifying what response to provide. If a request is made that does match any provided response, an ``AssertionError`` is raised; this will normally cause a test to fail, unless the code under test catches exceptions too aggressively. A test that completes without consuming all configured responses will cause an ``AssertionError`` to be raised during teardown. Test runners based on ``unittest`` will usually report this as an error rather than a failure, but it'll require a developer to take a look, and that's the point. If multiple configurations are made for the same request method and URL (whether responses or errors), they'll be provided to the application in the order configured. .. _Keeper Technology: http://www.keepertech.com/
7b7c529771bae32e1bfec6b2ae93d1987d006b32
[ "Python", "reStructuredText", "INI" ]
6
Python
arwankhoiruddin/kt.testing
dc0064ce716064ad53221caea2b02ec767e0a956
2abb8985305656c46e84348c7cfaa31270fa453d
refs/heads/master
<file_sep># Generator node-jsper My personal node project generator, using Yo. ![](http://i.imgur.com/JHaAlBJ.png) <file_sep># <%= projectName %> <%= projectDesc %> ## Development ### Style An `.editorconfig` and `.jshintrc` enforce a coding style. ### Tasks Gulp is used as a task runner. Install it globally using `npm install -g gulp`. To see a list of gulp commands, run `gulp help`. ### Git hooks Upon commiting or pushing, a git hook wil automatically runt code linting or tests. <file_sep>'use strict'; var util = require('util'); var yeoman = require('yeoman-generator'); var yosay = require('yosay'); var GithubApi = require('github'); var changeCase = require('change-case'); var github = new GithubApi({ version: '3.0.0' }); if (process.env.GITHUB_TOKEN) { github.authenticate({ type: 'oauth', token: process.env.GITHUB_TOKEN }); } var NodeJsperGenerator = yeoman.generators.Base.extend({ initializing: function () { }, prompting: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay('Welcome to the awesome node.jsper generator!')); var prompts = [{ type: 'input', name: 'projectName', message: 'What is the project name?', validate: function(projectName) { if (!projectName) { return 'Project must have a name'; } else { return true; } } }, { type: 'input', name: 'projectDesc', message: 'What is the project description?', default: '' }]; this.prompt(prompts, function (props) { this.projectName = props.projectName; this.projectDesc = props.projectDesc; done(); }.bind(this)); }, configuring: function() { var done = this.async(); this.destinationRoot(changeCase.paramCase(this.projectName)); this.projectIndex = util.format('lib/%s.js', changeCase.paramCase(this.projectName)); github.repos.create({ name: this.projectName, description: this.projectDesc }, function(err, result) { if (err) { throw err; } this.gitLink = result.git_url; this.gitPage = result.html_url; this.gitIssues = result.issues_url.replace('{/number}', ''); this.gitSSH = result.ssh_url; done(); }.bind(this)); }, writing: function() { this.copy('gitignore', '.gitignore'); this.copy('npmignore', '.npmignore'); this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); this.copy('gulpfile.js', 'gulpfile.js'); this.template('_package.json', 'package.json'); this.mkdir('lib'); this.copy('index.js', this.projectIndex); this.mkdir('examples'); this.template('_README.md', 'README.md'); }, install: function() { this.npmInstall(); }, end: function() { this.spawnCommand('git', ['init']); this.spawnCommand('git', ['add', '.']); this.spawnCommand('git', ['commit', '-m', 'First commit.']); this.spawnCommand('git', ['remote', 'add', 'origin', this.gitSSH]); this.spawnCommand('git', ['push', 'origin', 'master', '-u']); } }); module.exports = NodeJsperGenerator;
d6a0af6466dee3f7a82718f11d6d75569911d1c0
[ "Markdown", "JavaScript" ]
3
Markdown
jwoudenberg/generator-node-jsper
27ca30952cbb2a7ba0a6f65fef7e3260898e098d
e692eb66b828d64e28ec10caee863dcb7ca5b941
refs/heads/main
<repo_name>ahsar04/siskas<file_sep>/src/SisKas/Report.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SisKas; import java.awt.Dimension; import java.awt.Toolkit; import java.sql.Connection; import java.sql.DriverManager; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.view.JasperViewer; import Config.Conn; import java.util.HashMap; /** * * @author <NAME> */ public class Report extends javax.swing.JFrame { /** * Creates new form Report */ public Report() { 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() { jPanel1 = new javax.swing.JPanel(); btnReport = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); coba = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnReport.setText("Print"); btnReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnReportActionPerformed(evt); } }); jLabel1.setText("Cetak Data Barang"); coba.setText("T202107061"); coba.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cobaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(142, 142, 142) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnReport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(coba, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(67, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(91, 91, 91) .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnReport) .addComponent(coba, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(154, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReportActionPerformed // TODO add your handling code here: Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } try { conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db_siskas","root",""); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } // String location = "C:\\Users\\<NAME>\\OneDrive\\Documents\\NetBeansProjects\\"; String file= "C:\\Users\\<NAME>\\OneDrive\\Desktop\\MATKUL\\SMT 2\\WSIBD\\siskas\\src\\SisKas\\Struk.jrxml"; JasperReport jr; try { HashMap hash = new HashMap(); hash.put("kdTransaksi", coba.getText()); jr = JasperCompileManager.compileReport(file); JasperPrint jp = JasperFillManager.fillReport(jr, hash, conn); JasperViewer.viewReport(jp); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } }//GEN-LAST:event_btnReportActionPerformed private void cobaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cobaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cobaActionPerformed /** * @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 ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Report().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnReport; private javax.swing.JTextField coba; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables } <file_sep>/src/Config/Config.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Config; import java.awt.event.KeyEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author <NAME> */ public class Config { Connection con; PreparedStatement pst; ResultSet rs; Statement st; String SQL; int i; public Config() { try { Class.forName("com.mysql.jdbc.Driver"); String Database="db_siskas"; String Username="root"; String Password=""; con = DriverManager.getConnection("jdbc:mysql://localhost/"+Database, Username, Password); System.out.println("Koneksi Berhasil"); } catch (ClassNotFoundException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } } //Overload fungsi untuk eksekusi query select semua kolom dengan where public void selectAllCondition(String nameTable, String condition) { try { SQL = "SELECT * FROM " + nameTable + " WHERE " + condition; pst = con.prepareStatement(SQL); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } } public void insertDB(String nameTable, String[] namecolumn, String[] value) { try { SQL = "INSERT INTO " + nameTable +" ("; for (i = 0; i <= namecolumn.length - 1; i++) { SQL +=namecolumn[i]; if (i < namecolumn.length - 1) { SQL += ","; } } SQL+=") VALUES("; for (i = 0; i <= value.length - 1; i++) { SQL += "'" + value[i] + "'"; if (i < value.length - 1) { SQL += ","; } } SQL += ")"; pst = con.prepareStatement(SQL); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } } // public ResultSet selectDB(String tbl) { try { SQL ="select * from "+tbl; st = con.createStatement(); rs = st.executeQuery(SQL); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } return rs; } // public void deleteDB(String tbl,String colum, String primary) { try { SQL = "delete from "+tbl+" where "+colum+"=?"; pst = con.prepareStatement(SQL); pst.setString(1, primary); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } } public void updateDB(String nameTable, String[] namecolumn, String[] value, String condition) { try { SQL = "UPDATE " + nameTable + " SET "; for (i = 0; i <= namecolumn.length - 1; i++) { SQL += namecolumn[i] + "='" + value[i] + "'"; if (i < namecolumn.length - 1) { SQL += ","; } } SQL += " WHERE " + condition; pst = con.prepareStatement(SQL); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex); } } // public void FilterHuruf(KeyEvent a) { // if (Character.isDigit(a.getKeyChar())) { // a.consume(); // //Pesan Dialog Boleh Di Hapus Ini Hanya Sebagai Contoh // JOptionPane.showMessageDialog(null, "Masukan Hanya Huruf", "Peringatan", JOptionPane.WARNING_MESSAGE); // } // } // // //Method Untuk Menyaring Angka // public void FilterAngka(KeyEvent b) { // if (Character.isAlphabetic(b.getKeyChar())) { // b.consume(); // //Pesan Dialog Boleh Di Hapus Ini Hanya Sebagai Contoh // JOptionPane.showMessageDialog(null, "Masukan Hanya Angka", "Peringatan", JOptionPane.WARNING_MESSAGE); // } // } // // //Method Untuk Menyaring Huruf Besar // public void HurufBesar(KeyEvent c) { // if (Character.isLowerCase(c.getKeyChar())) { // c.consume(); // //Pesan Dialog Boleh Di Hapus Ini Hanya Sebagai Contoh // JOptionPane.showMessageDialog(null, "Masukan Hanya Huruf Besar", "Peringatan", JOptionPane.WARNING_MESSAGE); // } // } // // //Method Untuk Menyaring Huruf Kecil // public void HurufKecil(KeyEvent d) { // if (Character.isUpperCase(d.getKeyChar())) { // d.consume(); // //Pesan Dialog Boleh Di Hapus Ini Hanya Sebagai Contoh // JOptionPane.showMessageDialog(null, "Masukan Hanya Huruf Kecil", "Peringatan", JOptionPane.WARNING_MESSAGE); // } // } // //Method Untuk Membatasi Jumlah Karakter // public void JumlahKarakter(KeyEvent e) { // if (Charakter.getText().length() == 8) { // e.consume(); // //Pesan Dialog Boleh Di Hapus Ini Hanya Sebagai Contoh // JOptionPane.showMessageDialog(null, "Maksimal yang dimasukan Hanya 8 Karakter", "Peringatan", JOptionPane.WARNING_MESSAGE); // } // } } <file_sep>/src/SisKas/DataPenjualan.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SisKas; /** * * @author user */ import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; import Config.Conn; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.sql.Connection; import java.sql.DriverManager; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; import java.util.HashMap; import javax.swing.JFrame; import javax.swing.JOptionPane; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.view.JasperViewer; public class DataPenjualan extends javax.swing.JInternalFrame { /** * Creates new form DataPenjualan */ String tanggal; public DataPenjualan() { db = new Conn(); initComponents(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); tanggal = dateFormat.format(date); tgl_awal.setText(tanggal); tgl_akhir.setText(tanggal); showTable(); showDetail(""); } public void showTable() { String cari = txtCari.getText(); String tglAwal = tgl_awal.getText() ; String tglAkhir = tgl_akhir.getText() ; // if (tgl_awal.getText()=="") { // tglAwal = tanggal; // } // if (tgl_akhir.getText()==""){ // tglAkhir=tanggal; // } try { tbmPenjualan = new DefaultTableModel(new String[]{"Kode Transaksi", "Tanggal", "Jumlah Barang", "Total Harga", "Total Bayar", "Kembalian"},0); ResultSet rs; rs = db.selectDB("tb_transaksi WHERE tgl_transaksi >= '"+tglAwal+"' and tgl_transaksi <= '"+tglAkhir+"' and kd_transaksi LIKE '%"+cari+"%'"); while (rs.next()) { tbmPenjualan.addRow(new Object[]{ rs.getString("kd_transaksi"), rs.getString("tgl_transaksi"), rs.getString("jml_barang"), rs.getString("total_tagihan"), rs.getString("total_bayar"), rs.getString("kembalian") }); } } catch (SQLException ex) { Logger.getLogger(DataPenjualan.class.getName()).log(Level.SEVERE, null, ex); } tb_transaksi.setModel(tbmPenjualan); } public void showDetail(String getKode) { try { tbmDetail = new DefaultTableModel(new String[]{"Kode Barang", "Nama Barang", "Qty", "Sub Total"},0); ResultSet rs; rs = db.selectDB("tb_detail,tb_barang where tb_detail.kd_barang= tb_barang.kd_barang and kd_transaksi = '"+getKode+"'"); while (rs.next()) { tbmDetail.addRow(new Object[]{ rs.getString("tb_detail.kd_barang"), rs.getString("tb_barang.nama_barang"), rs.getString("tb_detail.qty"), rs.getString("tb_detail.sub_total") }); } } catch (SQLException ex) { Logger.getLogger(DataPenjualan.class.getName()).log(Level.SEVERE, null, ex); } tblDetail.setModel(tbmDetail); } /** * 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() { jLabel2 = new javax.swing.JLabel(); tgl_awal = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); tgl_akhir = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); tb_transaksi = new javax.swing.JTable(); txtCari = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); btnOk = new javax.swing.JButton(); btnPrint = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); tblDetail = new javax.swing.JTable(); lbl = new javax.swing.JLabel(); kode = new javax.swing.JLabel(); tglTransaksi = new javax.swing.JLabel(); setTitle("Data Penjualan"); jLabel2.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel2.setText("Tanggal"); jLabel1.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel1.setText("S/D"); tb_transaksi.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "Kode", "Tanggal", "T. Tagihan", "T. Bayar", "Kembalian", "Aksi" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); tb_transaksi.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tb_transaksiMouseClicked(evt); } }); jScrollPane1.setViewportView(tb_transaksi); txtCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCariActionPerformed(evt); } }); txtCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtCariKeyTyped(evt); } }); jLabel3.setText("Cari (Kode Transaksi) :"); btnOk.setBackground(new java.awt.Color(0, 153, 208)); btnOk.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N btnOk.setForeground(new java.awt.Color(255, 255, 255)); btnOk.setText("OK"); btnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOkActionPerformed(evt); } }); btnPrint.setBackground(new java.awt.Color(0, 153, 208)); btnPrint.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N btnPrint.setForeground(new java.awt.Color(255, 255, 255)); btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-print-48.png"))); // NOI18N btnPrint.setText("Print "); btnPrint.setToolTipText(""); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); tblDetail.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" } )); jScrollPane2.setViewportView(tblDetail); lbl.setText("Detail Transaksi:"); kode.setText("Kode : Txxxxxxxxxxx"); tglTransaksi.setText("Tanggal: yyyy-MM-dd"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 635, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(365, 365, 365) .addComponent(btnPrint))) .addGap(18, 18, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lbl) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(kode, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tglTransaksi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)) .addGap(30, 30, 30)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tgl_awal, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(tgl_akhir, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnOk) .addGap(79, 681, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(tgl_awal, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(tgl_akhir, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnOk)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnPrint, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(kode, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tglTransaksi, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCariActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtCariActionPerformed private void txtCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCariKeyTyped // TODO add your handling code here: showTable(); }//GEN-LAST:event_txtCariKeyTyped private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed // TODO add your handling code here: showTable(); }//GEN-LAST:event_btnOkActionPerformed private void tb_transaksiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tb_transaksiMouseClicked // TODO add your handling code here: int row; row = tb_transaksi.getSelectedRow(); String kdTransaksi = tb_transaksi.getValueAt(row, 0).toString(); String tgl = tb_transaksi.getValueAt(row, 1).toString(); showDetail(kdTransaksi); kode.setText("Kode: "+kdTransaksi); tglTransaksi.setText("Tanggal: "+tgl); }//GEN-LAST:event_tb_transaksiMouseClicked private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed // TODO add your handling code here: Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } try { conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db_siskas","root",""); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } // String location = "C:\\Users\\<NAME>\\OneDrive\\Documents\\NetBeansProjects\\"; String file= "C:\\Users\\<NAME>\\OneDrive\\Desktop\\MATKUL\\SMT 2\\WSIBD\\siskas\\src\\SisKas\\dataTransaksi.jrxml"; JasperReport jr; try { jr = JasperCompileManager.compileReport(file); JasperPrint jp = JasperFillManager.fillReport(jr, null, conn); net.sf.jasperreports.swing.JRViewer jv = new net.sf.jasperreports.swing.JRViewer(jp); // JasperViewer.viewReport(jp); JFrame jf = new JFrame(); jf.getContentPane().add(jv); jf.validate(); jf.setVisible(true); jf.setSize(new Dimension(1200,900)); jf.setLocation(300,100); jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); jf.setTitle("Struk Pembelian"); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } }//GEN-LAST:event_btnPrintActionPerformed DefaultTableModel tbmPenjualan; DefaultTableModel tbmDetail; Conn db; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnOk; private javax.swing.JButton btnPrint; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel kode; private javax.swing.JLabel lbl; private javax.swing.JTable tb_transaksi; private javax.swing.JTable tblDetail; private javax.swing.JLabel tglTransaksi; private javax.swing.JTextField tgl_akhir; private javax.swing.JTextField tgl_awal; private javax.swing.JTextField txtCari; // End of variables declaration//GEN-END:variables } <file_sep>/Readme.txt Workshop Sistem Informasi Desktop Golongan C kelompok 1 - buat database dengan nama db_siskas - import database - buka aplikasi di netbeant - ubah semua lokasi file report yang ada pada tombol print - jalankan aplikasi - hak akses: - pegawai username: pegawai password: <PASSWORD> - admin master username: admin password: <PASSWORD> cp: <EMAIL> <EMAIL> list pembagian tugas project: https://docs.google.com/spreadsheets/d/1tOB9AnahyJHLq4UjfybSE50XDByFfl6Gia-ZJpP4zvU/edit?usp=sharing <file_sep>/src/SisKas/MenuAdmin.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SisKas; import Config.Conn; import java.awt.Dimension; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.view.JasperViewer; /** * * @author user */ public class MenuAdmin extends javax.swing.JInternalFrame { /** * Creates new form MenuAdmin */ public MenuAdmin() { db = new Conn(); initComponents(); btnDelete.setEnabled(false); btnUpdate.setEnabled(false); showTable(); int row; row = tblAdm.getRowCount(); String id_admin = tblAdm.getValueAt(row-1, 1).toString(); int i = Integer.parseInt(id_admin.substring(3))+1; adminId.setText("adm"+i); adminId.setEnabled(false); } public void showTable() { String cari = txtCari.getText(); String column=""; if (ListCari.getSelectedItem()=="Kode Admin") { column="admin_id"; }else if (ListCari.getSelectedItem()=="Nama Admin") { column="nama"; } try { tbmAdm = new DefaultTableModel(new String[]{"NO", "Id Admin ", "Nama ", "Telp", "Alamat", "Username", "Password", "Hak Akses"},0); ResultSet rs; int i=1; rs = db.selectDB("tb_admin WHERE "+column+" LIKE '%"+cari+"%'"); while (rs.next()) { String hakAkses=""; if (Integer.parseInt(rs.getString("akses"))==1) { hakAkses ="Admin Master"; }else{ hakAkses ="Pegawai"; } tbmAdm.addRow(new Object[]{ i, rs.getString("admin_id"), rs.getString("nama"), rs.getString("telp"), rs.getString("alamat"), rs.getString("username"), rs.getString("password"), hakAkses }); i++; } } catch (SQLException ex) { Logger.getLogger(MenuBarang.class.getName()).log(Level.SEVERE, null, ex); } tblAdm.setModel(tbmAdm); } /** * 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() { jComboBox1 = new javax.swing.JComboBox<>(); jInternalFrame1 = new javax.swing.JInternalFrame(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jTextField6 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jTextField4 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jTable3 = new javax.swing.JTable(); jLabel11 = new javax.swing.JLabel(); nmAdmin = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); user = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); pass = new javax.swing.JTextField(); btnClear = new javax.swing.JButton(); btnUpdate = new javax.swing.JButton(); btnInser = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); tblAdm = new javax.swing.JTable(); jScrollPane1 = new javax.swing.JScrollPane(); alamat = new javax.swing.JTextArea(); telp = new javax.swing.JTextField(); akses = new javax.swing.JComboBox<>(); adminId = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); btnDelete = new javax.swing.JButton(); txtCari = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); ListCari = new javax.swing.JComboBox<>(); btnPrint = new javax.swing.JButton(); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); setTitle("Data Admin"); setMinimumSize(new java.awt.Dimension(1070, 1151)); jLabel1.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel1.setText("Kode Barang"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel3.setText("Nama Barang"); jLabel7.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel7.setText("Satuan"); jLabel6.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel6.setText("Stok"); jLabel4.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel4.setText("Harga Beli"); jLabel5.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel5.setText("Harga Jual"); jButton6.setText("UP"); jTable3.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "Kode ", "Nama Barang", "Satuan", "Harga Beli", "Harga Jual", "Stok", "Aksi" } )); jScrollPane3.setViewportView(jTable3); javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane()); jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout); jInternalFrame1Layout.setHorizontalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addGap(18, 18, 18) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField2) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton6))) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(168, 168, 168)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(95, 95, 95)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3) .addContainerGap()) ); jInternalFrame1Layout.setVerticalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinner1)))) .addGap(3, 3, 3)) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(104, 104, 104) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(82, 82, 82) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(337, 337, 337)) ); jLabel11.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel11.setText("Nama"); nmAdmin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nmAdminActionPerformed(evt); } }); jLabel13.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel13.setText("Telepon"); jLabel12.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel12.setText("Akses"); jLabel8.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel8.setText("Username"); jLabel10.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel10.setText("Alamat"); jLabel9.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel9.setText("Password"); btnClear.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-minus-48.png"))); // NOI18N btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-checkmark-48.png"))); // NOI18N btnUpdate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUpdateActionPerformed(evt); } }); btnInser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-plus-48.png"))); // NOI18N btnInser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnInserActionPerformed(evt); } }); tblAdm.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "No", "Nama", "Telepon", "Alamat", "Username", "Password", "Aksi" } )); tblAdm.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblAdmMouseClicked(evt); } }); jScrollPane4.setViewportView(tblAdm); alamat.setColumns(20); alamat.setRows(5); jScrollPane1.setViewportView(alamat); akses.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Pegawai", "Admin Master" })); akses.setToolTipText(""); adminId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adminIdActionPerformed(evt); } }); jLabel14.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N jLabel14.setText("ID Admin"); btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-trash-48.png"))); // NOI18N btnDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteActionPerformed(evt); } }); txtCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCariActionPerformed(evt); } }); txtCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtCariKeyTyped(evt); } }); jLabel2.setText("Cari Admin"); ListCari.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nama Admin", "Kode Admin" })); ListCari.setToolTipText(""); ListCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ListCariActionPerformed(evt); } }); btnPrint.setBackground(new java.awt.Color(0, 153, 208)); btnPrint.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N btnPrint.setForeground(new java.awt.Color(255, 255, 255)); btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SisKas/icons/icons8-print-48.png"))); // NOI18N btnPrint.setText("Print "); btnPrint.setToolTipText(""); btnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPrintActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(akses, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(adminId, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(telp, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nmAdmin, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(ListCari, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnInser, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnPrint)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pass) .addComponent(user) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGap(30, 30, 30)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 597, Short.MAX_VALUE) .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 597, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(adminId, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nmAdmin, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(telp, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(akses, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jLabel8)) .addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(btnUpdate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnInser, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ListCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(btnPrint, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 351, Short.MAX_VALUE) .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 351, Short.MAX_VALUE))) ); btnClear.getAccessibleContext().setAccessibleDescription(""); btnUpdate.getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void nmAdminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nmAdminActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nmAdminActionPerformed private void btnInserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserActionPerformed // TODO add your handling code here: String hakAkes=""; if (akses.getSelectedItem()=="Admin Master") { hakAkes="1"; }else{ hakAkes="0"; } String[] colom = { "admin_id", "nama", "telp", "alamat", "username", "<PASSWORD>", "akses" }; String[] value = { adminId.getText(), nmAdmin.getText(), telp.getText(), alamat.getText(), user.getText(), pass.getText(), hakAkes }; // if (hrgBeli.getText().matches("[0-9]*")&&hrgJual.getText().matches("[0-9]*")&&stok.getText().matches("[0-9]*")) { db.insertDB("tb_admin", colom, value); showTable(); btnClearActionPerformed(evt); // } else { // JOptionPane.showMessageDialog(null, "Kolom harga dan stok harus angka", "Peringatan", JOptionPane.WARNING_MESSAGE); // } }//GEN-LAST:event_btnInserActionPerformed private void tblAdmMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAdmMouseClicked // TODO add your handling code here: int row; row = tblAdm.getSelectedRow(); adminId.setText(tblAdm.getValueAt(row, 1).toString()); nmAdmin.setText(tblAdm.getValueAt(row, 2).toString()); telp.setText(tblAdm.getValueAt(row, 3).toString()); alamat.setText(tblAdm.getValueAt(row, 4).toString()); user.setText(tblAdm.getValueAt(row, 5).toString()); pass.setText(tblAdm.getValueAt(row, 6).toString()); akses.setSelectedItem(tblAdm.getValueAt(row, 7).toString()); btnDelete.setEnabled(true); btnUpdate.setEnabled(true); btnInser.setEnabled(false); }//GEN-LAST:event_tblAdmMouseClicked private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed // TODO add your handling code here: String hakAkses=""; if (akses.getSelectedItem()=="Admin Master") { hakAkses="1"; }else{ hakAkses="0"; } String[] colom = { "nama", "telp", "alamat", "username", "password", "akses" }; String[] value = { nmAdmin.getText(), telp.getText(), alamat.getText(), user.getText(), pass.getText(), hakAkses }; // if (hrgBeli.getText().matches("[0-9]*")&&hrgJual.getText().matches("[0-9]*")&&stok.getText().matches("[0-9]*")) { String primaryKey =adminId.getText(); db.updateDB("tb_admin", colom, value, "admin_id = '"+primaryKey+"'"); showTable(); // } else { // JOptionPane.showMessageDialog(null, "Kolom harga dan stok harus angka", "Peringatan", JOptionPane.WARNING_MESSAGE); // } }//GEN-LAST:event_btnUpdateActionPerformed private void adminIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adminIdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adminIdActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed // TODO add your handling code here: nmAdmin.setText(""); telp.setText(""); alamat.setText(""); user.setText(""); pass.setText(""); akses.setSelectedItem("Pegawai"); btnDelete.setEnabled(false); btnUpdate.setEnabled(false); btnInser.setEnabled(true); }//GEN-LAST:event_btnClearActionPerformed private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed // TODO add your handling code here: String Primary= adminId.getText(); int confirm =JOptionPane.showConfirmDialog(this,"Yakin hapus "+Primary+"?","Hapus data",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); if (confirm == JOptionPane.YES_OPTION){ db.deleteDB("tb_admin", "admin_id", Primary); showTable(); }if(confirm == JOptionPane.NO_OPTION){ } }//GEN-LAST:event_btnDeleteActionPerformed private void txtCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCariActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtCariActionPerformed private void txtCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCariKeyTyped // TODO add your handling code here: showTable(); }//GEN-LAST:event_txtCariKeyTyped private void ListCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ListCariActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ListCariActionPerformed private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed // TODO add your handling code here: Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } try { conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db_siskas","root",""); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } // String location = "C:\\Users\\<NAME>\\OneDrive\\Documents\\NetBeansProjects\\"; String file= "C:\\Users\\<NAME>\\OneDrive\\Desktop\\MATKUL\\SMT 2\\WSIBD\\siskas\\src\\SisKas\\dataAdmin.jrxml"; JasperReport jr; try { jr = JasperCompileManager.compileReport(file); JasperPrint jp = JasperFillManager.fillReport(jr, null, conn); net.sf.jasperreports.swing.JRViewer jv = new net.sf.jasperreports.swing.JRViewer(jp); // JasperViewer.viewReport(jp); JFrame jf = new JFrame(); jf.getContentPane().add(jv); jf.validate(); jf.setVisible(true); jf.setSize(new Dimension(1200,900)); jf.setLocation(300,100); jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); jf.setTitle("Laporan Data Admin"); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE,null,ex); } }//GEN-LAST:event_btnPrintActionPerformed Conn db; DefaultTableModel tbmAdm; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> ListCari; private javax.swing.JTextField adminId; private javax.swing.JComboBox<String> akses; private javax.swing.JTextArea alamat; private javax.swing.JButton btnClear; private javax.swing.JButton btnDelete; private javax.swing.JButton btnInser; private javax.swing.JButton btnPrint; private javax.swing.JButton btnUpdate; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JInternalFrame jInternalFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSpinner jSpinner1; private javax.swing.JTable jTable3; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField6; private javax.swing.JTextField nmAdmin; private javax.swing.JTextField pass; private javax.swing.JTable tblAdm; private javax.swing.JTextField telp; private javax.swing.JTextField txtCari; private javax.swing.JTextField user; // End of variables declaration//GEN-END:variables } <file_sep>/db_siskas.sql -- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 20, 2021 at 09:44 AM -- Server version: 10.4.18-MariaDB -- PHP Version: 8.0.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `db_siskas` -- -- -------------------------------------------------------- -- -- Table structure for table `tb_admin` -- CREATE TABLE `tb_admin` ( `admin_id` varchar(13) NOT NULL, `nama` varchar(50) NOT NULL, `telp` varchar(13) NOT NULL, `alamat` text NOT NULL, `username` varchar(25) NOT NULL, `password` varchar(25) NOT NULL, `akses` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tb_admin` -- INSERT INTO `tb_admin` (`admin_id`, `nama`, `telp`, `alamat`, `username`, `password`, `akses`) VALUES ('adm1', '<NAME>', '082267687322', 'jl. Merbabu Rt.2 Rw. 20. desa tanggul wetan, kec. Tanggul, Kab Jember', 'asr', '24434', 1), ('adm2', '<NAME>', '082345678912', 'Probolinggo', 'cph', '11111', 0), ('adm3', 'Kelompok 1', '08123456789', 'coba ', 'admin', 'admin', 1); -- -------------------------------------------------------- -- -- Table structure for table `tb_barang` -- CREATE TABLE `tb_barang` ( `id` int(11) NOT NULL, `kd_barang` varchar(13) NOT NULL, `nama_barang` varchar(50) NOT NULL, `satuan` varchar(25) NOT NULL, `harga_beli` int(11) NOT NULL, `harga_jual` int(11) NOT NULL, `stok` int(7) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tb_barang` -- INSERT INTO `tb_barang` (`id`, `kd_barang`, `nama_barang`, `satuan`, `harga_beli`, `harga_jual`, `stok`) VALUES (1, 'brg1', 'Bolpoint Honaga', 'pcs', 1500, 2000, 72), (2, 'brg2', 'Busur', 'pcs', 1000, 2000, 30), (3, 'brg3', 'Spidol Warna', 'pack', 13000, 14000, 33), (4, 'brg4', 'Kwitansi', 'pcs', 3000, 4000, 4), (5, 'brg5', 'Buku Gambar A4', 'pcs', 2000, 3000, 0), (6, 'brg6', 'Buku Gambar A3', 'pcs', 5000, 6000, 30), (7, 'brg7', 'Kaos Kaki', 'pcs', 4000, 5000, 2), (8, 'brg8', 'Maps Kertas', 'pcs', 500, 1000, 32), (9, 'brg9', 'Maps Plastik', 'pcs', 2000, 3000, 9), (10, 'brg10', 'Hasduk', 'pcs', 14000, 16000, 50), (11, 'brg11', '<NAME>', 'pack', 13000, 14000, 39), (12, 'brg12', 'spidol', 'pcs', 1500, 2500, 48), (13, 'brg13', 'K<NAME>', 'Lembar', 200, 250, 21), (14, 'brg14', 'K<NAME>', 'Lembar', 5000, 6000, 9), (15, 'brg15', 'Kertas Manila', 'Lembar', 2000, 3000, 11), (16, 'brg16', 'Nota', 'pcs', 2500, 3000, 4), (17, 'brg17', 'Buku Isi 38', 'pack', 20000, 22000, 11), (18, 'brg18', 'Buku Isi 58', 'pcs', 3000, 4500, 39), (19, 'brg19', 'penggaris', 'pcs', 1500, 2500, 20), (20, 'brg20', 'buku', 'pack', 11000, 15000, 43), (21, 'brg21', 'Pencil', 'pcs', 500, 1000, 12), (22, 'brg22', 'Penghapus', 'pcs', 1500, 2000, 20), (23, 'brg23', 'Sendal', 'pcs', 18000, 20000, 30), (25, 'brg24', 'Sampul', 'pcs', 250, 500, 20), (26, 'brg25', 'tas', 'pcs', 3000, 4000, 10), (27, 'brg26', 'Bolpoint Faber Castel', 'pcs', 2500, 3000, 80), (28, 'brg27', 'softcase', 'pcs', 7500, 10000, 15), (29, 'brg28', 'tupperware', 'pcs', 50000, 85000, 20); -- -------------------------------------------------------- -- -- Table structure for table `tb_detail` -- CREATE TABLE `tb_detail` ( `kd_transaksi` varchar(25) NOT NULL, `kd_barang` varchar(13) NOT NULL, `qty` int(4) NOT NULL, `sub_total` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tb_detail` -- INSERT INTO `tb_detail` (`kd_transaksi`, `kd_barang`, `qty`, `sub_total`) VALUES ('T202107061', 'brg1', 2, 4000), ('T202107061', 'brg2', 5, 12500), ('T202107071', 'brg1', 1, 2000), ('T202107071', 'brg2', 6, 15000), ('T202107072', 'brg1', 1, 2000), ('T202107072', 'brg5', 1, 3000), ('T202107072', 'brg12', 1, 2500), ('T202107072', 'brg7', 5, 25000), ('T202107072', 'brg16', 16, 48000), ('T202107072', 'brg17', 2, 44000), ('T202107073', 'brg1', 1, 2000), ('T202107073', 'brg7', 3, 15000), ('T202107073', 'brg13', 15, 3750), ('T202107073', 'brg17', 6, 132000), ('T202107073', 'brg15', 1, 3000), ('T202107081', 'brg7', 10, 50000), ('T202107082', 'brg2', 1, 2000), ('T202107083', 'brg1', 1, 2000), ('T202107084', 'brg2', 1, 2000), ('T202107085', 'brg5', 6, 18000), ('T202107085', 'brg3', 2, 28000), ('T202107085', 'brg1', 10, 20000), ('T202107086', 'brg1', 10, 20000), ('T202107087', 'brg1', 1, 2000), ('T202107087', 'brg2', 1, 2000), ('T202107088', 'brg2', 1, 2000), ('T202107181', 'brg2', 1, 2000), ('T202107181', 'brg3', 1, 14000), ('T202107201', 'brg3', 1, 14000), ('T202107201', 'brg1', 2, 4000), ('T202107202', 'brg5', 1, 3000), ('T202107202', 'brg1', 1, 2000), ('T202107203', 'brg1', 1, 2000), ('T202107207', 'brg2', 1, 2000), ('T202107208', 'brg3', 1, 14000), ('T202107209', 'brg4', 1, 4000), ('T2021072010', 'brg4', 1, 4000), ('T2021072011', 'brg2', 1, 2000), ('T2021072011', 'brg4', 1, 4000), ('T2021072011', 'brg3', 1, 14000), ('T2021072011', 'brg8', 1, 1000), ('T2021072011', 'brg13', 3, 750), ('T2021072012', 'brg2', 1, 2000), ('T2021072013', 'brg2', 1, 2000), ('T2021072013', 'brg1', 3, 6000), ('T2021072013', 'brg20', 1, 15000), ('T2021072013', 'brg18', 1, 4500), ('T2021072013', 'brg17', 1, 22000), ('T2021072013', 'brg15', 5, 15000), ('T2021072014', 'brg4', 1, 4000), ('T2021072014', 'brg2', 1, 2000), ('T2021072014', 'brg5', 1, 3000), ('T2021072014', 'brg4', 1, 4000), ('T2021072014', 'brg13', 1, 250), ('T2021072016', 'brg1', 1, 2000), ('T2021072017', 'brg3', 1, 14000), ('T2021072017', 'brg8', 1, 1000), ('T2021072017', 'brg11', 1, 14000), ('T2021072018', 'brg4', 1, 4000), ('T2021072018', 'brg5', 1, 3000), ('T2021072019', 'brg9', 1, 3000), ('T2021072019', 'brg8', 1, 1000), ('T2021072019', 'brg14', 1, 6000); -- -------------------------------------------------------- -- -- Table structure for table `tb_transaksi` -- CREATE TABLE `tb_transaksi` ( `no` int(11) NOT NULL, `kd_transaksi` varchar(25) NOT NULL, `tgl_transaksi` varchar(10) NOT NULL, `jml_barang` int(7) DEFAULT NULL, `total_tagihan` int(11) NOT NULL, `total_bayar` int(11) NOT NULL, `kembalian` int(11) NOT NULL, `ket` text DEFAULT NULL, `admin_id` varchar(13) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tb_transaksi` -- INSERT INTO `tb_transaksi` (`no`, `kd_transaksi`, `tgl_transaksi`, `jml_barang`, `total_tagihan`, `total_bayar`, `kembalian`, `ket`, `admin_id`) VALUES (1, 'T202107061', '2021-07-06', 7, 16500, 50000, 33500, '', 'adm1'), (2, 'T202107071', '2021-07-07', 7, 17000, 20000, 3000, '', 'adm1'), (3, 'T202107072', '2021-07-07', 26, 124500, 150000, 25500, '', 'adm1'), (4, 'T202107073', '2021-07-07', 26, 155750, 200000, 44250, '', 'adm1'), (5, 'T202107081', '2021-07-08', 10, 50000, 100000, 50000, '', 'adm1'), (6, 'T202107082', '2021-07-08', 1, 2000, 5000, 3000, '', 'adm1'), (7, 'T202107083', '2021-07-08', 1, 2000, 5000, 3000, '', 'adm1'), (8, 'T202107084', '2021-07-08', 1, 2000, 10000, 8000, '', 'adm1'), (9, 'T202107085', '2021-07-08', 18, 66000, 100000, 34000, '', 'adm1'), (10, 'T202107086', '2021-07-08', 10, 20000, 50000, 30000, '', 'adm1'), (11, 'T202107087', '2021-07-08', 2, 4000, 5000, 1000, '', 'adm1'), (12, 'T202107088', '2021-07-08', 1, 2000, 5000, 3000, '', 'adm1'), (13, 'T202107181', '2021-07-18', 2, 16000, 20000, 4000, '', 'adm1'), (14, 'T202107201', '2021-07-20', 3, 18000, 20000, 2000, '', 'adm3'), (15, 'T202107202', '2021-07-20', 2, 5000, 5000, 0, '', 'adm3'), (16, 'T202107203', '2021-07-20', 1, 2000, 5000, 3000, '', 'adm3'), (17, 'T202107204', '2021-07-20', 0, 2000, 5000, 3000, '', 'adm3'), (18, 'T202107205', '2021-07-20', 0, 2000, 5000, 3000, '', 'adm3'), (19, 'T202107206', '2021-07-20', 0, 2000, 5000, 3000, '', 'adm3'), (20, 'T202107207', '2021-07-20', 1, 2000, 5000, 3000, '', 'adm1'), (21, 'T202107208', '2021-07-20', 1, 14000, 15000, 1000, '', 'adm3'), (22, 'T202107209', '2021-07-20', 1, 4000, 5000, 1000, '', 'adm3'), (23, 'T2021072010', '2021-07-20', 1, 4000, 10000, 6000, '', 'adm3'), (24, 'T2021072011', '2021-07-20', 7, 21750, 25000, 3250, '', 'adm3'), (25, 'T2021072012', '2021-07-20', 1, 2000, 20000, 18000, '', 'adm3'), (26, 'T2021072013', '2021-07-20', 12, 64500, 70000, 5500, '', 'adm1'), (27, 'T2021072014', '2021-07-20', 3, 7250, 10000, 2750, '', 'adm3'), (28, 'T2021072015', '2021-07-20', 0, 7250, 10000, 2750, '', 'adm3'), (29, 'T2021072016', '2021-07-20', 1, 2000, 5000, 3000, '', 'adm3'), (30, 'T2021072017', '2021-07-20', 3, 29000, 30000, 1000, '', 'adm3'), (31, 'T2021072018', '2021-07-20', 2, 7000, 10000, 3000, '', 'adm3'), (32, 'T2021072019', '2021-07-20', 2, 7000, 10000, 3000, NULL, 'adm1'), (33, 'T2021072020', '2021-07-20', 0, 7000, 10000, 3000, NULL, 'adm1'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tb_admin` -- ALTER TABLE `tb_admin` ADD PRIMARY KEY (`admin_id`); -- -- Indexes for table `tb_barang` -- ALTER TABLE `tb_barang` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tb_detail` -- ALTER TABLE `tb_detail` ADD KEY `detail` (`kd_transaksi`), ADD KEY `detail barang` (`kd_barang`); -- -- Indexes for table `tb_transaksi` -- ALTER TABLE `tb_transaksi` ADD PRIMARY KEY (`no`), ADD KEY `melayani` (`admin_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tb_barang` -- ALTER TABLE `tb_barang` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31; -- -- AUTO_INCREMENT for table `tb_transaksi` -- ALTER TABLE `tb_transaksi` MODIFY `no` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; 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 */;
d71b2bb28fa3b945b9105ff49c2067388ef22626
[ "Java", "Text", "SQL" ]
6
Java
ahsar04/siskas
9f74f17b8fe0829ae482a234d42ff20293a169cb
0d0db7a3b786fb3d1431ce47b596804403de1fe8
refs/heads/master
<repo_name>weedwong/webpack-demo<file_sep>/readme.md ### webpack 打包构建配置模板项目<file_sep>/config/loader/dva-config-loader.js module.exports = function (source) { // todo var paths = this.context.replace(/\//ig,'\\').split('\\'), moduleName = paths[paths.length -2]; if (moduleName === 'dva-router-config') { source = source.replace("var _convertRoutes = require('./convertRoutes');",` var _convertRoutes = require('./convertRoutes'); var _Redirect = require('./Redirect'); var _Redirect2 = _interopRequireDefault(_Redirect); `).replace('exports.matchRoutes = _matchRoutes2.default;',` exports.matchRoutes = _matchRoutes2.default; exports.redirect = _Redirect2.default; `); } if (moduleName === 'dva') { source = source.replace('require("history/createHashHistory")','require("history").createHashHistory'); } return source; }<file_sep>/src/router/index.js import React from 'react'; import { Router, Route } from 'dva/router'; import Home from '../pages/home/index'; const router = ({ history }) => { return ( <Router history={history}> <Route path="/home" component={Home} /> </Router> ); } export default router;<file_sep>/config/webpack.config.dev.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', devServer: { port: 3000, open: true, inline: true, publicPath: path.join(__dirname, './../dist/') }, plugins: [ new HtmlWebpackPlugin({ inject: true, filename: '../index.html', template: path.join(__dirname, './../public/index.ejs') }) ] }<file_sep>/scripts/build.js 'use strict'; const Webpack = require('webpack'); const webpackConfig = require('../config/webpack.config.base'); const webpackConfigDev = require('../config/webpack.config.prod'); const {devServer, ...prodConfig} = webpackConfigDev; process.env.NODE_ENV = prodConfig.mode; /** * 使用webpack打包 */ const compiler = Webpack(Object.assign({}, webpackConfig, prodConfig)); compiler.run((err) => { if (err) { console.log(err) } });
7332eafcd599893d742d421f894525989b29355f
[ "Markdown", "JavaScript" ]
5
Markdown
weedwong/webpack-demo
c619a8cbd8ba04d8067e4b0ac7b58294604ba1da
6d75669cbe545337e9e3d5f0815e3064a0024500
refs/heads/main
<repo_name>tanujgyan/Data_Structures_using_Python<file_sep>/CountingValleys.py #!/bin/python3 import math import os import random import re import sys def countingValleys(steps, path): level=0 valley=0 for p in path: if(p=='U'): level+=1 elif(p=='D'): level-=1 if(level==0 and p=='U'): valley+=1 return valley if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') fptr = sys.stdout steps = int(input().strip()) path = input() result = countingValleys(steps, path) fptr.write(str(result) + '\n') fptr.close()<file_sep>/JumpingOnClouds.py #!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): jumps=0 index=0 while index<len(c): #try jumping 2 clouds if(index+2<len(c) and c[index+2]==0): index+=2 jumps+=1 #try jumping 1 cloud if 2 clouds are not feasible elif(index+1 <len(c) and c[index+1]==0): index+=1 jumps+=1 #if you land on last cloud break out of the loop and return result if(index==len(c)-1): break return jumps if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') fptr = sys.stdout n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c) fptr.write(str(result) + '\n') fptr.close() <file_sep>/README.md # Data_Structures_using_Python Hacker Rank Interview Preparation Kit Questions using Python 3
74461e30ffb4243307946ef44d4c6b53284a071c
[ "Markdown", "Python" ]
3
Python
tanujgyan/Data_Structures_using_Python
968b01d0a69e78a3341d5d18b98492436c4f9335
825513d0e4373ab1ff41463026afe4c2da0169f6
refs/heads/master
<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 PokerStart { public partial class frmCadastroJogadores : Form { public frmCadastroJogadores() { InitializeComponent(); textID.Enabled = false; } private void BotaoCriarContaBancaria_Click(object sender, EventArgs e) { } } }
fe45c504321af29a3360d5257664ce84b422540d
[ "C#" ]
1
C#
diego-fagundes/PokerStart
84e5a9cb6662b6accbf8f6b372768d8825e5e02d
16bd33134eae59d38eb5f3b82742069004687cb8
refs/heads/master
<file_sep> name = input("What's your name?") name = name.strip().title() print("Nice to meet you " + name) age = input("How old are you?") print("Interesting, you are " + age + " years old.") age = int(age) days_in_year = 365.242 days_old = age * days_in_year print("You are " + str(days_old) + " days old")
64b02c5a37e294cb4b368a053924f4d2fe1c1d11
[ "Python" ]
1
Python
smuch738/python-projects
fe8a8e9da8b0ac144f968c0cec9132a6c538fbcb
3c92ec0b325a153b22c7021fecc6ad4aa1fa3756
refs/heads/master
<file_sep># Using `require` * esm then newrelic ``` $ node -r esm -r newrelic run_require.js Is pg instrumented? true ``` * NR then esm ``` $ node -r newrelic -r esm run_require.js Is pg instrumented? false ``` # Using `import` * esm then newrelic ``` $ node -r esm -r newrelic run_esm.js Is pg instrumented? false ``` * NR then esm ``` $ node -r newrelic -r esm run_esm.js Is pg instrumented? false ``` <file_sep>'use strict'; import * as Pg from 'pg' const client = new Pg.Client(); console.log('Is pg instrumented?', client.query.toString().includes('wrapper'));
0ad4bf1115f5556bee8e43cdfd9c218f43ed2dc8
[ "Markdown", "JavaScript" ]
2
Markdown
vdeturckheim/esm-nr-pg
32095e5b3ec50177f3bfb538ec1e22cd2c7e825b
470b20032f0b6ac8bdeef78edb9eb48e7f1d0578
refs/heads/master
<file_sep>#!/usr/bin/env python3 import sys import datetime import requests from colorama import init init() def unix_time(dt): epoch = datetime.datetime.utcfromtimestamp(0) return int((dt - epoch).total_seconds()) - 7200 def print_menu(menu): print('\n\033[1m{} \033[36m{}\033[0m'.format(menu['title'], menu['price'])) for item in menu['menu']: print(' - ' + item) def print_version(): print('STJEREM/coop 0.0.4') if len(sys.argv) == 2 and sys.argv[1] == '--version': print_version() exit() if len(sys.argv) == 1: location = input('Location: ') else: location = sys.argv[1] data = requests.get('https://themachine.jeremystucki.com/api/v1/coop/menus/{}'.format(location)) current_day = unix_time(datetime.datetime.combine(datetime.datetime.now().date(), datetime.time())) results = data.json()['results'] if len(results) == 0: print('\033[31mno menus found for {}\033[0m'.format(location)) exit(1) for menu in results: if menu['timestamp'] == current_day: if len(sys.argv) < 3 or (len(sys.argv) == 3 and sys.argv[2] == menu['title']): print_menu(menu) print() <file_sep>// // MenuDetailViewController.swift // Coop // // Created by <NAME> on 16.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class MenuDetailViewController: UIViewController { private let menu: Menu private let dishesLabel = UILabel() init(forMenu menu: Menu) { self.menu = menu super.init(nibName: nil, bundle: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let dishesLabel = UILabel() dishesLabel.numberOfLines = menu.dishes.count dishesLabel.text = menu.dishes.joined(separator: "\n") var topSpacing = UIApplication.shared.statusBarFrame.size.height if UIDevice.current.userInterfaceIdiom == .pad { let titleLabel = UILabel() titleLabel.font = titleLabel.font.withSize(30) titleLabel.text = menu.title titleLabel.frame = CGRect(x: 20, y: topSpacing + 20, width: 0, height: 0) titleLabel.sizeToFit() view.addSubview(titleLabel) dishesLabel.frame = CGRect(x: 20, y: titleLabel.frame.maxY + 10, width: 0, height: 0) } if UIDevice.current.userInterfaceIdiom == .phone { topSpacing += navigationController!.navigationBar.bounds.size.height dishesLabel.frame = CGRect(x: 20, y: topSpacing + 20, width: 0, height: 0) } dishesLabel.sizeToFit() view.addSubview(dishesLabel) view.backgroundColor = .groupTableViewBackground } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import json import flask import pymongo from flask import Flask, Response app = Flask(__name__) db = pymongo.MongoClient('mongodb').get_database('coop') @app.route('/api/v1/coop/menus') def all_menus(): return flask.jsonify({'results': list(db.get_collection('menus').find({}, {'_id': 0, 'location_lower': 0}))}) @app.route('/api/v1/coop/menus/<location>') def menus_for_location(location): return flask.jsonify({'results': list(db.get_collection('menus') .find({'location_lower': location.lower()}, {'_id': 0, 'location': 0, 'location_lower': 0, 'location_id': 0}))}) @app.route('/api/v1/coop/menus/<location>/<timestamp>') def menus_for_location_and_timestamp(location, timestamp): try: int(timestamp) except ValueError: return Response( response=json.dumps({'results': [], 'error': 'timestamp is not an int'}), mimetype='application/json', status=400 ) return flask.jsonify( {'results': list(db.get_collection('menus') .find({'location_lower': location.lower(), 'timestamp': int(timestamp)}, {'_id': 0, 'location': 0, 'timestamp': 0, 'location_lower': 0, 'location_id': 0}))}) def get_limit(arguments): if 'limit' not in arguments: return 20 if arguments['limit'] == 'none': return None return int(arguments['limit']) @app.route('/api/v1/coop/stats') def stats(): return flask.jsonify({'results': list(db.get_collection('menu_stats').find({}, {'_id': 0, 'location_lower': 0, 'location_id': 0}))}) def aggregate_stats(aggregation, request_params, location): pipeline = [] if location is not None: pipeline.append({'$match': {'location_lower': location.lower()}}) pipeline += aggregation if 'asc' in request_params: pipeline.append({'$sort': {'count': 1}}) else: pipeline.append({'$sort': {'count': -1}}) try: limit = get_limit(request_params) except ValueError: return Response( response=json.dumps({'results': [], 'error': 'limit is not an int or "none"'}), mimetype='application/json', status=400 ) if limit is not None: pipeline.append({'$limit': limit}) return flask.jsonify({'results': list(db.get_collection('menu_stats').aggregate(pipeline))}) @app.route('/api/v1/coop/locations') def locations(): return flask.jsonify({'results': list(db.get_collection('menus').distinct('location'))}) @app.route('/api/v1/coop/stats/locations') def stats_locations(): return flask.jsonify({'results': list(db.get_collection('menu_stats').distinct('location'))}) @app.route('/api/v1/coop/stats/menus') @app.route('/api/v1/coop/stats/menus/<location>') def menu_stats(location=None): pipeline = [ { '$group': { '_id': '$menu', 'count': {'$sum': 1} } }, { '$project': { 'menu': '$_id', '_id': 0, 'count': 1 } } ] return aggregate_stats(pipeline, flask.request.args, location) @app.route('/api/v1/coop/stats/dishes') @app.route('/api/v1/coop/stats/dishes/<location>') def dishes_stats(location=None): pipeline = [ { '$unwind': '$menu' }, { '$group': { '_id': '$menu', 'count': {'$sum': 1} } }, { '$project': { 'menu': '$_id', '_id': 0, 'count': 1 } } ] return aggregate_stats(pipeline, flask.request.args, location) @app.errorhandler(404) def not_found(_): return flask.jsonify({'error': 'page not found'}), 404 if __name__ == '__main__': app.run('0.0.0.0', '80') <file_sep>import HTTPClient import Core class HTTPClientWrapper { enum HTTPClientError: Error { case invalidUrlError } enum RequestMethod { case GET } let httpClient: Client let contentNegotiation = ContentNegotiationMiddleware(mediaTypes: [JSON.self], mode: .client) init(baseUrl: URL) throws { httpClient = try Client(url: baseUrl) } convenience init(baseUrl: String) throws { guard let url = URL(string: baseUrl) else { throw HTTPClientError.invalidUrlError } try self.init(baseUrl: url) } func request(method: RequestMethod, endpoint: String) throws -> Map? { return try httpClient.get(endpoint, middleware: [contentNegotiation]).content } } <file_sep>// // LocationsViewController.swift // Coop // // Created by <NAME> on 12.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol LocationsViewControllerInput { func displayLocations(_ locations: [Location]) func displayFavoriteLocations(_ favoriteLocations: [Location]) } protocol LocationsViewControllerOutput { func viewInitialized() func viewWillBecomeVisible() func showMenus(forLocation location: Location) } class LocationsViewController: UITableViewController { var presenter: LocationsViewControllerOutput! private let searchController = UISearchController(searchResultsController: nil) private var hasFavorites: Bool { return !filteredFavoriteLocations.isEmpty } private var searchText: String { return searchController.searchBar.text!.lowercased() } fileprivate var locations = [Location]() private var filteredLocations: [Location] { return locations.filter({ $0.name.lowercased().hasPrefix(searchText) }) } fileprivate var favoriteLocations = [Location]() private var filteredFavoriteLocations: [Location] { return favoriteLocations.filter({ $0.name.lowercased().hasPrefix(searchText) }) } init() { super.init(style: .plain) } convenience required init?(coder aDecoder: NSCoder) { self.init() } override func viewWillAppear(_ animated: Bool) { presenter.viewWillBecomeVisible() } override func viewDidLoad() { definesPresentationContext = true searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false tableView.tableHeaderView = searchController.searchBar presenter.viewInitialized() } override func numberOfSections(in tableView: UITableView) -> Int { return hasFavorites ? 2 : 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 && hasFavorites { return NSLocalizedString("Favorites", comment: "") } return hasFavorites ? NSLocalizedString("All", comment: "") : nil } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (section == 0 && hasFavorites ? filteredFavoriteLocations : filteredLocations).count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let locations = indexPath.section == 0 && hasFavorites ? filteredFavoriteLocations : filteredLocations let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.accessoryType = .disclosureIndicator cell.textLabel!.text = locations[indexPath.row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let locations = indexPath.section == 0 && hasFavorites ? filteredFavoriteLocations : filteredLocations presenter.showMenus(forLocation: locations[indexPath.row]) tableView.deselectRow(at: indexPath, animated: true) } } extension LocationsViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { tableView.reloadData() } } extension LocationsViewController: LocationsViewControllerInput { func displayLocations(_ locations: [Location]) { self.locations = locations tableView.reloadData() } func displayFavoriteLocations(_ favoriteLocations: [Location]) { self.favoriteLocations = favoriteLocations tableView.reloadData() } } <file_sep>// // LocationsInteractor.swift // Coop // // Created by <NAME> on 12.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import Alamofire protocol LocationsInteractorInput { func fetchLocations() func fetchFavoriteLocations() } protocol LocationsInteractorOutput { func locationsFetched(_ locations: [Location]) func favoriteLocationsFetched(_ favoriteLocations: [Location]) func connectionErrorOccured() } class LocationsInteractor: LocationsInteractorInput { var presenter: LocationsInteractorOutput! private let url = Configuration.baseUrl.appendingPathComponent("locations") func fetchLocations() { Alamofire.request(url).responseJSON { response in var locations = [Location]() if response.result.isFailure { return self.presenter.connectionErrorOccured() } for locationName in (response.result.value! as! NSDictionary)["results"] as! NSArray { locations.append(Location(name: locationName as! String)) } self.presenter.locationsFetched(locations) } } func fetchFavoriteLocations() { var favoriteLocations = [Location]() for locationName in Configuration.favoriteLocations { favoriteLocations.append(Location(name: locationName)) } presenter.favoriteLocationsFetched(favoriteLocations) } } <file_sep>import Foundation extension Date { func getTimestampForToday() -> Int { let date = Calendar.current.startOfDay(for: Date()) // Seriously, I have no idea #if os(Linux) return Int(date.timeIntervalSince1970) - 7200 #else return Int(date.timeIntervalSince1970) #endif } } <file_sep>// // UITests.swift // UITests // // Created by <NAME> on 19.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest import UIKit class UITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } func testExample() { let app = XCUIApplication() setupSnapshot(app) app.launch() let tablesQuery = app.tables tablesQuery.staticTexts["Aarau"].tap() let aarauNavigationBar = app.navigationBars["Aarau"] aarauNavigationBar.buttons["empty star"].tap() aarauNavigationBar.buttons.element(boundBy: 0).tap() tablesQuery.staticTexts["Baden"].tap() let badenNavigationBar = app.navigationBars["Baden"] badenNavigationBar.buttons["empty star"].tap() badenNavigationBar.buttons.element(boundBy: 0).tap() snapshot("Favorites") XCUIApplication().tables.children(matching: .cell).element(boundBy: 1).tap() snapshot("Restaurant") XCUIApplication().tables.children(matching: .cell).element(boundBy: 0).tap() snapshot("Menu") } } <file_sep>import Foundation import Core class CoopAPI { let client: HTTPClientWrapper init() throws { client = try HTTPClientWrapper(baseUrl: "https://themachine.jeremystucki.com") } func getLocations() -> [String] { do { let content = try client.request(method: .GET, endpoint: "/api/v1/coop/locations") if let locations: [String] = try content?.get("results") { return locations } } catch { } return [] } func getMenus(forLocation location: String) -> [Menu] { do { let content = try client.request(method: .GET, endpoint: "/api/v1/coop/menus/\(location)/\(Date().getTimestampForToday())") if let results: [Map] = try content?.get("results") { return try parseMenus(results) } } catch { } return [] } private func parseMenus(_ menuMaps: [Map]) throws -> [Menu] { var menus = [Menu]() for menuMap in menuMaps { menus.append(try parseMenu(menuMap)) } return menus } private func parseMenu(_ menuMap: Map) throws -> Menu { return Menu(title: try menuMap.get("title"), menu: try menuMap.get("menu"), price: try menuMap.get("price")) } } <file_sep># Coop ## Supported locations - All ## Clients ### Installation on iOS The app is available from the [AppStore](https://appsto.re/ch/EAI0cb.i). ### Installation on SailfishOS The app is now available on your Jolla App Store. ### Installation on OSX There is a brew tap [available](https://github.com/bash/homebrew-coop) for coop: ```bash brew tap bash/homebrew-coop brew install coop-rust ``` ### Installation on Windows #### Powershell There is also a powershell module: ```powershell Invoke-WebRequest -OutFile CoopInstaller.ps1 -Uri https://raw.githubusercontent.com/STJEREM/coop/development/client/powershell/Installer.ps1; .\CoopInstaller.ps1 ``` ### Cross-Platform #### Java There is a java application by [@randalf98](https://github.com/randalf98). The jar can be downloaded [here](https://github.com/Randalf98/CoopApplication/releases). #### Python You can download the python script [here](https://github.com/STJEREM/coop/blob/development/client/python/coop). #### Rust A rust client is available at [bash/coop-rust](https://github.com/bash/coop-rust). <br /> ## API The api is hosted at [themachine.jeremystucki.com](https://themachine.jeremystucki.com). ### Locations #### /api/v1/coop/locations ```GET /api/v1/coop/locations``` ```json { "results": [ "Baden", "Egerkingen", "Zofingen", "Olten", "Wettingen", "Lenzburg", "Aarau", "Frick", "Luzern", "Emmenbrücke" ] } ``` Returns all supported locations. ### Menus #### /api/v1/coop/menus ```GET /api/v1/coop/menus``` ```json { "results": [ { "location": "Baden", "menu": [ "Kalbsbratwurst", "Zwiebelsauce", "R\u00f6sti", "Saisonsalat" ], "price": 12.95, "timestamp": 1461880800.0, "title": "Wochenmen\u00fc" } ] } ``` Returns all menus for all restaurants. #### /api/v1/coop/menus/\<location> ```GET /api/v1/coop/menus/Aarau``` ```json { "results": [ { "menu": [ "Kalbsbratwurst", "Zwiebelsauce", "R\u00f6sti", "Saisonsalat" ], "price": 12.95, "timestamp": 1461880800.0, "title": "Wochenmen\u00fc" } ] } ``` Returns all menus for a given restaurant. #### /api/v1/coop/menus/\<location>/\<timestamp> ```GET /api/v1/coop/menus/Aarau/1461967200``` ```json { "results": [ { "menu": [ "Kalbsbratwurst", "Zwiebelsauce", "R\u00f6sti", "Saisonsalat" ], "price": 12.95, "timestamp": 1461967200.0, "title": "Wochenmen\u00fc" } ] } ``` Returns all menus for a given restaurant and timestamp (midnight). ### Stats You can sort all stats ascending by passing ```asc``` as a query parameter. You can also provide a limit. The default limit is 20. The limit can also be set to none to get all data. #### /api/v1/coop/stats ```GET /api/v1/coop/stats``` ```json { "results": [ { "location": "Baden", "menu": [ "Pouletflügeli", "BBQ-Sauce", "Kartoffel-Wedges" ], "price": 9.95, "timestamp": 1461794400, "title": "Special" } ] } ``` Returns all menus for all restaurants for all timestamps. #### /api/v1/coop/stats/menus ```GET /api/v1/coop/stats/menus``` ```json { "results": [ { "count": 21, "menu": [ "Pouletflügeli", "BBQ-Sauce", "Kartoffel-Wedges" ] } ] } ``` Returns all menus and how many times they were listed for all restaurants for all timestamps. #### /api/v1/coop/stats/menus/\<location> ```GET /api/v1/coop/stats/menus/Aarau``` ```json { "results": [ { "count": 3, "menu": [ "Kalbsbratwurst", "Zwiebelsauce", "Rösti", "Saisonsalat" ] } ] } ``` Returns all menus and how many times they were listed for a given restaurant for all timestamps. #### /api/v1/coop/stats/dishes ```GET /api/v1/coop/stats/dishes``` ```json { "results": [ { "count": 48, "menu": "Saisonsalat" }, ] } ``` Returns all dishes and how many times they were listed for all restaurants for all timestamps. #### /api/v1/coop/stats/dishes/\<location> ```GET /api/v1/coop/stats/dishes/Aarau``` ```json { "results": [ { "count": 9, "menu": "Saisonsalat" } ] } ``` Returns all dishes and how many times they were listed for a given restaurant for all timestamps. <br /> ## Thanks to [@bash](https://github.com/bash) [@bauidch](https://github.com/bauidch) [@randalf98](https://github.com/randalf98) <file_sep>import datetime import requests import telepot import time # TODO refactor bot = telepot.Bot('<key>') def unix_time(dt): epoch = datetime.datetime.utcfromtimestamp(0) return int((dt - epoch).total_seconds()) def handle(message): sender = message['chat']['id'] if not message or message['text'] == '/start': return bot.sendMessage(sender, 'Hi, I can look up the menu plan of a coop restaurant for you. Just send me "/menus LOCATION" and I will look it up.') if message['text'][:7] != '/menus ': return bot.sendMessage(sender, 'Sorry, I don\'t understand. Please use the "/menus LOCATION" syntax.') location = message['text'][7:] current_day = unix_time(datetime.datetime.combine(datetime.datetime.now().date(), datetime.time())) print(current_day) menus = requests.get('https://themachine.jeremystucki.com/api/v1/coop/menus/{}/{}'.format(location, current_day)).json()['results'] if not menus: return bot.sendMessage(sender, 'Sorry, I did not find any menus for {} today'.format(location)) response = '' for menu in menus: response += '*{}* - _{}_'.format(menu['title'], menu['price']) for dish in menu['menu']: response += '\n{}'.format(dish) response += '\n\n' bot.sendMessage(sender, response, parse_mode='Markdown') bot.message_loop(handle) while 1: time.sleep(10) <file_sep>// // MenusViewController.swift // Coop // // Created by <NAME> on 13.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import UIKit protocol MenusViewControllerInput { func showEmptyStar() func showFullStar() func displayMenus(_ menus: [(Date, [Menu])]) } protocol MenusViewControllerOutput { func starClicked() func showMenuDetails(forMenu menu: Menu) func viewInitialized() } class MenusViewController: UITableViewController { var presenter: MenusViewControllerOutput! fileprivate var menus = [(Date, [Menu])]() init() { super.init(style: .grouped) } convenience required init?(coder aDecoder: NSCoder) { self.init() } override func viewDidLoad() { super.viewDidLoad() presenter.viewInitialized() } override func numberOfSections(in tableView: UITableView) -> Int { return menus.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let format = DateFormatter() format.dateFormat = "EEEE" return format.string(from: menus[section].0) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus[section].1.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let menu = menus[indexPath.section].1[indexPath.row] let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.textLabel?.text = menu.title cell.detailTextLabel?.text = "CHF " + String(format: "%.2f", menu.price) cell.accessoryType = .disclosureIndicator return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { presenter.showMenuDetails(forMenu: menus[indexPath.section].1[indexPath.row]) tableView.deselectRow(at: indexPath, animated: true) } func starClicked() { presenter.starClicked() } fileprivate func showBarButtonImage(_ image: UIImage) { let button = UIBarButtonItem(image: image, style: .done, target: self, action: #selector(MenusViewController.starClicked)) navigationItem.setRightBarButton(button, animated: true) } } extension MenusViewController: MenusViewControllerInput { func showEmptyStar() { showBarButtonImage(UIImage(named: "empty star")!.withRenderingMode(.alwaysOriginal)) } func showFullStar() { showBarButtonImage(UIImage(named: "full star")!.withRenderingMode(.alwaysOriginal)) } func displayMenus(_ menus: [(Date, [Menu])]) { self.menus = menus tableView.reloadData() } } <file_sep>// // MenusRouter.swift // Coop // // Created by <NAME> on 13.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol MenusRouterOutput: NetworkRouterOutput { } class MenusRouter: NetworkRouter { let viewController: UIViewController let presenter: NetworkRouterOutput // TODO: figure out why MenusRouterOutput does not work here var detailViewController: UIViewController? init(forLocation location: Location) { let viewController = MenusViewController() let interactor = MenusInteractor(forLocation: location) let presenter = MenusPresenter() viewController.title = location.name interactor.presenter = presenter viewController.presenter = presenter presenter.viewController = viewController presenter.interactor = interactor self.presenter = presenter self.viewController = viewController presenter.router = self } func showMenuDetails(forMenu menu: Menu) { let menuDetailViewController = MenuDetailRouter(forMenu: menu).viewController if UIDevice.current.userInterfaceIdiom == .phone { viewController.navigationController?.pushViewController(menuDetailViewController, animated: true) } if UIDevice.current.userInterfaceIdiom == .pad { viewController.splitViewController?.showDetailViewController(menuDetailViewController, sender: self) } self.detailViewController = menuDetailViewController } } <file_sep>// // GroupBy.swift // Coop // // Created by <NAME> on 14/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation public extension Sequence { func categorise<U : Hashable>(_ keyFunc: (Iterator.Element) -> U) -> [U:[Iterator.Element]] { var dict: [U:[Iterator.Element]] = [:] for el in self { let key = keyFunc(el) if case nil = dict[key]?.append(el) { dict[key] = [el] } } return dict } } <file_sep>cmake_minimum_required(VERSION 3.6) project(Coop) file(GLOB SOURCES Sources/*.swift Packages/*/Sources/*/*/*.swift) add_custom_target(Coop COMMAND swift build WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} SOURCES ${SOURCES} Package.swift) <file_sep>struct Menu { let title: String let menu: [String] let price: Double var pretty: String { var result = "\(title.bold) \(String(price).bold.blue)\n" for item in menu { result += "- \(item)\n" } return result } } <file_sep>// // NetworkRouter.swift // Coop // // Created by <NAME> on 17.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol NetworkRouterOutput: ConnectionErrorRouterOutput { } protocol NetworkRouter: ConnectionErrorRouterOutput { var viewController: UIViewController { get } var presenter: NetworkRouterOutput { get } } extension NetworkRouter { func retryPressed() { presenter.retryPressed() } func showConnectionError() { viewController.present(ConnectionErrorRouter(output: presenter).viewController, animated: true) } } <file_sep>// // ConnectionErrorRouter.swift // Coop // // Created by <NAME> on 16.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol ConnectionErrorRouterOutput { func retryPressed() } class ConnectionErrorRouter { let viewController: UIViewController let output: ConnectionErrorRouterOutput init(output: ConnectionErrorRouterOutput) { let alert = UIAlertController( title: NSLocalizedString("Connection error", comment: ""), message: NSLocalizedString("Make sure you are connected to the internet.", comment: ""), preferredStyle: .alert ) self.output = output self.viewController = alert alert.addAction(UIAlertAction(title: NSLocalizedString("Retry", comment: ""), style: .default, handler: { (action) in self.output.retryPressed() } )) } func retryPressed() { output.retryPressed() } } <file_sep>FROM python:3.5 ADD grabber.py . ADD config.yml . ADD requirements.txt . RUN pip install -r requirements.txt CMD python grabber.py <file_sep>#if os(Linux) import Glibc #else import Darwin #endif let api = try CoopAPI() let usage = "Usage: coop [ locations | menus <location> ]" if CommandLine.arguments.count == 1 { print(usage) exit(0) } if CommandLine.arguments[1].lowercased() == "locations" { print(api.getLocations().joined(separator: "\n")) } else if CommandLine.arguments[1].lowercased() == "menus" && CommandLine.arguments.count > 2 { api.getMenus(forLocation: CommandLine.arguments[2]).forEach({ print($0.pretty) }) } else { print(usage) } <file_sep>// // Configuration.swift // Coop // // Created by <NAME> on 12/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation struct Configuration { private static let mode = Bundle.main.infoDictionary!["Configuration"] as! String private static let confiugrations = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "Configuration", ofType: "plist")!)! private static let currentConfiguration = confiugrations[mode] as! NSDictionary static let baseUrl = URL(string: currentConfiguration["API-Endpoint"] as! String)! static var favoriteLocations: Set<String> { get { return Set(UserDefaults.standard.stringArray(forKey: "favoriteLocations") ?? []) } set(newValue) { UserDefaults.standard.set(Array(newValue), forKey: "favoriteLocations") } } } <file_sep>// // MenusInteractor.swift // Coop // // Created by <NAME> on 13.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import Alamofire protocol MenusInteractorInput { var location: Location { get set } func fetchMenus() } protocol MenusInteractorOutput { func menusFetched(_ menus: [Menu]) func connectionErrorOccured() } class MenusInteractor: MenusInteractorInput { var presenter: MenusInteractorOutput! var location: Location private let url = Configuration.baseUrl.appendingPathComponent("menus") init(forLocation location: Location) { self.location = location } func fetchMenus() { Alamofire.request(url.appendingPathComponent(location.name)).responseJSON { response in var menus = [Menu]() if response.result.isFailure { return self.presenter.connectionErrorOccured() } for menu in (response.result.value! as! NSDictionary)["results"] as! NSArray { if let menu = self.parseMenu(menu as! NSDictionary) { menus.append(menu) } } self.presenter.menusFetched(menus) } } func parseMenu(_ menu: NSDictionary) -> Menu? { guard let title = menu["title"] as? String else { return nil } guard let price = menu["price"] as? Double else { return nil } guard let dishes = menu["menu"] as? [String] else { return nil } guard let date = menu["timestamp"] as? Double else { return nil } return Menu(title: title, price: price, dishes: dishes, date: Date(timeIntervalSince1970: date + 7200), location: location) } } <file_sep>FROM python:3.5 ADD telegram.py . ADD requirements.txt . RUN pip install -r requirements.txt CMD python telegram.py <file_sep>import datetime import re import pymongo import requests import yaml from bs4 import BeautifulSoup db = pymongo.MongoClient('mongodb').get_database('coop') menus = [] def get_data_for_restaurant(restaurant_id, name): url = 'http://www.coop.ch/pb/site/restaurant/node/73195219/Lde/index.html' headers = { 'Cookie': 'mapstart-restaurant=' + restaurant_id, 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36' } data = requests.get(url, headers=headers) dom = BeautifulSoup(data.text, 'html.parser') weekdays = [] for element in dom.find_all('span', {'id': re.compile('^tab-restaurant-\d$')}): year = datetime.datetime.now().year timestamp = datetime.datetime.strptime(element.contents[0][3:] + str(year), '%d.%m%Y').timestamp() weekdays.append(timestamp) for index, table in enumerate(dom.find_all('table', {'class': 'outer'})): for row in table.find_all('tr', recursive=False): menu_tag = row.find('td', {'class': 'inner col1'}).contents menu = [item for item in menu_tag if isinstance(item, str)] title_tag = row.find('td', {'class': 'outer col1'}).contents title = title_tag[0] price_tag = row.find('td', {'class': 'outer col3'}).contents price = price_tag[0] menus.append({ 'location_id': int(restaurant_id), 'location': name, 'location_lower': name.lower(), 'menu': menu, 'price': float(price), 'timestamp': weekdays[index], 'title': title }) with open('config.yml') as config_file: config = yaml.load(config_file) for name, restaurant_id in config['restaurants'].items(): get_data_for_restaurant(restaurant_id, name) db.get_collection('menus_temp').insert_many(menus) db.get_collection('menus_temp').rename('menus', dropTarget=True) db.get_collection('menus').create_index([('location_lower', pymongo.ASCENDING), ('timestamp', pymongo.ASCENDING)]) db.get_collection('menus').create_index('location') most_recent_timestamp = min([menu['timestamp'] for menu in menus]) stats = [menu for menu in menus if menu['timestamp'] == most_recent_timestamp] if db.get_collection('menu_stats').find_one({'timestamp': most_recent_timestamp}) is None: db.get_collection('menu_stats').insert_many(stats) db.get_collection('menu_stats').create_index([('location_lower', pymongo.ASCENDING), ('timestamp', pymongo.ASCENDING)]) <file_sep>// // MenusPresenter.swift // Coop // // Created by <NAME> on 13.10.16. // Copyright © 2016 <NAME>. All rights reserved. // class MenusPresenter { var viewController: MenusViewControllerInput! var interactor: MenusInteractorInput! var router: MenusRouter! fileprivate func displayStar() { if interactor.location.isFavorite { viewController.showFullStar() } else { viewController.showEmptyStar() } } } extension MenusPresenter: MenusViewControllerOutput { func showMenuDetails(forMenu menu: Menu) { router.showMenuDetails(forMenu: menu) } func starClicked() { interactor.location.isFavorite = !interactor.location.isFavorite displayStar() } func viewInitialized() { displayStar() interactor.fetchMenus() } } extension MenusPresenter: MenusInteractorOutput { func menusFetched(_ menus: [Menu]) { let sortedMenus = menus.sorted() viewController.displayMenus(sortedMenus.categorise({ $0.date }).sorted(by: { $0.key < $1.key })) } func connectionErrorOccured() { router.showConnectionError() } } extension MenusPresenter: MenusRouterOutput { func retryPressed() { interactor.fetchMenus() } } <file_sep>import Foundation extension String { var bold: String { return "\u{001B}[1m\(self)\u{001B}[0m" } var blue: String { return "\u{001B}[36m\(self)\u{001B}[0m" } } <file_sep>FROM python:3.5 ADD api.py . ADD requirements.txt . RUN pip install -r requirements.txt CMD python api.py <file_sep>pymongo requests beautifulsoup4 pyaml <file_sep>// // LocationsRouter.swift // Coop // // Created by <NAME> on 12.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol LocationsRouterOutput: NetworkRouterOutput { } class LocationsRouter: NetworkRouter { let viewController: UIViewController let presenter: NetworkRouterOutput // TODO: figure out why LocationsRouterOutput does not work here init() { let viewController = LocationsViewController() let interactor = LocationsInteractor() let presenter = LocationsPresenter() viewController.title = NSLocalizedString("Locations", comment: "") interactor.presenter = presenter viewController.presenter = presenter presenter.viewController = viewController presenter.interactor = interactor self.presenter = presenter self.viewController = viewController presenter.router = self } func showMenus(forLocation location: Location) { viewController.navigationController!.pushViewController(MenusRouter(forLocation: location).viewController, animated: true) } } <file_sep>// // Location.swift // Coop // // Created by <NAME> on 11.10.16. // Copyright © 2016 <NAME>. All rights reserved. // struct Location { let name: String // TODO: refactor var isFavorite: Bool { get { return Configuration.favoriteLocations.contains(name) } set(newValue) { if newValue { Configuration.favoriteLocations.insert(name) } else { Configuration.favoriteLocations.remove(name) } } } } extension Location: Comparable { public static func ==(lhs: Location, rhs: Location) -> Bool { return lhs.name == rhs.name } public static func <(lhs: Location, rhs: Location) -> Bool { return lhs.name < rhs.name } public static func <=(lhs: Location, rhs: Location) -> Bool { return lhs.name <= rhs.name } public static func >=(lhs: Location, rhs: Location) -> Bool { return lhs.name >= rhs.name } public static func >(lhs: Location, rhs: Location) -> Bool { return lhs.name > rhs.name } } <file_sep>// // Menu.swift // Coop // // Created by <NAME> on 11.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation struct Menu { let title: String let price: Double let dishes: [String] let date: Date let location: Location } // This allows the compiler to use whole module optimization extension Menu: Comparable { public static func <(lhs: Menu, rhs: Menu) -> Bool { if lhs.title.lowercased() == rhs.title.lowercased() { return lhs.price < rhs.price } return lhs.title.lowercased() < rhs.title.lowercased() } public static func <=(lhs: Menu, rhs: Menu) -> Bool { if lhs.title.lowercased() == rhs.title.lowercased() { return lhs.price <= rhs.price } return lhs.title.lowercased() <= rhs.title.lowercased() } public static func >=(lhs: Menu, rhs: Menu) -> Bool { if lhs.title.lowercased() == rhs.title.lowercased() { return lhs.price >= rhs.price } return lhs.title.lowercased() >= rhs.title.lowercased() } public static func >(lhs: Menu, rhs: Menu) -> Bool { if lhs.title.lowercased() == rhs.title.lowercased() { return lhs.price > rhs.price } return lhs.title.lowercased() > rhs.title.lowercased() } public static func ==(lhs: Menu, rhs: Menu) -> Bool { return lhs.title == rhs.title && lhs.price == rhs.price && lhs.dishes == rhs.dishes && lhs.date == rhs.date && lhs.location == rhs.location } } <file_sep><?php header('Content-Type: application/json'); $baseUrl = 'https://themachine.jeremystucki.com/api/v1/coop/menus'; $midnight = new DateTime; $midnight->setTime(0, 0); $timestamp = $midnight->getTimestamp(); $location = $_POST['text']; $handle = curl_init(); curl_setopt($handle, CURLOPT_URL, $baseUrl . '/' . urlencode($location) . '/' . $timestamp); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); $body = curl_exec($handle); curl_close($handle); $data = json_decode($body, true); $menus = []; foreach($data['results'] as $menu) { $text = '*' . $menu['title'] . '* - ' . $menu['price']; foreach($menu['menu'] as $dish) { $text .= PHP_EOL . '-' . $dish; } $menus[] = $text; } $attachments = []; if (empty($data['results'])) { $attachments[] = [ 'color' => 'warning', 'text' => 'We couldn\'t find any menus for \'' . $location . '\'' ]; } echo json_encode([ 'text' => implode(PHP_EOL . PHP_EOL, $menus), 'parse' => 'full', 'attachments' => $attachments ]); <file_sep>devices([ "iPhone 4s", "iPhone 6", "iPhone 6 Plus", "iPhone 5", "iPad Pro (9.7 inch)" ]) languages([ "en-US", "de-CH", ]) launch_arguments([ "--erase_simulator", "--localize_simulator" ]) <file_sep>// // LocationsPresenter.swift // Coop // // Created by <NAME> on 12.10.16. // Copyright © 2016 <NAME>. All rights reserved. // class LocationsPresenter { var viewController: LocationsViewControllerInput! var interactor: LocationsInteractorInput! var router: LocationsRouter! } extension LocationsPresenter: LocationsViewControllerOutput { func viewInitialized() { interactor.fetchFavoriteLocations() interactor.fetchLocations() } func viewWillBecomeVisible() { interactor.fetchFavoriteLocations() } func showMenus(forLocation location: Location) { router.showMenus(forLocation: location) } } extension LocationsPresenter: LocationsInteractorOutput { func locationsFetched(_ locations: [Location]) { viewController.displayLocations(locations.sorted()) } func favoriteLocationsFetched(_ favoriteLocations: [Location]) { viewController.displayFavoriteLocations(favoriteLocations.sorted()) } func connectionErrorOccured() { router.showConnectionError() } } extension LocationsPresenter: LocationsRouterOutput { func retryPressed() { interactor.fetchLocations() } } <file_sep>requests==2.9.1 colorama==0.3.7 <file_sep>// // MenuDetailRouter.swift // Coop // // Created by <NAME> on 16.10.16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class MenuDetailRouter { let viewController: UIViewController init(forMenu menu: Menu) { viewController = MenuDetailViewController(forMenu: menu) viewController.title = menu.title } } <file_sep>// // AppDelegate.swift // Coop // // Created by <NAME> on 12/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let locationsRouter = LocationsRouter() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let rootViewController = UINavigationController(rootViewController: locationsRouter.viewController) window = UIWindow(frame: UIScreen.main.bounds) if UIDevice.current.userInterfaceIdiom == .phone { window!.rootViewController = rootViewController } if UIDevice.current.userInterfaceIdiom == .pad { let splitViewController = UISplitViewController() splitViewController.viewControllers.append(rootViewController) splitViewController.preferredDisplayMode = .allVisible window!.rootViewController = splitViewController } window!.makeKeyAndVisible() return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { locationsRouter.showMenus(forLocation: Location(name: shortcutItem.localizedTitle)) } func applicationWillResignActive(_ application: UIApplication) { var shortcutItems = [UIApplicationShortcutItem]() for location in Configuration.favoriteLocations { shortcutItems.append(UIApplicationShortcutItem(type: "favoriteLocation", localizedTitle: location)) } UIApplication.shared.shortcutItems = shortcutItems } @objc func showSettings() { } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { switch url.host { case "settings"?: showSettings() default: return false } return true } }
860adf82d00f98395ef4a629d0e6e22faa4dff6a
[ "CMake", "Ruby", "Swift", "Markdown", "Python", "Text", "PHP", "Dockerfile" ]
37
Python
jeremystucki/coop
8af0bb1e61829380afab88ed3dc171e582b00c65
6488f383e04c5ddfadb520f75a0013b6518a5493
refs/heads/master
<repo_name>atomaszewski/warsztat<file_sep>/Magazyn.py # program wyswietla stan magazynu wraz z cena, nastepnie wykonuje zamowienie online # sprawdza czy produkt jest dostepny na magazynie i aktualizuje stan magazynu # na koniec zwraca kwote jaka mamy zaplacic lista_zakupow = ["jablko", 'gruszka', 'cytryna', "banan", "banan", "arbuz" ] asortyment_cena = { "jablko": 2, "gruszka": 5, "banan": 3, "cytryna": 11, "arbuz": 1.5, } stan_magazyn = { "jablko": 10, "gruszka": 11, "banan": 120, "cytryna": 6, "arbuz": 0, } zapowiedz = "witaj ponizej jest lista produktow dostepnych w naszym magazynie wraz z cenami" print(zapowiedz.upper()) for klucz in asortyment_cena: # petla wyswietlajaca stan magazynu print(klucz) print("cena: %s" % asortyment_cena[klucz]) print("stan: %s" % stan_magazyn[klucz]) calosc = 0 for klucz in asortyment_cena: # petla wyswietlajaca ceny do produktow mix = asortyment_cena[klucz] * stan_magazyn[klucz] calosc = calosc + mix print("wartosc: ", calosc) print('________________') print("stan magazyny przed: ", stan_magazyn) print('________________') print("zamowienie sklada sie z:", len(lista_zakupow), lista_zakupow) def zamowienie(produkty): # funkcja wraz z petla sprawdzajaca stan magazynu i odejmujaca po 1 produkcie calosc_zamowienia = 0 for produkt in produkty: if stan_magazyn[produkt] == 0: print([produkt], "BRAK") if stan_magazyn[produkt] > 0 : calosc_zamowienia = calosc_zamowienia + asortyment_cena[produkt] stan_magazyn[produkt] = stan_magazyn[produkt] - 1 return calosc_zamowienia print("kwota do zaplaty", zamowienie(lista_zakupow)) print('________________') print("stan magazynu po: ", stan_magazyn) <file_sep>/gra_w_statki.py print( """to jest prosta gra w zbijanie statku twoje zadanie bedzie polegac na tym aby, majac cztery strzaly (0-4)znalesc statek !!POWODZENIA!!""" ) from random import randint # przywolanie modulu do generowania losowych liczb plansza = [] for _ in range(5): # funkcja ta tworzy nasza tablice gdzie z range(0 ,1, 2, 3, 4, ) plansza.append(["0"]* 5) # birzzemy tylko pozycje 0 i zwiekszamy ja o 5 razy # tworzy nam sie lista dluga a dokladnie 5X ['0', '0', '0', '0', '0'] # ta funkcja ponizej ma nam wyswietlin nasza wczesniej wyzej strorzona liste nie w jednym ciagu def wydruk_planszy(plansza): # tylko w kolejnych wierszach for pola in plansza: print(pola) #wydruk_planszy(plansza) # wydruk tej samej planszy tylko ze usuwamy zbedne elementy # aby nasza plansza ladniej wygladala usuwamy "" pozostawiajac tylko same O def wydruk_planszy_czyszczenie(plansza): for linia in plansza: print(" ".join(linia)) wydruk_planszy_czyszczenie(plansza) # kojene dwie funkcje to beda nasze zmienne pionowa i pozioma , (statek_linia_ponioma oraz statek_linia_pionowa) # w nich umieszczimy nasz statwek losowo # uzyjemy tutaj moduli randint def linia_pozioma(plansza): return randint(0, len(plansza) -1) def linia_pionowa(plansza): return randint(0, len(plansza) - 1) statek_pozycja_x = linia_pozioma(plansza) #( row) statek_pozycja_y = linia_pionowa(plansza) # (col) # gdy juz ukryliśmy nasz statek pora aby zgadnac i dac mozliwosc podania dwoch liczb # calosc umieszczamy w petli ktora konczy sie wraz z czterema probami tura = 0 while tura < 4: pozycja_x = int() pozycja_y = int() while pozycja_x != -1: try: pozycja_x = int(input("podaj pozycje x :")) except(ValueError, NameError): print("Błąd, to nie jest liczba \n") continue try: pozycja_y = int(input("podaj pozycje y :")) except(ValueError, NameError): print("Błąd, to nie jest liczba \n") print("podaj jeszcze raz dwie liczby\n") continue if int(pozycja_y) > 0 or int(pozycja_y) == 0: break if int(pozycja_x) > 0 or int(pozycja_x) == 0: break # sprawdzamy tutaj czy nasze namiary sa takie same jak losowe gdzie ukryty zostal statek if statek_pozycja_x == pozycja_x and statek_pozycja_y == pozycja_y: print("Gratulacje! zatopiles moj statek ") break # tutaj sprawdzamy czy podane liczby mieszcza sie w zasiegu naszej mapy elif pozycja_x not in range(5) or pozycja_y not in range(5): print("strzal po za zakres mapy, spruboj jeszcze raz!! ") # tutaj sprawdzamy czy juz wczesniej nie strzelalismy w to miejsce elif plansza[pozycja_x][pozycja_y] == "x": print("Juz tu strzelaleś, wybierz inne koordynaty !!") else: # po sprawdzeniu i przy braku trafienia wyswietla sie informacja # tutaj odlicza sie nasza petla, oraz na mapie zaznacza sie miejsce gdzie celowalismy print("Pudlo, sprobuj jeszcze raz") plansza[pozycja_x][pozycja_y] = "x" print(wydruk_planszy_czyszczenie(plansza)) tura = tura + 1 print("to jest tura: ",tura) if tura == 4: print("koniec strzalów, Game Over") input("\n\nAby zakonczyc program, nacisnij klawisz Enter.") <file_sep>/README.md dodatkowa linia # warsztat
554ecb92ecc6f2f68c0ffa38b17426a6e5daed5e
[ "Markdown", "Python" ]
3
Python
atomaszewski/warsztat
2eb57f4eb79dd7b8f19cee5d974d988aadf92c8e
a481886c3116c750c0ff95b215c713cd4a9fd1f5
refs/heads/master
<repo_name>zpiao1/CIRViz<file_sep>/src/main/java/cir/cirviz/api/util/StreamModifier.java package cir.cirviz.api.util; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamModifier<T> { private Map<String, Comparator<T>> comparatorMap = Collections.emptyMap(); public StreamModifier(Map<String, Comparator<T>> comparatorMap) { this.comparatorMap = comparatorMap; } public Stream<T> modify(Stream<T> stream, String orderBy, boolean asc, long limit) { if (orderBy == null || orderBy.isEmpty()) { return stream.limit(limit); } Comparator<T> comparator = comparatorMap.get(orderBy); if (comparator != null) { stream = stream.sorted(comparator); } if (!asc) { List<T> list = stream.collect(Collectors.toList()); Collections.reverse(list); stream = list.stream(); } return stream.limit(limit); } } <file_sep>/src/main/java/cir/cirviz/api/service/VenueService.java package cir.cirviz.api.service; import cir.cirviz.data.entity.Paper; import java.util.List; public interface VenueService { List<String> getVenues(); List<Paper> getPapersByVenue(String venue); } <file_sep>/src/main/java/cir/cirviz/api/controller/AuthorApi.java package cir.cirviz.api.controller; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.List; public interface AuthorApi { List<Author> getAuthors( String name, String orderBy, boolean asc, long limit ); long getAuthorsCount(); Author getAuthorById(String authorId); List<Paper> getPapersByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getPapersCountByAuthor(String authorId); List<Integer> getYearsOfPapersByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getYearsOfPapersCountByAuthor(String authorId); List<String> getKeyPhrasesOfPapersByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getKeyPhrasesCountOfPapersByAuthor(String authorId); List<String> getVenuesOfPapersByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getVenuesCountOfPapersByAuthor(String authorId); List<Paper> getCitedPapersWrittenByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getCitedPapersCountWrittenByAuthor(String authorId); List<Paper> getPapersCitedByAuthor( String authorId, String orderBy, boolean asc, long limit ); long getPapersCountCitedByAuthor(String authorId); } <file_sep>/src/main/java/cir/cirviz/api/service/KeyPhraseServiceImpl.java package cir.cirviz.api.service; import cir.cirviz.data.PaperRepository; import cir.cirviz.data.entity.Paper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class KeyPhraseServiceImpl implements KeyPhraseService { private final PaperRepository paperRepository; @Autowired public KeyPhraseServiceImpl(PaperRepository paperRepository) { this.paperRepository = paperRepository; } @Override public List<String> getKeyPhrases() { return new ArrayList<>(paperRepository.getKeyPhraseToPapers().keySet()); } @Override public List<Paper> getPapersByKeyPhrase(String keyPhrase) { return paperRepository.getKeyPhraseToPapers().getOrDefault(keyPhrase, Collections.emptyList()); } } <file_sep>/src/main/resources/static/task2/task2.js const svg = d3.select('svg'); const width = +svg.attr('width'); const height = +svg.attr('height'); const format = d3.format(',d'); const color = d3.scaleOrdinal(d3.schemeCategory20); const pack = d3.pack() .size([width, height]) .padding(1.5); d3.json( 'http://localhost:8080/api/venues/ArXiv/papers?orderBy=inCitations&asc=false&limit=5') .get((error, papers) => { if (error) { throw error; } const data = papers.map(p => ({id: p.id, value: p.inCitations.length})); const root = d3.hierarchy({children: data}) .sum(d => d.value) .each(d => console.log(d)); const node = svg.selectAll('.node') .data(pack(root).leaves()) .enter().append('g') .attr('class', 'node') .attr('transform', d => `translate(${d.x},${d.y})`); node.append('circle') .attr('id', d => d.data.id) .attr('r', d => d.r) .style('fill', d => color(d.package)); node.append('clipPath') .attr('id', d => `clip-${d.data.id}`) .append('use') .attr('xlink:href', d => `#${d.data.id}`); node.append('text') .attr('clip-path', d => `url(#clip-${d.data.id})`) .selectAll('tspan') .data(d => papers.find(p => p.id === d.data.id).title.split(' ')) .enter().append('tspan') .attr('x', 0) .attr('y', (d, i, nodes) => 13 + (i - nodes.length / 2 - 0.5) * 10) .text(d => d); node.append('title') .text(d => { const paper = papers.find(p => p.id === d.data.id); const authors = paper.authors.map(a => a.name); return `Title: ${paper.title}\n` + `Authors: ${authors.join(', ')}\n` + `InCitations: ${format(d.data.value)}`; }); });<file_sep>/src/main/java/cir/cirviz/data/ParserService.java package cir.cirviz.data; public interface ParserService { void parse(); } <file_sep>/src/main/java/cir/cirviz/api/service/AuthorServiceImpl.java package cir.cirviz.api.service; import cir.cirviz.data.PaperRepository; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AuthorServiceImpl implements AuthorService { private final PaperRepository paperRepository; @Autowired public AuthorServiceImpl(PaperRepository paperRepository) { this.paperRepository = paperRepository; } @Override public List<Author> getAuthors() { return new ArrayList<>(paperRepository.getAuthors().values()); } @Override public Author getAuthorById(String authorId) { return paperRepository.getAuthors().get(authorId); } @Override public List<Paper> getPapersByAuthor(Author author) { return getPapersByAuthorId(author.getId()); } @Override public List<Paper> getPapersByAuthorId(String authorId) { return paperRepository.getAuthorToPapers().getOrDefault(authorId, Collections.emptyList()); } } <file_sep>/src/main/java/cir/cirviz/data/PaperRepositoryImpl.java package cir.cirviz.data; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @Repository public class PaperRepositoryImpl implements PaperRepository { private static Logger logger = LoggerFactory.getLogger(PaperRepositoryImpl.class); private ConcurrentMap<String, Paper> papers = new ConcurrentHashMap<>(); private ConcurrentMap<String, Author> authors = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Author>> paperToAuthors = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Paper>> authorToPapers = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Paper>> inCitations = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Paper>> outCitations = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Paper>> keyPhraseToPapers = new ConcurrentHashMap<>(); private ConcurrentMap<String, List<Paper>> venueToPapers = new ConcurrentHashMap<>(); private ConcurrentMap<Integer, List<Paper>> yearToPapers = new ConcurrentHashMap<>(); private static <K, V> void preprocessMapToList(ConcurrentMap<K, List<V>> map, K key) { map.putIfAbsent(key, Collections.synchronizedList(new ArrayList<>())); } public void addPaper(Paper paper) { String id = paper.getId(); papers.put(id, paper); } public void save() { buildRelations(); } private void addAuthor(Author author) { String id = author.getId(); authors.put(id, author); } private void buildRelations() { papers.values() .parallelStream() .forEach(this::buildRelationForPaper); } private void buildPaperAuthorRelation(Paper paper, Author author) { String paperId = paper.getId(); String authorId = author.getId(); preprocessMapToList(paperToAuthors, paperId); paperToAuthors.get(paperId).add(author); preprocessMapToList(authorToPapers, authorId); authorToPapers.get(authorId).add(paper); } private void buildCitationRelation(Paper citingPaper, Paper citedPaper) { // InCitations: citedPaperId -> List of papers citing this one // OutCitations: citingPaperId -> List of papers this one is citing String citingPaperId = citingPaper.getId(); String citedPaperId = citedPaper.getId(); preprocessMapToList(inCitations, citedPaperId); inCitations.get(citedPaperId).add(citingPaper); preprocessMapToList(outCitations, citingPaperId); outCitations.get(citingPaperId).add(citedPaper); } private void buildPaperKeyPhraseRelation(Paper paper, String keyPhrase) { preprocessMapToList(keyPhraseToPapers, keyPhrase); keyPhraseToPapers.get(keyPhrase).add(paper); } private void buildPaperVenueRelation(Paper paper, String venue) { preprocessMapToList(venueToPapers, venue); venueToPapers.get(venue).add(paper); } private void buildYearVenueRelation(Paper paper, int year) { preprocessMapToList(yearToPapers, year); yearToPapers.get(year).add(paper); } public Map<String, Paper> getPapers() { return papers; } public Map<String, Author> getAuthors() { return authors; } public Map<String, List<Author>> getPaperToAuthors() { return paperToAuthors; } public Map<String, List<Paper>> getAuthorToPapers() { return authorToPapers; } public Map<String, List<Paper>> getInCitations() { return inCitations; } public Map<String, List<Paper>> getOutCitations() { return outCitations; } public Map<String, List<Paper>> getKeyPhraseToPapers() { return keyPhraseToPapers; } public Map<String, List<Paper>> getVenueToPapers() { return venueToPapers; } public Map<Integer, List<Paper>> getYearToPapers() { return yearToPapers; } private void buildRelationForPaper(Paper paper) { paper.getAuthors() .parallelStream() .forEach(author -> { addAuthor(author); buildPaperAuthorRelation(paper, author); }); List<String> inCitations = paper.getInCitations(); Iterator<String> inCitationsIterator = inCitations.iterator(); while (inCitationsIterator.hasNext()) { String inCitationId = inCitationsIterator.next(); Paper citingPaper = papers.get(inCitationId); if (citingPaper != null) { buildCitationRelation(citingPaper, paper); } else { inCitationsIterator.remove(); // Remove IDs of non-existing papers } } List<String> outCitations = paper.getOutCitations(); Iterator<String> outCitationsIterator = outCitations.iterator(); while (outCitationsIterator.hasNext()) { String outCitationId = outCitationsIterator.next(); Paper citedPaper = papers.get(outCitationId); if (citedPaper != null) { buildCitationRelation(paper, citedPaper); } else { outCitationsIterator.remove(); // Remove IDs of non-existing papers } } paper.getKeyPhrases() .parallelStream() .forEach(keyPhrase -> buildPaperKeyPhraseRelation(paper, keyPhrase)); buildPaperVenueRelation(paper, paper.getVenue()); buildYearVenueRelation(paper, paper.getYear()); logger.info("Finished paper: " + paper.getId()); } } <file_sep>/src/main/java/cir/cirviz/api/controller/PaperApiController.java package cir.cirviz.api.controller; import cir.cirviz.api.service.PaperService; import cir.cirviz.api.util.ModelComparators; import cir.cirviz.api.util.NotFoundException; import cir.cirviz.api.util.StreamModifier; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class PaperApiController implements PaperApi { private final PaperService paperService; private final ModelComparators modelComparators; @Autowired public PaperApiController(PaperService paperService, ModelComparators modelComparators) { this.paperService = paperService; this.modelComparators = modelComparators; } @GetMapping("/api/papers") @Override public List<Paper> getPapers( @RequestParam(name = "title", required = false) String title, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = paperService.getPapers().stream(); if (title != null && !title.isEmpty()) { papers = papers .filter(paper -> paper.getTitle().toLowerCase().contains(title.toLowerCase())) .distinct(); } StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @GetMapping("/api/papers/count") @Override public long getPapersCount() { return paperService.getPapers().size(); } @GetMapping("/api/papers/{id}") @Override public Paper getPaperById(@PathVariable(name = "id") String paperId) { Paper paper = paperService.getPaperById(paperId); if (paper == null) { throw new NotFoundException("Paper with id: " + paperId + " is not found."); } return paper; } @GetMapping("/api/papers/{id}/authors") @Override public List<Author> getAuthorsOfPaper( @PathVariable(name = "id") String paperId, @RequestParam(name = "orderBy", required = false, defaultValue = "name") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Author> authors = getPaperById(paperId).getAuthors().stream(); StreamModifier<Author> modifier = new StreamModifier<>( modelComparators.getAuthorComparatorMap()); authors = modifier.modify(authors, orderBy, asc, limit); return authors.collect(Collectors.toList()); } @GetMapping("/api/papers/{id}/authors/count") @Override public long getAuthorsCountOfPaper(@PathVariable(name = "id") String paperId) { return getPaperById(paperId).getAuthors().size(); } @GetMapping("/api/papers/{id}/year") @Override public int getYearOfPaper(@PathVariable(name = "id") String paperId) { return getPaperById(paperId).getYear(); } @GetMapping("/api/papers/{id}/keyPhrases") @Override public List<String> getKeyPhrasesOfPaper( @PathVariable(name = "id") String paperId, @RequestParam(name = "orderBy", required = false, defaultValue = "keyPhrase") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<String> keyPhrases = getPaperById(paperId).getKeyPhrases().stream(); StreamModifier<String> modifier = new StreamModifier<>( modelComparators.getKeyPhraseComparatorMap()); keyPhrases = modifier.modify(keyPhrases, orderBy, asc, limit); return keyPhrases.collect(Collectors.toList()); } @GetMapping("/api/papers/{id}/keyPhrases/count") @Override public long getKeyPhrasesCountOfPaper(@PathVariable(name = "id") String paperId) { return getPaperById(paperId).getKeyPhrases().size(); } @GetMapping("/api/papers/{id}/venue") @Override public String getVenueOfPaper(@PathVariable(name = "id") String paperId) { return getPaperById(paperId).getVenue(); } @GetMapping("/api/papers/{id}/outCitations") @Override public List<Paper> getOutCitationsOfPaper( @PathVariable(name = "id") String paperId, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = paperService.getOutCitationsByPaperId(paperId).stream(); StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @GetMapping("/api/papers/{id}/outCitations/count") @Override public long getOutCitationsCountOfPaper(@PathVariable(name = "id") String paperId) { return paperService.getOutCitationsByPaperId(paperId).size(); } @GetMapping("/api/papers/{id}/inCitations") @Override public List<Paper> getInCitationsOfPaper( @PathVariable(name = "id") String paperId, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = paperService.getInCitationsByPaperId(paperId).stream(); StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @Override public long getInCitationsCountOfPaper(String paperId) { return paperService.getInCitationsByPaperId(paperId).size(); } } <file_sep>/README.md #CIRViz - Visualization of conferece papers This project contains 2 parts: * API: See `/src/main/java/cir/cirviz/api/`. This provides RESTful APIs for the paper data collected. Mapped to URL `/api` * Visualization: See `/src/main/resources/static/`. This serves HTML pages written using D3. Each page queries from the API and displays the corresponding visualization. URLs: `/resources/static/task2/index.html`, `/resources/static/task3/index.html`, `/resources/static/task4/index.html`. ###Note Please put the 200,000 lines JSON file in `/src/main/resources/data`, and the file name should be `dataset.json` (as defined in `application.properties`).<file_sep>/src/main/java/cir/cirviz/api/controller/KeyPhrasesApi.java package cir.cirviz.api.controller; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.List; public interface KeyPhrasesApi { List<String> getKeyPhrases( String orderBy, boolean asc, long limit ); long getKeyPhrasesCount(); String getKeyPhrase(String keyPhrase); List<Paper> getPapersByKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getPapersCountByKeyPhrase(String keyPhrase); List<Author> getAuthorsByKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getAuthorsCountByKeyPhrase(String keyPhrase); List<Integer> getYearsByKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getYearsCountByKeyPhrase(String keyPhrase); List<String> getVenuesByKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getVenuesCountByKeyPhrase(String keyPhrase); List<Paper> getCitationsByKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getCitationsCountByKeyPhrase(String keyPhrase); List<Paper> getPapersCitingPapersWithKeyPhrase( String keyPhrase, String orderBy, boolean asc, long limit ); long getPapersCountCitingPapersWithKeyPhrase(String keyPhrase); } <file_sep>/src/main/resources/application.properties server.address=0.0.0.0 spring.mvc.static-path-pattern=/resources/static/** dataset.path=classpath:data/dataset.json<file_sep>/src/main/java/cir/cirviz/api/ApiConfig.java package cir.cirviz.api; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class ApiConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**"); } } <file_sep>/src/main/java/cir/cirviz/api/util/ModelComparators.java package cir.cirviz.api.util; import cir.cirviz.api.service.AuthorService; import cir.cirviz.api.service.KeyPhraseService; import cir.cirviz.api.service.PaperService; import cir.cirviz.api.service.VenueService; import cir.cirviz.api.service.YearService; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ModelComparators { private final AuthorService authorService; private final YearService yearService; private final KeyPhraseService keyPhraseService; private final VenueService venueService; private final PaperService paperService; private final Map<String, Comparator<Paper>> paperComparatorMap = new HashMap<>(); private final Map<String, Comparator<Author>> authorComparatorMap = new HashMap<>(); private final Map<String, Comparator<Integer>> yearComparatorMap = new HashMap<>(); private final Map<String, Comparator<String>> venueComparatorMap = new HashMap<>(); private final Map<String, Comparator<String>> keyPhraseComparatorMap = new HashMap<>(); @Autowired public ModelComparators(AuthorService authorService, YearService yearService, KeyPhraseService keyPhraseService, VenueService venueService, PaperService paperService) { this.authorService = authorService; this.yearService = yearService; this.keyPhraseService = keyPhraseService; this.venueService = venueService; this.paperService = paperService; initPaperComparatorMap(); initAuthorComparatorMap(); initYearComparatorMap(); initVenueComparatorMap(); initKeyPhraseComparatorMap(); } private void initPaperComparatorMap() { paperComparatorMap.put("title", Comparator.comparing(Paper::getTitle)); paperComparatorMap .put("authors", Comparator.comparingInt(p -> paperService.getAuthorsByPaper(p).size())); paperComparatorMap.put("inCitations", Comparator.comparingInt(p -> paperService.getInCitationsByPaper(p).size())); paperComparatorMap.put("outCitations", Comparator.comparingInt(p -> paperService.getOutCitationsByPaper(p).size())); paperComparatorMap.put("keyPhrases", Comparator.comparingInt(p -> paperService.getKeyPhrasesByPaper(p).size())); paperComparatorMap.put("pdfUrls", Comparator.comparingInt(p -> p.getPdfUrls().size())); paperComparatorMap.put("s2Url", Comparator.comparing(Paper::getS2Url)); paperComparatorMap.put("venue", Comparator.comparing(paperService::getVenueByPaper)); paperComparatorMap.put("year", Comparator.comparingInt(paperService::getYearByPaper)); paperComparatorMap.put("abstract", Comparator.comparing(Paper::getPaperAbstract)); } private void initAuthorComparatorMap() { authorComparatorMap.put("name", Comparator.comparing(Author::getName)); authorComparatorMap .put("papers", Comparator.comparingInt(a -> authorService.getPapersByAuthor(a).size())); } private void initYearComparatorMap() { yearComparatorMap.put("year", Comparator.comparingInt(y -> y)); yearComparatorMap .put("papers", Comparator.comparingInt(y -> yearService.getPapersByYear(y).size())); } private void initVenueComparatorMap() { venueComparatorMap.put("venue", Comparator.comparing(v -> v)); venueComparatorMap .put("papers", Comparator.comparingInt(v -> venueService.getPapersByVenue(v).size())); } private void initKeyPhraseComparatorMap() { keyPhraseComparatorMap.put("keyPhrase", Comparator.comparing(k -> k)); keyPhraseComparatorMap.put("papers", Comparator.comparingInt(k -> keyPhraseService.getPapersByKeyPhrase(k).size())); } public Map<String, Comparator<Paper>> getPaperComparatorMap() { return paperComparatorMap; } public Map<String, Comparator<Author>> getAuthorComparatorMap() { return authorComparatorMap; } public Map<String, Comparator<Integer>> getYearComparatorMap() { return yearComparatorMap; } public Map<String, Comparator<String>> getVenueComparatorMap() { return venueComparatorMap; } public Map<String, Comparator<String>> getKeyPhraseComparatorMap() { return keyPhraseComparatorMap; } } <file_sep>/src/main/java/cir/cirviz/data/entity/Paper.java package cir.cirviz.data.entity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @JsonInclude(JsonInclude.Include.NON_NULL) public class Paper { private static Logger logger = LoggerFactory.getLogger(Paper.class); @JsonProperty("authors") private List<Author> authors = new ArrayList<>(); @JsonProperty("id") private String id; @JsonProperty("inCitations") private List<String> inCitations = new ArrayList<>(); @JsonProperty("keyPhrases") private List<String> keyPhrases = new ArrayList<>(); @JsonProperty("outCitations") private List<String> outCitations = new ArrayList<>(); @JsonProperty("paperAbstract") private String paperAbstract; @JsonProperty("pdfUrls") private List<String> pdfUrls = new ArrayList<>(); @JsonProperty("s2Url") private String s2Url; @JsonProperty("title") private String title; @JsonProperty("venue") private String venue; @JsonProperty("year") private int year; protected Paper() { } public Paper(List<Author> authors, String id, List<String> inCitations, List<String> keyPhrases, List<String> outCitations, String paperAbstract, List<String> pdfUrls, String s2Url, String title, String venue, int year) { this.authors = authors; this.id = id; this.inCitations = inCitations; this.keyPhrases = keyPhrases; this.outCitations = outCitations; this.paperAbstract = paperAbstract; this.pdfUrls = pdfUrls; this.s2Url = s2Url; this.title = title; this.venue = venue; this.year = year; } @JsonProperty("authors") public List<Author> getAuthors() { return authors; } @JsonProperty("id") public String getId() { return id; } @JsonProperty("inCitations") public List<String> getInCitations() { return inCitations; } @JsonProperty("keyPhrases") public List<String> getKeyPhrases() { return keyPhrases; } @JsonProperty("outCitations") public List<String> getOutCitations() { return outCitations; } @JsonProperty("paperAbstract") public String getPaperAbstract() { return paperAbstract; } @JsonProperty("pdfUrls") public List<String> getPdfUrls() { return pdfUrls; } @JsonProperty("s2Url") public String getS2Url() { return s2Url; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("venue") public String getVenue() { return venue; } @JsonProperty("year") public int getYear() { return year; } @Override public String toString() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { logger.warn("Error in writing Author: " + e.getMessage()); } return super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Paper)) { return false; } Paper paper = (Paper) o; return getYear() == paper.getYear() && Objects.equals(getAuthors(), paper.getAuthors()) && Objects.equals(getId(), paper.getId()) && Objects.equals(getInCitations(), paper.getInCitations()) && Objects.equals(getKeyPhrases(), paper.getKeyPhrases()) && Objects.equals(getOutCitations(), paper.getOutCitations()) && Objects.equals(getPaperAbstract(), paper.getPaperAbstract()) && Objects.equals(getPdfUrls(), paper.getPdfUrls()) && Objects.equals(getS2Url(), paper.getS2Url()) && Objects.equals(getTitle(), paper.getTitle()) && Objects.equals(getVenue(), paper.getVenue()); } @Override public int hashCode() { return Objects.hash(getAuthors(), getId(), getInCitations(), getKeyPhrases(), getOutCitations(), getPaperAbstract(), getPdfUrls(), getS2Url(), getTitle(), getVenue(), getYear()); } }<file_sep>/src/main/java/cir/cirviz/api/service/YearServiceImpl.java package cir.cirviz.api.service; import cir.cirviz.data.PaperRepository; import cir.cirviz.data.entity.Paper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class YearServiceImpl implements YearService { private final PaperRepository paperRepository; @Autowired public YearServiceImpl(PaperRepository paperRepository) { this.paperRepository = paperRepository; } @Override public List<Integer> getYears() { return new ArrayList<>(paperRepository.getYearToPapers().keySet()); } @Override public List<Paper> getPapersByYear(int year) { return paperRepository.getYearToPapers().getOrDefault(year, Collections.emptyList()); } } <file_sep>/src/main/java/cir/cirviz/api/controller/YearApi.java package cir.cirviz.api.controller; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.List; public interface YearApi { List<Integer> getYears( String orderBy, boolean asc, long limit ); long getYearsCount(); int getYear(int year); List<Paper> getPapersByYear( int year, String orderBy, boolean asc, long limit ); long getPapersCountByYear(int year); List<Author> getAuthorsByYear( int year, String orderBy, boolean asc, long limit ); long getAuthorsCountByYear(int year); List<String> getVenuesByYear( int year, String orderBy, boolean asc, long limit ); long getVenuesCountByYear(int year); List<String> getKeyPhrasesByYear( int year, String orderBy, boolean asc, long limit ); long getKeyPhrasesCountByYear(int year); List<Paper> getCitationsByYear( int year, String orderBy, boolean asc, long limit ); long getCitationsCountByYear(int year); List<Paper> getPapersCitingPapersAtYear( int year, String orderBy, boolean asc, long limit ); long getPapersCountCitingPapersAtYear(int year); } <file_sep>/src/main/resources/static/task1/task1.js (async () => { const svg = d3.select('svg'); const margin = { top: 50, left: 200, right: 50, bottom: 100 }; const width = +svg.attr('width') - margin.left - margin.right; const height = +svg.attr('height') - margin.top - margin.bottom; const color = d3.scaleOrdinal(d3.schemeCategory10); const authors = await getData(); var data = authors.map(author => { return { name: author.name, count: author.papers.length } }); var keys = data.map(author => author.name); var values = data.map(author => author.count); const x = d3.scaleLinear() .domain([0, d3.max(values)]) .range([0, width]); const y = d3.scaleBand() .domain(keys) .rangeRound([0, height]) .padding(0.05, 0.05); const chart = svg.append('g') .attr('height', height) .attr('width', width) .attr('transform', `translate(${margin.left},${margin.top})`); chart.append('g') .attr('transform', `translate(0,${height})`) .call(d3.axisBottom(x)); chart.append('g') .call(d3.axisLeft(y)); const bar = chart.selectAll('.bar') .data(data) .enter() .append('g') .attr('class', 'bar'); bar.append('rect') .attr('x', 0) .attr('y', d => y(d.name)) .attr('height', y.bandwidth()) .attr('width', d => x(d.count)) .attr('fill', d => color(d.name)); bar.append('text') .attr('x', d => x(d.count) + 5) .attr('y', d => y(d.name)) .attr('dy', '1em') .style('text-anchor', 'start') .text(d => d.count); // Label title svg.append('text') .attr('x', (margin.left + width + margin.right) / 2) .attr('y', 0) .attr('dy', '1em') .style('text-anchor', 'middle') .style('font-size', 20) .text('Top 10 Authors for ArXiv'); // Label x-axis svg.append('text') .attr('x', margin.left + width / 2) .attr('y', margin.top + height + margin.bottom / 2) .style('text-anchor', 'middle') .text('Number of Publications'); // Label y-axis svg.append('text') .attr('x', 0) .attr('y', margin.top + height / 2) .style('text-anchor', 'start') .text('Author'); })(); async function getData() { const papersCount = await getJsonFromUrl('http://localhost:8080/api/venues/ArXiv/papers/count'); const papers = await getJsonFromUrl(`http://localhost:8080/api/venues/ArXiv/papers?limit=${papersCount}`); const authors = new Map(); papers.forEach(paper => { paper.authors.forEach(author => { const authorData = authors.get(author.id); if (!authorData) { authors.set(author.id, { name: author.name, id: author.id, papers: new Map() }); } else { const newPapers = authorData.papers; newPapers.set(paper.id, paper); } }); }); const authorsArray = [...authors.values()]; authorsArray.sort((a1, a2) => { if (a1.papers.size > a2.papers.size) { return -1; } else if (a1.papers.size < a2.papers.size) { return 1; } else if (a1.id < a2.id) { return -1; } else { return 1; } }); return authorsArray.slice(0, 10) .map(author => ({...author, papers: [...author.papers.values()]})); } function getJsonFromUrl(url) { return new Promise((resolve, reject) => { d3.json(url, (error, json) => { if (error) { reject(error); } else { resolve(json); } }); }); } <file_sep>/src/main/java/cir/cirviz/api/service/VenueServiceImpl.java package cir.cirviz.api.service; import cir.cirviz.data.PaperRepository; import cir.cirviz.data.entity.Paper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class VenueServiceImpl implements VenueService { private final PaperRepository paperRepository; @Autowired public VenueServiceImpl(PaperRepository paperRepository) { this.paperRepository = paperRepository; } @Override public List<String> getVenues() { return new ArrayList<>(paperRepository.getVenueToPapers().keySet()); } @Override public List<Paper> getPapersByVenue(String venue) { return paperRepository.getVenueToPapers().getOrDefault(venue, Collections.emptyList()); } } <file_sep>/src/main/java/cir/cirviz/api/controller/VenueApiController.java package cir.cirviz.api.controller; import cir.cirviz.api.service.PaperService; import cir.cirviz.api.service.VenueService; import cir.cirviz.api.util.ModelComparators; import cir.cirviz.api.util.NotFoundException; import cir.cirviz.api.util.StreamModifier; import cir.cirviz.data.entity.Author; import cir.cirviz.data.entity.Paper; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class VenueApiController implements VenueApi { private final VenueService venueService; private final PaperService paperService; private final ModelComparators modelComparators; @Autowired public VenueApiController(VenueService venueService, PaperService paperService, ModelComparators modelComparators) { this.venueService = venueService; this.paperService = paperService; this.modelComparators = modelComparators; } @GetMapping("/api/venues") @Override public List<String> getVenues( @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<String> venues = venueService.getVenues().stream(); StreamModifier<String> modifier = new StreamModifier<>( modelComparators.getVenueComparatorMap()); venues = modifier.modify(venues, orderBy, asc, limit); return venues.collect(Collectors.toList()); } @GetMapping("/api/venues/count") @Override public long getVenuesCount() { return venueService.getVenues().size(); } @GetMapping("/api/venues/{venue}") @Override public String getVenue(@PathVariable(name = "venue") String venue) { List<String> venues = venueService.getVenues(); if (venues.contains(venue)) { return venue; } else { throw new NotFoundException("Venue: " + venue + " is not found."); } } @GetMapping("/api/venues/{venue}/papers") @Override public List<Paper> getPapersByVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = venueService.getPapersByVenue(venue).stream(); StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @GetMapping("/api/venues/{venue}/papers/count") @Override public long getPapersCountByVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).size(); } @GetMapping("/api/venues/{venue}/authors") @Override public List<Author> getAuthorsByVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Author> authors = venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paper.getAuthors().stream()) .distinct(); StreamModifier<Author> modifier = new StreamModifier<>( modelComparators.getAuthorComparatorMap()); authors = modifier.modify(authors, orderBy, asc, limit); return authors.collect(Collectors.toList()); } @GetMapping("/api/venues/{venue}/authors/count") @Override public long getAuthorsCountByVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paper.getAuthors().stream()) .distinct() .count(); } @GetMapping("/api/venues/{venue}/years") @Override public List<Integer> getYearsByVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Integer> years = venueService.getPapersByVenue(venue).stream() .map(Paper::getYear) .distinct(); StreamModifier<Integer> modifier = new StreamModifier<>( modelComparators.getYearComparatorMap()); years = modifier.modify(years, orderBy, asc, limit); return years.collect(Collectors.toList()); } @GetMapping("/api/venues/{venue}/years/count") @Override public long getYearsCountByVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).stream() .map(Paper::getYear) .distinct() .count(); } @GetMapping("/api/venues/{venue}/keyPhrases") @Override public List<String> getKeyPhrasesByVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<String> keyPhrases = venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paper.getKeyPhrases().stream()) .distinct(); StreamModifier<String> modifier = new StreamModifier<>( modelComparators.getKeyPhraseComparatorMap()); keyPhrases = modifier.modify(keyPhrases, orderBy, asc, limit); return keyPhrases.collect(Collectors.toList()); } @GetMapping("/api/venue/{venue}/keyPhrases/count") @Override public long getKeyPhrasesCountByVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paper.getKeyPhrases().stream()) .distinct() .count(); } @GetMapping("/api/venues/{venue}/outCitations") @Override public List<Paper> getCitationsByVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paperService.getOutCitationsByPaper(paper).stream()) .distinct(); StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @GetMapping("/api/venues/{venue}/outCitations/count") @Override public long getCitationsCountByVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paperService.getOutCitationsByPaper(paper).stream()) .distinct() .count(); } @GetMapping("/api/venues/{venue}/inCitations") @Override public List<Paper> getPapersCitingPapersAtVenue( @PathVariable(name = "venue") String venue, @RequestParam(name = "orderBy", required = false, defaultValue = "title") String orderBy, @RequestParam(name = "asc", required = false, defaultValue = "true") boolean asc, @RequestParam(name = "limit", required = false, defaultValue = "10") long limit ) { Stream<Paper> papers = venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paperService.getInCitationsByPaper(paper).stream()) .distinct(); StreamModifier<Paper> modifier = new StreamModifier<>(modelComparators.getPaperComparatorMap()); papers = modifier.modify(papers, orderBy, asc, limit); return papers.collect(Collectors.toList()); } @GetMapping("/api/venues/{venue}/inCitations/count") @Override public long getPapersCountCitingPapersAtVenue(@PathVariable(name = "venue") String venue) { return venueService.getPapersByVenue(venue).stream() .flatMap(paper -> paperService.getInCitationsByPaper(paper).stream()) .distinct() .count(); } }
8d84dce84554417884cdfe982f678f28339a1492
[ "JavaScript", "Java", "Markdown", "INI" ]
20
Java
zpiao1/CIRViz
612c81813cc9148e655a5f917c9f2053e71ada0e
c5187c14e0caf38e412ce32eb21e1d1cd2ddd035
refs/heads/master
<repo_name>Ganter123/Node11<file_sep>/index.js var express = require('express') var bodyParser = require('body-parser') var cookieParser = require('cookie-parser') var mongoose = require('mongoose') var User = require('./models/user') var fs = require('fs') var ca = fs.readFileSync('./mongodb-cert.crt') var key = fs.readFileSync('./mongodb.pem') var cert = fs.readFileSync('./mongodb-cert.crt') var http = require('http') var app = express() /** * Connection Options for MongoDB * @namespace */ var options = { autoIndex: false, // Don't build indexes reconnectTries: 30, // Retry up to 30 times reconnectInterval: 500, // Reconnect every 500ms poolSize: 10, // Maintain up to 10 socket connections bufferMaxEntries: 0, useNewUrlParser: true, sslValidate: true, sslKey: cert, sslCert: cert } /** * MongoDb Connection Function * Will retry after 5 seconds if not connected * @function * @requires {object} connection configuration object */ const connectWithRetry = () => { mongoose.connect('mongodb+srv://docker:<EMAIL>/test ', options).then(()=>{ console.log('MongoDB is connected') }).catch(err=>{ console.log('MongoDB connection unsuccessful, retry after 5 seconds.', err) setTimeout(connectWithRetry, 5000) }) } connectWithRetry() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.text()) app.use(bodyParser.json({ type: 'application/json'})) app.use(cookieParser()) /** * Rest API * @function * @returns {string} Server is Running */ app.get('/', (req, resp) => resp.json({status: 200, message: 'Server is Running'}) ) /** * API for get all users data * @function * @returns {object} json data for all users */ app.get('/getUsers', (req, resp) => { User.find((err, result) => { if (err) resp.send({status: 500, data: err}) resp.json(result) }) }) /** * API for Save User to DB * @function * @requires {object} request object with below params in body * @param {string} firstName required * @param {string} lastName required * @param {string} email required * @param {string} contactNo * @param {string} address * * @returns {object} if error returns error object else return string with user data back */ app.post('/saveUser', (req, resp) => { var user = new User({ 'firstName': req.body.firstName, 'lastName': req.body.lastName, 'email': req.body.email, 'contactNo': req.body.contactNo, 'address': req.body.address }) user.save((err, data) => { if (err) resp.send(err) else resp.json({message: 'User successfully added!', data }) }) }) /** * Delete User By Id * /deleteUser/:id * @function * @param {string} id in url * @return {json} json Object with Message and result object * */ app.delete('/deleteUser/:id', (req, resp) => { User.remove({_id: req.param.id}, (err, data) => { if (err) resp.send(err) resp.json({message: 'User successfully Deleted.'}, data) }) }) /** * Get User By Id API * /getUserById/:id * @function * @param {string} userId in url * @returns {object} userObject */ app.get('/getUserById/:id', (req, resp) => { User.findById(req.param.id, (err, data) => { if(err) resp.send(err) resp.json(data) }) }) /** * Update User By Id * /updateUser/:id * @function * @param {string} id in url * @param {string} firstName required * @param {string} lastName required * @param {string} email required * @param {string} contactNo * @param {string} address * * @returns {object} updated User Object */ app.post('/updateUser/:id', (req, resp) => { User.findById({_id: req.param.id}, (err, data) => { if(err) resp.send(err) Object.assign(data, req.body).save( (err, result) => { if(err) resp.send(err) resp.json({message: 'User Updated.', result}) }) }) }) /* app.listen(3000, () => { console.log('Server is Running on Port 3000'); }); */ const server = http.createServer(app) server.on('listening',function(){ console.log('ok, server is running') }) server.listen(8080) module.exports = server <file_sep>/Dockerfile FROM Node11 USER root RUN git clone https://github.com/Ganter123/Node11.git RUN apt update RUN apt install -y mongodb RUN service mongodb start RUN npm install eslint -y EXPOSE 27017 COPY docker-entrypoint.sh /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin ENTRYPOINT ["docker-entrypoint.sh"] CMD ["npm", "start"]
6e18e27a0dca785d8d3b1215d753117940e7d386
[ "JavaScript", "Dockerfile" ]
2
JavaScript
Ganter123/Node11
a2484c9ef64995c10540e6ef38242f577f27dc53
8f20e072a8b87f853f493f2f706c37c1323fe22a
refs/heads/master
<file_sep># Logic Topology Design Implementation of a greedy heuristic to solve the problem of the logic topology design in an optical network. To run the code it is necessary to link the library jgrapht-core-0.9.2.jar. The archive is part of JGraphT, a free Java class library that provides mathematical graph-theory objects and algorithms. The entire library can be found at [JGraphT](https://github.com/jgrapht/jgrapht). <file_sep>package ltd; import org.jgrapht.graph.DefaultDirectedWeightedGraph; import org.jgrapht.graph.DefaultWeightedEdge; public class Matrix { private int row; private int column; double[][] m; public Matrix(int row, int column){ this.row = row; this.column = column; m = new double[row][column]; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ m[i][j]=-1; } } } public Matrix (Matrix matrix){ row = matrix.getRow(); column = matrix.getColumn(); m = new double[row][column]; for(int i=0; i<row; i++){ for(int j=0; j<column; j++){ m[i][j] = matrix.getElement(i, j); } } } public Matrix() { // TODO Auto-generated constructor stub } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public double[][] getM() { return m; } public void setM(double[][] m) { this.m = m; } public void setElement(int i, int j, double elem){ m[i][j] = elem; } public double getElement(int i, int j){ return m[i][j]; } public double getMax(){ double max = 0; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]>max){ max = m[i][j]; } } } return max; } public int getRowMax(){ double max = 0; int iMax = 0; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]>max){ iMax = i; max = m[i][j]; } } } return iMax; } public int getColumnMax(){ double max = 0; int jMax = 0; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]>max){ jMax = j; max = m[i][j]; } } } return jMax; } public boolean isPresent(double elem){ boolean flag = false; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]==elem) flag = true; } } return flag; } public int rowElem(double elem){ int rowElem; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]==elem){ rowElem = i; return rowElem; } } } return 0; } public int colElem(double elem){ int colElem; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]==elem){ colElem = j; return colElem; } } } return 0; } public void findEmpties(Matrix positions){ int index; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]==-1){ index = (j + 1) % this.column; if(m[i][index]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, j); positions.setElement(1, 0, i); positions.setElement(1, 1, index); return; } index = (j + this.column -1) % this.column; if(m[i][index]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, j); positions.setElement(1, 0, i); positions.setElement(1, 1, index); return; } index = (i + 1) % this.row; if(m[index][j]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, j); positions.setElement(1, 0, index); positions.setElement(1, 1, j); return; } index = (i + this.row - 1) % this.row; if(m[index][j]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, j); positions.setElement(1, 0, index); positions.setElement(1, 1, j); return; } } } } } public void findNearEmpty(Matrix positions, int i, int j){ int index; index = (j + 1) % this.column; if(m[i][index]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, index); } index = (j + this.column -1) % this.column; if(m[i][index]==-1){ positions.setElement(0, 0, i); positions.setElement(0, 1, index); } index = (i + 1) % this.row; if(m[index][j]==-1){ positions.setElement(0, 0, index); positions.setElement(0, 1, j); } index = (i + this.row - 1) % this.row; if(m[index][j]==-1){ positions.setElement(0, 0, index); positions.setElement(0, 1, j); } } public boolean full(){ for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ if(m[i][j]==-1) return false; } } return true; } public void clone(Matrix cloned){ cloned.setColumn(this.column); cloned.setRow(this.row); for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ cloned.setElement(i, j, getElement(i,j)); } } } public String toString (){ String s = ""; for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ s = s + (m[i][j] + " "); } s = s + ("\n"); } return s; } public DefaultDirectedWeightedGraph<String, DefaultWeightedEdge> matrixToGraph(){ DefaultDirectedWeightedGraph<String, DefaultWeightedEdge> graph; DefaultWeightedEdge edge = new DefaultWeightedEdge(); int index; graph = new DefaultDirectedWeightedGraph<>(DefaultWeightedEdge.class); for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ graph.addVertex("v" + (int)m[i][j]); } } for(int i=0; i<this.row; i++){ for(int j=0; j<this.column; j++){ index = (j + 1) % this.column; edge = graph.addEdge("v" + (int)m[i][j], "v" + (int)m[i][index]); if(edge != null) graph.setEdgeWeight(edge, 1); index = (j + this.column -1) % this.column; edge = graph.addEdge("v" + (int)m[i][j], "v" + (int)m[i][index]); if(edge != null) graph.setEdgeWeight(edge, 1); index = (i + 1) % this.row; edge = graph.addEdge("v" + (int)m[i][j], "v" + (int)m[index][j]); if(edge != null) graph.setEdgeWeight(edge, 1); index = (i + this.row - 1) % this.row; edge = graph.addEdge("v" + (int)m[i][j], "v" + (int)m[index][j]); if(edge != null) graph.setEdgeWeight(edge, 1); } } return graph; } public void swap(double entry1, double entry2){ int row1; int row2; int col1; int col2; row1 = rowElem(entry1); col1 = colElem(entry1); row2 = rowElem(entry2); col2 = colElem(entry2); m[row1][col1] = entry2; m[row2][col2] = entry1; } }
d1200a5b69750afe1163456411ee89d9ebc432a3
[ "Markdown", "Java" ]
2
Markdown
martema/logic_topology_design
b2fbb5d01ea8862d825118c14d1eff7c19b1a8a9
37fea5368d897fc017307b6ce66116da10ad2500
refs/heads/master
<repo_name>cybort/Xamarin.Android-AlipaySDKBindingDemo<file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='HttpUrlHeader']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/HttpUrlHeader", DoNotGenerateAcw=true)] public partial class HttpUrlHeader : global::Java.Lang.Object, global::Java.IO.ISerializable { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/HttpUrlHeader", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (HttpUrlHeader); } } protected HttpUrlHeader (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlHeader']/constructor[@name='HttpUrlHeader' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe HttpUrlHeader () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (HttpUrlHeader)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_getHeaders; #pragma warning disable 0169 static Delegate GetGetHeadersHandler () { if (cb_getHeaders == null) cb_getHeaders = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetHeaders); return cb_getHeaders; } static IntPtr n_GetHeaders (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (__this.Headers); } #pragma warning restore 0169 static Delegate cb_setHeaders_Ljava_util_Map_; #pragma warning disable 0169 static Delegate GetSetHeaders_Ljava_util_Map_Handler () { if (cb_setHeaders_Ljava_util_Map_ == null) cb_setHeaders_Ljava_util_Map_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetHeaders_Ljava_util_Map_); return cb_setHeaders_Ljava_util_Map_; } static void n_SetHeaders_Ljava_util_Map_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var p0 = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); __this.Headers = p0; } #pragma warning restore 0169 static IntPtr id_getHeaders; static IntPtr id_setHeaders_Ljava_util_Map_; public virtual unsafe global::System.Collections.Generic.IDictionary<string, string> Headers { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlHeader']/method[@name='getHeaders' and count(parameter)=0]" [Register ("getHeaders", "()Ljava/util/Map;", "GetGetHeadersHandler")] get { if (id_getHeaders == IntPtr.Zero) id_getHeaders = JNIEnv.GetMethodID (class_ref, "getHeaders", "()Ljava/util/Map;"); try { if (((object) this).GetType () == ThresholdType) return global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getHeaders), JniHandleOwnership.TransferLocalRef); else return global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getHeaders", "()Ljava/util/Map;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlHeader']/method[@name='setHeaders' and count(parameter)=1 and parameter[1][@type='java.util.Map&lt;java.lang.String, java.lang.String&gt;']]" [Register ("setHeaders", "(Ljava/util/Map;)V", "GetSetHeaders_Ljava_util_Map_Handler")] set { if (id_setHeaders_Ljava_util_Map_ == IntPtr.Zero) id_setHeaders_Ljava_util_Map_ = JNIEnv.GetMethodID (class_ref, "setHeaders", "(Ljava/util/Map;)V"); IntPtr native_value = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setHeaders_Ljava_util_Map_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setHeaders", "(Ljava/util/Map;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static Delegate cb_getHead_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetGetHead_Ljava_lang_String_Handler () { if (cb_getHead_Ljava_lang_String_ == null) cb_getHead_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_GetHead_Ljava_lang_String_); return cb_getHead_Ljava_lang_String_; } static IntPtr n_GetHead_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.GetHead (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_getHead_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='HttpUrlHeader']/method[@name='getHead' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("getHead", "(Ljava/lang/String;)Ljava/lang/String;", "GetGetHead_Ljava_lang_String_Handler")] public virtual unsafe string GetHead (string p0) { if (id_getHead_Ljava_lang_String_ == IntPtr.Zero) id_getHead_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "getHead", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getHead_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getHead", "(Ljava/lang/String;)Ljava/lang/String;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_setHead_Ljava_lang_String_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetHead_Ljava_lang_String_Ljava_lang_String_Handler () { if (cb_setHead_Ljava_lang_String_Ljava_lang_String_ == null) cb_setHead_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_SetHead_Ljava_lang_String_Ljava_lang_String_); return cb_setHead_Ljava_lang_String_Ljava_lang_String_; } static void n_SetHead_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); __this.SetHead (p0, p1); } #pragma warning restore 0169 static IntPtr id_setHead_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='HttpUrlHeader']/method[@name='setHead' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]" [Register ("setHead", "(Ljava/lang/String;Ljava/lang/String;)V", "GetSetHead_Ljava_lang_String_Ljava_lang_String_Handler")] public virtual unsafe void SetHead (string p0, string p1) { if (id_setHead_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_setHead_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setHead", "(Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setHead_Ljava_lang_String_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setHead", "(Ljava/lang/String;Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractDeserializer.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AbstractDeserializer']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractDeserializer", DoNotGenerateAcw=true)] public abstract partial class AbstractDeserializer : global::Java.Lang.Object, global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.IDeserializer { static IntPtr mData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='com.<EMAIL>']/class[@name='AbstractDeserializer']/field[@name='mData']" [Register ("mData")] protected IList<byte> MData { get { if (mData_jfieldId == IntPtr.Zero) mData_jfieldId = JNIEnv.GetFieldID (class_ref, "mData", "[B"); return global::Android.Runtime.JavaArray<byte>.FromJniHandle (JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mData_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (mData_jfieldId == IntPtr.Zero) mData_jfieldId = JNIEnv.GetFieldID (class_ref, "mData", "[B"); IntPtr native_value = global::Android.Runtime.JavaArray<byte>.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core.gwprotocol']/class[@name='AbstractDeserializer']/field[@name='mType']" [Register ("mType")] protected global::Java.Lang.Reflect.IType MType { get { if (mType_jfieldId == IntPtr.Zero) mType_jfieldId = JNIEnv.GetFieldID (class_ref, "mType", "Ljava/lang/reflect/Type;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mType_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.IType> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mType_jfieldId == IntPtr.Zero) mType_jfieldId = JNIEnv.GetFieldID (class_ref, "mType", "Ljava/lang/reflect/Type;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractDeserializer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AbstractDeserializer); } } protected AbstractDeserializer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_reflect_Type_arrayB; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='com.<EMAIL>']/class[@name='AbstractDeserializer']/constructor[@name='AbstractDeserializer' and count(parameter)=2 and parameter[1][@type='java.lang.reflect.Type'] and parameter[2][@type='byte[]']]" [Register (".ctor", "(Ljava/lang/reflect/Type;[B)V", "")] public unsafe AbstractDeserializer (global::Java.Lang.Reflect.IType p0, byte[] p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewArray (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); if (((object) this).GetType () != typeof (AbstractDeserializer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/reflect/Type;[B)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/reflect/Type;[B)V", __args); return; } if (id_ctor_Ljava_lang_reflect_Type_arrayB == IntPtr.Zero) id_ctor_Ljava_lang_reflect_Type_arrayB = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/reflect/Type;[B)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_reflect_Type_arrayB, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_reflect_Type_arrayB, __args); } finally { if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } } static Delegate cb_parser; #pragma warning disable 0169 static Delegate GetParserHandler () { if (cb_parser == null) cb_parser = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Parser); return cb_parser; } static IntPtr n_Parser (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractDeserializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractDeserializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Parser ()); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Deserializer']/method[@name='parser' and count(parameter)=0]" [Register ("parser", "()Ljava/lang/Object;", "GetParserHandler")] public abstract global::Java.Lang.Object Parser (); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractDeserializer", DoNotGenerateAcw=true)] internal partial class AbstractDeserializerInvoker : AbstractDeserializer { public AbstractDeserializerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (AbstractDeserializerInvoker); } } static IntPtr id_parser; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Deserializer']/method[@name='parser' and count(parameter)=0]" [Register ("parser", "()Ljava/lang/Object;", "GetParserHandler")] public override unsafe global::Java.Lang.Object Parser () { if (id_parser == IntPtr.Zero) id_parser = JNIEnv.GetMethodID (class_ref, "parser", "()Ljava/lang/Object;"); try { return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_parser), JniHandleOwnership.TransferLocalRef); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcFactory']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/RpcFactory", DoNotGenerateAcw=true)] public partial class RpcFactory : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/RpcFactory", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RpcFactory); } } protected RpcFactory (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcFactory']/constructor[@name='RpcFactory' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Config']]" [Register (".ctor", "(Lcom/alipay/android/phone/mrpc/core/Config;)V", "")] public unsafe RpcFactory (global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () != typeof (RpcFactory)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Lcom/alipay/android/phone/mrpc/core/Config;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Lcom/alipay/android/phone/mrpc/core/Config;)V", __args); return; } if (id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_ == IntPtr.Zero) id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/alipay/android/phone/mrpc/core/Config;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_, __args); } finally { } } static Delegate cb_getConfig; #pragma warning disable 0169 static Delegate GetGetConfigHandler () { if (cb_getConfig == null) cb_getConfig = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetConfig); return cb_getConfig; } static IntPtr n_GetConfig (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Config); } #pragma warning restore 0169 static IntPtr id_getConfig; public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig Config { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcFactory']/method[@name='getConfig' and count(parameter)=0]" [Register ("getConfig", "()Lcom/alipay/android/phone/mrpc/core/Config;", "GetGetConfigHandler")] get { if (id_getConfig == IntPtr.Zero) id_getConfig = JNIEnv.GetMethodID (class_ref, "getConfig", "()Lcom/alipay/android/phone/mrpc/core/Config;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getConfig), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getConfig", "()Lcom/alipay/android/phone/mrpc/core/Config;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getRpcProxy_Ljava_lang_Class_; #pragma warning disable 0169 static Delegate GetGetRpcProxy_Ljava_lang_Class_Handler () { if (cb_getRpcProxy_Ljava_lang_Class_ == null) cb_getRpcProxy_Ljava_lang_Class_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_GetRpcProxy_Ljava_lang_Class_); return cb_getRpcProxy_Ljava_lang_Class_; } static IntPtr n_GetRpcProxy_Ljava_lang_Class_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Class p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Class> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetRpcProxy (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_getRpcProxy_Ljava_lang_Class_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcFactory']/method[@name='getRpcProxy' and count(parameter)=1 and parameter[1][@type='java.lang.Class&lt;T&gt;']]" [Register ("getRpcProxy", "(Ljava/lang/Class;)Ljava/lang/Object;", "GetGetRpcProxy_Ljava_lang_Class_Handler")] [global::Java.Interop.JavaTypeParameters (new string [] {"T"})] public virtual unsafe global::Java.Lang.Object GetRpcProxy (global::Java.Lang.Class p0) { if (id_getRpcProxy_Ljava_lang_Class_ == IntPtr.Zero) id_getRpcProxy_Ljava_lang_Class_ = JNIEnv.GetMethodID (class_ref, "getRpcProxy", "(Ljava/lang/Class;)Ljava/lang/Object;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Java.Lang.Object __ret; if (((object) this).GetType () == ThresholdType) __ret = (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getRpcProxy_Ljava_lang_Class_, __args), JniHandleOwnership.TransferLocalRef); else __ret = (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getRpcProxy", "(Ljava/lang/Class;)Ljava/lang/Object;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.Util.H5PayResultModel.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.Util { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']" [global::Android.Runtime.Register ("com/alipay/sdk/util/H5PayResultModel", DoNotGenerateAcw=true)] public partial class H5PayResultModel : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/util/H5PayResultModel", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (H5PayResultModel); } } protected H5PayResultModel (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']/constructor[@name='H5PayResultModel' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe H5PayResultModel () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (H5PayResultModel)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_getResultCode; #pragma warning disable 0169 static Delegate GetGetResultCodeHandler () { if (cb_getResultCode == null) cb_getResultCode = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetResultCode); return cb_getResultCode; } static IntPtr n_GetResultCode (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Util.H5PayResultModel __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ResultCode); } #pragma warning restore 0169 static Delegate cb_setResultCode_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetResultCode_Ljava_lang_String_Handler () { if (cb_setResultCode_Ljava_lang_String_ == null) cb_setResultCode_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetResultCode_Ljava_lang_String_); return cb_setResultCode_Ljava_lang_String_; } static void n_SetResultCode_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Sdk.Util.H5PayResultModel __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.ResultCode = p0; } #pragma warning restore 0169 static IntPtr id_getResultCode; static IntPtr id_setResultCode_Ljava_lang_String_; public virtual unsafe string ResultCode { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']/method[@name='getResultCode' and count(parameter)=0]" [Register ("getResultCode", "()Ljava/lang/String;", "GetGetResultCodeHandler")] get { if (id_getResultCode == IntPtr.Zero) id_getResultCode = JNIEnv.GetMethodID (class_ref, "getResultCode", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getResultCode), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getResultCode", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']/method[@name='setResultCode' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("setResultCode", "(Ljava/lang/String;)V", "GetSetResultCode_Ljava_lang_String_Handler")] set { if (id_setResultCode_Ljava_lang_String_ == IntPtr.Zero) id_setResultCode_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setResultCode", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setResultCode_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setResultCode", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static Delegate cb_getReturnUrl; #pragma warning disable 0169 static Delegate GetGetReturnUrlHandler () { if (cb_getReturnUrl == null) cb_getReturnUrl = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetReturnUrl); return cb_getReturnUrl; } static IntPtr n_GetReturnUrl (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Util.H5PayResultModel __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ReturnUrl); } #pragma warning restore 0169 static Delegate cb_setReturnUrl_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetReturnUrl_Ljava_lang_String_Handler () { if (cb_setReturnUrl_Ljava_lang_String_ == null) cb_setReturnUrl_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetReturnUrl_Ljava_lang_String_); return cb_setReturnUrl_Ljava_lang_String_; } static void n_SetReturnUrl_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Sdk.Util.H5PayResultModel __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.ReturnUrl = p0; } #pragma warning restore 0169 static IntPtr id_getReturnUrl; static IntPtr id_setReturnUrl_Ljava_lang_String_; public virtual unsafe string ReturnUrl { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']/method[@name='getReturnUrl' and count(parameter)=0]" [Register ("getReturnUrl", "()Ljava/lang/String;", "GetGetReturnUrlHandler")] get { if (id_getReturnUrl == IntPtr.Zero) id_getReturnUrl = JNIEnv.GetMethodID (class_ref, "getReturnUrl", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getReturnUrl), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getReturnUrl", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='H5PayResultModel']/method[@name='setReturnUrl' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("setReturnUrl", "(Ljava/lang/String;)V", "GetSetReturnUrl_Ljava_lang_String_Handler")] set { if (id_setReturnUrl_Ljava_lang_String_ == IntPtr.Zero) id_setReturnUrl_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setReturnUrl", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setReturnUrl_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setReturnUrl", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.DeviceDataReportResult.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/result/DeviceDataReportResult", DoNotGenerateAcw=true)] public partial class DeviceDataReportResult : global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.BaseResult, global::Java.IO.ISerializable { static IntPtr apdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/field[@name='apdid']" [Register ("apdid")] public string Apdid { get { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr appListVer_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>.vkeydfp.result']/class[@name='DeviceDataReportResult']/field[@name='appListVer']" [Register ("appListVer")] public string AppListVer { get { if (appListVer_jfieldId == IntPtr.Zero) appListVer_jfieldId = JNIEnv.GetFieldID (class_ref, "appListVer", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, appListVer_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (appListVer_jfieldId == IntPtr.Zero) appListVer_jfieldId = JNIEnv.GetFieldID (class_ref, "appListVer", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, appListVer_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr bugTrackSwitch_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.result']/class[@name='DeviceDataReportResult']/field[@name='bugTrackSwitch']" [Register ("bugTrackSwitch")] public string BugTrackSwitch { get { if (bugTrackSwitch_jfieldId == IntPtr.Zero) bugTrackSwitch_jfieldId = JNIEnv.GetFieldID (class_ref, "bugTrackSwitch", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, bugTrackSwitch_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (bugTrackSwitch_jfieldId == IntPtr.Zero) bugTrackSwitch_jfieldId = JNIEnv.GetFieldID (class_ref, "bugTrackSwitch", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, bugTrackSwitch_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr currentTime_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/field[@name='currentTime']" [Register ("currentTime")] public string CurrentTime { get { if (currentTime_jfieldId == IntPtr.Zero) currentTime_jfieldId = JNIEnv.GetFieldID (class_ref, "currentTime", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, currentTime_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (currentTime_jfieldId == IntPtr.Zero) currentTime_jfieldId = JNIEnv.GetFieldID (class_ref, "currentTime", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, currentTime_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr token_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/field[@name='token']" [Register ("token")] public string Token { get { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, token_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, token_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr version_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/field[@name='version']" [Register ("version")] public string Version { get { if (version_jfieldId == IntPtr.Zero) version_jfieldId = JNIEnv.GetFieldID (class_ref, "version", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, version_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (version_jfieldId == IntPtr.Zero) version_jfieldId = JNIEnv.GetFieldID (class_ref, "version", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, version_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr vkeySwitch_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/field[@name='vkeySwitch']" [Register ("vkeySwitch")] public string VkeySwitch { get { if (vkeySwitch_jfieldId == IntPtr.Zero) vkeySwitch_jfieldId = JNIEnv.GetFieldID (class_ref, "vkeySwitch", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, vkeySwitch_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (vkeySwitch_jfieldId == IntPtr.Zero) vkeySwitch_jfieldId = JNIEnv.GetFieldID (class_ref, "vkeySwitch", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, vkeySwitch_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/result/DeviceDataReportResult", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DeviceDataReportResult); } } protected DeviceDataReportResult (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportResult']/constructor[@name='DeviceDataReportResult' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe DeviceDataReportResult () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (DeviceDataReportResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Mobile.Framework.Service.Annotation.OperationTypeAttribute.cs using System; namespace Com.Alipay.Mobile.Framework.Service.Annotation { [global::Android.Runtime.Annotation ("com.alipay.mobile.framework.service.annotation.OperationType")] public partial class OperationTypeAttribute : Attribute { [global::Android.Runtime.Register ("value")] public string Value { get; set; } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.UT.Device.UTDevice.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.UT.Device { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='UTDevice']" [global::Android.Runtime.Register ("com/ut/device/UTDevice", DoNotGenerateAcw=true)] public partial class UTDevice : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/ut/device/UTDevice", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (UTDevice); } } protected UTDevice (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='UTDevice']/constructor[@name='UTDevice' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe UTDevice () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (UTDevice)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_getAid_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='UTDevice']/method[@name='getAid' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='android.content.Context']]" [Register ("getAid", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/Context;)Ljava/lang/String;", "")] public static unsafe string GetAid (string p0, string p1, global::Android.Content.Context p2) { if (id_getAid_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_ == IntPtr.Zero) id_getAid_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "getAid", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/Context;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getAid_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_getAidAsync_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_Lcom_ut_device_AidCallback_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='UTDevice']/method[@name='getAidAsync' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='android.content.Context'] and parameter[4][@type='com.ut.device.AidCallback']]" [Register ("getAidAsync", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/Context;Lcom/ut/device/AidCallback;)V", "")] public static unsafe void GetAidAsync (string p0, string p1, global::Android.Content.Context p2, global::Com.UT.Device.IAidCallback p3) { if (id_getAidAsync_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_Lcom_ut_device_AidCallback_ == IntPtr.Zero) id_getAidAsync_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_Lcom_ut_device_AidCallback_ = JNIEnv.GetStaticMethodID (class_ref, "getAidAsync", "(Ljava/lang/String;Ljava/lang/String;Landroid/content/Context;Lcom/ut/device/AidCallback;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); JNIEnv.CallStaticVoidMethod (class_ref, id_getAidAsync_Ljava_lang_String_Ljava_lang_String_Landroid_content_Context_Lcom_ut_device_AidCallback_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_getUtdid_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='UTDevice']/method[@name='getUtdid' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("getUtdid", "(Landroid/content/Context;)Ljava/lang/String;", "")] public static unsafe string GetUtdid (global::Android.Content.Context p0) { if (id_getUtdid_Landroid_content_Context_ == IntPtr.Zero) id_getUtdid_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "getUtdid", "(Landroid/content/Context;)Ljava/lang/String;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getUtdid_Landroid_content_Context_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.AbstractRpcCaller.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AbstractRpcCaller']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/AbstractRpcCaller", DoNotGenerateAcw=true)] public abstract partial class AbstractRpcCaller : global::Java.Lang.Object, global::Com.Alipay.Android.Phone.Mrpc.Core.IRpcCaller { static IntPtr mContentType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AbstractRpcCaller']/field[@name='mContentType']" [Register ("mContentType")] protected string MContentType { get { if (mContentType_jfieldId == IntPtr.Zero) mContentType_jfieldId = JNIEnv.GetFieldID (class_ref, "mContentType", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mContentType_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mContentType_jfieldId == IntPtr.Zero) mContentType_jfieldId = JNIEnv.GetFieldID (class_ref, "mContentType", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mContentType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mId_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AbstractRpcCaller']/field[@name='mId']" [Register ("mId")] protected int MId { get { if (mId_jfieldId == IntPtr.Zero) mId_jfieldId = JNIEnv.GetFieldID (class_ref, "mId", "I"); return JNIEnv.GetIntField (((global::Java.Lang.Object) this).Handle, mId_jfieldId); } set { if (mId_jfieldId == IntPtr.Zero) mId_jfieldId = JNIEnv.GetFieldID (class_ref, "mId", "I"); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mId_jfieldId, value); } finally { } } } static IntPtr mMethod_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='AbstractRpcCaller']/field[@name='mMethod']" [Register ("mMethod")] protected global::Java.Lang.Reflect.Method MMethod { get { if (mMethod_jfieldId == IntPtr.Zero) mMethod_jfieldId = JNIEnv.GetFieldID (class_ref, "mMethod", "Ljava/lang/reflect/Method;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mMethod_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.Method> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mMethod_jfieldId == IntPtr.Zero) mMethod_jfieldId = JNIEnv.GetFieldID (class_ref, "mMethod", "Ljava/lang/reflect/Method;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mMethod_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mOperationType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='AbstractRpcCaller']/field[@name='mOperationType']" [Register ("mOperationType")] protected string MOperationType { get { if (mOperationType_jfieldId == IntPtr.Zero) mOperationType_jfieldId = JNIEnv.GetFieldID (class_ref, "mOperationType", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mOperationType_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mOperationType_jfieldId == IntPtr.Zero) mOperationType_jfieldId = JNIEnv.GetFieldID (class_ref, "mOperationType", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mOperationType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mReqData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='AbstractRpcCaller']/field[@name='mReqData']" [Register ("mReqData")] protected IList<byte> MReqData { get { if (mReqData_jfieldId == IntPtr.Zero) mReqData_jfieldId = JNIEnv.GetFieldID (class_ref, "mReqData", "[B"); return global::Android.Runtime.JavaArray<byte>.FromJniHandle (JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mReqData_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (mReqData_jfieldId == IntPtr.Zero) mReqData_jfieldId = JNIEnv.GetFieldID (class_ref, "mReqData", "[B"); IntPtr native_value = global::Android.Runtime.JavaArray<byte>.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mReqData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mResetCookie_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AbstractRpcCaller']/field[@name='mResetCookie']" [Register ("mResetCookie")] protected bool MResetCookie { get { if (mResetCookie_jfieldId == IntPtr.Zero) mResetCookie_jfieldId = JNIEnv.GetFieldID (class_ref, "mResetCookie", "Z"); return JNIEnv.GetBooleanField (((global::Java.Lang.Object) this).Handle, mResetCookie_jfieldId); } set { if (mResetCookie_jfieldId == IntPtr.Zero) mResetCookie_jfieldId = JNIEnv.GetFieldID (class_ref, "mResetCookie", "Z"); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mResetCookie_jfieldId, value); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/AbstractRpcCaller", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AbstractRpcCaller); } } protected AbstractRpcCaller (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBLjava_lang_String_Z; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>.android.phone.mrpc.core']/class[@name='AbstractRpcCaller']/constructor[@name='AbstractRpcCaller' and count(parameter)=6 and parameter[1][@type='java.lang.reflect.Method'] and parameter[2][@type='int'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='byte[]'] and parameter[5][@type='java.lang.String'] and parameter[6][@type='boolean']]" [Register (".ctor", "(Ljava/lang/reflect/Method;ILjava/lang/String;[BLjava/lang/String;Z)V", "")] public unsafe AbstractRpcCaller (global::Java.Lang.Reflect.Method p0, int p1, string p2, byte[] p3, string p4, bool p5) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p2 = JNIEnv.NewString (p2); IntPtr native_p3 = JNIEnv.NewArray (p3); IntPtr native_p4 = JNIEnv.NewString (p4); try { JValue* __args = stackalloc JValue [6]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); __args [3] = new JValue (native_p3); __args [4] = new JValue (native_p4); __args [5] = new JValue (p5); if (((object) this).GetType () != typeof (AbstractRpcCaller)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/reflect/Method;ILjava/lang/String;[BLjava/lang/String;Z)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/reflect/Method;ILjava/lang/String;[BLjava/lang/String;Z)V", __args); return; } if (id_ctor_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBLjava_lang_String_Z == IntPtr.Zero) id_ctor_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBLjava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/reflect/Method;ILjava/lang/String;[BLjava/lang/String;Z)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBLjava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBLjava_lang_String_Z, __args); } finally { JNIEnv.DeleteLocalRef (native_p2); if (p3 != null) { JNIEnv.CopyArray (native_p3, p3); JNIEnv.DeleteLocalRef (native_p3); } JNIEnv.DeleteLocalRef (native_p4); } } static Delegate cb_call; #pragma warning disable 0169 static Delegate GetCallHandler () { if (cb_call == null) cb_call = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Call); return cb_call; } static IntPtr n_Call (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.AbstractRpcCaller __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.AbstractRpcCaller> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Call ()); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='RpcCaller']/method[@name='call' and count(parameter)=0]" [Register ("call", "()Ljava/lang/Object;", "GetCallHandler")] public abstract global::Java.Lang.Object Call (); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/AbstractRpcCaller", DoNotGenerateAcw=true)] internal partial class AbstractRpcCallerInvoker : AbstractRpcCaller { public AbstractRpcCallerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (AbstractRpcCallerInvoker); } } static IntPtr id_call; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='RpcCaller']/method[@name='call' and count(parameter)=0]" [Register ("call", "()Ljava/lang/Object;", "GetCallHandler")] public override unsafe global::Java.Lang.Object Call () { if (id_call == IntPtr.Zero) id_call = JNIEnv.GetMethodID (class_ref, "call", "()Ljava/lang/Object;"); try { return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_call), JniHandleOwnership.TransferLocalRef); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.DeviceDataReportRequest.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/request/DeviceDataReportRequest", DoNotGenerateAcw=true)] public partial class DeviceDataReportRequest : global::Java.Lang.Object, global::Java.IO.ISerializable { static IntPtr apdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='apdid']" [Register ("apdid")] public string Apdid { get { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr dataMap_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='dataMap']" [Register ("dataMap")] public global::System.Collections.IDictionary DataMap { get { if (dataMap_jfieldId == IntPtr.Zero) dataMap_jfieldId = JNIEnv.GetFieldID (class_ref, "dataMap", "Ljava/util/Map;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, dataMap_jfieldId); return global::Android.Runtime.JavaDictionary.FromJniHandle (__ret, JniHandleOwnership.TransferLocalRef); } set { if (dataMap_jfieldId == IntPtr.Zero) dataMap_jfieldId = JNIEnv.GetFieldID (class_ref, "dataMap", "Ljava/util/Map;"); IntPtr native_value = global::Android.Runtime.JavaDictionary.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, dataMap_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr lastTime_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='lastTime']" [Register ("lastTime")] public string LastTime { get { if (lastTime_jfieldId == IntPtr.Zero) lastTime_jfieldId = JNIEnv.GetFieldID (class_ref, "lastTime", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, lastTime_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (lastTime_jfieldId == IntPtr.Zero) lastTime_jfieldId = JNIEnv.GetFieldID (class_ref, "lastTime", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, lastTime_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr os_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.<EMAIL>.tscenter.biz.rpc.vkeydfp.request']/class[@name='DeviceDataReportRequest']/field[@name='os']" [Register ("os")] public string Os { get { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, os_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, os_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr priApdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.request']/class[@name='DeviceDataReportRequest']/field[@name='priApdid']" [Register ("priApdid")] public string PriApdid { get { if (priApdid_jfieldId == IntPtr.Zero) priApdid_jfieldId = JNIEnv.GetFieldID (class_ref, "priApdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, priApdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (priApdid_jfieldId == IntPtr.Zero) priApdid_jfieldId = JNIEnv.GetFieldID (class_ref, "priApdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, priApdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr pubApdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='pubApdid']" [Register ("pubApdid")] public string PubApdid { get { if (pubApdid_jfieldId == IntPtr.Zero) pubApdid_jfieldId = JNIEnv.GetFieldID (class_ref, "pubApdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, pubApdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (pubApdid_jfieldId == IntPtr.Zero) pubApdid_jfieldId = JNIEnv.GetFieldID (class_ref, "pubApdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, pubApdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr token_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='token']" [Register ("token")] public string Token { get { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, token_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, token_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr umidToken_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.request']/class[@name='DeviceDataReportRequest']/field[@name='umidToken']" [Register ("umidToken")] public string UmidToken { get { if (umidToken_jfieldId == IntPtr.Zero) umidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "umidToken", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, umidToken_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (umidToken_jfieldId == IntPtr.Zero) umidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "umidToken", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, umidToken_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr version_jfieldId; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/field[@name='version']" [Register ("version")] public string Version { get { if (version_jfieldId == IntPtr.Zero) version_jfieldId = JNIEnv.GetFieldID (class_ref, "version", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, version_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (version_jfieldId == IntPtr.Zero) version_jfieldId = JNIEnv.GetFieldID (class_ref, "version", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, version_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/request/DeviceDataReportRequest", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DeviceDataReportRequest); } } protected DeviceDataReportRequest (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/<EMAIL>='<EMAIL>']/class[@name='DeviceDataReportRequest']/constructor[@name='DeviceDataReportRequest' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe DeviceDataReportRequest () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (DeviceDataReportRequest)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.BaseResult.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='BaseResult']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/result/BaseResult", DoNotGenerateAcw=true)] public partial class BaseResult : global::Java.Lang.Object, global::Java.IO.ISerializable { static IntPtr resultCode_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='BaseResult']/field[@name='resultCode']" [Register ("resultCode")] public string ResultCode { get { if (resultCode_jfieldId == IntPtr.Zero) resultCode_jfieldId = JNIEnv.GetFieldID (class_ref, "resultCode", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, resultCode_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (resultCode_jfieldId == IntPtr.Zero) resultCode_jfieldId = JNIEnv.GetFieldID (class_ref, "resultCode", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, resultCode_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr success_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='BaseResult']/field[@name='success']" [Register ("success")] public bool Success { get { if (success_jfieldId == IntPtr.Zero) success_jfieldId = JNIEnv.GetFieldID (class_ref, "success", "Z"); return JNIEnv.GetBooleanField (((global::Java.Lang.Object) this).Handle, success_jfieldId); } set { if (success_jfieldId == IntPtr.Zero) success_jfieldId = JNIEnv.GetFieldID (class_ref, "success", "Z"); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, success_jfieldId, value); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/result/BaseResult", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (BaseResult); } } protected BaseResult (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.<EMAIL>.rpc.vkeydfp.result']/class[@name='BaseResult']/constructor[@name='BaseResult' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe BaseResult () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (BaseResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/RpcInvoker", DoNotGenerateAcw=true)] public partial class RpcInvoker : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/RpcInvoker", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RpcInvoker); } } protected RpcInvoker (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lcom_alipay_android_phone_mrpc_core_RpcFactory_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']/constructor[@name='RpcInvoker' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.RpcFactory']]" [Register (".ctor", "(Lcom/alipay/android/phone/mrpc/core/RpcFactory;)V", "")] public unsafe RpcInvoker (global::Com.Alipay.Android.Phone.Mrpc.Core.RpcFactory p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () != typeof (RpcInvoker)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Lcom/alipay/android/phone/mrpc/core/RpcFactory;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Lcom/alipay/android/phone/mrpc/core/RpcFactory;)V", __args); return; } if (id_ctor_Lcom_alipay_android_phone_mrpc_core_RpcFactory_ == IntPtr.Zero) id_ctor_Lcom_alipay_android_phone_mrpc_core_RpcFactory_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/alipay/android/phone/mrpc/core/RpcFactory;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_RpcFactory_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_RpcFactory_, __args); } finally { } } static IntPtr id_addProtocolArgs_Ljava_lang_String_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='com.<EMAIL>.mrpc.core']/class[@name='RpcInvoker']/method[@name='addProtocolArgs' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.Object']]" [Register ("addProtocolArgs", "(Ljava/lang/String;Ljava/lang/Object;)V", "")] public static unsafe void AddProtocolArgs (string p0, global::Java.Lang.Object p1) { if (id_addProtocolArgs_Ljava_lang_String_Ljava_lang_Object_ == IntPtr.Zero) id_addProtocolArgs_Ljava_lang_String_Ljava_lang_Object_ = JNIEnv.GetStaticMethodID (class_ref, "addProtocolArgs", "(Ljava/lang/String;Ljava/lang/Object;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_addProtocolArgs_Ljava_lang_String_Ljava_lang_Object_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_batchBegin; #pragma warning disable 0169 static Delegate GetBatchBeginHandler () { if (cb_batchBegin == null) cb_batchBegin = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_BatchBegin); return cb_batchBegin; } static void n_BatchBegin (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.BatchBegin (); } #pragma warning restore 0169 static IntPtr id_batchBegin; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']/method[@name='batchBegin' and count(parameter)=0]" [Register ("batchBegin", "()V", "GetBatchBeginHandler")] public virtual unsafe void BatchBegin () { if (id_batchBegin == IntPtr.Zero) id_batchBegin = JNIEnv.GetMethodID (class_ref, "batchBegin", "()V"); try { if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_batchBegin); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "batchBegin", "()V")); } finally { } } static Delegate cb_batchCommit; #pragma warning disable 0169 static Delegate GetBatchCommitHandler () { if (cb_batchCommit == null) cb_batchCommit = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_BatchCommit); return cb_batchCommit; } static IntPtr n_BatchCommit (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.BatchCommit ()); } #pragma warning restore 0169 static IntPtr id_batchCommit; // Metadata.xml XPath method reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='RpcInvoker']/method[@name='batchCommit' and count(parameter)=0]" [Register ("batchCommit", "()Ljava/util/concurrent/FutureTask;", "GetBatchCommitHandler")] public virtual unsafe global::Java.Util.Concurrent.FutureTask BatchCommit () { if (id_batchCommit == IntPtr.Zero) id_batchCommit = JNIEnv.GetMethodID (class_ref, "batchCommit", "()Ljava/util/concurrent/FutureTask;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Java.Util.Concurrent.FutureTask> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_batchCommit), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Java.Util.Concurrent.FutureTask> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "batchCommit", "()Ljava/util/concurrent/FutureTask;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_getDeserializer_Ljava_lang_reflect_Type_arrayB; #pragma warning disable 0169 static Delegate GetGetDeserializer_Ljava_lang_reflect_Type_arrayBHandler () { if (cb_getDeserializer_Ljava_lang_reflect_Type_arrayB == null) cb_getDeserializer_Ljava_lang_reflect_Type_arrayB = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_GetDeserializer_Ljava_lang_reflect_Type_arrayB); return cb_getDeserializer_Ljava_lang_reflect_Type_arrayB; } static IntPtr n_GetDeserializer_Ljava_lang_reflect_Type_arrayB (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Reflect.IType p0 = (global::Java.Lang.Reflect.IType)global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.IType> (native_p0, JniHandleOwnership.DoNotTransfer); byte[] p1 = (byte[]) JNIEnv.GetArray (native_p1, JniHandleOwnership.DoNotTransfer, typeof (byte)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetDeserializer (p0, p1)); if (p1 != null) JNIEnv.CopyArray (p1, native_p1); return __ret; } #pragma warning restore 0169 static IntPtr id_getDeserializer_Ljava_lang_reflect_Type_arrayB; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']/method[@name='getDeserializer' and count(parameter)=2 and parameter[1][@type='java.lang.reflect.Type'] and parameter[2][@type='byte[]']]" [Register ("getDeserializer", "(Ljava/lang/reflect/Type;[B)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Deserializer;", "GetGetDeserializer_Ljava_lang_reflect_Type_arrayBHandler")] public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.IDeserializer GetDeserializer (global::Java.Lang.Reflect.IType p0, byte[] p1) { if (id_getDeserializer_Ljava_lang_reflect_Type_arrayB == IntPtr.Zero) id_getDeserializer_Ljava_lang_reflect_Type_arrayB = JNIEnv.GetMethodID (class_ref, "getDeserializer", "(Ljava/lang/reflect/Type;[B)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Deserializer;"); IntPtr native_p1 = JNIEnv.NewArray (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.IDeserializer __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.IDeserializer> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getDeserializer_Ljava_lang_reflect_Type_arrayB, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.IDeserializer> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getDeserializer", "(Ljava/lang/reflect/Type;[B)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Deserializer;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } } static Delegate cb_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_; #pragma warning disable 0169 static Delegate GetGetSerializer_ILjava_lang_String_arrayLjava_lang_Object_Handler () { if (cb_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_ == null) cb_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr, IntPtr, IntPtr>) n_GetSerializer_ILjava_lang_String_arrayLjava_lang_Object_); return cb_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_; } static IntPtr n_GetSerializer_ILjava_lang_String_arrayLjava_lang_Object_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object[] p2 = (global::Java.Lang.Object[]) JNIEnv.GetArray (native_p2, JniHandleOwnership.DoNotTransfer, typeof (global::Java.Lang.Object)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetSerializer (p0, p1, p2)); if (p2 != null) JNIEnv.CopyArray (p2, native_p2); return __ret; } #pragma warning restore 0169 static IntPtr id_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']/method[@name='getSerializer' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.Object[]']]" [Register ("getSerializer", "(ILjava/lang/String;[Ljava/lang/Object;)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Serializer;", "GetGetSerializer_ILjava_lang_String_arrayLjava_lang_Object_Handler")] public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer GetSerializer (int p0, string p1, global::Java.Lang.Object[] p2) { if (id_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_ == IntPtr.Zero) id_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "getSerializer", "(ILjava/lang/String;[Ljava/lang/Object;)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Serializer;"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewArray (p2); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (native_p2); global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getSerializer_ILjava_lang_String_arrayLjava_lang_Object_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getSerializer", "(ILjava/lang/String;[Ljava/lang/Object;)Lcom/alipay/android/phone/mrpc/core/gwprotocol/Serializer;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p1); if (p2 != null) { JNIEnv.CopyArray (native_p2, p2); JNIEnv.DeleteLocalRef (native_p2); } } } static Delegate cb_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ; #pragma warning disable 0169 static Delegate GetGetTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZHandler () { if (cb_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ == null) cb_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, int, IntPtr, IntPtr, bool, IntPtr>) n_GetTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ); return cb_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ; } static IntPtr n_GetTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1, IntPtr native_p2, IntPtr native_p3, bool p4) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Reflect.Method p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.Method> (native_p0, JniHandleOwnership.DoNotTransfer); string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer); byte[] p3 = (byte[]) JNIEnv.GetArray (native_p3, JniHandleOwnership.DoNotTransfer, typeof (byte)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetTransport (p0, p1, p2, p3, p4)); if (p3 != null) JNIEnv.CopyArray (p3, native_p3); return __ret; } #pragma warning restore 0169 static IntPtr id_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvoker']/method[@name='getTransport' and count(parameter)=5 and parameter[1][@type='java.lang.reflect.Method'] and parameter[2][@type='int'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='byte[]'] and parameter[5][@type='boolean']]" [Register ("getTransport", "(Ljava/lang/reflect/Method;ILjava/lang/String;[BZ)Lcom/alipay/android/phone/mrpc/core/RpcCaller;", "GetGetTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZHandler")] public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.IRpcCaller GetTransport (global::Java.Lang.Reflect.Method p0, int p1, string p2, byte[] p3, bool p4) { if (id_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ == IntPtr.Zero) id_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ = JNIEnv.GetMethodID (class_ref, "getTransport", "(Ljava/lang/reflect/Method;ILjava/lang/String;[BZ)Lcom/alipay/android/phone/mrpc/core/RpcCaller;"); IntPtr native_p2 = JNIEnv.NewString (p2); IntPtr native_p3 = JNIEnv.NewArray (p3); try { JValue* __args = stackalloc JValue [5]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); __args [3] = new JValue (native_p3); __args [4] = new JValue (p4); global::Com.Alipay.Android.Phone.Mrpc.Core.IRpcCaller __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IRpcCaller> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getTransport_Ljava_lang_reflect_Method_ILjava_lang_String_arrayBZ, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IRpcCaller> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getTransport", "(Ljava/lang/reflect/Method;ILjava/lang/String;[BZ)Lcom/alipay/android/phone/mrpc/core/RpcCaller;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p2); if (p3 != null) { JNIEnv.CopyArray (native_p3, p3); JNIEnv.DeleteLocalRef (native_p3); } } } static Delegate cb_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; #pragma warning disable 0169 static Delegate GetInvoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_Handler () { if (cb_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ == null) cb_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_Invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_); return cb_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; } static IntPtr n_Invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Class p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Class> (native_p1, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Reflect.Method p2 = global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.Method> (native_p2, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object[] p3 = (global::Java.Lang.Object[]) JNIEnv.GetArray (native_p3, JniHandleOwnership.DoNotTransfer, typeof (global::Java.Lang.Object)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.Invoke (p0, p1, p2, p3)); if (p3 != null) JNIEnv.CopyArray (p3, native_p3); return __ret; } #pragma warning restore 0169 static IntPtr id_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.<EMAIL>']/class[@name='RpcInvoker']/method[@name='invoke' and count(parameter)=4 and parameter[1][@type='java.lang.Object'] and parameter[2][@type='java.lang.Class&lt;?&gt;'] and parameter[3][@type='java.lang.reflect.Method'] and parameter[4][@type='java.lang.Object[]']]" [Register ("invoke", "(Ljava/lang/Object;Ljava/lang/Class;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;", "GetInvoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_Handler")] public virtual unsafe global::Java.Lang.Object Invoke (global::Java.Lang.Object p0, global::Java.Lang.Class p1, global::Java.Lang.Reflect.Method p2, global::Java.Lang.Object[] p3) { if (id_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ == IntPtr.Zero) id_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "invoke", "(Ljava/lang/Object;Ljava/lang/Class;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"); IntPtr native_p3 = JNIEnv.NewArray (p3); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (native_p3); global::Java.Lang.Object __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_invoke_Ljava_lang_Object_Ljava_lang_Class_Ljava_lang_reflect_Method_arrayLjava_lang_Object_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "invoke", "(Ljava/lang/Object;Ljava/lang/Class;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { if (p3 != null) { JNIEnv.CopyArray (native_p3, p3); JNIEnv.DeleteLocalRef (native_p3); } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol { // Metadata.xml XPath interface reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Serializer']" [Register ("com/alipay/android/phone/mrpc/core/gwprotocol/Serializer", "", "Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializerInvoker")] public partial interface ISerializer : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='packet' and count(parameter)=0]" [Register ("packet", "()[B", "GetPacketHandler:Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializerInvoker, AlipayBindingDemo")] byte[] Packet (); // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='setExtParam' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("setExtParam", "(Ljava/lang/Object;)V", "GetSetExtParam_Ljava_lang_Object_Handler:Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializerInvoker, AlipayBindingDemo")] void SetExtParam (global::Java.Lang.Object p0); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/Serializer", DoNotGenerateAcw=true)] internal class ISerializerInvoker : global::Java.Lang.Object, ISerializer { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/gwprotocol/Serializer"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ISerializerInvoker); } } IntPtr class_ref; public static ISerializer GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<ISerializer> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.phone.mrpc.core.gwprotocol.Serializer")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public ISerializerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_packet; #pragma warning disable 0169 static Delegate GetPacketHandler () { if (cb_packet == null) cb_packet = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Packet); return cb_packet; } static IntPtr n_Packet (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewArray (__this.Packet ()); } #pragma warning restore 0169 IntPtr id_packet; public unsafe byte[] Packet () { if (id_packet == IntPtr.Zero) id_packet = JNIEnv.GetMethodID (class_ref, "packet", "()[B"); return (byte[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_packet), JniHandleOwnership.TransferLocalRef, typeof (byte)); } static Delegate cb_setExtParam_Ljava_lang_Object_; #pragma warning disable 0169 static Delegate GetSetExtParam_Ljava_lang_Object_Handler () { if (cb_setExtParam_Ljava_lang_Object_ == null) cb_setExtParam_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetExtParam_Ljava_lang_Object_); return cb_setExtParam_Ljava_lang_Object_; } static void n_SetExtParam_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetExtParam (p0); } #pragma warning restore 0169 IntPtr id_setExtParam_Ljava_lang_Object_; public unsafe void SetExtParam (global::Java.Lang.Object p0) { if (id_setExtParam_Ljava_lang_Object_ == IntPtr.Zero) id_setExtParam_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "setExtParam", "(Ljava/lang/Object;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setExtParam_Ljava_lang_Object_, __args); } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.IConfig.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath interface reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Config']" [Register ("com/alipay/android/phone/mrpc/core/Config", "", "Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker")] public partial interface IConfig : IJavaObject { global::Android.Content.Context ApplicationContext { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Config']/method[@name='getApplicationContext' and count(parameter)=0]" [Register ("getApplicationContext", "()Landroid/content/Context;", "GetGetApplicationContextHandler:Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker, AlipayBindingDemo")] get; } bool IsGzip { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Config']/method[@name='isGzip' and count(parameter)=0]" [Register ("isGzip", "()Z", "GetIsGzipHandler:Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker, AlipayBindingDemo")] get; } global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams RpcParams { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Config']/method[@name='getRpcParams' and count(parameter)=0]" [Register ("getRpcParams", "()Lcom/alipay/android/phone/mrpc/core/RpcParams;", "GetGetRpcParamsHandler:Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker, AlipayBindingDemo")] get; } global::Com.Alipay.Android.Phone.Mrpc.Core.ITransport Transport { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Config']/method[@name='getTransport' and count(parameter)=0]" [Register ("getTransport", "()Lcom/alipay/android/phone/mrpc/core/Transport;", "GetGetTransportHandler:Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker, AlipayBindingDemo")] get; } string Url { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Config']/method[@name='getUrl' and count(parameter)=0]" [Register ("getUrl", "()Ljava/lang/String;", "GetGetUrlHandler:Com.Alipay.Android.Phone.Mrpc.Core.IConfigInvoker, AlipayBindingDemo")] get; } } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/Config", DoNotGenerateAcw=true)] internal class IConfigInvoker : global::Java.Lang.Object, IConfig { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/Config"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IConfigInvoker); } } IntPtr class_ref; public static IConfig GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IConfig> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.phone.mrpc.core.Config")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IConfigInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_getApplicationContext; #pragma warning disable 0169 static Delegate GetGetApplicationContextHandler () { if (cb_getApplicationContext == null) cb_getApplicationContext = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetApplicationContext); return cb_getApplicationContext; } static IntPtr n_GetApplicationContext (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.ApplicationContext); } #pragma warning restore 0169 IntPtr id_getApplicationContext; public unsafe global::Android.Content.Context ApplicationContext { get { if (id_getApplicationContext == IntPtr.Zero) id_getApplicationContext = JNIEnv.GetMethodID (class_ref, "getApplicationContext", "()Landroid/content/Context;"); return global::Java.Lang.Object.GetObject<global::Android.Content.Context> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getApplicationContext), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_isGzip; #pragma warning disable 0169 static Delegate GetIsGzipHandler () { if (cb_isGzip == null) cb_isGzip = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsGzip); return cb_isGzip; } static bool n_IsGzip (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsGzip; } #pragma warning restore 0169 IntPtr id_isGzip; public unsafe bool IsGzip { get { if (id_isGzip == IntPtr.Zero) id_isGzip = JNIEnv.GetMethodID (class_ref, "isGzip", "()Z"); return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isGzip); } } static Delegate cb_getRpcParams; #pragma warning disable 0169 static Delegate GetGetRpcParamsHandler () { if (cb_getRpcParams == null) cb_getRpcParams = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetRpcParams); return cb_getRpcParams; } static IntPtr n_GetRpcParams (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.RpcParams); } #pragma warning restore 0169 IntPtr id_getRpcParams; public unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams RpcParams { get { if (id_getRpcParams == IntPtr.Zero) id_getRpcParams = JNIEnv.GetMethodID (class_ref, "getRpcParams", "()Lcom/alipay/android/phone/mrpc/core/RpcParams;"); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getRpcParams), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getTransport; #pragma warning disable 0169 static Delegate GetGetTransportHandler () { if (cb_getTransport == null) cb_getTransport = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetTransport); return cb_getTransport; } static IntPtr n_GetTransport (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Transport); } #pragma warning restore 0169 IntPtr id_getTransport; public unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.ITransport Transport { get { if (id_getTransport == IntPtr.Zero) id_getTransport = JNIEnv.GetMethodID (class_ref, "getTransport", "()Lcom/alipay/android/phone/mrpc/core/Transport;"); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransport> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getTransport), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getUrl; #pragma warning disable 0169 static Delegate GetGetUrlHandler () { if (cb_getUrl == null) cb_getUrl = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetUrl); return cb_getUrl; } static IntPtr n_GetUrl (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Url); } #pragma warning restore 0169 IntPtr id_getUrl; public unsafe string Url { get { if (id_getUrl == IntPtr.Zero) id_getUrl = JNIEnv.GetMethodID (class_ref, "getUrl", "()Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getUrl), JniHandleOwnership.TransferLocalRef); } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AbstractSerializer']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractSerializer", DoNotGenerateAcw=true)] public abstract partial class AbstractSerializer : global::Java.Lang.Object, global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.ISerializer { static IntPtr mOperationType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='com.<EMAIL>pc.core.gwprotocol']/class[@name='AbstractSerializer']/field[@name='mOperationType']" [Register ("mOperationType")] protected string MOperationType { get { if (mOperationType_jfieldId == IntPtr.Zero) mOperationType_jfieldId = JNIEnv.GetFieldID (class_ref, "mOperationType", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mOperationType_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mOperationType_jfieldId == IntPtr.Zero) mOperationType_jfieldId = JNIEnv.GetFieldID (class_ref, "mOperationType", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mOperationType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mParams_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core.gwprotocol']/class[@name='AbstractSerializer']/field[@name='mParams']" [Register ("mParams")] protected global::Java.Lang.Object MParams { get { if (mParams_jfieldId == IntPtr.Zero) mParams_jfieldId = JNIEnv.GetFieldID (class_ref, "mParams", "Ljava/lang/Object;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mParams_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mParams_jfieldId == IntPtr.Zero) mParams_jfieldId = JNIEnv.GetFieldID (class_ref, "mParams", "Ljava/lang/Object;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mParams_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractSerializer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AbstractSerializer); } } protected AbstractSerializer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_Object_; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.<EMAIL>.android.phone.mrpc.core.gwprotocol']/class[@name='AbstractSerializer']/constructor[@name='AbstractSerializer' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.Object']]" [Register (".ctor", "(Ljava/lang/String;Ljava/lang/Object;)V", "")] public unsafe AbstractSerializer (string p0, global::Java.Lang.Object p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); if (((object) this).GetType () != typeof (AbstractSerializer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/String;Ljava/lang/Object;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/String;Ljava/lang/Object;)V", __args); return; } if (id_ctor_Ljava_lang_String_Ljava_lang_Object_ == IntPtr.Zero) id_ctor_Ljava_lang_String_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/Object;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_Object_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_Object_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_packet; #pragma warning disable 0169 static Delegate GetPacketHandler () { if (cb_packet == null) cb_packet = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Packet); return cb_packet; } static IntPtr n_Packet (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewArray (__this.Packet ()); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='packet' and count(parameter)=0]" [Register ("packet", "()[B", "GetPacketHandler")] public abstract byte[] Packet (); static Delegate cb_setExtParam_Ljava_lang_Object_; #pragma warning disable 0169 static Delegate GetSetExtParam_Ljava_lang_Object_Handler () { if (cb_setExtParam_Ljava_lang_Object_ == null) cb_setExtParam_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetExtParam_Ljava_lang_Object_); return cb_setExtParam_Ljava_lang_Object_; } static void n_SetExtParam_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetExtParam (p0); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='setExtParam' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("setExtParam", "(Ljava/lang/Object;)V", "GetSetExtParam_Ljava_lang_Object_Handler")] public abstract void SetExtParam (global::Java.Lang.Object p0); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/AbstractSerializer", DoNotGenerateAcw=true)] internal partial class AbstractSerializerInvoker : AbstractSerializer { public AbstractSerializerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (AbstractSerializerInvoker); } } static IntPtr id_packet; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='packet' and count(parameter)=0]" [Register ("packet", "()[B", "GetPacketHandler")] public override unsafe byte[] Packet () { if (id_packet == IntPtr.Zero) id_packet = JNIEnv.GetMethodID (class_ref, "packet", "()[B"); try { return (byte[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_packet), JniHandleOwnership.TransferLocalRef, typeof (byte)); } finally { } } static IntPtr id_setExtParam_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Serializer']/method[@name='setExtParam' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("setExtParam", "(Ljava/lang/Object;)V", "GetSetExtParam_Ljava_lang_Object_Handler")] public override unsafe void SetExtParam (global::Java.Lang.Object p0) { if (id_setExtParam_Ljava_lang_Object_ == IntPtr.Zero) id_setExtParam_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "setExtParam", "(Ljava/lang/Object;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setExtParam_Ljava_lang_Object_, __args); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Mobile.Framework.Service.Annotation.UpdateDeviceInfoAttribute.cs using System; namespace Com.Alipay.Mobile.Framework.Service.Annotation { [global::Android.Runtime.Annotation ("com.alipay.mobile.framework.service.annotation.UpdateDeviceInfo")] public partial class UpdateDeviceInfoAttribute : Attribute { } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.App.H5PayActivity.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.App { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='H5PayActivity']" [global::Android.Runtime.Register ("com/alipay/sdk/app/H5PayActivity", DoNotGenerateAcw=true)] public partial class H5PayActivity : global::Android.App.Activity { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/app/H5PayActivity", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (H5PayActivity); } } protected H5PayActivity (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='H5PayActivity']/constructor[@name='H5PayActivity' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe H5PayActivity () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (H5PayActivity)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_a; #pragma warning disable 0169 static Delegate GetAHandler () { if (cb_a == null) cb_a = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_A); return cb_a; } static void n_A (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.App.H5PayActivity __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.H5PayActivity> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.A (); } #pragma warning restore 0169 static IntPtr id_a; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='H5PayActivity']/method[@name='a' and count(parameter)=0]" [Register ("a", "()V", "GetAHandler")] public virtual unsafe void A () { if (id_a == IntPtr.Zero) id_a = JNIEnv.GetMethodID (class_ref, "a", "()V"); try { if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_a); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "a", "()V")); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath interface reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']" [Register ("com/alipay/android/phone/mrpc/core/TransportCallback", "", "Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker")] public partial interface ITransportCallback : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']/method[@name='onCancelled' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request']]" [Register ("onCancelled", "(Lcom/alipay/android/phone/mrpc/core/Request;)V", "GetOnCancelled_Lcom_alipay_android_phone_mrpc_core_Request_Handler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker, AlipayBindingDemo")] void OnCancelled (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0); // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']/method[@name='onFailed' and count(parameter)=3 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request'] and parameter[2][@type='int'] and parameter[3][@type='java.lang.String']]" [Register ("onFailed", "(Lcom/alipay/android/phone/mrpc/core/Request;ILjava/lang/String;)V", "GetOnFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_Handler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker, AlipayBindingDemo")] void OnFailed (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, int p1, string p2); // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']/method[@name='onPostExecute' and count(parameter)=2 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request'] and parameter[2][@type='com.alipay.android.phone.mrpc.core.Response']]" [Register ("onPostExecute", "(Lcom/alipay/android/phone/mrpc/core/Request;Lcom/alipay/android/phone/mrpc/core/Response;)V", "GetOnPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_Handler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker, AlipayBindingDemo")] void OnPostExecute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, global::Com.Alipay.Android.Phone.Mrpc.Core.Response p1); // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']/method[@name='onPreExecute' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request']]" [Register ("onPreExecute", "(Lcom/alipay/android/phone/mrpc/core/Request;)V", "GetOnPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_Handler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker, AlipayBindingDemo")] void OnPreExecute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0); // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='TransportCallback']/method[@name='onProgressUpdate' and count(parameter)=2 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request'] and parameter[2][@type='double']]" [Register ("onProgressUpdate", "(Lcom/alipay/android/phone/mrpc/core/Request;D)V", "GetOnProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_DHandler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallbackInvoker, AlipayBindingDemo")] void OnProgressUpdate (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, double p1); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/TransportCallback", DoNotGenerateAcw=true)] internal class ITransportCallbackInvoker : global::Java.Lang.Object, ITransportCallback { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/TransportCallback"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ITransportCallbackInvoker); } } IntPtr class_ref; public static ITransportCallback GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<ITransportCallback> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.phone.mrpc.core.TransportCallback")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public ITransportCallbackInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_; #pragma warning disable 0169 static Delegate GetOnCancelled_Lcom_alipay_android_phone_mrpc_core_Request_Handler () { if (cb_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_ == null) cb_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnCancelled_Lcom_alipay_android_phone_mrpc_core_Request_); return cb_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_; } static void n_OnCancelled_Lcom_alipay_android_phone_mrpc_core_Request_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnCancelled (p0); } #pragma warning restore 0169 IntPtr id_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_; public unsafe void OnCancelled (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0) { if (id_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_ == IntPtr.Zero) id_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_ = JNIEnv.GetMethodID (class_ref, "onCancelled", "(Lcom/alipay/android/phone/mrpc/core/Request;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onCancelled_Lcom_alipay_android_phone_mrpc_core_Request_, __args); } static Delegate cb_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_; #pragma warning disable 0169 static Delegate GetOnFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_Handler () { if (cb_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_ == null) cb_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, int, IntPtr>) n_OnFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_); return cb_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_; } static void n_OnFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1, IntPtr native_p2) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer); __this.OnFailed (p0, p1, p2); } #pragma warning restore 0169 IntPtr id_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_; public unsafe void OnFailed (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, int p1, string p2) { if (id_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_ == IntPtr.Zero) id_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_ = JNIEnv.GetMethodID (class_ref, "onFailed", "(Lcom/alipay/android/phone/mrpc/core/Request;ILjava/lang/String;)V"); IntPtr native_p2 = JNIEnv.NewString (p2); JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onFailed_Lcom_alipay_android_phone_mrpc_core_Request_ILjava_lang_String_, __args); JNIEnv.DeleteLocalRef (native_p2); } static Delegate cb_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_; #pragma warning disable 0169 static Delegate GetOnPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_Handler () { if (cb_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_ == null) cb_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_OnPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_); return cb_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_; } static void n_OnPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Response p1 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Response> (native_p1, JniHandleOwnership.DoNotTransfer); __this.OnPostExecute (p0, p1); } #pragma warning restore 0169 IntPtr id_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_; public unsafe void OnPostExecute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, global::Com.Alipay.Android.Phone.Mrpc.Core.Response p1) { if (id_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_ == IntPtr.Zero) id_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_ = JNIEnv.GetMethodID (class_ref, "onPostExecute", "(Lcom/alipay/android/phone/mrpc/core/Request;Lcom/alipay/android/phone/mrpc/core/Response;)V"); JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onPostExecute_Lcom_alipay_android_phone_mrpc_core_Request_Lcom_alipay_android_phone_mrpc_core_Response_, __args); } static Delegate cb_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_; #pragma warning disable 0169 static Delegate GetOnPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_Handler () { if (cb_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_ == null) cb_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_); return cb_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_; } static void n_OnPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnPreExecute (p0); } #pragma warning restore 0169 IntPtr id_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_; public unsafe void OnPreExecute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0) { if (id_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_ == IntPtr.Zero) id_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_ = JNIEnv.GetMethodID (class_ref, "onPreExecute", "(Lcom/alipay/android/phone/mrpc/core/Request;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onPreExecute_Lcom_alipay_android_phone_mrpc_core_Request_, __args); } static Delegate cb_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D; #pragma warning disable 0169 static Delegate GetOnProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_DHandler () { if (cb_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D == null) cb_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, double>) n_OnProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D); return cb_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D; } static void n_OnProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, double p1) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnProgressUpdate (p0, p1); } #pragma warning restore 0169 IntPtr id_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D; public unsafe void OnProgressUpdate (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0, double p1) { if (id_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D == IntPtr.Zero) id_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D = JNIEnv.GetMethodID (class_ref, "onProgressUpdate", "(Lcom/alipay/android/phone/mrpc/core/Request;D)V"); JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onProgressUpdate_Lcom_alipay_android_phone_mrpc_core_Request_D, __args); } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonDeserializer.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='JsonDeserializer']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/JsonDeserializer", DoNotGenerateAcw=true)] public partial class JsonDeserializer : global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractDeserializer { internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/gwprotocol/JsonDeserializer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (JsonDeserializer); } } protected JsonDeserializer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_reflect_Type_arrayB; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='JsonDeserializer']/constructor[@name='JsonDeserializer' and count(parameter)=2 and parameter[1][@type='java.lang.reflect.Type'] and parameter[2][@type='byte[]']]" [Register (".ctor", "(Ljava/lang/reflect/Type;[B)V", "")] public unsafe JsonDeserializer (global::Java.Lang.Reflect.IType p0, byte[] p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewArray (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); if (((object) this).GetType () != typeof (JsonDeserializer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/reflect/Type;[B)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/reflect/Type;[B)V", __args); return; } if (id_ctor_Ljava_lang_reflect_Type_arrayB == IntPtr.Zero) id_ctor_Ljava_lang_reflect_Type_arrayB = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/reflect/Type;[B)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_reflect_Type_arrayB, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_reflect_Type_arrayB, __args); } finally { if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } } static Delegate cb_parser; #pragma warning disable 0169 static Delegate GetParserHandler () { if (cb_parser == null) cb_parser = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Parser); return cb_parser; } static IntPtr n_Parser (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonDeserializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonDeserializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Parser ()); } #pragma warning restore 0169 static IntPtr id_parser; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.mrpc.core.gwprotocol']/class[@name='JsonDeserializer']/method[@name='parser' and count(parameter)=0]" [Register ("parser", "()Ljava/lang/Object;", "GetParserHandler")] public override unsafe global::Java.Lang.Object Parser () { if (id_parser == IntPtr.Zero) id_parser = JNIEnv.GetMethodID (class_ref, "parser", "()Ljava/lang/Object;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_parser), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "parser", "()Ljava/lang/Object;")), JniHandleOwnership.TransferLocalRef); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/HttpUrlResponse", DoNotGenerateAcw=true)] public partial class HttpUrlResponse : global::Com.Alipay.Android.Phone.Mrpc.Core.Response { internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/HttpUrlResponse", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (HttpUrlResponse); } } protected HttpUrlResponse (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ILjava_lang_String_arrayB; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/constructor[@name='HttpUrlResponse' and count(parameter)=4 and parameter[1][@type='com.alipay.android.phone.mrpc.core.HttpUrlHeader'] and parameter[2][@type='int'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='byte[]']]" [Register (".ctor", "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;ILjava/lang/String;[B)V", "")] public unsafe HttpUrlResponse (global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader p0, int p1, string p2, byte[] p3) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p2 = JNIEnv.NewString (p2); IntPtr native_p3 = JNIEnv.NewArray (p3); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); __args [3] = new JValue (native_p3); if (((object) this).GetType () != typeof (HttpUrlResponse)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;ILjava/lang/String;[B)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;ILjava/lang/String;[B)V", __args); return; } if (id_ctor_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ILjava_lang_String_arrayB == IntPtr.Zero) id_ctor_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ILjava_lang_String_arrayB = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;ILjava/lang/String;[B)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ILjava_lang_String_arrayB, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ILjava_lang_String_arrayB, __args); } finally { JNIEnv.DeleteLocalRef (native_p2); if (p3 != null) { JNIEnv.CopyArray (native_p3, p3); JNIEnv.DeleteLocalRef (native_p3); } } } static Delegate cb_getCharset; #pragma warning disable 0169 static Delegate GetGetCharsetHandler () { if (cb_getCharset == null) cb_getCharset = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetCharset); return cb_getCharset; } static IntPtr n_GetCharset (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Charset); } #pragma warning restore 0169 static Delegate cb_setCharset_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetCharset_Ljava_lang_String_Handler () { if (cb_setCharset_Ljava_lang_String_ == null) cb_setCharset_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetCharset_Ljava_lang_String_); return cb_setCharset_Ljava_lang_String_; } static void n_SetCharset_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.Charset = p0; } #pragma warning restore 0169 static IntPtr id_getCharset; static IntPtr id_setCharset_Ljava_lang_String_; public virtual unsafe string Charset { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getCharset' and count(parameter)=0]" [Register ("getCharset", "()Ljava/lang/String;", "GetGetCharsetHandler")] get { if (id_getCharset == IntPtr.Zero) id_getCharset = JNIEnv.GetMethodID (class_ref, "getCharset", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getCharset), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCharset", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='setCharset' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("setCharset", "(Ljava/lang/String;)V", "GetSetCharset_Ljava_lang_String_Handler")] set { if (id_setCharset_Ljava_lang_String_ == IntPtr.Zero) id_setCharset_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setCharset", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setCharset_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setCharset", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static Delegate cb_getCode; #pragma warning disable 0169 static Delegate GetGetCodeHandler () { if (cb_getCode == null) cb_getCode = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetCode); return cb_getCode; } static int n_GetCode (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Code; } #pragma warning restore 0169 static IntPtr id_getCode; public virtual unsafe int Code { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getCode' and count(parameter)=0]" [Register ("getCode", "()I", "GetGetCodeHandler")] get { if (id_getCode == IntPtr.Zero) id_getCode = JNIEnv.GetMethodID (class_ref, "getCode", "()I"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_getCode); else return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCode", "()I")); } finally { } } } static Delegate cb_getCreateTime; #pragma warning disable 0169 static Delegate GetGetCreateTimeHandler () { if (cb_getCreateTime == null) cb_getCreateTime = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, long>) n_GetCreateTime); return cb_getCreateTime; } static long n_GetCreateTime (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.CreateTime; } #pragma warning restore 0169 static Delegate cb_setCreateTime_J; #pragma warning disable 0169 static Delegate GetSetCreateTime_JHandler () { if (cb_setCreateTime_J == null) cb_setCreateTime_J = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, long>) n_SetCreateTime_J); return cb_setCreateTime_J; } static void n_SetCreateTime_J (IntPtr jnienv, IntPtr native__this, long p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.CreateTime = p0; } #pragma warning restore 0169 static IntPtr id_getCreateTime; static IntPtr id_setCreateTime_J; public virtual unsafe long CreateTime { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getCreateTime' and count(parameter)=0]" [Register ("getCreateTime", "()J", "GetGetCreateTimeHandler")] get { if (id_getCreateTime == IntPtr.Zero) id_getCreateTime = JNIEnv.GetMethodID (class_ref, "getCreateTime", "()J"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallLongMethod (((global::Java.Lang.Object) this).Handle, id_getCreateTime); else return JNIEnv.CallNonvirtualLongMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCreateTime", "()J")); } finally { } } // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='setCreateTime' and count(parameter)=1 and parameter[1][@type='long']]" [Register ("setCreateTime", "(J)V", "GetSetCreateTime_JHandler")] set { if (id_setCreateTime_J == IntPtr.Zero) id_setCreateTime_J = JNIEnv.GetMethodID (class_ref, "setCreateTime", "(J)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setCreateTime_J, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setCreateTime", "(J)V"), __args); } finally { } } } static Delegate cb_getHeader; #pragma warning disable 0169 static Delegate GetGetHeaderHandler () { if (cb_getHeader == null) cb_getHeader = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetHeader); return cb_getHeader; } static IntPtr n_GetHeader (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Header); } #pragma warning restore 0169 static Delegate cb_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_; #pragma warning disable 0169 static Delegate GetSetHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_Handler () { if (cb_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ == null) cb_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_); return cb_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_; } static void n_SetHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (native_p0, JniHandleOwnership.DoNotTransfer); __this.Header = p0; } #pragma warning restore 0169 static IntPtr id_getHeader; static IntPtr id_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_; public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader Header { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getHeader' and count(parameter)=0]" [Register ("getHeader", "()Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;", "GetGetHeaderHandler")] get { if (id_getHeader == IntPtr.Zero) id_getHeader = JNIEnv.GetMethodID (class_ref, "getHeader", "()Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getHeader), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlHeader> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getHeader", "()Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='<EMAIL>.android.phone.mrpc.core']/class[@name='HttpUrlResponse']/method[@name='setHeader' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.HttpUrlHeader']]" [Register ("setHeader", "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;)V", "GetSetHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_Handler")] set { if (id_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ == IntPtr.Zero) id_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_ = JNIEnv.GetMethodID (class_ref, "setHeader", "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setHeader_Lcom_alipay_android_phone_mrpc_core_HttpUrlHeader_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setHeader", "(Lcom/alipay/android/phone/mrpc/core/HttpUrlHeader;)V"), __args); } finally { } } } static Delegate cb_getMsg; #pragma warning disable 0169 static Delegate GetGetMsgHandler () { if (cb_getMsg == null) cb_getMsg = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetMsg); return cb_getMsg; } static IntPtr n_GetMsg (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Msg); } #pragma warning restore 0169 static IntPtr id_getMsg; public virtual unsafe string Msg { // Metadata.xml XPath method reference: path="/api/package[@name='com.<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getMsg' and count(parameter)=0]" [Register ("getMsg", "()Ljava/lang/String;", "GetGetMsgHandler")] get { if (id_getMsg == IntPtr.Zero) id_getMsg = JNIEnv.GetMethodID (class_ref, "getMsg", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getMsg), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMsg", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getPeriod; #pragma warning disable 0169 static Delegate GetGetPeriodHandler () { if (cb_getPeriod == null) cb_getPeriod = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, long>) n_GetPeriod); return cb_getPeriod; } static long n_GetPeriod (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Period; } #pragma warning restore 0169 static Delegate cb_setPeriod_J; #pragma warning disable 0169 static Delegate GetSetPeriod_JHandler () { if (cb_setPeriod_J == null) cb_setPeriod_J = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, long>) n_SetPeriod_J); return cb_setPeriod_J; } static void n_SetPeriod_J (IntPtr jnienv, IntPtr native__this, long p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpUrlResponse> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Period = p0; } #pragma warning restore 0169 static IntPtr id_getPeriod; static IntPtr id_setPeriod_J; public virtual unsafe long Period { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='HttpUrlResponse']/method[@name='getPeriod' and count(parameter)=0]" [Register ("getPeriod", "()J", "GetGetPeriodHandler")] get { if (id_getPeriod == IntPtr.Zero) id_getPeriod = JNIEnv.GetMethodID (class_ref, "getPeriod", "()J"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallLongMethod (((global::Java.Lang.Object) this).Handle, id_getPeriod); else return JNIEnv.CallNonvirtualLongMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPeriod", "()J")); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='<EMAIL>.core']/class[@name='HttpUrlResponse']/method[@name='setPeriod' and count(parameter)=1 and parameter[1][@type='long']]" [Register ("setPeriod", "(J)V", "GetSetPeriod_JHandler")] set { if (id_setPeriod_J == IntPtr.Zero) id_setPeriod_J = JNIEnv.GetMethodID (class_ref, "setPeriod", "(J)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setPeriod_J, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setPeriod", "(J)V"), __args); } finally { } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportRequest.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='DataReportRequest']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/report/general/model/DataReportRequest", DoNotGenerateAcw=true)] public partial class DataReportRequest : global::Java.Lang.Object, global::Java.IO.ISerializable { static IntPtr bizData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DataReportRequest']/field[@name='bizData']" [Register ("bizData")] public global::System.Collections.IDictionary BizData { get { if (bizData_jfieldId == IntPtr.Zero) bizData_jfieldId = JNIEnv.GetFieldID (class_ref, "bizData", "Ljava/util/Map;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, bizData_jfieldId); return global::Android.Runtime.JavaDictionary.FromJniHandle (__ret, JniHandleOwnership.TransferLocalRef); } set { if (bizData_jfieldId == IntPtr.Zero) bizData_jfieldId = JNIEnv.GetFieldID (class_ref, "bizData", "Ljava/util/Map;"); IntPtr native_value = global::Android.Runtime.JavaDictionary.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, bizData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr bizType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='<EMAIL>.model']/class[@name='DataReportRequest']/field[@name='bizType']" [Register ("bizType")] public string BizType { get { if (bizType_jfieldId == IntPtr.Zero) bizType_jfieldId = JNIEnv.GetFieldID (class_ref, "bizType", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, bizType_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (bizType_jfieldId == IntPtr.Zero) bizType_jfieldId = JNIEnv.GetFieldID (class_ref, "bizType", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, bizType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr deviceData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.report.general.model']/class[@name='DataReportRequest']/field[@name='deviceData']" [Register ("deviceData")] public global::System.Collections.IDictionary DeviceData { get { if (deviceData_jfieldId == IntPtr.Zero) deviceData_jfieldId = JNIEnv.GetFieldID (class_ref, "deviceData", "Ljava/util/Map;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, deviceData_jfieldId); return global::Android.Runtime.JavaDictionary.FromJniHandle (__ret, JniHandleOwnership.TransferLocalRef); } set { if (deviceData_jfieldId == IntPtr.Zero) deviceData_jfieldId = JNIEnv.GetFieldID (class_ref, "deviceData", "Ljava/util/Map;"); IntPtr native_value = global::Android.Runtime.JavaDictionary.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, deviceData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr os_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='DataReportRequest']/field[@name='os']" [Register ("os")] public string Os { get { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, os_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, os_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr rpcVersion_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='DataReportRequest']/field[@name='rpcVersion']" [Register ("rpcVersion")] public string RpcVersion { get { if (rpcVersion_jfieldId == IntPtr.Zero) rpcVersion_jfieldId = JNIEnv.GetFieldID (class_ref, "rpcVersion", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, rpcVersion_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (rpcVersion_jfieldId == IntPtr.Zero) rpcVersion_jfieldId = JNIEnv.GetFieldID (class_ref, "rpcVersion", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, rpcVersion_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/report/general/model/DataReportRequest", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DataReportRequest); } } protected DataReportRequest (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>.report.general.model']/class[@name='DataReportRequest']/constructor[@name='DataReportRequest' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe DataReportRequest () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (DataReportRequest)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='JsonSerializer']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/gwprotocol/JsonSerializer", DoNotGenerateAcw=true)] public partial class JsonSerializer : global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.AbstractSerializer { // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='JsonSerializer']/field[@name='VERSION']" [Register ("VERSION")] public const string Version = (string) "1.0.0"; internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/gwprotocol/JsonSerializer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (JsonSerializer); } } protected JsonSerializer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_ILjava_lang_String_Ljava_lang_Object_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='JsonSerializer']/constructor[@name='JsonSerializer' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.Object']]" [Register (".ctor", "(ILjava/lang/String;Ljava/lang/Object;)V", "")] public unsafe JsonSerializer (int p0, string p1, global::Java.Lang.Object p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); if (((object) this).GetType () != typeof (JsonSerializer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(ILjava/lang/String;Ljava/lang/Object;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(ILjava/lang/String;Ljava/lang/Object;)V", __args); return; } if (id_ctor_ILjava_lang_String_Ljava_lang_Object_ == IntPtr.Zero) id_ctor_ILjava_lang_String_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "<init>", "(ILjava/lang/String;Ljava/lang/Object;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_ILjava_lang_String_Ljava_lang_Object_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_ILjava_lang_String_Ljava_lang_Object_, __args); } finally { JNIEnv.DeleteLocalRef (native_p1); } } static Delegate cb_getId; #pragma warning disable 0169 static Delegate GetGetIdHandler () { if (cb_getId == null) cb_getId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetId); return cb_getId; } static int n_GetId (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Id; } #pragma warning restore 0169 static Delegate cb_setId_I; #pragma warning disable 0169 static Delegate GetSetId_IHandler () { if (cb_setId_I == null) cb_setId_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetId_I); return cb_setId_I; } static void n_SetId_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Id = p0; } #pragma warning restore 0169 static IntPtr id_getId; static IntPtr id_setId_I; public virtual unsafe int Id { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.core.gwprotocol']/class[@name='JsonSerializer']/method[@name='getId' and count(parameter)=0]" [Register ("getId", "()I", "GetGetIdHandler")] get { if (id_getId == IntPtr.Zero) id_getId = JNIEnv.GetMethodID (class_ref, "getId", "()I"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_getId); else return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getId", "()I")); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.android.<EMAIL>.mrpc.core.gwprotocol']/class[@name='JsonSerializer']/method[@name='setId' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("setId", "(I)V", "GetSetId_IHandler")] set { if (id_setId_I == IntPtr.Zero) id_setId_I = JNIEnv.GetMethodID (class_ref, "setId", "(I)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setId_I, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setId", "(I)V"), __args); } finally { } } } static Delegate cb_packet; #pragma warning disable 0169 static Delegate GetPacketHandler () { if (cb_packet == null) cb_packet = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Packet); return cb_packet; } static IntPtr n_Packet (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewArray (__this.Packet ()); } #pragma warning restore 0169 static IntPtr id_packet; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>.mrpc.core.gwprotocol']/class[@name='JsonSerializer']/method[@name='packet' and count(parameter)=0]" [Register ("packet", "()[B", "GetPacketHandler")] public override unsafe byte[] Packet () { if (id_packet == IntPtr.Zero) id_packet = JNIEnv.GetMethodID (class_ref, "packet", "()[B"); try { if (((object) this).GetType () == ThresholdType) return (byte[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_packet), JniHandleOwnership.TransferLocalRef, typeof (byte)); else return (byte[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "packet", "()[B")), JniHandleOwnership.TransferLocalRef, typeof (byte)); } finally { } } static Delegate cb_setExtParam_Ljava_lang_Object_; #pragma warning disable 0169 static Delegate GetSetExtParam_Ljava_lang_Object_Handler () { if (cb_setExtParam_Ljava_lang_Object_ == null) cb_setExtParam_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetExtParam_Ljava_lang_Object_); return cb_setExtParam_Ljava_lang_Object_; } static void n_SetExtParam_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Gwprotocol.JsonSerializer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetExtParam (p0); } #pragma warning restore 0169 static IntPtr id_setExtParam_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>.mrpc.core.gwprotocol']/class[@name='JsonSerializer']/method[@name='setExtParam' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("setExtParam", "(Ljava/lang/Object;)V", "GetSetExtParam_Ljava_lang_Object_Handler")] public override unsafe void SetExtParam (global::Java.Lang.Object p0) { if (id_setExtParam_Ljava_lang_Object_ == IntPtr.Zero) id_setExtParam_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "setExtParam", "(Ljava/lang/Object;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setExtParam_Ljava_lang_Object_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setExtParam", "(Ljava/lang/Object;)V"), __args); } finally { } } } } <file_sep>/AlipayDemo.Droid/PayActivity.cs using Android.App; using Android.Widget; using Android.OS; using System; using System.Threading; using Com.Alipay.Sdk.App; namespace AlipayDemo.Droid { [Activity(Label = "AlipayDemo.Droid", MainLauncher = true, Icon = "@drawable/icon")] public class PayActivity : Activity { public static string PARTNER = "2017031506227928"; public static string SELLER = "";//商户收款的支付宝账号 string RSA_PRIVATE = "<KEY>; //商户密钥 protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Pay); PayTask payTask = new PayTask(this); Toast.MakeText(this, payTask.Version, ToastLength.Long).Show(); var btn = FindViewById<Button>(Resource.Id.btnPay); btn.Click += btn_Click; } void Logger_Info(string msg) { using (System.IO.StreamWriter srFile = new System.IO.StreamWriter("/sdcard/zzl.txt", true)) { srFile.WriteLine(string.Format("{0}{1}{2}" , DateTime.Now.ToString().PadRight(20) , ("[ThreadID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]").PadRight(14) , msg)); srFile.Close(); srFile.Dispose(); } } void btn_Click(object sender, EventArgs e) { try { System.Threading.Thread the = new System.Threading.Thread(Pay); the.Start(); } catch (Exception ex) { Logger_Info("1" + ex.Message); } } private void Pay() { try { var con = getOrderInfo("test", "testbody"); var sign = SignatureUtils.Sign(con, RSA_PRIVATE); sign = Java.Net.URLEncoder.Encode(sign, "utf-8"); con += "&sign=\"" + sign + "\"&" + MySignType; PayTask pa = new PayTask(this); var result = pa.Pay(con, false); Logger_Info("支付宝result:" + result); } catch (Exception ex) { Logger_Info("2" + ex.Message + ex.StackTrace); } } #region 组合 public String getOrderInfo(String subject, String body) { // 签约合作者身份ID String orderInfo = "partner=" + "\"" + PARTNER + "\""; // 签约卖家支付宝账号 orderInfo += "&seller_id=" + "\"" + SELLER + "\""; // 商户网站唯一订单号 orderInfo += "&out_trade_no=" + "\"DJ" + DateTime.Now.ToString("yyyyMMddhhmmss") + "\""; // 商品名称 orderInfo += "&subject=" + "\"" + subject + "\""; // 商品详情 orderInfo += "&body=" + "\"" + body + "\""; // 商品金额 orderInfo += "&total_fee=" + "\"" + 1 + "\""; // 服务器异步通知页面路径 orderInfo += "&notify_url=" + "\"" + "www.huuncle.com" + "\""; // 服务接口名称, 固定值 orderInfo += "&payment_type=\"1\""; // 参数编码, 固定值 orderInfo += "&_input_charset=\"utf-8\""; // 设置未付款交易的超时时间 // 默认30分钟,一旦超时,该笔交易就会自动被关闭。 // 取值范围:1m~15d。 // m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。 // 该参数数值不接受小数点,如1.5h,可转换为90m。 orderInfo += "&it_b_pay=\"30m\""; // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付 // orderInfo += "&extern_token=" + "\"" + extern_token + "\""; // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空 orderInfo += "&return_url=www.huuncle"; // 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用) // orderInfo += "&paymethod=\"expressGateway\""; return orderInfo; } public String MySignType { get { return "sign_type=\"RSA\""; } } #endregion } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.App.IAlixPay.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.App { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IAlixPay.Stub']" [global::Android.Runtime.Register ("com/alipay/android/app/IAlixPay$Stub", DoNotGenerateAcw=true)] public abstract partial class AlixPayStub : global::Android.OS.Binder, global::Com.Alipay.Android.App.IAlixPay { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/app/IAlixPay$Stub", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AlixPayStub); } } protected AlixPayStub (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IAlixPay.Stub']/constructor[@name='IAlixPay.Stub' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe AlixPayStub () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (AlixPayStub)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_asBinder; #pragma warning disable 0169 static Delegate GetAsBinderHandler () { if (cb_asBinder == null) cb_asBinder = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_AsBinder); return cb_asBinder; } static IntPtr n_AsBinder (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.AsBinder ()); } #pragma warning restore 0169 static IntPtr id_asBinder; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IAlixPay.Stub']/method[@name='asBinder' and count(parameter)=0]" [Register ("asBinder", "()Landroid/os/IBinder;", "GetAsBinderHandler")] public virtual unsafe global::Android.OS.IBinder AsBinder () { if (id_asBinder == IntPtr.Zero) id_asBinder = JNIEnv.GetMethodID (class_ref, "asBinder", "()Landroid/os/IBinder;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_asBinder), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "asBinder", "()Landroid/os/IBinder;")), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_asInterface_Landroid_os_IBinder_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IAlixPay.Stub']/method[@name='asInterface' and count(parameter)=1 and parameter[1][@type='android.os.IBinder']]" [Register ("asInterface", "(Landroid/os/IBinder;)Lcom/alipay/android/app/IAlixPay;", "")] public static unsafe global::Com.Alipay.Android.App.IAlixPay AsInterface (global::Android.OS.IBinder p0) { if (id_asInterface_Landroid_os_IBinder_ == IntPtr.Zero) id_asInterface_Landroid_os_IBinder_ = JNIEnv.GetStaticMethodID (class_ref, "asInterface", "(Landroid/os/IBinder;)Lcom/alipay/android/app/IAlixPay;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Android.App.IAlixPay __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (JNIEnv.CallStaticObjectMethod (class_ref, id_asInterface_Landroid_os_IBinder_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; #pragma warning disable 0169 static Delegate GetOnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_IHandler () { if (cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I == null) cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr, IntPtr, int, bool>) n_OnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I); return cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; } static bool n_OnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2, int p3) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.OS.Parcel p1 = global::Java.Lang.Object.GetObject<global::Android.OS.Parcel> (native_p1, JniHandleOwnership.DoNotTransfer); global::Android.OS.Parcel p2 = global::Java.Lang.Object.GetObject<global::Android.OS.Parcel> (native_p2, JniHandleOwnership.DoNotTransfer); bool __ret = __this.OnTransact (p0, p1, p2, p3); return __ret; } #pragma warning restore 0169 static IntPtr id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IAlixPay.Stub']/method[@name='onTransact' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='android.os.Parcel'] and parameter[3][@type='android.os.Parcel'] and parameter[4][@type='int']]" [Register ("onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", "GetOnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_IHandler")] public virtual unsafe bool OnTransact (int p0, global::Android.OS.Parcel p1, global::Android.OS.Parcel p2, int p3) { if (id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I == IntPtr.Zero) id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I = JNIEnv.GetMethodID (class_ref, "onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z"); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); bool __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I, __args); else __ret = JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z"), __args); return __ret; } finally { } } static Delegate cb_Pay_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetPay_Ljava_lang_String_Handler () { if (cb_Pay_Ljava_lang_String_ == null) cb_Pay_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_Pay_Ljava_lang_String_); return cb_Pay_Ljava_lang_String_; } static IntPtr n_Pay_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.Pay (p0)); return __ret; } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='Pay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("Pay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPay_Ljava_lang_String_Handler")] public abstract string Pay (string p0); static Delegate cb_prePay_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetPrePay_Ljava_lang_String_Handler () { if (cb_prePay_Ljava_lang_String_ == null) cb_prePay_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_PrePay_Ljava_lang_String_); return cb_prePay_Ljava_lang_String_; } static IntPtr n_PrePay_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.PrePay (p0)); return __ret; } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='prePay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("prePay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPrePay_Ljava_lang_String_Handler")] public abstract string PrePay (string p0); static Delegate cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; #pragma warning disable 0169 static Delegate GetRegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler () { if (cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == null) cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_); return cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; } static void n_RegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.App.IRemoteServiceCallback p0 = (global::Com.Alipay.Android.App.IRemoteServiceCallback)global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (native_p0, JniHandleOwnership.DoNotTransfer); __this.RegisterCallback (p0); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='registerCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.app.IRemoteServiceCallback']]" [Register ("registerCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetRegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler")] public abstract void RegisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0); static Delegate cb_test; #pragma warning disable 0169 static Delegate GetTestHandler () { if (cb_test == null) cb_test = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Test); return cb_test; } static IntPtr n_Test (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Test ()); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='test' and count(parameter)=0]" [Register ("test", "()Ljava/lang/String;", "GetTestHandler")] public abstract string Test (); static Delegate cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; #pragma warning disable 0169 static Delegate GetUnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler () { if (cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == null) cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_UnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_); return cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; } static void n_UnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.AlixPayStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.AlixPayStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.App.IRemoteServiceCallback p0 = (global::Com.Alipay.Android.App.IRemoteServiceCallback)global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (native_p0, JniHandleOwnership.DoNotTransfer); __this.UnregisterCallback (p0); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='unregisterCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.app.IRemoteServiceCallback']]" [Register ("unregisterCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetUnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler")] public abstract void UnregisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0); } [global::Android.Runtime.Register ("com/alipay/android/app/IAlixPay$Stub", DoNotGenerateAcw=true)] internal partial class AlixPayStubInvoker : AlixPayStub { public AlixPayStubInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (AlixPayStubInvoker); } } static IntPtr id_Pay_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='Pay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("Pay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPay_Ljava_lang_String_Handler")] public override unsafe string Pay (string p0) { if (id_Pay_Ljava_lang_String_ == IntPtr.Zero) id_Pay_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "Pay", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_Pay_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_prePay_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='prePay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("prePay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPrePay_Ljava_lang_String_Handler")] public override unsafe string PrePay (string p0) { if (id_prePay_Ljava_lang_String_ == IntPtr.Zero) id_prePay_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "prePay", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_prePay_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='registerCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.app.IRemoteServiceCallback']]" [Register ("registerCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetRegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler")] public override unsafe void RegisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0) { if (id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == IntPtr.Zero) id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNIEnv.GetMethodID (class_ref, "registerCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_, __args); } finally { } } static IntPtr id_test; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='test' and count(parameter)=0]" [Register ("test", "()Ljava/lang/String;", "GetTestHandler")] public override unsafe string Test () { if (id_test == IntPtr.Zero) id_test = JNIEnv.GetMethodID (class_ref, "test", "()Ljava/lang/String;"); try { return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_test), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='unregisterCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.app.IRemoteServiceCallback']]" [Register ("unregisterCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetUnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler")] public override unsafe void UnregisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0) { if (id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == IntPtr.Zero) id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNIEnv.GetMethodID (class_ref, "unregisterCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_, __args); } finally { } } } // Metadata.xml XPath interface reference: path="/api/<EMAIL>']/interface[@name='IAlixPay']" [Register ("com/alipay/android/app/IAlixPay", "", "Com.Alipay.Android.App.IAlixPayInvoker")] public partial interface IAlixPay : global::Android.OS.IInterface { // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='Pay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("Pay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPay_Ljava_lang_String_Handler:Com.Alipay.Android.App.IAlixPayInvoker, AlipayBindingDemo")] string Pay (string p0); // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='prePay' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("prePay", "(Ljava/lang/String;)Ljava/lang/String;", "GetPrePay_Ljava_lang_String_Handler:Com.Alipay.Android.App.IAlixPayInvoker, AlipayBindingDemo")] string PrePay (string p0); // Metadata.xml XPath method reference: path="/api/<EMAIL>']/interface[@name='IAlixPay']/method[@name='registerCallback' and count(parameter)=1 and parameter[1][@type='com.<EMAIL>.android.app.IRemoteServiceCallback']]" [Register ("registerCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetRegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler:Com.Alipay.Android.App.IAlixPayInvoker, AlipayBindingDemo")] void RegisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0); // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='test' and count(parameter)=0]" [Register ("test", "()Ljava/lang/String;", "GetTestHandler:Com.Alipay.Android.App.IAlixPayInvoker, AlipayBindingDemo")] string Test (); // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IAlixPay']/method[@name='unregisterCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.app.IRemoteServiceCallback']]" [Register ("unregisterCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V", "GetUnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler:Com.Alipay.Android.App.IAlixPayInvoker, AlipayBindingDemo")] void UnregisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0); } [global::Android.Runtime.Register ("com/alipay/android/app/IAlixPay", DoNotGenerateAcw=true)] internal class IAlixPayInvoker : global::Java.Lang.Object, IAlixPay { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/app/IAlixPay"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IAlixPayInvoker); } } IntPtr class_ref; public static IAlixPay GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IAlixPay> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.app.IAlixPay")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IAlixPayInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_Pay_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetPay_Ljava_lang_String_Handler () { if (cb_Pay_Ljava_lang_String_ == null) cb_Pay_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_Pay_Ljava_lang_String_); return cb_Pay_Ljava_lang_String_; } static IntPtr n_Pay_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.Pay (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_Pay_Ljava_lang_String_; public unsafe string Pay (string p0) { if (id_Pay_Ljava_lang_String_ == IntPtr.Zero) id_Pay_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "Pay", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_Pay_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static Delegate cb_prePay_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetPrePay_Ljava_lang_String_Handler () { if (cb_prePay_Ljava_lang_String_ == null) cb_prePay_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_PrePay_Ljava_lang_String_); return cb_prePay_Ljava_lang_String_; } static IntPtr n_PrePay_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.PrePay (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_prePay_Ljava_lang_String_; public unsafe string PrePay (string p0) { if (id_prePay_Ljava_lang_String_ == IntPtr.Zero) id_prePay_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "prePay", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_prePay_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static Delegate cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; #pragma warning disable 0169 static Delegate GetRegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler () { if (cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == null) cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_); return cb_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; } static void n_RegisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.App.IRemoteServiceCallback p0 = (global::Com.Alipay.Android.App.IRemoteServiceCallback)global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (native_p0, JniHandleOwnership.DoNotTransfer); __this.RegisterCallback (p0); } #pragma warning restore 0169 IntPtr id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; public unsafe void RegisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0) { if (id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == IntPtr.Zero) id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNIEnv.GetMethodID (class_ref, "registerCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_registerCallback_Lcom_alipay_android_app_IRemoteServiceCallback_, __args); } static Delegate cb_test; #pragma warning disable 0169 static Delegate GetTestHandler () { if (cb_test == null) cb_test = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Test); return cb_test; } static IntPtr n_Test (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Test ()); } #pragma warning restore 0169 IntPtr id_test; public unsafe string Test () { if (id_test == IntPtr.Zero) id_test = JNIEnv.GetMethodID (class_ref, "test", "()Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_test), JniHandleOwnership.TransferLocalRef); } static Delegate cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; #pragma warning disable 0169 static Delegate GetUnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_Handler () { if (cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == null) cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_UnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_); return cb_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; } static void n_UnregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.App.IRemoteServiceCallback p0 = (global::Com.Alipay.Android.App.IRemoteServiceCallback)global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (native_p0, JniHandleOwnership.DoNotTransfer); __this.UnregisterCallback (p0); } #pragma warning restore 0169 IntPtr id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_; public unsafe void UnregisterCallback (global::Com.Alipay.Android.App.IRemoteServiceCallback p0) { if (id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ == IntPtr.Zero) id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_ = JNIEnv.GetMethodID (class_ref, "unregisterCallback", "(Lcom/alipay/android/app/IRemoteServiceCallback;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_unregisterCallback_Lcom_alipay_android_app_IRemoteServiceCallback_, __args); } static Delegate cb_asBinder; #pragma warning disable 0169 static Delegate GetAsBinderHandler () { if (cb_asBinder == null) cb_asBinder = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_AsBinder); return cb_asBinder; } static IntPtr n_AsBinder (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.IAlixPay __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IAlixPay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.AsBinder ()); } #pragma warning restore 0169 IntPtr id_asBinder; public unsafe global::Android.OS.IBinder AsBinder () { if (id_asBinder == IntPtr.Zero) id_asBinder = JNIEnv.GetMethodID (class_ref, "asBinder", "()Landroid/os/IBinder;"); return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_asBinder), JniHandleOwnership.TransferLocalRef); } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.IOUtil.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IOUtil']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/IOUtil", DoNotGenerateAcw=true)] public partial class IOUtil : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/IOUtil", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IOUtil); } } protected IOUtil (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IOUtil']/constructor[@name='IOUtil' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe IOUtil () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (IOUtil)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_InputStreamToByte_Ljava_io_InputStream_; // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='IOUtil']/method[@name='InputStreamToByte' and count(parameter)=1 and parameter[1][@type='java.io.InputStream']]" [Register ("InputStreamToByte", "(Ljava/io/InputStream;)[B", "")] public static unsafe byte[] InputStreamToByte (global::System.IO.Stream p0) { if (id_InputStreamToByte_Ljava_io_InputStream_ == IntPtr.Zero) id_InputStreamToByte_Ljava_io_InputStream_ = JNIEnv.GetStaticMethodID (class_ref, "InputStreamToByte", "(Ljava/io/InputStream;)[B"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); byte[] __ret = (byte[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_InputStreamToByte_Ljava_io_InputStream_, __args), JniHandleOwnership.TransferLocalRef, typeof (byte)); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_closeStream_Ljava_io_Closeable_; // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='IOUtil']/method[@name='closeStream' and count(parameter)=1 and parameter[1][@type='java.io.Closeable']]" [Register ("closeStream", "(Ljava/io/Closeable;)V", "")] public static unsafe void CloseStream (global::Java.IO.ICloseable p0) { if (id_closeStream_Ljava_io_Closeable_ == IntPtr.Zero) id_closeStream_Ljava_io_Closeable_ = JNIEnv.GetStaticMethodID (class_ref, "closeStream", "(Ljava/io/Closeable;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallStaticVoidMethod (class_ref, id_closeStream_Ljava_io_Closeable_, __args); } finally { } } static IntPtr id_convertStreamToString_Ljava_io_InputStream_; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='IOUtil']/method[@name='convertStreamToString' and count(parameter)=1 and parameter[1][@type='java.io.InputStream']]" [Register ("convertStreamToString", "(Ljava/io/InputStream;)Ljava/lang/String;", "")] public static unsafe string ConvertStreamToString (global::System.IO.Stream p0) { if (id_convertStreamToString_Ljava_io_InputStream_ == IntPtr.Zero) id_convertStreamToString_Ljava_io_InputStream_ = JNIEnv.GetStaticMethodID (class_ref, "convertStreamToString", "(Ljava/io/InputStream;)Ljava/lang/String;"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_convertStreamToString_Ljava_io_InputStream_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_fileToByte_Ljava_io_File_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IOUtil']/method[@name='fileToByte' and count(parameter)=1 and parameter[1][@type='java.io.File']]" [Register ("fileToByte", "(Ljava/io/File;)[B", "")] public static unsafe byte[] FileToByte (global::Java.IO.File p0) { if (id_fileToByte_Ljava_io_File_ == IntPtr.Zero) id_fileToByte_Ljava_io_File_ = JNIEnv.GetStaticMethodID (class_ref, "fileToByte", "(Ljava/io/File;)[B"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); byte[] __ret = (byte[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_fileToByte_Ljava_io_File_, __args), JniHandleOwnership.TransferLocalRef, typeof (byte)); return __ret; } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.App.IRemoteServiceCallback.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.App { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']" [global::Android.Runtime.Register ("com/alipay/android/app/IRemoteServiceCallback$Stub", DoNotGenerateAcw=true)] public abstract partial class RemoteServiceCallbackStub : global::Android.OS.Binder, global::Com.Alipay.Android.App.IRemoteServiceCallback { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/app/IRemoteServiceCallback$Stub", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RemoteServiceCallbackStub); } } protected RemoteServiceCallbackStub (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/constructor[@name='IRemoteServiceCallback.Stub' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe RemoteServiceCallbackStub () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (RemoteServiceCallbackStub)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_asBinder; #pragma warning disable 0169 static Delegate GetAsBinderHandler () { if (cb_asBinder == null) cb_asBinder = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_AsBinder); return cb_asBinder; } static IntPtr n_AsBinder (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.RemoteServiceCallbackStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.RemoteServiceCallbackStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.AsBinder ()); } #pragma warning restore 0169 static IntPtr id_asBinder; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/method[@name='asBinder' and count(parameter)=0]" [Register ("asBinder", "()Landroid/os/IBinder;", "GetAsBinderHandler")] public virtual unsafe global::Android.OS.IBinder AsBinder () { if (id_asBinder == IntPtr.Zero) id_asBinder = JNIEnv.GetMethodID (class_ref, "asBinder", "()Landroid/os/IBinder;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_asBinder), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "asBinder", "()Landroid/os/IBinder;")), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_asInterface_Landroid_os_IBinder_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/method[@name='asInterface' and count(parameter)=1 and parameter[1][@type='android.os.IBinder']]" [Register ("asInterface", "(Landroid/os/IBinder;)Lcom/alipay/android/app/IRemoteServiceCallback;", "")] public static unsafe global::Com.Alipay.Android.App.IRemoteServiceCallback AsInterface (global::Android.OS.IBinder p0) { if (id_asInterface_Landroid_os_IBinder_ == IntPtr.Zero) id_asInterface_Landroid_os_IBinder_ = JNIEnv.GetStaticMethodID (class_ref, "asInterface", "(Landroid/os/IBinder;)Lcom/alipay/android/app/IRemoteServiceCallback;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Android.App.IRemoteServiceCallback __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (JNIEnv.CallStaticObjectMethod (class_ref, id_asInterface_Landroid_os_IBinder_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; #pragma warning disable 0169 static Delegate GetOnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_IHandler () { if (cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I == null) cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr, IntPtr, int, bool>) n_OnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I); return cb_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; } static bool n_OnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2, int p3) { global::Com.Alipay.Android.App.RemoteServiceCallbackStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.RemoteServiceCallbackStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.OS.Parcel p1 = global::Java.Lang.Object.GetObject<global::Android.OS.Parcel> (native_p1, JniHandleOwnership.DoNotTransfer); global::Android.OS.Parcel p2 = global::Java.Lang.Object.GetObject<global::Android.OS.Parcel> (native_p2, JniHandleOwnership.DoNotTransfer); bool __ret = __this.OnTransact (p0, p1, p2, p3); return __ret; } #pragma warning restore 0169 static IntPtr id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/method[@name='onTransact' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='android.os.Parcel'] and parameter[3][@type='android.os.Parcel'] and parameter[4][@type='int']]" [Register ("onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", "GetOnTransact_ILandroid_os_Parcel_Landroid_os_Parcel_IHandler")] public virtual unsafe bool OnTransact (int p0, global::Android.OS.Parcel p1, global::Android.OS.Parcel p2, int p3) { if (id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I == IntPtr.Zero) id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I = JNIEnv.GetMethodID (class_ref, "onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z"); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); bool __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_onTransact_ILandroid_os_Parcel_Landroid_os_Parcel_I, __args); else __ret = JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onTransact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z"), __args); return __ret; } finally { } } static Delegate cb_payEnd_ZLjava_lang_String_; #pragma warning disable 0169 static Delegate GetPayEnd_ZLjava_lang_String_Handler () { if (cb_payEnd_ZLjava_lang_String_ == null) cb_payEnd_ZLjava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, IntPtr>) n_PayEnd_ZLjava_lang_String_); return cb_payEnd_ZLjava_lang_String_; } static void n_PayEnd_ZLjava_lang_String_ (IntPtr jnienv, IntPtr native__this, bool p0, IntPtr native_p1) { global::Com.Alipay.Android.App.RemoteServiceCallbackStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.RemoteServiceCallbackStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); __this.PayEnd (p0, p1); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='payEnd' and count(parameter)=2 and parameter[1][@type='boolean'] and parameter[2][@type='java.lang.String']]" [Register ("payEnd", "(ZLjava/lang/String;)V", "GetPayEnd_ZLjava_lang_String_Handler")] public abstract void PayEnd (bool p0, string p1); static Delegate cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; #pragma warning disable 0169 static Delegate GetStartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_Handler () { if (cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ == null) cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, int, IntPtr>) n_StartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_); return cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; } static void n_StartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, int p2, IntPtr native_p3) { global::Com.Alipay.Android.App.RemoteServiceCallbackStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.RemoteServiceCallbackStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); global::Android.OS.Bundle p3 = global::Java.Lang.Object.GetObject<global::Android.OS.Bundle> (native_p3, JniHandleOwnership.DoNotTransfer); __this.StartActivity (p0, p1, p2, p3); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='startActivity' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='int'] and parameter[4][@type='android.os.Bundle']]" [Register ("startActivity", "(Ljava/lang/String;Ljava/lang/String;ILandroid/os/Bundle;)V", "GetStartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_Handler")] public abstract void StartActivity (string p0, string p1, int p2, global::Android.OS.Bundle p3); static Delegate cb_isHideLoadingScreen; #pragma warning disable 0169 static Delegate GetIsHideLoadingScreenHandler () { if (cb_isHideLoadingScreen == null) cb_isHideLoadingScreen = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsHideLoadingScreen); return cb_isHideLoadingScreen; } static bool n_IsHideLoadingScreen (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.RemoteServiceCallbackStub __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.RemoteServiceCallbackStub> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsHideLoadingScreen; } #pragma warning restore 0169 public abstract bool IsHideLoadingScreen { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/method[@name='isHideLoadingScreen' and count(parameter)=0]" [Register ("isHideLoadingScreen", "()Z", "GetIsHideLoadingScreenHandler")] get; } } [global::Android.Runtime.Register ("com/alipay/android/app/IRemoteServiceCallback$Stub", DoNotGenerateAcw=true)] internal partial class RemoteServiceCallbackStubInvoker : RemoteServiceCallbackStub { public RemoteServiceCallbackStubInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (RemoteServiceCallbackStubInvoker); } } static IntPtr id_isHideLoadingScreen; public override unsafe bool IsHideLoadingScreen { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='IRemoteServiceCallback.Stub']/method[@name='isHideLoadingScreen' and count(parameter)=0]" [Register ("isHideLoadingScreen", "()Z", "GetIsHideLoadingScreenHandler")] get { if (id_isHideLoadingScreen == IntPtr.Zero) id_isHideLoadingScreen = JNIEnv.GetMethodID (class_ref, "isHideLoadingScreen", "()Z"); try { return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isHideLoadingScreen); } finally { } } } static IntPtr id_payEnd_ZLjava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='payEnd' and count(parameter)=2 and parameter[1][@type='boolean'] and parameter[2][@type='java.lang.String']]" [Register ("payEnd", "(ZLjava/lang/String;)V", "GetPayEnd_ZLjava_lang_String_Handler")] public override unsafe void PayEnd (bool p0, string p1) { if (id_payEnd_ZLjava_lang_String_ == IntPtr.Zero) id_payEnd_ZLjava_lang_String_ = JNIEnv.GetMethodID (class_ref, "payEnd", "(ZLjava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_payEnd_ZLjava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='startActivity' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='int'] and parameter[4][@type='android.os.Bundle']]" [Register ("startActivity", "(Ljava/lang/String;Ljava/lang/String;ILandroid/os/Bundle;)V", "GetStartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_Handler")] public override unsafe void StartActivity (string p0, string p1, int p2, global::Android.OS.Bundle p3) { if (id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ == IntPtr.Zero) id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ = JNIEnv.GetMethodID (class_ref, "startActivity", "(Ljava/lang/String;Ljava/lang/String;ILandroid/os/Bundle;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } } } // Metadata.xml XPath interface reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']" [Register ("com/alipay/android/app/IRemoteServiceCallback", "", "Com.Alipay.Android.App.IRemoteServiceCallbackInvoker")] public partial interface IRemoteServiceCallback : global::Android.OS.IInterface { bool IsHideLoadingScreen { // Metadata.xml XPath method reference: path="/api/<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='isHideLoadingScreen' and count(parameter)=0]" [Register ("isHideLoadingScreen", "()Z", "GetIsHideLoadingScreenHandler:Com.Alipay.Android.App.IRemoteServiceCallbackInvoker, AlipayBindingDemo")] get; } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='payEnd' and count(parameter)=2 and parameter[1][@type='boolean'] and parameter[2][@type='java.lang.String']]" [Register ("payEnd", "(ZLjava/lang/String;)V", "GetPayEnd_ZLjava_lang_String_Handler:Com.Alipay.Android.App.IRemoteServiceCallbackInvoker, AlipayBindingDemo")] void PayEnd (bool p0, string p1); // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='IRemoteServiceCallback']/method[@name='startActivity' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='int'] and parameter[4][@type='android.os.Bundle']]" [Register ("startActivity", "(Ljava/lang/String;Ljava/lang/String;ILandroid/os/Bundle;)V", "GetStartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_Handler:Com.Alipay.Android.App.IRemoteServiceCallbackInvoker, AlipayBindingDemo")] void StartActivity (string p0, string p1, int p2, global::Android.OS.Bundle p3); } [global::Android.Runtime.Register ("com/alipay/android/app/IRemoteServiceCallback", DoNotGenerateAcw=true)] internal class IRemoteServiceCallbackInvoker : global::Java.Lang.Object, IRemoteServiceCallback { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/app/IRemoteServiceCallback"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IRemoteServiceCallbackInvoker); } } IntPtr class_ref; public static IRemoteServiceCallback GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IRemoteServiceCallback> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.app.IRemoteServiceCallback")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IRemoteServiceCallbackInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_isHideLoadingScreen; #pragma warning disable 0169 static Delegate GetIsHideLoadingScreenHandler () { if (cb_isHideLoadingScreen == null) cb_isHideLoadingScreen = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsHideLoadingScreen); return cb_isHideLoadingScreen; } static bool n_IsHideLoadingScreen (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.IRemoteServiceCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsHideLoadingScreen; } #pragma warning restore 0169 IntPtr id_isHideLoadingScreen; public unsafe bool IsHideLoadingScreen { get { if (id_isHideLoadingScreen == IntPtr.Zero) id_isHideLoadingScreen = JNIEnv.GetMethodID (class_ref, "isHideLoadingScreen", "()Z"); return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isHideLoadingScreen); } } static Delegate cb_payEnd_ZLjava_lang_String_; #pragma warning disable 0169 static Delegate GetPayEnd_ZLjava_lang_String_Handler () { if (cb_payEnd_ZLjava_lang_String_ == null) cb_payEnd_ZLjava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, IntPtr>) n_PayEnd_ZLjava_lang_String_); return cb_payEnd_ZLjava_lang_String_; } static void n_PayEnd_ZLjava_lang_String_ (IntPtr jnienv, IntPtr native__this, bool p0, IntPtr native_p1) { global::Com.Alipay.Android.App.IRemoteServiceCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); __this.PayEnd (p0, p1); } #pragma warning restore 0169 IntPtr id_payEnd_ZLjava_lang_String_; public unsafe void PayEnd (bool p0, string p1) { if (id_payEnd_ZLjava_lang_String_ == IntPtr.Zero) id_payEnd_ZLjava_lang_String_ = JNIEnv.GetMethodID (class_ref, "payEnd", "(ZLjava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_payEnd_ZLjava_lang_String_, __args); JNIEnv.DeleteLocalRef (native_p1); } static Delegate cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; #pragma warning disable 0169 static Delegate GetStartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_Handler () { if (cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ == null) cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, int, IntPtr>) n_StartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_); return cb_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; } static void n_StartActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, int p2, IntPtr native_p3) { global::Com.Alipay.Android.App.IRemoteServiceCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); global::Android.OS.Bundle p3 = global::Java.Lang.Object.GetObject<global::Android.OS.Bundle> (native_p3, JniHandleOwnership.DoNotTransfer); __this.StartActivity (p0, p1, p2, p3); } #pragma warning restore 0169 IntPtr id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_; public unsafe void StartActivity (string p0, string p1, int p2, global::Android.OS.Bundle p3) { if (id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ == IntPtr.Zero) id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_ = JNIEnv.GetMethodID (class_ref, "startActivity", "(Ljava/lang/String;Ljava/lang/String;ILandroid/os/Bundle;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_startActivity_Ljava_lang_String_Ljava_lang_String_ILandroid_os_Bundle_, __args); JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } static Delegate cb_asBinder; #pragma warning disable 0169 static Delegate GetAsBinderHandler () { if (cb_asBinder == null) cb_asBinder = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_AsBinder); return cb_asBinder; } static IntPtr n_AsBinder (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.App.IRemoteServiceCallback __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.App.IRemoteServiceCallback> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.AsBinder ()); } #pragma warning restore 0169 IntPtr id_asBinder; public unsafe global::Android.OS.IBinder AsBinder () { if (id_asBinder == IntPtr.Zero) id_asBinder = JNIEnv.GetMethodID (class_ref, "asBinder", "()Landroid/os/IBinder;"); return global::Java.Lang.Object.GetObject<global::Android.OS.IBinder> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_asBinder), JniHandleOwnership.TransferLocalRef); } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.App.AuthTask.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.App { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AuthTask']" [global::Android.Runtime.Register ("com/alipay/sdk/app/AuthTask", DoNotGenerateAcw=true)] public partial class AuthTask : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/app/AuthTask", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AuthTask); } } protected AuthTask (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Landroid_app_Activity_; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AuthTask']/constructor[@name='AuthTask' and count(parameter)=1 and parameter[1][@type='android.app.Activity']]" [Register (".ctor", "(Landroid/app/Activity;)V", "")] public unsafe AuthTask (global::Android.App.Activity p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () != typeof (AuthTask)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Landroid/app/Activity;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Landroid/app/Activity;)V", __args); return; } if (id_ctor_Landroid_app_Activity_ == IntPtr.Zero) id_ctor_Landroid_app_Activity_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/app/Activity;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_app_Activity_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Landroid_app_Activity_, __args); } finally { } } static Delegate cb_auth_Ljava_lang_String_Z; #pragma warning disable 0169 static Delegate GetAuth_Ljava_lang_String_ZHandler () { if (cb_auth_Ljava_lang_String_Z == null) cb_auth_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool, IntPtr>) n_Auth_Ljava_lang_String_Z); return cb_auth_Ljava_lang_String_Z; } static IntPtr n_Auth_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, bool p1) { global::Com.Alipay.Sdk.App.AuthTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.AuthTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.Auth (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_auth_Ljava_lang_String_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.alipay.sdk.app']/class[@name='AuthTask']/method[@name='auth' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean']]" [Register ("auth", "(Ljava/lang/String;Z)Ljava/lang/String;", "GetAuth_Ljava_lang_String_ZHandler")] public virtual unsafe string Auth (string p0, bool p1) { if (id_auth_Ljava_lang_String_Z == IntPtr.Zero) id_auth_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "auth", "(Ljava/lang/String;Z)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); string __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_auth_Ljava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "auth", "(Ljava/lang/String;Z)Ljava/lang/String;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_authV2_Ljava_lang_String_Z; #pragma warning disable 0169 static Delegate GetAuthV2_Ljava_lang_String_ZHandler () { if (cb_authV2_Ljava_lang_String_Z == null) cb_authV2_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool, IntPtr>) n_AuthV2_Ljava_lang_String_Z); return cb_authV2_Ljava_lang_String_Z; } static IntPtr n_AuthV2_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, bool p1) { global::Com.Alipay.Sdk.App.AuthTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.AuthTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (__this.AuthV2 (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_authV2_Ljava_lang_String_Z; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AuthTask']/method[@name='authV2' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean']]" [Register ("authV2", "(Ljava/lang/String;Z)Ljava/util/Map;", "GetAuthV2_Ljava_lang_String_ZHandler")] public virtual unsafe global::System.Collections.Generic.IDictionary<string, string> AuthV2 (string p0, bool p1) { if (id_authV2_Ljava_lang_String_Z == IntPtr.Zero) id_authV2_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "authV2", "(Ljava/lang/String;Z)Ljava/util/Map;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::System.Collections.Generic.IDictionary<string, string> __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_authV2_Ljava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "authV2", "(Ljava/lang/String;Z)Ljava/util/Map;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } } } <file_sep>/README.md # Xamarin.Android-AlipaySDKBindingDemo Xamarin.Android 绑定支付宝SDK, 调用支付宝示例 <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.App.PayTask.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.App { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='PayTask']" [global::Android.Runtime.Register ("com/alipay/sdk/app/PayTask", DoNotGenerateAcw=true)] public partial class PayTask : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/app/PayTask", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PayTask); } } protected PayTask (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Landroid_app_Activity_; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='PayTask']/constructor[@name='PayTask' and count(parameter)=1 and parameter[1][@type='android.app.Activity']]" [Register (".ctor", "(Landroid/app/Activity;)V", "")] public unsafe PayTask (global::Android.App.Activity p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () != typeof (PayTask)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Landroid/app/Activity;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Landroid/app/Activity;)V", __args); return; } if (id_ctor_Landroid_app_Activity_ == IntPtr.Zero) id_ctor_Landroid_app_Activity_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/app/Activity;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_app_Activity_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Landroid_app_Activity_, __args); } finally { } } static Delegate cb_getVersion; #pragma warning disable 0169 static Delegate GetGetVersionHandler () { if (cb_getVersion == null) cb_getVersion = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetVersion); return cb_getVersion; } static IntPtr n_GetVersion (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Version); } #pragma warning restore 0169 static IntPtr id_getVersion; public virtual unsafe string Version { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='PayTask']/method[@name='getVersion' and count(parameter)=0]" [Register ("getVersion", "()Ljava/lang/String;", "GetGetVersionHandler")] get { if (id_getVersion == IntPtr.Zero) id_getVersion = JNIEnv.GetMethodID (class_ref, "getVersion", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getVersion), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getVersion", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetFetchOrderInfoFromH5PayUrl_Ljava_lang_String_Handler () { if (cb_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_ == null) cb_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_FetchOrderInfoFromH5PayUrl_Ljava_lang_String_); return cb_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_; } static IntPtr n_FetchOrderInfoFromH5PayUrl_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.FetchOrderInfoFromH5PayUrl (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='PayTask']/method[@name='fetchOrderInfoFromH5PayUrl' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("fetchOrderInfoFromH5PayUrl", "(Ljava/lang/String;)Ljava/lang/String;", "GetFetchOrderInfoFromH5PayUrl_Ljava_lang_String_Handler")] public virtual unsafe string FetchOrderInfoFromH5PayUrl (string p0) { if (id_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_ == IntPtr.Zero) id_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "fetchOrderInfoFromH5PayUrl", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); string __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_fetchOrderInfoFromH5PayUrl_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "fetchOrderInfoFromH5PayUrl", "(Ljava/lang/String;)Ljava/lang/String;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_fetchTradeToken; #pragma warning disable 0169 static Delegate GetFetchTradeTokenHandler () { if (cb_fetchTradeToken == null) cb_fetchTradeToken = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_FetchTradeToken); return cb_fetchTradeToken; } static IntPtr n_FetchTradeToken (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.FetchTradeToken ()); } #pragma warning restore 0169 static IntPtr id_fetchTradeToken; // Metadata.xml XPath method reference: path="/api/<EMAIL>']/class[@name='PayTask']/method[@name='fetchTradeToken' and count(parameter)=0]" [Register ("fetchTradeToken", "()Ljava/lang/String;", "GetFetchTradeTokenHandler")] public virtual unsafe string FetchTradeToken () { if (id_fetchTradeToken == IntPtr.Zero) id_fetchTradeToken = JNIEnv.GetMethodID (class_ref, "fetchTradeToken", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_fetchTradeToken), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "fetchTradeToken", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_h5Pay_Ljava_lang_String_Z; #pragma warning disable 0169 static Delegate GetH5Pay_Ljava_lang_String_ZHandler () { if (cb_h5Pay_Ljava_lang_String_Z == null) cb_h5Pay_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool, IntPtr>) n_H5Pay_Ljava_lang_String_Z); return cb_h5Pay_Ljava_lang_String_Z; } static IntPtr n_H5Pay_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, bool p1) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.H5Pay (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_h5Pay_Ljava_lang_String_Z; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='PayTask']/method[@name='h5Pay' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean']]" [Register ("h5Pay", "(Ljava/lang/String;Z)Lcom/alipay/sdk/util/H5PayResultModel;", "GetH5Pay_Ljava_lang_String_ZHandler")] public virtual unsafe global::Com.Alipay.Sdk.Util.H5PayResultModel H5Pay (string p0, bool p1) { if (id_h5Pay_Ljava_lang_String_Z == IntPtr.Zero) id_h5Pay_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "h5Pay", "(Ljava/lang/String;Z)Lcom/alipay/sdk/util/H5PayResultModel;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::Com.Alipay.Sdk.Util.H5PayResultModel __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_h5Pay_Ljava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Util.H5PayResultModel> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "h5Pay", "(Ljava/lang/String;Z)Lcom/alipay/sdk/util/H5PayResultModel;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_pay_Ljava_lang_String_Z; #pragma warning disable 0169 static Delegate GetPay_Ljava_lang_String_ZHandler () { if (cb_pay_Ljava_lang_String_Z == null) cb_pay_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool, IntPtr>) n_Pay_Ljava_lang_String_Z); return cb_pay_Ljava_lang_String_Z; } static IntPtr n_Pay_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, bool p1) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.Pay (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_pay_Ljava_lang_String_Z; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='PayTask']/method[@name='pay' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean']]" [Register ("pay", "(Ljava/lang/String;Z)Ljava/lang/String;", "GetPay_Ljava_lang_String_ZHandler")] public virtual unsafe string Pay (string p0, bool p1) { if (id_pay_Ljava_lang_String_Z == IntPtr.Zero) id_pay_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "pay", "(Ljava/lang/String;Z)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); string __ret; if (((object) this).GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_pay_Ljava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "pay", "(Ljava/lang/String;Z)Ljava/lang/String;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_payV2_Ljava_lang_String_Z; #pragma warning disable 0169 static Delegate GetPayV2_Ljava_lang_String_ZHandler () { if (cb_payV2_Ljava_lang_String_Z == null) cb_payV2_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool, IntPtr>) n_PayV2_Ljava_lang_String_Z); return cb_payV2_Ljava_lang_String_Z; } static IntPtr n_PayV2_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, bool p1) { global::Com.Alipay.Sdk.App.PayTask __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.PayTask> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (__this.PayV2 (p0, p1)); return __ret; } #pragma warning restore 0169 static IntPtr id_payV2_Ljava_lang_String_Z; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='PayTask']/method[@name='payV2' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean']]" [Register ("payV2", "(Ljava/lang/String;Z)Ljava/util/Map;", "GetPayV2_Ljava_lang_String_ZHandler")] public virtual unsafe global::System.Collections.Generic.IDictionary<string, string> PayV2 (string p0, bool p1) { if (id_payV2_Ljava_lang_String_Z == IntPtr.Zero) id_payV2_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "payV2", "(Ljava/lang/String;Z)Ljava/util/Map;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); global::System.Collections.Generic.IDictionary<string, string> __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_payV2_Ljava_lang_String_Z, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "payV2", "(Ljava/lang/String;Z)Ljava/util/Map;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AppListCmdRequest']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest", DoNotGenerateAcw=true)] public partial class AppListCmdRequest : global::Java.Lang.Object, global::Java.IO.ISerializable { static IntPtr apdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AppListCmdRequest']/field[@name='apdid']" [Register ("apdid")] public string Apdid { get { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr applist_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='AppListCmdRequest']/field[@name='applist']" [Register ("applist")] public string Applist { get { if (applist_jfieldId == IntPtr.Zero) applist_jfieldId = JNIEnv.GetFieldID (class_ref, "applist", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, applist_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (applist_jfieldId == IntPtr.Zero) applist_jfieldId = JNIEnv.GetFieldID (class_ref, "applist", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, applist_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr os_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.request']/class[@name='AppListCmdRequest']/field[@name='os']" [Register ("os")] public string Os { get { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, os_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (os_jfieldId == IntPtr.Zero) os_jfieldId = JNIEnv.GetFieldID (class_ref, "os", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, os_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr token_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.<EMAIL>']/class[@name='AppListCmdRequest']/field[@name='token']" [Register ("token")] public string Token { get { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, token_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (token_jfieldId == IntPtr.Zero) token_jfieldId = JNIEnv.GetFieldID (class_ref, "token", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, token_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr userId_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.request']/class[@name='AppListCmdRequest']/field[@name='userId']" [Register ("userId")] public string UserId { get { if (userId_jfieldId == IntPtr.Zero) userId_jfieldId = JNIEnv.GetFieldID (class_ref, "userId", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, userId_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (userId_jfieldId == IntPtr.Zero) userId_jfieldId = JNIEnv.GetFieldID (class_ref, "userId", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, userId_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AppListCmdRequest); } } protected AppListCmdRequest (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.alipay.tscenter.biz.rpc.vkeydfp.request']/class[@name='AppListCmdRequest']/constructor[@name='AppListCmdRequest' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe AppListCmdRequest () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (AppListCmdRequest)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListResult.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AppListResult']" [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/result/AppListResult", DoNotGenerateAcw=true)] public partial class AppListResult : global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.BaseResult, global::Java.IO.ISerializable { static IntPtr appListData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='AppListResult']/field[@name='appListData']" [Register ("appListData")] public string AppListData { get { if (appListData_jfieldId == IntPtr.Zero) appListData_jfieldId = JNIEnv.GetFieldID (class_ref, "appListData", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, appListData_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (appListData_jfieldId == IntPtr.Zero) appListData_jfieldId = JNIEnv.GetFieldID (class_ref, "appListData", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, appListData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr appListVer_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='<EMAIL>.biz.rpc.vkeydfp.result']/class[@name='AppListResult']/field[@name='appListVer']" [Register ("appListVer")] public string AppListVer { get { if (appListVer_jfieldId == IntPtr.Zero) appListVer_jfieldId = JNIEnv.GetFieldID (class_ref, "appListVer", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, appListVer_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (appListVer_jfieldId == IntPtr.Zero) appListVer_jfieldId = JNIEnv.GetFieldID (class_ref, "appListVer", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, appListVer_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/result/AppListResult", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AppListResult); } } protected AppListResult (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AppListResult']/constructor[@name='AppListResult' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe AppListResult () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (AppListResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.HttpException.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/HttpException", DoNotGenerateAcw=true)] public partial class HttpException : global::Java.Lang.Exception { // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_AUTH_ERROR']" [Register ("NETWORK_AUTH_ERROR")] public const int NetworkAuthError = (int) 8; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_CONNECTION_EXCEPTION']" [Register ("NETWORK_CONNECTION_EXCEPTION")] public const int NetworkConnectionException = (int) 3; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_DNS_ERROR']" [Register ("NETWORK_DNS_ERROR")] public const int NetworkDnsError = (int) 9; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_IO_EXCEPTION']" [Register ("NETWORK_IO_EXCEPTION")] public const int NetworkIoException = (int) 6; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_SCHEDULE_ERROR']" [Register ("NETWORK_SCHEDULE_ERROR")] public const int NetworkScheduleError = (int) 7; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='com.alipay.android.phone.mrpc.core']/class[@name='HttpException']/field[@name='NETWORK_SERVER_EXCEPTION']" [Register ("NETWORK_SERVER_EXCEPTION")] public const int NetworkServerException = (int) 5; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_SOCKET_EXCEPTION']" [Register ("NETWORK_SOCKET_EXCEPTION")] public const int NetworkSocketException = (int) 4; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_SSL_EXCEPTION']" [Register ("NETWORK_SSL_EXCEPTION")] public const int NetworkSslException = (int) 2; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_UNAVAILABLE']" [Register ("NETWORK_UNAVAILABLE")] public const int NetworkUnavailable = (int) 1; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/field[@name='NETWORK_UNKNOWN_ERROR']" [Register ("NETWORK_UNKNOWN_ERROR")] public const int NetworkUnknownError = (int) 0; internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/HttpException", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (HttpException); } } protected HttpException (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.alipay.android.phone.mrpc.core']/class[@name='HttpException']/constructor[@name='HttpException' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/String;)V", "")] public unsafe HttpException (string p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Throwable) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); if (((object) this).GetType () != typeof (HttpException)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Throwable) this).Handle, "(Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Throwable) this).Handle, class_ref, id_ctor_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_ctor_Ljava_lang_Integer_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='com.<EMAIL>']/class[@name='HttpException']/constructor[@name='HttpException' and count(parameter)=2 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/Integer;Ljava/lang/String;)V", "")] public unsafe HttpException (global::Java.Lang.Integer p0, string p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Throwable) this).Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString (p1); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); if (((object) this).GetType () != typeof (HttpException)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/Integer;Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Throwable) this).Handle, "(Ljava/lang/Integer;Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_Integer_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_Integer_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/Integer;Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Throwable) this).Handle, class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p1); } } static Delegate cb_getCode; #pragma warning disable 0169 static Delegate GetGetCodeHandler () { if (cb_getCode == null) cb_getCode = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetCode); return cb_getCode; } static int n_GetCode (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpException> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Code; } #pragma warning restore 0169 static IntPtr id_getCode; public virtual unsafe int Code { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>.mrpc.core']/class[@name='HttpException']/method[@name='getCode' and count(parameter)=0]" [Register ("getCode", "()I", "GetGetCodeHandler")] get { if (id_getCode == IntPtr.Zero) id_getCode = JNIEnv.GetMethodID (class_ref, "getCode", "()I"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallIntMethod (((global::Java.Lang.Throwable) this).Handle, id_getCode); else return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Throwable) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCode", "()I")); } finally { } } } static Delegate cb_getMsg; #pragma warning disable 0169 static Delegate GetGetMsgHandler () { if (cb_getMsg == null) cb_getMsg = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetMsg); return cb_getMsg; } static IntPtr n_GetMsg (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.HttpException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.HttpException> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Msg); } #pragma warning restore 0169 static IntPtr id_getMsg; public virtual unsafe string Msg { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='HttpException']/method[@name='getMsg' and count(parameter)=0]" [Register ("getMsg", "()Ljava/lang/String;", "GetGetMsgHandler")] get { if (id_getMsg == IntPtr.Zero) id_getMsg = JNIEnv.GetMethodID (class_ref, "getMsg", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Throwable) this).Handle, id_getMsg), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Throwable) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMsg", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.RpcParams.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcParams']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/RpcParams", DoNotGenerateAcw=true)] public partial class RpcParams : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/RpcParams", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RpcParams); } } protected RpcParams (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='RpcParams']/constructor[@name='RpcParams' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe RpcParams () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (RpcParams)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_getGwUrl; #pragma warning disable 0169 static Delegate GetGetGwUrlHandler () { if (cb_getGwUrl == null) cb_getGwUrl = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetGwUrl); return cb_getGwUrl; } static IntPtr n_GetGwUrl (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.GwUrl); } #pragma warning restore 0169 static Delegate cb_setGwUrl_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetGwUrl_Ljava_lang_String_Handler () { if (cb_setGwUrl_Ljava_lang_String_ == null) cb_setGwUrl_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetGwUrl_Ljava_lang_String_); return cb_setGwUrl_Ljava_lang_String_; } static void n_SetGwUrl_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.GwUrl = p0; } #pragma warning restore 0169 static IntPtr id_getGwUrl; static IntPtr id_setGwUrl_Ljava_lang_String_; public virtual unsafe string GwUrl { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='getGwUrl' and count(parameter)=0]" [Register ("getGwUrl", "()Ljava/lang/String;", "GetGetGwUrlHandler")] get { if (id_getGwUrl == IntPtr.Zero) id_getGwUrl = JNIEnv.GetMethodID (class_ref, "getGwUrl", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getGwUrl), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getGwUrl", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='setGwUrl' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("setGwUrl", "(Ljava/lang/String;)V", "GetSetGwUrl_Ljava_lang_String_Handler")] set { if (id_setGwUrl_Ljava_lang_String_ == IntPtr.Zero) id_setGwUrl_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setGwUrl", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setGwUrl_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setGwUrl", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static Delegate cb_isGzip; #pragma warning disable 0169 static Delegate GetIsGzipHandler () { if (cb_isGzip == null) cb_isGzip = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsGzip); return cb_isGzip; } static bool n_IsGzip (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Gzip; } #pragma warning restore 0169 static Delegate cb_setGzip_Z; #pragma warning disable 0169 static Delegate GetSetGzip_ZHandler () { if (cb_setGzip_Z == null) cb_setGzip_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetGzip_Z); return cb_setGzip_Z; } static void n_SetGzip_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Gzip = p0; } #pragma warning restore 0169 static IntPtr id_isGzip; static IntPtr id_setGzip_Z; public virtual unsafe bool Gzip { // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='isGzip' and count(parameter)=0]" [Register ("isGzip", "()Z", "GetIsGzipHandler")] get { if (id_isGzip == IntPtr.Zero) id_isGzip = JNIEnv.GetMethodID (class_ref, "isGzip", "()Z"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isGzip); else return JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isGzip", "()Z")); } finally { } } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='setGzip' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setGzip", "(Z)V", "GetSetGzip_ZHandler")] set { if (id_setGzip_Z == IntPtr.Zero) id_setGzip_Z = JNIEnv.GetMethodID (class_ref, "setGzip", "(Z)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setGzip_Z, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setGzip", "(Z)V"), __args); } finally { } } } static Delegate cb_getHeaders; #pragma warning disable 0169 static Delegate GetGetHeadersHandler () { if (cb_getHeaders == null) cb_getHeaders = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetHeaders); return cb_getHeaders; } static IntPtr n_GetHeaders (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return global::Android.Runtime.JavaList.ToLocalJniHandle (__this.Headers); } #pragma warning restore 0169 static Delegate cb_setHeaders_Ljava_util_List_; #pragma warning disable 0169 static Delegate GetSetHeaders_Ljava_util_List_Handler () { if (cb_setHeaders_Ljava_util_List_ == null) cb_setHeaders_Ljava_util_List_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetHeaders_Ljava_util_List_); return cb_setHeaders_Ljava_util_List_; } static void n_SetHeaders_Ljava_util_List_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var p0 = global::Android.Runtime.JavaList.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); __this.Headers = p0; } #pragma warning restore 0169 static IntPtr id_getHeaders; static IntPtr id_setHeaders_Ljava_util_List_; public virtual unsafe global::System.Collections.IList Headers { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='getHeaders' and count(parameter)=0]" [Register ("getHeaders", "()Ljava/util/List;", "GetGetHeadersHandler")] get { if (id_getHeaders == IntPtr.Zero) id_getHeaders = JNIEnv.GetMethodID (class_ref, "getHeaders", "()Ljava/util/List;"); try { if (((object) this).GetType () == ThresholdType) return global::Android.Runtime.JavaList.FromJniHandle (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getHeaders), JniHandleOwnership.TransferLocalRef); else return global::Android.Runtime.JavaList.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getHeaders", "()Ljava/util/List;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcParams']/method[@name='setHeaders' and count(parameter)=1 and parameter[1][@type='java.util.List']]" [Register ("setHeaders", "(Ljava/util/List;)V", "GetSetHeaders_Ljava_util_List_Handler")] set { if (id_setHeaders_Ljava_util_List_ == IntPtr.Zero) id_setHeaders_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "setHeaders", "(Ljava/util/List;)V"); IntPtr native_value = global::Android.Runtime.JavaList.ToLocalJniHandle (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setHeaders_Ljava_util_List_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setHeaders", "(Ljava/util/List;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Response.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Response']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/Response", DoNotGenerateAcw=true)] public partial class Response : global::Java.Lang.Object { static IntPtr mContentType_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Response']/field[@name='mContentType']" [Register ("mContentType")] protected string MContentType { get { if (mContentType_jfieldId == IntPtr.Zero) mContentType_jfieldId = JNIEnv.GetFieldID (class_ref, "mContentType", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mContentType_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mContentType_jfieldId == IntPtr.Zero) mContentType_jfieldId = JNIEnv.GetFieldID (class_ref, "mContentType", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mContentType_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mResData_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Response']/field[@name='mResData']" [Register ("mResData")] protected IList<byte> MResData { get { if (mResData_jfieldId == IntPtr.Zero) mResData_jfieldId = JNIEnv.GetFieldID (class_ref, "mResData", "[B"); return global::Android.Runtime.JavaArray<byte>.FromJniHandle (JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mResData_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (mResData_jfieldId == IntPtr.Zero) mResData_jfieldId = JNIEnv.GetFieldID (class_ref, "mResData", "[B"); IntPtr native_value = global::Android.Runtime.JavaArray<byte>.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mResData_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/Response", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Response); } } protected Response (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='com.<EMAIL>']/class[@name='Response']/constructor[@name='Response' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe Response () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (Response)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_getContentType; #pragma warning disable 0169 static Delegate GetGetContentTypeHandler () { if (cb_getContentType == null) cb_getContentType = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetContentType); return cb_getContentType; } static IntPtr n_GetContentType (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Response __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Response> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ContentType); } #pragma warning restore 0169 static Delegate cb_setContentType_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetContentType_Ljava_lang_String_Handler () { if (cb_setContentType_Ljava_lang_String_ == null) cb_setContentType_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetContentType_Ljava_lang_String_); return cb_setContentType_Ljava_lang_String_; } static void n_SetContentType_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Response __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Response> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.ContentType = p0; } #pragma warning restore 0169 static IntPtr id_getContentType; static IntPtr id_setContentType_Ljava_lang_String_; public virtual unsafe string ContentType { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Response']/method[@name='getContentType' and count(parameter)=0]" [Register ("getContentType", "()Ljava/lang/String;", "GetGetContentTypeHandler")] get { if (id_getContentType == IntPtr.Zero) id_getContentType = JNIEnv.GetMethodID (class_ref, "getContentType", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getContentType), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getContentType", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='Response']/method[@name='setContentType' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("setContentType", "(Ljava/lang/String;)V", "GetSetContentType_Ljava_lang_String_Handler")] set { if (id_setContentType_Ljava_lang_String_ == IntPtr.Zero) id_setContentType_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setContentType", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString (value); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_value); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setContentType_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setContentType", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static Delegate cb_getResData; #pragma warning disable 0169 static Delegate GetGetResDataHandler () { if (cb_getResData == null) cb_getResData = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetResData); return cb_getResData; } static IntPtr n_GetResData (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Response __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Response> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewArray (__this.GetResData ()); } #pragma warning restore 0169 static IntPtr id_getResData; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Response']/method[@name='getResData' and count(parameter)=0]" [Register ("getResData", "()[B", "GetGetResDataHandler")] public virtual unsafe byte[] GetResData () { if (id_getResData == IntPtr.Zero) id_getResData = JNIEnv.GetMethodID (class_ref, "getResData", "()[B"); try { if (((object) this).GetType () == ThresholdType) return (byte[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getResData), JniHandleOwnership.TransferLocalRef, typeof (byte)); else return (byte[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getResData", "()[B")), JniHandleOwnership.TransferLocalRef, typeof (byte)); } finally { } } static Delegate cb_setResData_arrayB; #pragma warning disable 0169 static Delegate GetSetResData_arrayBHandler () { if (cb_setResData_arrayB == null) cb_setResData_arrayB = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetResData_arrayB); return cb_setResData_arrayB; } static void n_SetResData_arrayB (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Response __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Response> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte)); __this.SetResData (p0); if (p0 != null) JNIEnv.CopyArray (p0, native_p0); } #pragma warning restore 0169 static IntPtr id_setResData_arrayB; // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>']/class[@name='Response']/method[@name='setResData' and count(parameter)=1 and parameter[1][@type='byte[]']]" [Register ("setResData", "([B)V", "GetSetResData_arrayBHandler")] public virtual unsafe void SetResData (byte[] p0) { if (id_setResData_arrayB == IntPtr.Zero) id_setResData_arrayB = JNIEnv.GetMethodID (class_ref, "setResData", "([B)V"); IntPtr native_p0 = JNIEnv.NewArray (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setResData_arrayB, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setResData", "([B)V"), __args); } finally { if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Report.General.IDataReportService.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Report.General { // Metadata.xml XPath interface reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='DataReportService']" [Register ("com/alipay/tscenter/biz/rpc/report/general/DataReportService", "", "Com.Alipay.Tscenter.Biz.Rpc.Report.General.IDataReportServiceInvoker")] public partial interface IDataReportService : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='DataReportService']/method[@name='reportData' and count(parameter)=1 and parameter[1][@type='com.alipay.tscenter.biz.rpc.report.general.model.DataReportRequest']]" [Register ("reportData", "(Lcom/alipay/tscenter/biz/rpc/report/general/model/DataReportRequest;)Lcom/alipay/tscenter/biz/rpc/report/general/model/DataReportResult;", "GetReportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_Handler:Com.Alipay.Tscenter.Biz.Rpc.Report.General.IDataReportServiceInvoker, AlipayBindingDemo")] global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportResult ReportData (global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportRequest p0); } [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/report/general/DataReportService", DoNotGenerateAcw=true)] internal class IDataReportServiceInvoker : global::Java.Lang.Object, IDataReportService { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/report/general/DataReportService"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IDataReportServiceInvoker); } } IntPtr class_ref; public static IDataReportService GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IDataReportService> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.tscenter.biz.rpc.report.general.DataReportService")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IDataReportServiceInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_; #pragma warning disable 0169 static Delegate GetReportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_Handler () { if (cb_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_ == null) cb_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_ReportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_); return cb_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_; } static IntPtr n_ReportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.IDataReportService __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.IDataReportService> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportRequest p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportRequest> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.ReportData (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_; public unsafe global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportResult ReportData (global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportRequest p0) { if (id_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_ == IntPtr.Zero) id_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_ = JNIEnv.GetMethodID (class_ref, "reportData", "(Lcom/alipay/tscenter/biz/rpc/report/general/model/DataReportRequest;)Lcom/alipay/tscenter/biz/rpc/report/general/model/DataReportResult;"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportResult __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Report.General.Model.DataReportResult> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_reportData_Lcom_alipay_tscenter_biz_rpc_report_general_model_DataReportRequest_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.MiscUtils.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='MiscUtils']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/MiscUtils", DoNotGenerateAcw=true)] public sealed partial class MiscUtils : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@<EMAIL>='MiscUtils']/field[@name='RC_PACKAGE_NAME']" [Register ("RC_PACKAGE_NAME")] public const string RcPackageName = (string) "com.eg.android.AlipayGphoneRC"; internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/MiscUtils", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (MiscUtils); } } internal MiscUtils (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/<EMAIL>='<EMAIL>']/class[@name='MiscUtils']/constructor[@name='MiscUtils' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe MiscUtils () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (MiscUtils)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_isDebugger_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='MiscUtils']/method[@name='isDebugger' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("isDebugger", "(Landroid/content/Context;)Z", "")] public static unsafe bool IsDebugger (global::Android.Content.Context p0) { if (id_isDebugger_Landroid_content_Context_ == IntPtr.Zero) id_isDebugger_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "isDebugger", "(Landroid/content/Context;)Z"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); bool __ret = JNIEnv.CallStaticBooleanMethod (class_ref, id_isDebugger_Landroid_content_Context_, __args); return __ret; } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.RpcInvocationHandler.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvocationHandler']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/RpcInvocationHandler", DoNotGenerateAcw=true)] public partial class RpcInvocationHandler : global::Java.Lang.Object, global::Java.Lang.Reflect.IInvocationHandler { static IntPtr mClazz_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='RpcInvocationHandler']/field[@name='mClazz']" [Register ("mClazz")] protected global::Java.Lang.Class MClazz { get { if (mClazz_jfieldId == IntPtr.Zero) mClazz_jfieldId = JNIEnv.GetFieldID (class_ref, "mClazz", "Ljava/lang/Class;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mClazz_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Lang.Class> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mClazz_jfieldId == IntPtr.Zero) mClazz_jfieldId = JNIEnv.GetFieldID (class_ref, "mClazz", "Ljava/lang/Class;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mClazz_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mConfig_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcInvocationHandler']/field[@name='mConfig']" [Register ("mConfig")] protected global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig MConfig { get { if (mConfig_jfieldId == IntPtr.Zero) mConfig_jfieldId = JNIEnv.GetFieldID (class_ref, "mConfig", "Lcom/alipay/android/phone/mrpc/core/Config;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mConfig_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mConfig_jfieldId == IntPtr.Zero) mConfig_jfieldId = JNIEnv.GetFieldID (class_ref, "mConfig", "Lcom/alipay/android/phone/mrpc/core/Config;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mConfig_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr mRpcInvoker_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='com.<EMAIL>pc.core']/class[@name='RpcInvocationHandler']/field[@name='mRpcInvoker']" [Register ("mRpcInvoker")] protected global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker MRpcInvoker { get { if (mRpcInvoker_jfieldId == IntPtr.Zero) mRpcInvoker_jfieldId = JNIEnv.GetFieldID (class_ref, "mRpcInvoker", "Lcom/alipay/android/phone/mrpc/core/RpcInvoker;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mRpcInvoker_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mRpcInvoker_jfieldId == IntPtr.Zero) mRpcInvoker_jfieldId = JNIEnv.GetFieldID (class_ref, "mRpcInvoker", "Lcom/alipay/android/phone/mrpc/core/RpcInvoker;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mRpcInvoker_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/RpcInvocationHandler", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RpcInvocationHandler); } } protected RpcInvocationHandler (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_Ljava_lang_Class_Lcom_alipay_android_phone_mrpc_core_RpcInvoker_; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='RpcInvocationHandler']/constructor[@name='RpcInvocationHandler' and count(parameter)=3 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Config'] and parameter[2][@type='java.lang.Class&lt;?&gt;'] and parameter[3][@type='com.alipay.android.phone.mrpc.core.RpcInvoker']]" [Register (".ctor", "(Lcom/alipay/android/phone/mrpc/core/Config;Ljava/lang/Class;Lcom/alipay/android/phone/mrpc/core/RpcInvoker;)V", "")] public unsafe RpcInvocationHandler (global::Com.Alipay.Android.Phone.Mrpc.Core.IConfig p0, global::Java.Lang.Class p1, global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvoker p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); if (((object) this).GetType () != typeof (RpcInvocationHandler)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Lcom/alipay/android/phone/mrpc/core/Config;Ljava/lang/Class;Lcom/alipay/android/phone/mrpc/core/RpcInvoker;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Lcom/alipay/android/phone/mrpc/core/Config;Ljava/lang/Class;Lcom/alipay/android/phone/mrpc/core/RpcInvoker;)V", __args); return; } if (id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_Ljava_lang_Class_Lcom_alipay_android_phone_mrpc_core_RpcInvoker_ == IntPtr.Zero) id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_Ljava_lang_Class_Lcom_alipay_android_phone_mrpc_core_RpcInvoker_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/alipay/android/phone/mrpc/core/Config;Ljava/lang/Class;Lcom/alipay/android/phone/mrpc/core/RpcInvoker;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_Ljava_lang_Class_Lcom_alipay_android_phone_mrpc_core_RpcInvoker_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Lcom_alipay_android_phone_mrpc_core_Config_Ljava_lang_Class_Lcom_alipay_android_phone_mrpc_core_RpcInvoker_, __args); } finally { } } static Delegate cb_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; #pragma warning disable 0169 static Delegate GetInvoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_Handler () { if (cb_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ == null) cb_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_Invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_); return cb_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; } static IntPtr n_Invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvocationHandler __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcInvocationHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Reflect.Method p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Reflect.Method> (native_p1, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object[] p2 = (global::Java.Lang.Object[]) JNIEnv.GetArray (native_p2, JniHandleOwnership.DoNotTransfer, typeof (global::Java.Lang.Object)); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.Invoke (p0, p1, p2)); if (p2 != null) JNIEnv.CopyArray (p2, native_p2); return __ret; } #pragma warning restore 0169 static IntPtr id_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='com.<EMAIL>.mrpc.core']/class[@name='RpcInvocationHandler']/method[@name='invoke' and count(parameter)=3 and parameter[1][@type='java.lang.Object'] and parameter[2][@type='java.lang.reflect.Method'] and parameter[3][@type='java.lang.Object[]']]" [Register ("invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;", "GetInvoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_Handler")] public virtual unsafe global::Java.Lang.Object Invoke (global::Java.Lang.Object p0, global::Java.Lang.Reflect.Method p1, global::Java.Lang.Object[] p2) { if (id_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ == IntPtr.Zero) id_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"); IntPtr native_p2 = JNIEnv.NewArray (p2); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); global::Java.Lang.Object __ret; if (((object) this).GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_invoke_Ljava_lang_Object_Ljava_lang_reflect_Method_arrayLjava_lang_Object_, __args), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"), __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { if (p2 != null) { JNIEnv.CopyArray (native_p2, p2); JNIEnv.DeleteLocalRef (native_p2); } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.Auth.APAuthInfo.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.Auth { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='APAuthInfo']" [global::Android.Runtime.Register ("com/alipay/sdk/auth/APAuthInfo", DoNotGenerateAcw=true)] public partial class APAuthInfo : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/auth/APAuthInfo", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (APAuthInfo); } } protected APAuthInfo (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APAuthInfo']/constructor[@name='APAuthInfo' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "")] public unsafe APAuthInfo (string p0, string p1, string p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (native_p2); if (((object) this).GetType () != typeof (APAuthInfo)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } } static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.<EMAIL>.sdk.auth']/class[@name='APAuthInfo']/constructor[@name='APAuthInfo' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "")] public unsafe APAuthInfo (string p0, string p1, string p2, string p3) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); IntPtr native_p3 = JNIEnv.NewString (p3); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (native_p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (native_p2); __args [3] = new JValue (native_p3); if (((object) this).GetType () != typeof (APAuthInfo)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); JNIEnv.DeleteLocalRef (native_p3); } } static Delegate cb_getAppId; #pragma warning disable 0169 static Delegate GetGetAppIdHandler () { if (cb_getAppId == null) cb_getAppId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetAppId); return cb_getAppId; } static IntPtr n_GetAppId (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Auth.APAuthInfo __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Auth.APAuthInfo> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.AppId); } #pragma warning restore 0169 static IntPtr id_getAppId; public virtual unsafe string AppId { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APAuthInfo']/method[@name='getAppId' and count(parameter)=0]" [Register ("getAppId", "()Ljava/lang/String;", "GetGetAppIdHandler")] get { if (id_getAppId == IntPtr.Zero) id_getAppId = JNIEnv.GetMethodID (class_ref, "getAppId", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getAppId), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getAppId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getPid; #pragma warning disable 0169 static Delegate GetGetPidHandler () { if (cb_getPid == null) cb_getPid = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPid); return cb_getPid; } static IntPtr n_GetPid (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Auth.APAuthInfo __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Auth.APAuthInfo> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Pid); } #pragma warning restore 0169 static IntPtr id_getPid; public virtual unsafe string Pid { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APAuthInfo']/method[@name='getPid' and count(parameter)=0]" [Register ("getPid", "()Ljava/lang/String;", "GetGetPidHandler")] get { if (id_getPid == IntPtr.Zero) id_getPid = JNIEnv.GetMethodID (class_ref, "getPid", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getPid), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPid", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getProductId; #pragma warning disable 0169 static Delegate GetGetProductIdHandler () { if (cb_getProductId == null) cb_getProductId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetProductId); return cb_getProductId; } static IntPtr n_GetProductId (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Auth.APAuthInfo __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Auth.APAuthInfo> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ProductId); } #pragma warning restore 0169 static IntPtr id_getProductId; public virtual unsafe string ProductId { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>']/class[@name='APAuth<EMAIL>']/method[@name='getProductId' and count(parameter)=0]" [Register ("getProductId", "()Ljava/lang/String;", "GetGetProductIdHandler")] get { if (id_getProductId == IntPtr.Zero) id_getProductId = JNIEnv.GetMethodID (class_ref, "getProductId", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getProductId), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getProductId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getRedirectUri; #pragma warning disable 0169 static Delegate GetGetRedirectUriHandler () { if (cb_getRedirectUri == null) cb_getRedirectUri = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetRedirectUri); return cb_getRedirectUri; } static IntPtr n_GetRedirectUri (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Sdk.Auth.APAuthInfo __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.Auth.APAuthInfo> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.RedirectUri); } #pragma warning restore 0169 static IntPtr id_getRedirectUri; public virtual unsafe string RedirectUri { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APAuthInfo']/method[@name='getRedirectUri' and count(parameter)=0]" [Register ("getRedirectUri", "()Ljava/lang/String;", "GetGetRedirectUriHandler")] get { if (id_getRedirectUri == IntPtr.Zero) id_getRedirectUri = JNIEnv.GetMethodID (class_ref, "getRedirectUri", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getRedirectUri), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getRedirectUri", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.ThreadUtil.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='ThreadUtil']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/ThreadUtil", DoNotGenerateAcw=true)] public partial class ThreadUtil : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/ThreadUtil", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ThreadUtil); } } protected ThreadUtil (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='ThreadUtil']/constructor[@name='ThreadUtil' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe ThreadUtil () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (ThreadUtil)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_checkMainThread; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='ThreadUtil']/method[@name='checkMainThread' and count(parameter)=0]" [Register ("checkMainThread", "()Z", "")] public static unsafe bool CheckMainThread () { if (id_checkMainThread == IntPtr.Zero) id_checkMainThread = JNIEnv.GetStaticMethodID (class_ref, "checkMainThread", "()Z"); try { return JNIEnv.CallStaticBooleanMethod (class_ref, id_checkMainThread); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.UT.Device.AidConstants.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.UT.Device { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AidConstants']" [global::Android.Runtime.Register ("com/ut/device/AidConstants", DoNotGenerateAcw=true)] public partial class AidConstants : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/<EMAIL>']/class[@name='AidConstants']/field[@name='EVENT_NETWORK_ERROR']" [Register ("EVENT_NETWORK_ERROR")] public const int EventNetworkError = (int) 1003; // Metadata.xml XPath field reference: path="/api/<EMAIL>']/class[@name='AidConstants']/field[@name='EVENT_REQUEST_FAILED']" [Register ("EVENT_REQUEST_FAILED")] public const int EventRequestFailed = (int) 1002; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AidConstants']/field[@name='EVENT_REQUEST_STARTED']" [Register ("EVENT_REQUEST_STARTED")] public const int EventRequestStarted = (int) 1000; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AidConstants']/field[@name='EVENT_REQUEST_SUCCESS']" [Register ("EVENT_REQUEST_SUCCESS")] public const int EventRequestSuccess = (int) 1001; internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/ut/device/AidConstants", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AidConstants); } } protected AidConstants (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AidConstants']/constructor[@name='AidConstants' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe AidConstants () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (AidConstants)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.App.EnvUtils.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.App { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='EnvUtils']" [global::Android.Runtime.Register ("com/alipay/sdk/app/EnvUtils", DoNotGenerateAcw=true)] public partial class EnvUtils : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/<EMAIL>='<EMAIL>']/class[@name='EnvUtils.EnvEnum']" [global::Android.Runtime.Register ("com/alipay/sdk/app/EnvUtils$EnvEnum", DoNotGenerateAcw=true)] public sealed partial class EnvEnum : global::Java.Lang.Enum { static IntPtr ONLINE_jfieldId; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/class[@name='EnvUtils.EnvEnum']/field[@name='ONLINE']" [Register ("ONLINE")] public static global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum Online { get { if (ONLINE_jfieldId == IntPtr.Zero) ONLINE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ONLINE", "Lcom/alipay/sdk/app/EnvUtils$EnvEnum;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ONLINE_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr SANDBOX_jfieldId; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/class[@name='EnvUtils.EnvEnum']/field[@name='SANDBOX']" [Register ("SANDBOX")] public static global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum Sandbox { get { if (SANDBOX_jfieldId == IntPtr.Zero) SANDBOX_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "SANDBOX", "Lcom/alipay/sdk/app/EnvUtils$EnvEnum;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, SANDBOX_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/app/EnvUtils$EnvEnum", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (EnvEnum); } } internal EnvEnum (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvUtils.EnvEnum']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lcom/alipay/sdk/app/EnvUtils$EnvEnum;", "")] public static unsafe global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lcom/alipay/sdk/app/EnvUtils$EnvEnum;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@<EMAIL>='EnvUtils.EnvEnum']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lcom/alipay/sdk/app/EnvUtils$EnvEnum;", "")] public static unsafe global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lcom/alipay/sdk/app/EnvUtils$EnvEnum;"); try { return (global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/app/EnvUtils", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (EnvUtils); } } protected EnvUtils (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvUtils']/constructor[@name='EnvUtils' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe EnvUtils () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (EnvUtils)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_isSandBox; public static unsafe bool IsSandBox { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvUtils']/method[@name='isSandBox' and count(parameter)=0]" [Register ("isSandBox", "()Z", "GetIsSandBoxHandler")] get { if (id_isSandBox == IntPtr.Zero) id_isSandBox = JNIEnv.GetStaticMethodID (class_ref, "isSandBox", "()Z"); try { return JNIEnv.CallStaticBooleanMethod (class_ref, id_isSandBox); } finally { } } } static IntPtr id_geEnv; // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='EnvUtils']/method[@name='geEnv' and count(parameter)=0]" [Register ("geEnv", "()Lcom/alipay/sdk/app/EnvUtils$EnvEnum;", "")] public static unsafe global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum GeEnv () { if (id_geEnv == IntPtr.Zero) id_geEnv = JNIEnv.GetStaticMethodID (class_ref, "geEnv", "()Lcom/alipay/sdk/app/EnvUtils$EnvEnum;"); try { return global::Java.Lang.Object.GetObject<global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum> (JNIEnv.CallStaticObjectMethod (class_ref, id_geEnv), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_setEnv_Lcom_alipay_sdk_app_EnvUtils_EnvEnum_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvUtils']/method[@name='setEnv' and count(parameter)=1 and parameter[1][@type='com.alipay.sdk.app.EnvUtils.EnvEnum']]" [Register ("setEnv", "(Lcom/alipay/sdk/app/EnvUtils$EnvEnum;)V", "")] public static unsafe void SetEnv (global::Com.Alipay.Sdk.App.EnvUtils.EnvEnum p0) { if (id_setEnv_Lcom_alipay_sdk_app_EnvUtils_EnvEnum_ == IntPtr.Zero) id_setEnv_Lcom_alipay_sdk_app_EnvUtils_EnvEnum_ = JNIEnv.GetStaticMethodID (class_ref, "setEnv", "(Lcom/alipay/sdk/app/EnvUtils$EnvEnum;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallStaticVoidMethod (class_ref, id_setEnv_Lcom_alipay_sdk_app_EnvUtils_EnvEnum_, __args); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdService.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp { // Metadata.xml XPath interface reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='AppListCmdService']" [Register ("com/alipay/tscenter/biz/rpc/vkeydfp/AppListCmdService", "", "Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdServiceInvoker")] public partial interface IAppListCmdService : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='AppListCmdService']/method[@name='getAppListCmd' and count(parameter)=1 and parameter[1][@type='com.alipay.tscenter.biz.rpc.vkeydfp.request.AppListCmdRequest']]" [Register ("getAppListCmd", "(Lcom/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest;)Lcom/alipay/tscenter/biz/rpc/vkeydfp/result/AppListCmdResult;", "GetGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_Handler:Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdServiceInvoker, AlipayBindingDemo")] global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult GetAppListCmd (global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0); // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='AppListCmdService']/method[@name='reGetAppListCmd' and count(parameter)=1 and parameter[1][@type='com.alipay.tscenter.biz.rpc.vkeydfp.request.AppListCmdRequest']]" [Register ("reGetAppListCmd", "(Lcom/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest;)Lcom/alipay/tscenter/biz/rpc/vkeydfp/result/AppListCmdResult;", "GetReGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_Handler:Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdServiceInvoker, AlipayBindingDemo")] global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult ReGetAppListCmd (global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0); } [global::Android.Runtime.Register ("com/alipay/tscenter/biz/rpc/vkeydfp/AppListCmdService", DoNotGenerateAcw=true)] internal class IAppListCmdServiceInvoker : global::Java.Lang.Object, IAppListCmdService { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/tscenter/biz/rpc/vkeydfp/AppListCmdService"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IAppListCmdServiceInvoker); } } IntPtr class_ref; public static IAppListCmdService GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IAppListCmdService> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.tscenter.biz.rpc.vkeydfp.AppListCmdService")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IAppListCmdServiceInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; #pragma warning disable 0169 static Delegate GetGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_Handler () { if (cb_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ == null) cb_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_GetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_); return cb_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; } static IntPtr n_GetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdService __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdService> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetAppListCmd (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; public unsafe global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult GetAppListCmd (global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0) { if (id_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ == IntPtr.Zero) id_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ = JNIEnv.GetMethodID (class_ref, "getAppListCmd", "(Lcom/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest;)Lcom/alipay/tscenter/biz/rpc/vkeydfp/result/AppListCmdResult;"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } static Delegate cb_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; #pragma warning disable 0169 static Delegate GetReGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_Handler () { if (cb_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ == null) cb_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_ReGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_); return cb_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; } static IntPtr n_ReGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdService __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.IAppListCmdService> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.ReGetAppListCmd (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_; public unsafe global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult ReGetAppListCmd (global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Request.AppListCmdRequest p0) { if (id_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ == IntPtr.Zero) id_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_ = JNIEnv.GetMethodID (class_ref, "reGetAppListCmd", "(Lcom/alipay/tscenter/biz/rpc/vkeydfp/request/AppListCmdRequest;)Lcom/alipay/tscenter/biz/rpc/vkeydfp/result/AppListCmdResult;"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Tscenter.Biz.Rpc.Vkeydfp.Result.AppListCmdResult> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_reGetAppListCmd_Lcom_alipay_tscenter_biz_rpc_vkeydfp_request_AppListCmdRequest_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Apmobilesecuritysdk.Face { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk']" [global::Android.Runtime.Register ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk", DoNotGenerateAcw=true)] public partial class APSecuritySdk : global::Java.Lang.Object { // Metadata.xml XPath interface reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='APSecuritySdk.InitResultListener']" [Register ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener", "", "Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk/IInitResultListenerInvoker")] public partial interface IInitResultListener : IJavaObject { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='APSecuritySdk.InitResultListener']/method[@name='onResult' and count(parameter)=1 and parameter[1][@type='com.alipay.apmobilesecuritysdk.face.APSecuritySdk.TokenResult']]" [Register ("onResult", "(Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult;)V", "GetOnResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_Handler:Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk/IInitResultListenerInvoker, AlipayBindingDemo")] void OnResult (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0); } [global::Android.Runtime.Register ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener", DoNotGenerateAcw=true)] internal class IInitResultListenerInvoker : global::Java.Lang.Object, IInitResultListener { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IInitResultListenerInvoker); } } IntPtr class_ref; public static IInitResultListener GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IInitResultListener> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.apmobilesecuritysdk.face.APSecuritySdk.InitResultListener")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IInitResultListenerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_; #pragma warning disable 0169 static Delegate GetOnResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_Handler () { if (cb_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_ == null) cb_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_); return cb_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_; } static void n_OnResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnResult (p0); } #pragma warning restore 0169 IntPtr id_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_; public unsafe void OnResult (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0) { if (id_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_ == IntPtr.Zero) id_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_ = JNIEnv.GetMethodID (class_ref, "onResult", "(Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onResult_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_TokenResult_, __args); } } public partial class InitResultEventArgs : global::System.EventArgs { public InitResultEventArgs (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0) { this.p0 = p0; } global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0; public global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult P0 { get { return p0; } } } [global::Android.Runtime.Register ("mono/com/alipay/apmobilesecuritysdk/face/APSecuritySdk_InitResultListenerImplementor")] internal sealed partial class IInitResultListenerImplementor : global::Java.Lang.Object, IInitResultListener { object sender; public IInitResultListenerImplementor (object sender) : base ( global::Android.Runtime.JNIEnv.StartCreateInstance ("mono/com/alipay/apmobilesecuritysdk/face/APSecuritySdk_InitResultListenerImplementor", "()V"), JniHandleOwnership.TransferLocalRef) { global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); this.sender = sender; } #pragma warning disable 0649 public EventHandler<InitResultEventArgs> Handler; #pragma warning restore 0649 public void OnResult (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult p0) { var __h = Handler; if (__h != null) __h (sender, new InitResultEventArgs (p0)); } internal static bool __IsEmpty (IInitResultListenerImplementor value) { return value.Handler == null; } } // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']" [global::Android.Runtime.Register ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult", DoNotGenerateAcw=true)] public partial class TokenResult : global::Java.Lang.Object { static IntPtr apdid_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']/field[@name='apdid']" [Register ("apdid")] public string Apdid { get { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (apdid_jfieldId == IntPtr.Zero) apdid_jfieldId = JNIEnv.GetFieldID (class_ref, "apdid", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, apdid_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr apdidToken_jfieldId; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']/field[@name='apdidToken']" [Register ("apdidToken")] public string ApdidToken { get { if (apdidToken_jfieldId == IntPtr.Zero) apdidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "apdidToken", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, apdidToken_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (apdidToken_jfieldId == IntPtr.Zero) apdidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "apdidToken", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, apdidToken_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr clientKey_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']/field[@name='clientKey']" [Register ("clientKey")] public string ClientKey { get { if (clientKey_jfieldId == IntPtr.Zero) clientKey_jfieldId = JNIEnv.GetFieldID (class_ref, "clientKey", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, clientKey_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (clientKey_jfieldId == IntPtr.Zero) clientKey_jfieldId = JNIEnv.GetFieldID (class_ref, "clientKey", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, clientKey_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr umidToken_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']/field[@name='umidToken']" [Register ("umidToken")] public string UmidToken { get { if (umidToken_jfieldId == IntPtr.Zero) umidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "umidToken", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, umidToken_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (umidToken_jfieldId == IntPtr.Zero) umidToken_jfieldId = JNIEnv.GetFieldID (class_ref, "umidToken", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, umidToken_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (TokenResult); } } protected TokenResult (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk.TokenResult']/constructor[@name='APSecuritySdk.TokenResult' and count(parameter)=1 and parameter[1][@type='com.alipay.apmobilesecuritysdk.face.APSecuritySdk']]" [Register (".ctor", "(Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk;)V", "")] public unsafe TokenResult (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __self) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (__self); if (((object) this).GetType () != typeof (TokenResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(L" + global::Android.Runtime.JNIEnv.GetJniName (GetType ().DeclaringType) + ";)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(L" + global::Android.Runtime.JNIEnv.GetJniName (GetType ().DeclaringType) + ";)V", __args); return; } if (id_ctor_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_ == IntPtr.Zero) id_ctor_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_, __args); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/apmobilesecuritysdk/face/APSecuritySdk", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (APSecuritySdk); } } protected APSecuritySdk (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static Delegate cb_getApdidToken; #pragma warning disable 0169 static Delegate GetGetApdidTokenHandler () { if (cb_getApdidToken == null) cb_getApdidToken = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetApdidToken); return cb_getApdidToken; } static IntPtr n_GetApdidToken (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ApdidToken); } #pragma warning restore 0169 static IntPtr id_getApdidToken; public virtual unsafe string ApdidToken { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getApdidToken' and count(parameter)=0]" [Register ("getApdidToken", "()Ljava/lang/String;", "GetGetApdidTokenHandler")] get { if (id_getApdidToken == IntPtr.Zero) id_getApdidToken = JNIEnv.GetMethodID (class_ref, "getApdidToken", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getApdidToken), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getApdidToken", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getSdkName; #pragma warning disable 0169 static Delegate GetGetSdkNameHandler () { if (cb_getSdkName == null) cb_getSdkName = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetSdkName); return cb_getSdkName; } static IntPtr n_GetSdkName (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.SdkName); } #pragma warning restore 0169 static IntPtr id_getSdkName; public virtual unsafe string SdkName { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getSdkName' and count(parameter)=0]" [Register ("getSdkName", "()Ljava/lang/String;", "GetGetSdkNameHandler")] get { if (id_getSdkName == IntPtr.Zero) id_getSdkName = JNIEnv.GetMethodID (class_ref, "getSdkName", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getSdkName), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getSdkName", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getSdkVersion; #pragma warning disable 0169 static Delegate GetGetSdkVersionHandler () { if (cb_getSdkVersion == null) cb_getSdkVersion = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetSdkVersion); return cb_getSdkVersion; } static IntPtr n_GetSdkVersion (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.SdkVersion); } #pragma warning restore 0169 static IntPtr id_getSdkVersion; public virtual unsafe string SdkVersion { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>security<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getSdkVersion' and count(parameter)=0]" [Register ("getSdkVersion", "()Ljava/lang/String;", "GetGetSdkVersionHandler")] get { if (id_getSdkVersion == IntPtr.Zero) id_getSdkVersion = JNIEnv.GetMethodID (class_ref, "getSdkVersion", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getSdkVersion), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getSdkVersion", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static IntPtr id_getInstance_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getInstance' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("getInstance", "(Landroid/content/Context;)Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk;", "")] public static unsafe global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk GetInstance (global::Android.Content.Context p0) { if (id_getInstance_Landroid_content_Context_ == IntPtr.Zero) id_getInstance_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "getInstance", "(Landroid/content/Context;)Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __ret = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (JNIEnv.CallStaticObjectMethod (class_ref, id_getInstance_Landroid_content_Context_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_getTokenResult; #pragma warning disable 0169 static Delegate GetGetTokenResultHandler () { if (cb_getTokenResult == null) cb_getTokenResult = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetTokenResult); return cb_getTokenResult; } static IntPtr n_GetTokenResult (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.GetTokenResult ()); } #pragma warning restore 0169 static IntPtr id_getTokenResult; // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getTokenResult' and count(parameter)=0]" [Register ("getTokenResult", "()Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult;", "GetGetTokenResultHandler")] public virtual unsafe global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult GetTokenResult () { if (id_getTokenResult == IntPtr.Zero) id_getTokenResult = JNIEnv.GetMethodID (class_ref, "getTokenResult", "()Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getTokenResult), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.TokenResult> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getTokenResult", "()Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$TokenResult;")), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_getUtdid_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='APSecuritySdk']/method[@name='getUtdid' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("getUtdid", "(Landroid/content/Context;)Ljava/lang/String;", "")] public static unsafe string GetUtdid (global::Android.Content.Context p0) { if (id_getUtdid_Landroid_content_Context_ == IntPtr.Zero) id_getUtdid_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "getUtdid", "(Landroid/content/Context;)Ljava/lang/String;"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getUtdid_Landroid_content_Context_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { } } static Delegate cb_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_; #pragma warning disable 0169 static Delegate GetInitToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_Handler () { if (cb_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_ == null) cb_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr, IntPtr>) n_InitToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_); return cb_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_; } static void n_InitToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2) { global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var p1 = global::Android.Runtime.JavaDictionary<string, string>.FromJniHandle (native_p1, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener p2 = (global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener)global::Java.Lang.Object.GetObject<global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener> (native_p2, JniHandleOwnership.DoNotTransfer); __this.InitToken (p0, p1, p2); } #pragma warning restore 0169 static IntPtr id_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_; // Metadata.xml XPath method reference: path="/api/package[@name='com.<EMAIL>securitysdk.<EMAIL>']/class[@name='APSecuritySdk']/method[@name='initToken' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='java.util.Map&lt;java.lang.String, java.lang.String&gt;'] and parameter[3][@type='com.alipay.apmobilesecuritysdk.face.APSecuritySdk.InitResultListener']]" [Register ("initToken", "(ILjava/util/Map;Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener;)V", "GetInitToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_Handler")] public virtual unsafe void InitToken (int p0, global::System.Collections.Generic.IDictionary<string, string> p1, global::Com.Alipay.Apmobilesecuritysdk.Face.APSecuritySdk.IInitResultListener p2) { if (id_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_ == IntPtr.Zero) id_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_ = JNIEnv.GetMethodID (class_ref, "initToken", "(ILjava/util/Map;Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener;)V"); IntPtr native_p1 = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (p1); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_initToken_ILjava_util_Map_Lcom_alipay_apmobilesecuritysdk_face_APSecuritySdk_InitResultListener_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "initToken", "(ILjava/util/Map;Lcom/alipay/apmobilesecuritysdk/face/APSecuritySdk$InitResultListener;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_p1); } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.Request.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='Request']" [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/Request", DoNotGenerateAcw=true)] public abstract partial class Request : global::Java.Lang.Object { static IntPtr mCallback_jfieldId; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='Request']/field[@name='mCallback']" [Register ("mCallback")] protected global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback MCallback { get { if (mCallback_jfieldId == IntPtr.Zero) mCallback_jfieldId = JNIEnv.GetFieldID (class_ref, "mCallback", "Lcom/alipay/android/phone/mrpc/core/TransportCallback;"); IntPtr __ret = JNIEnv.GetObjectField (((global::Java.Lang.Object) this).Handle, mCallback_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mCallback_jfieldId == IntPtr.Zero) mCallback_jfieldId = JNIEnv.GetFieldID (class_ref, "mCallback", "Lcom/alipay/android/phone/mrpc/core/TransportCallback;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (((global::Java.Lang.Object) this).Handle, mCallback_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/Request", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Request); } } protected Request (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Request']/constructor[@name='Request' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe Request () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (Request)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static Delegate cb_getCallback; #pragma warning disable 0169 static Delegate GetGetCallbackHandler () { if (cb_getCallback == null) cb_getCallback = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetCallback); return cb_getCallback; } static IntPtr n_GetCallback (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Request __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Callback); } #pragma warning restore 0169 static IntPtr id_getCallback; public virtual unsafe global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback Callback { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Request']/method[@name='getCallback' and count(parameter)=0]" [Register ("getCallback", "()Lcom/alipay/android/phone/mrpc/core/TransportCallback;", "GetGetCallbackHandler")] get { if (id_getCallback == IntPtr.Zero) id_getCallback = JNIEnv.GetMethodID (class_ref, "getCallback", "()Lcom/alipay/android/phone/mrpc/core/TransportCallback;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getCallback), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCallback", "()Lcom/alipay/android/phone/mrpc/core/TransportCallback;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_isCanceled; #pragma warning disable 0169 static Delegate GetIsCanceledHandler () { if (cb_isCanceled == null) cb_isCanceled = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsCanceled); return cb_isCanceled; } static bool n_IsCanceled (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Request __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsCanceled; } #pragma warning restore 0169 static IntPtr id_isCanceled; public virtual unsafe bool IsCanceled { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.phone.mrpc.core']/class[@name='Request']/method[@name='isCanceled' and count(parameter)=0]" [Register ("isCanceled", "()Z", "GetIsCanceledHandler")] get { if (id_isCanceled == IntPtr.Zero) id_isCanceled = JNIEnv.GetMethodID (class_ref, "isCanceled", "()Z"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isCanceled); else return JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isCanceled", "()Z")); } finally { } } } static Delegate cb_cancel; #pragma warning disable 0169 static Delegate GetCancelHandler () { if (cb_cancel == null) cb_cancel = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Cancel); return cb_cancel; } static void n_Cancel (IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.Request __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Cancel (); } #pragma warning restore 0169 static IntPtr id_cancel; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='Request']/method[@name='cancel' and count(parameter)=0]" [Register ("cancel", "()V", "GetCancelHandler")] public virtual unsafe void Cancel () { if (id_cancel == IntPtr.Zero) id_cancel = JNIEnv.GetMethodID (class_ref, "cancel", "()V"); try { if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_cancel); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "cancel", "()V")); } finally { } } static Delegate cb_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_; #pragma warning disable 0169 static Delegate GetSetTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_Handler () { if (cb_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_ == null) cb_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_); return cb_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_; } static void n_SetTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.Request __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback p0 = (global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback)global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetTransportCallback (p0); } #pragma warning restore 0169 static IntPtr id_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_; // Metadata.xml XPath method reference: path="/api/package[@name='<EMAIL>']/class[@name='Request']/method[@name='setTransportCallback' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.TransportCallback']]" [Register ("setTransportCallback", "(Lcom/alipay/android/phone/mrpc/core/TransportCallback;)V", "GetSetTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_Handler")] public virtual unsafe void SetTransportCallback (global::Com.Alipay.Android.Phone.Mrpc.Core.ITransportCallback p0) { if (id_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_ == IntPtr.Zero) id_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_ = JNIEnv.GetMethodID (class_ref, "setTransportCallback", "(Lcom/alipay/android/phone/mrpc/core/TransportCallback;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () == ThresholdType) JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setTransportCallback_Lcom_alipay_android_phone_mrpc_core_TransportCallback_, __args); else JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setTransportCallback", "(Lcom/alipay/android/phone/mrpc/core/TransportCallback;)V"), __args); } finally { } } } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/Request", DoNotGenerateAcw=true)] internal partial class RequestInvoker : Request { public RequestInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (RequestInvoker); } } } } <file_sep>/AlipayBindingDemo/RpcException.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath class reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcException']" [global::Android.Runtime.Register("com/alipay/android/phone/mrpc/core/RpcException", DoNotGenerateAcw = true)] public partial class RpcException : global::Java.Lang.RuntimeException { [Register("com/alipay/android/phone/mrpc/core/RpcException$ErrorCode", DoNotGenerateAcw = true)] public abstract class ErrorCode : Java.Lang.Object { internal ErrorCode() { } // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_DESERIALIZER_ERROR']" [Register("CLIENT_DESERIALIZER_ERROR")] public const int ClientDeserializerError = (int)10; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_HANDLE_ERROR']" [Register("CLIENT_HANDLE_ERROR")] public const int ClientHandleError = (int)9; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_INTERUPTED_ERROR']" [Register("CLIENT_INTERUPTED_ERROR")] public const int ClientInteruptedError = (int)13; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_LOGIN_FAIL_ERROR']" [Register("CLIENT_LOGIN_FAIL_ERROR")] public const int ClientLoginFailError = (int)11; // Metadata.xml XPath field reference: path="/api/package[@name='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_AUTH_ERROR']" [Register("CLIENT_NETWORK_AUTH_ERROR")] public const int ClientNetworkAuthError = (int)15; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_CACHE_ERROR']" [Register("CLIENT_NETWORK_CACHE_ERROR")] public const int ClientNetworkCacheError = (int)14; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_CONNECTION_ERROR']" [Register("CLIENT_NETWORK_CONNECTION_ERROR")] public const int ClientNetworkConnectionError = (int)4; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_DNS_ERROR']" [Register("CLIENT_NETWORK_DNS_ERROR")] public const int ClientNetworkDnsError = (int)16; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_ERROR']" [Register("CLIENT_NETWORK_ERROR")] public const int ClientNetworkError = (int)7; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='CLIENT_NETWORK_SCHEDULE_ERROR']" [Register("CLIENT_NETWORK_SCHEDULE_ERROR")] public const int ClientNetworkScheduleError = (int)8; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_SERVER_ERROR']" [Register("CLIENT_NETWORK_SERVER_ERROR")] public const int ClientNetworkServerError = (int)6; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_SOCKET_ERROR']" [Register("CLIENT_NETWORK_SOCKET_ERROR")] public const int ClientNetworkSocketError = (int)5; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_SSL_ERROR']" [Register("CLIENT_NETWORK_SSL_ERROR")] public const int ClientNetworkSslError = (int)3; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_NETWORK_UNAVAILABLE_ERROR']" [Register("CLIENT_NETWORK_UNAVAILABLE_ERROR")] public const int ClientNetworkUnavailableError = (int)2; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_TRANSPORT_UNAVAILABAL_ERROR']" [Register("CLIENT_TRANSPORT_UNAVAILABAL_ERROR")] public const int ClientTransportUnavailabalError = (int)1; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_UNKNOWN_ERROR']" [Register("CLIENT_UNKNOWN_ERROR")] public const int ClientUnknownError = (int)0; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='CLIENT_USER_CHANGE_ERROR']" [Register("CLIENT_USER_CHANGE_ERROR")] public const int ClientUserChangeError = (int)12; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='OK']" [Register("OK")] public const int Ok = (int)1000; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_BIZEXCEPTION']" [Register("SERVER_BIZEXCEPTION")] public const int ServerBizexception = (int)6666; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_CREATEPROXYERROR']" [Register("SERVER_CREATEPROXYERROR")] public const int ServerCreateproxyerror = (int)4003; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_ILLEGALACCESS']" [Register("SERVER_ILLEGALACCESS")] public const int ServerIllegalaccess = (int)6003; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_ILLEGALARGUMENT']" [Register("SERVER_ILLEGALARGUMENT")] public const int ServerIllegalargument = (int)6005; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_INVOKEEXCEEDLIMIT']" [Register("SERVER_INVOKEEXCEEDLIMIT")] public const int ServerInvokeexceedlimit = (int)1002; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_JSONPARSEREXCEPTION']" [Register("SERVER_JSONPARSEREXCEPTION")] public const int ServerJsonparserexception = (int)6004; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='SERVER_METHODNOTFOUND']" [Register("SERVER_METHODNOTFOUND")] public const int ServerMethodnotfound = (int)6001; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_OPERATIONTYPEMISSED']" [Register("SERVER_OPERATIONTYPEMISSED")] public const int ServerOperationtypemissed = (int)3000; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='SERVER_PARAMMISSING']" [Register("SERVER_PARAMMISSING")] public const int ServerParammissing = (int)6002; // Metadata.xml XPath field reference: path="/api/package[@<EMAIL>='<EMAIL>']/interface[@name='<EMAIL>']/field[@name='SERVER_PERMISSIONDENY']" [Register("SERVER_PERMISSIONDENY")] public const int ServerPermissiondeny = (int)1001; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='<EMAIL>']/field[@name='SERVER_REMOTEACCESSEXCEPTION']" [Register("SERVER_REMOTEACCESSEXCEPTION")] public const int ServerRemoteaccessexception = (int)4002; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='<EMAIL>']/field[@name='SERVER_REQUESTDATAMISSED']" [Register("SERVER_REQUESTDATAMISSED")] public const int ServerRequestdatamissed = (int)3001; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='SERVER_REQUESTTIMEOUT']" [Register("SERVER_REQUESTTIMEOUT")] public const int ServerRequesttimeout = (int)4001; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='SERVER_SERVICENOTFOUND']" [Register("SERVER_SERVICENOTFOUND")] public const int ServerServicenotfound = (int)6000; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='SERVER_SESSIONSTATUS']" [Register("SERVER_SESSIONSTATUS")] public const int ServerSessionstatus = (int)2000; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@<EMAIL>='Rpc<EMAIL>']/field[@name='SERVER_UNKNOWERROR']" [Register("SERVER_UNKNOWERROR")] public const int ServerUnknowerror = (int)5000; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Rpc<EMAIL>']/field[@name='SERVER_VALUEINVALID']" [Register("SERVER_VALUEINVALID")] public const int ServerValueinvalid = (int)3002; } [Register("com/alipay/android/phone/mrpc/core/RpcException$ErrorCode", DoNotGenerateAcw = true)] [global::System.Obsolete("Use the 'ErrorCode' type. This type will be removed in a future release.")] public abstract class ErrorCodeConsts : ErrorCode { private ErrorCodeConsts() { } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass("com/alipay/android/phone/mrpc/core/RpcException", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof(RpcException); } } protected RpcException(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } static IntPtr id_ctor_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcException']/constructor[@name='RpcException' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register(".ctor", "(Ljava/lang/String;)V", "")] public unsafe RpcException(string p0) : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (this.Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewString(p0); try { JValue* __args = stackalloc JValue[1]; __args[0] = new JValue(native_p0); if (((object)this).GetType() != typeof(RpcException)) { SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(((object)this).GetType(), "(Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance(this.Handle, "(Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_String_ = JNIEnv.GetMethodID(class_ref, "<init>", "(Ljava/lang/String;)V"); SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(class_ref, id_ctor_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance(this.Handle, class_ref, id_ctor_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef(native_p0); } } static IntPtr id_ctor_Ljava_lang_Integer_Ljava_lang_String_Ljava_lang_Throwable_; // Metadata.xml XPath constructor reference: path="/api/package[@name='<EMAIL>']/class[@name='RpcException']/constructor[@name='RpcException' and count(parameter)=3 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.Throwable']]" [Register(".ctor", "(Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/Throwable;)V", "")] public unsafe RpcException(global::Java.Lang.Integer p0, string p1, global::Java.Lang.Throwable p2) : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (this.Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString(p1); try { JValue* __args = stackalloc JValue[3]; __args[0] = new JValue(p0); __args[1] = new JValue(native_p1); __args[2] = new JValue(p2); if (((object)this).GetType() != typeof(RpcException)) { SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(((object)this).GetType(), "(Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/Throwable;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance(this.Handle, "(Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/Throwable;)V", __args); return; } if (id_ctor_Ljava_lang_Integer_Ljava_lang_String_Ljava_lang_Throwable_ == IntPtr.Zero) id_ctor_Ljava_lang_Integer_Ljava_lang_String_Ljava_lang_Throwable_ = JNIEnv.GetMethodID(class_ref, "<init>", "(Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/Throwable;)V"); SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_Ljava_lang_Throwable_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance(this.Handle, class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_Ljava_lang_Throwable_, __args); } finally { JNIEnv.DeleteLocalRef(native_p1); } } static IntPtr id_ctor_Ljava_lang_Integer_Ljava_lang_Throwable_; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='RpcException']/constructor[@name='RpcException' and count(parameter)=2 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.Throwable']]" [Register(".ctor", "(Ljava/lang/Integer;Ljava/lang/Throwable;)V", "")] public unsafe RpcException(global::Java.Lang.Integer p0, global::Java.Lang.Throwable p1) : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (this.Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue[2]; __args[0] = new JValue(p0); __args[1] = new JValue(p1); if (((object)this).GetType() != typeof(RpcException)) { SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(((object)this).GetType(), "(Ljava/lang/Integer;Ljava/lang/Throwable;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance(this.Handle, "(Ljava/lang/Integer;Ljava/lang/Throwable;)V", __args); return; } if (id_ctor_Ljava_lang_Integer_Ljava_lang_Throwable_ == IntPtr.Zero) id_ctor_Ljava_lang_Integer_Ljava_lang_Throwable_ = JNIEnv.GetMethodID(class_ref, "<init>", "(Ljava/lang/Integer;Ljava/lang/Throwable;)V"); SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_Throwable_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance(this.Handle, class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_Throwable_, __args); } finally { } } static IntPtr id_ctor_Ljava_lang_Integer_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='com.<EMAIL>']/class[@name='RpcException']/constructor[@name='RpcException' and count(parameter)=2 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.String']]" [Register(".ctor", "(Ljava/lang/Integer;Ljava/lang/String;)V", "")] public unsafe RpcException(global::Java.Lang.Integer p0, string p1) : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (this.Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString(p1); try { JValue* __args = stackalloc JValue[2]; __args[0] = new JValue(p0); __args[1] = new JValue(native_p1); if (((object)this).GetType() != typeof(RpcException)) { SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(((object)this).GetType(), "(Ljava/lang/Integer;Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance(this.Handle, "(Ljava/lang/Integer;Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_Integer_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_Integer_Ljava_lang_String_ = JNIEnv.GetMethodID(class_ref, "<init>", "(Ljava/lang/Integer;Ljava/lang/String;)V"); SetHandle( global::Android.Runtime.JNIEnv.StartCreateInstance(class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance(this.Handle, class_ref, id_ctor_Ljava_lang_Integer_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef(native_p1); } } static Delegate cb_getCode; #pragma warning disable 0169 static Delegate GetGetCodeHandler() { if (cb_getCode == null) cb_getCode = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int>)n_GetCode); return cb_getCode; } static int n_GetCode(IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException>(jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Code; } #pragma warning restore 0169 static IntPtr id_getCode; public virtual unsafe int Code { // Metadata.xml XPath method reference: path="/api/package[@<EMAIL>='com.<EMAIL>.mrpc.core']/class[@name='RpcException']/method[@name='getCode' and count(parameter)=0]" [Register("getCode", "()I", "GetGetCodeHandler")] get { if (id_getCode == IntPtr.Zero) id_getCode = JNIEnv.GetMethodID(class_ref, "getCode", "()I"); try { if (((object)this).GetType() == ThresholdType) return JNIEnv.CallIntMethod(this.Handle, id_getCode); else return JNIEnv.CallNonvirtualIntMethod(this.Handle, ThresholdClass, JNIEnv.GetMethodID(ThresholdClass, "getCode", "()I")); } finally { } } } static Delegate cb_getMsg; #pragma warning disable 0169 static Delegate GetGetMsgHandler() { if (cb_getMsg == null) cb_getMsg = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr>)n_GetMsg); return cb_getMsg; } static IntPtr n_GetMsg(IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException>(jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString(__this.Msg); } #pragma warning restore 0169 static IntPtr id_getMsg; public virtual unsafe string Msg { // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='RpcException']/method[@name='getMsg' and count(parameter)=0]" [Register("getMsg", "()Ljava/lang/String;", "GetGetMsgHandler")] get { if (id_getMsg == IntPtr.Zero) id_getMsg = JNIEnv.GetMethodID(class_ref, "getMsg", "()Ljava/lang/String;"); try { if (((object)this).GetType() == ThresholdType) return JNIEnv.GetString(JNIEnv.CallObjectMethod(this.Handle, id_getMsg), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString(JNIEnv.CallNonvirtualObjectMethod(this.Handle, ThresholdClass, JNIEnv.GetMethodID(ThresholdClass, "getMsg", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getOperationType; #pragma warning disable 0169 static Delegate GetGetOperationTypeHandler() { if (cb_getOperationType == null) cb_getOperationType = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr>)n_GetOperationType); return cb_getOperationType; } static IntPtr n_GetOperationType(IntPtr jnienv, IntPtr native__this) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException>(jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString(__this.OperationType); } #pragma warning restore 0169 static Delegate cb_setOperationType_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetOperationType_Ljava_lang_String_Handler() { if (cb_setOperationType_Ljava_lang_String_ == null) cb_setOperationType_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate((Action<IntPtr, IntPtr, IntPtr>)n_SetOperationType_Ljava_lang_String_); return cb_setOperationType_Ljava_lang_String_; } static void n_SetOperationType_Ljava_lang_String_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.RpcException>(jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString(native_p0, JniHandleOwnership.DoNotTransfer); __this.OperationType = p0; } #pragma warning restore 0169 static IntPtr id_getOperationType; static IntPtr id_setOperationType_Ljava_lang_String_; public virtual unsafe string OperationType { // Metadata.xml XPath method reference: path="/api/package[@name='com.<EMAIL>.android.phone.mrpc.core']/class[@name='RpcException']/method[@name='getOperationType' and count(parameter)=0]" [Register("getOperationType", "()Ljava/lang/String;", "GetGetOperationTypeHandler")] get { if (id_getOperationType == IntPtr.Zero) id_getOperationType = JNIEnv.GetMethodID(class_ref, "getOperationType", "()Ljava/lang/String;"); try { if (((object)this).GetType() == ThresholdType) return JNIEnv.GetString(JNIEnv.CallObjectMethod(this.Handle, id_getOperationType), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString(JNIEnv.CallNonvirtualObjectMethod(this.Handle, ThresholdClass, JNIEnv.GetMethodID(ThresholdClass, "getOperationType", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='RpcException']/method[@name='setOperationType' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register("setOperationType", "(Ljava/lang/String;)V", "GetSetOperationType_Ljava_lang_String_Handler")] set { if (id_setOperationType_Ljava_lang_String_ == IntPtr.Zero) id_setOperationType_Ljava_lang_String_ = JNIEnv.GetMethodID(class_ref, "setOperationType", "(Ljava/lang/String;)V"); IntPtr native_value = JNIEnv.NewString(value); try { JValue* __args = stackalloc JValue[1]; __args[0] = new JValue(native_value); if (((object)this).GetType() == ThresholdType) JNIEnv.CallVoidMethod(this.Handle, id_setOperationType_Ljava_lang_String_, __args); else JNIEnv.CallNonvirtualVoidMethod(this.Handle, ThresholdClass, JNIEnv.GetMethodID(ThresholdClass, "setOperationType", "(Ljava/lang/String;)V"), __args); } finally { JNIEnv.DeleteLocalRef(native_value); } } } static IntPtr id_format_Ljava_lang_Integer_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/<EMAIL>='<EMAIL>']/class[@name='RpcException']/method[@name='format' and count(parameter)=2 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.String']]" [Register("format", "(Ljava/lang/Integer;Ljava/lang/String;)Ljava/lang/String;", "")] protected static unsafe string Format(global::Java.Lang.Integer p0, string p1) { if (id_format_Ljava_lang_Integer_Ljava_lang_String_ == IntPtr.Zero) id_format_Ljava_lang_Integer_Ljava_lang_String_ = JNIEnv.GetStaticMethodID(class_ref, "format", "(Ljava/lang/Integer;Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p1 = JNIEnv.NewString(p1); try { JValue* __args = stackalloc JValue[2]; __args[0] = new JValue(p0); __args[1] = new JValue(native_p1); string __ret = JNIEnv.GetString(JNIEnv.CallStaticObjectMethod(class_ref, id_format_Ljava_lang_Integer_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef(native_p1); } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Android.Phone.Mrpc.Core.ITransport.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Android.Phone.Mrpc.Core { // Metadata.xml XPath interface reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Transport']" [Register ("com/alipay/android/phone/mrpc/core/Transport", "", "Com.Alipay.Android.Phone.Mrpc.Core.ITransportInvoker")] public partial interface ITransport : IJavaObject { // Metadata.xml XPath method reference: path="/api/<EMAIL>='<EMAIL>']/interface[@name='Transport']/method[@name='execute' and count(parameter)=1 and parameter[1][@type='com.alipay.android.phone.mrpc.core.Request']]" [Register ("execute", "(Lcom/alipay/android/phone/mrpc/core/Request;)Ljava/util/concurrent/Future;", "GetExecute_Lcom_alipay_android_phone_mrpc_core_Request_Handler:Com.Alipay.Android.Phone.Mrpc.Core.ITransportInvoker, AlipayBindingDemo")] global::Java.Util.Concurrent.IFuture Execute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0); } [global::Android.Runtime.Register ("com/alipay/android/phone/mrpc/core/Transport", DoNotGenerateAcw=true)] internal class ITransportInvoker : global::Java.Lang.Object, ITransport { static IntPtr java_class_ref = JNIEnv.FindClass ("com/alipay/android/phone/mrpc/core/Transport"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ITransportInvoker); } } IntPtr class_ref; public static ITransport GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<ITransport> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "com.alipay.android.phone.mrpc.core.Transport")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public ITransportInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_execute_Lcom_alipay_android_phone_mrpc_core_Request_; #pragma warning disable 0169 static Delegate GetExecute_Lcom_alipay_android_phone_mrpc_core_Request_Handler () { if (cb_execute_Lcom_alipay_android_phone_mrpc_core_Request_ == null) cb_execute_Lcom_alipay_android_phone_mrpc_core_Request_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_Execute_Lcom_alipay_android_phone_mrpc_core_Request_); return cb_execute_Lcom_alipay_android_phone_mrpc_core_Request_; } static IntPtr n_Execute_Lcom_alipay_android_phone_mrpc_core_Request_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Alipay.Android.Phone.Mrpc.Core.ITransport __this = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.ITransport> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0 = global::Java.Lang.Object.GetObject<global::Com.Alipay.Android.Phone.Mrpc.Core.Request> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.Execute (p0)); return __ret; } #pragma warning restore 0169 IntPtr id_execute_Lcom_alipay_android_phone_mrpc_core_Request_; public unsafe global::Java.Util.Concurrent.IFuture Execute (global::Com.Alipay.Android.Phone.Mrpc.Core.Request p0) { if (id_execute_Lcom_alipay_android_phone_mrpc_core_Request_ == IntPtr.Zero) id_execute_Lcom_alipay_android_phone_mrpc_core_Request_ = JNIEnv.GetMethodID (class_ref, "execute", "(Lcom/alipay/android/phone/mrpc/core/Request;)Ljava/util/concurrent/Future;"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); global::Java.Util.Concurrent.IFuture __ret = global::Java.Lang.Object.GetObject<global::Java.Util.Concurrent.IFuture> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_execute_Lcom_alipay_android_phone_mrpc_core_Request_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Sdk.Auth.AlipaySDK.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Sdk.Auth { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='AlipaySDK']" [global::Android.Runtime.Register ("com/alipay/sdk/auth/AlipaySDK", DoNotGenerateAcw=true)] public partial class AlipaySDK : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/sdk/auth/AlipaySDK", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (AlipaySDK); } } protected AlipaySDK (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@<EMAIL>='<EMAIL>']/class[@name='AlipaySDK']/constructor[@name='AlipaySDK' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe AlipaySDK () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (AlipaySDK)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_auth_Landroid_app_Activity_Lcom_alipay_sdk_auth_APAuthInfo_; // Metadata.xml XPath method reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='AlipaySDK']/method[@name='auth' and count(parameter)=2 and parameter[1][@type='android.app.Activity'] and parameter[2][@type='com.alipay.sdk.auth.APAuthInfo']]" [Register ("auth", "(Landroid/app/Activity;Lcom/alipay/sdk/auth/APAuthInfo;)V", "")] public static unsafe void Auth (global::Android.App.Activity p0, global::Com.Alipay.Sdk.Auth.APAuthInfo p1) { if (id_auth_Landroid_app_Activity_Lcom_alipay_sdk_auth_APAuthInfo_ == IntPtr.Zero) id_auth_Landroid_app_Activity_Lcom_alipay_sdk_auth_APAuthInfo_ = JNIEnv.GetStaticMethodID (class_ref, "auth", "(Landroid/app/Activity;Lcom/alipay/sdk/auth/APAuthInfo;)V"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_auth_Landroid_app_Activity_Lcom_alipay_sdk_auth_APAuthInfo_, __args); } finally { } } } } <file_sep>/AlipayBindingDemo/obj/Debug/generated/src/Com.Alipay.Apmobilesecuritysdk.Face.EnvModeConfig.cs using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Alipay.Apmobilesecuritysdk.Face { // Metadata.xml XPath class reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']" [global::Android.Runtime.Register ("com/alipay/apmobilesecuritysdk/face/EnvModeConfig", DoNotGenerateAcw=true)] public partial class EnvModeConfig : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/field[@name='ENVIRONMENT_AAA']" [Register ("ENVIRONMENT_AAA")] public const int EnvironmentAaa = (int) 4; // Metadata.xml XPath field reference: path="/api/<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/field[@name='ENVIRONMENT_DAILY']" [Register ("ENVIRONMENT_DAILY")] public const int EnvironmentDaily = (int) 1; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/field[@name='ENVIRONMENT_ONLINE']" [Register ("ENVIRONMENT_ONLINE")] public const int EnvironmentOnline = (int) 0; // Metadata.xml XPath field reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/field[@name='ENVIRONMENT_PRE']" [Register ("ENVIRONMENT_PRE")] public const int EnvironmentPre = (int) 2; // Metadata.xml XPath field reference: path="/<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/field[@name='ENVIRONMENT_SIT']" [Register ("ENVIRONMENT_SIT")] public const int EnvironmentSit = (int) 3; internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/alipay/apmobilesecuritysdk/face/EnvModeConfig", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (EnvModeConfig); } } protected EnvModeConfig (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[<EMAIL>='<EMAIL>']/class[@name='EnvModeConfig']/constructor[@name='EnvModeConfig' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe EnvModeConfig () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (EnvModeConfig)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } } }
e096e8da4173905a7a7ed61b51c95f9f51f72ee4
[ "Markdown", "C#" ]
47
C#
cybort/Xamarin.Android-AlipaySDKBindingDemo
10b06a54587c817123cd71e83d3eedc24c411137
a2dbcc394196da81a23ef3ba989cdbe9a40c4455
refs/heads/master
<file_sep>from flask import Flask, request, jsonify import os, sys, socket, parsingxls oss = os.name app = Flask(__name__) #Роут предоставляет доступ к методу run_operating с параметром = '-s' из класса Run в файле ves.py @app.route("/get_svin", methods=['POST', 'GET']) def svin(): if request.method == 'GET': if parsingxls.verify_ip(request.environ['REMOTE_ADDR']) == 1: parsingxls.run('-s') res = open('tmp/svin_res.r', mode='r+', encoding='utf-8') return res.read(), {'Content-Type': 'text/json'} else: return "Access denied" #Роут предоставляет доступ к методу run_operating с параметром = '-k' из класса Run в файле ves.py @app.route("/get_korm", methods=['POST', 'GET']) def korm(): if request.method == 'GET': if parsingxls.verify_ip(request.environ['REMOTE_ADDR']) == 1: parsingxls.run('-k') res = open('tmp/korm_res.r', mode='r+', encoding='utf-8') return res.read(),{'Content-Type': 'text/json'} else: return "Access denied" @app.route("/cleantemp", methods=['POST', 'GET']) def cleantemp(): if request.method == 'GET': if access.verify_ip(request.environ['REMOTE_ADDR']) == 1: parsingxls.cleaner() @app.route("/view_my_ip", methods=['POST', 'GET']) def viewip(): if request.method == 'GET': return request.environ['REMOTE_ADDR'] #В зависимости от операционной системе стартует веб сервер при выполнении скрипта server.py if oss == 'posix': if __name__ == "__main__": app.run('192.168.100.34', port=8000) if oss == 'nt': if __name__ == "__main__": app.run(host=socket.gethostbyname(socket.getfqdn()),port=8000)<file_sep>import os,sys,xlrd,datetime,calendar,smtplib, shutil from datetime import date from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def dayweek(par): #Определение дня недели dayweek = calendar.day_abbr[datetime.date.weekday(datetime.date.today())] if par == '-s': days = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'] return days[date.weekday(date.today())] if par == '-k': days = ['пнд', 'вт', 'ср', 'чт', 'птн', 'сб', 'вс'] return days[date.weekday(date.today())] class ParseXls(object): def __init__(self, parampars): self.parampars = parampars self.dayweek = calendar.day_abbr[datetime.date.weekday(datetime.date.today())] self.tempfolder = f'{sys.path[0]}/tmp' self.saleid = {'отъем': 400, 'Свиньи товарные до 95 кг ': 609, 'Свиньи товарные 95 - 110 кг ': 609, 'Свиньи товарные 110-120 кг ': 609, 'Свиньи товарные 120-130 кг ': 609, 'Свиньи товарные от 130 кг ': 609, 'Выбраковка с откорма 50-70': 606, 'Выбраковка с откорма 70 и выше': 605, 'Брак с откорма от 50 кг': 604, 'Свиноматки основные до 200 кг': 114, 'Свиноматки основные от 200 кг': 114, 'Свинки до 200 кг': 302, 'Свинки от 200 кг': 312, 'Свиноматки брак': 112, 'Крипторхи': 615, 'Брак хряки до 150 кг': 610, 'Брак хряки от 150 кг': 611, 'тех. Брак хряки до 150 кг': 201, 'тех. Брак хряки от 150 кг': 203, 'Свинки ремонтные': 304, 'хряки ремонтные': 306} self.errfile = open('tmp/errfile.src', 'a', encoding='utf-8') self.svinresult = open(f'{self.tempfolder}/svin_res.r', 'a', encoding='utf-8') self.kormresult = open(f'{self.tempfolder}/korm_res.r', 'a', encoding='utf-8') self.info = log_info() self.error = log_error() self.curr_date = datetime.date.today() if self.parampars == '-s': saleid = {'отъем': 400, 'Свиньи товарные до 95 кг ': 609, 'Свиньи товарные 95 - 110 кг ': 609, 'Свиньи товарные 110-120 кг ': 609, 'Свиньи товарные 120-130 кг ': 609, 'Свиньи товарные от 130 кг ': 609, 'Выбраковка с откорма 50-70': 606, 'Выбраковка с откорма 70 и выше': 605, 'Брак с откорма от 50 кг': 604, 'Свиноматки основные до 200 кг': 114, 'Свиноматки основные от 200 кг': 114, 'Свинки до 200 кг': 302, 'Свинки от 200 кг': 312, 'Свиноматки брак': 112, 'Крипторхи': 615, 'Брак хряки до 150 кг': 610, 'Брак хряки от 150 кг': 611, 'тех. Брак хряки до 150 кг': 201, 'тех. Брак хряки от 150 кг': 203, 'Свинки ремонтные': 304, 'хряки ремонтные': 306} try: wb = xlrd.open_workbook(f'{self.tempfolder}/svin_temp.xlsm', formatting_info=False, encoding_override="utf-8", on_demand=True) sheet = wb.sheet_by_index(1) for rownum in range(sheet.nrows): row = sheet.row_values(rownum) if row[2] == dayweek('-s'): if row[3] >= 1.0: xldate = row[3] date = xlrd.xldate_as_datetime(xldate, wb.datemode).strftime("%d/%m/%y") xltime = row[6] if xltime == '': self.errfile.write(f'В строке {str(rownum)} не указано время<br>\n') continue pointin = row[4] if pointin == '': self.errfile.write(f'Ошибка в строке {str(rownum)} не указана конечная точка<br>\n') continue sales = str(row[5]) if sales == '': self.errfile.write(f'Ошибка в строке {str(rownum)} не указано наименование товара<br>\n') continue pointout = row[10] if pointout == '': self.errfile.write(f'Ошибка в строке {str(rownum)} не указана точка отправления<br>\n') continue driver = row[16] if driver == '': self.errfile.write(f'Ошибка в строке {str(rownum)} не указан водитель<br>\n') continue carnumber = row[17] if carnumber == '': self.errfile.write(f'Ошибка в строке {str(rownum)} не указан номер машины<br>\n') continue trailernumber = str(row[19]) if trailernumber == '': self.errfile.write(f'Ошибка в строке {str(rownum)} отсутствует информация по номеру прицепа<br>\n') continue not_cr = row[13] if not_cr != '': continue slid = saleid.get(sales) year, month, day, hour, minute, second = xlrd.xldate_as_tuple(xltime, wb.datemode) ti = datetime.time(hour, minute).hour if slid == None: slid = '' time = xlrd.xldate_as_datetime(xltime, wb.datemode).strftime(f'{ti}:%M') tr = trailernumber.split() tnum = ''.join(tr) self.svinresult.write(("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % (date, time, pointin, sales.strip(), pointout, driver, carnumber, tnum, row[20], slid))) self.svinresult.close() self.errfile.close() except: log_error(f'Данные из файла svin_temp.xlsm не получены, {sys.stderr}') else: log_info('Данные из файла korm_temp.xlsm получены') err_ms = open('tmp/errfile.src', 'r', encoding='utf-8') try: ErrSend('-s', err_ms.read(), ['<EMAIL>', '<EMAIL>'], '192.168.100.238', 25) except: log_error(f'Ошбка отправки сообщения с ощибками, {sys.stderr}') err_ms.close() if self.parampars == '-k': try: wb = xlrd.open_workbook(f'tmp/korm_temp.xls', formatting_info=False, encoding_override='utf-8', on_demand=True) data = wb.sheet_by_index(0) for rownum in range(data.nrows): if rownum < 4: continue if rownum > 8830: break row = data.row_values(rownum) if not row[5]: continue year, month, day, hour, minute, second = xlrd.xldate_as_tuple(row[1], wb.datemode) dat = datetime.date(year, month, day) if dat != self.curr_date: continue if row[5] >= 1.0: row[5] = row[5] - 1.0 xldate = row[1] date = xlrd.xldate_as_datetime(xldate, wb.datemode).strftime("%d/%m/%y") xltime = row[5] xl_numrow = int(row[2]) if xltime == '': continue markofkorm = row[6] if markofkorm == '': self.errfile.write(f'В строке {str(rownum)} не указана марка корма<br>\n') continue tonofmark = row[7] if tonofmark == '': errfile.write(f'В строке {str(rownum)} не указан вес по маркам<br>\n') continue typekorm = row[8] if typekorm == '': self.errfile.write(f'В строке {str(rownum)} не указан тип корма<br>\n') continue out = row[9] if out == '': self.errfile.write(f'В строке {str(rownum)} не указано откуда корм<br>\n') continue insale = row[10] if insale == '': errfile.write(f'В строке {str(rownum)} точка прибытия по маркам<br>\n') continue driver = row[17] if driver == '': errfile.write(f'В строке {str(rownum)} отсутствуют данные по водителю<br>\n') continue carnumber = row[18] if carnumber == '': errfile.write(f'В строке {str(rownum)} не указан номер машины<br>\n') continue trailernumber = row[19] if trailernumber == '': errfile.write(f'В строке {str(rownum)} отсутствует информация по прицепу<br>\n') continue try: wtf = int(row[16]) except: wtf = row[16] if wtf == '': continue xldoubletime = row[80] if xldoubletime == '': errfile.write(f'В строке {str(rownum)} не продублироваанна дата<br>\n') hr = time = xlrd.xldate_as_datetime(xltime, wb.datemode).hour time = xlrd.xldate_as_datetime(xltime, wb.datemode).strftime(f'{hr}:%M') try: doubletime = xlrd.xldate_as_datetime(xldoubletime, wb.datemode).strftime("%Y-%m-%d") except: doubletime = '' self.kormresult.write(("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % (date, time, markofkorm, tonofmark, typekorm, out, insale, driver, carnumber, trailernumber, wtf, xl_numrow, doubletime))) self.kormresult.close() self.errfile.close() except: log_error(f'Данные из файла korm_temp.xls не получены, {sys.stderr}') else: log_info('Данные из файла korm_temp.xls получены') err_ms = open('tmp/errfile.src', 'r', encoding='utf-8') try: ErrSend('-k',err_ms.read(),['<EMAIL>', '<EMAIL>'],'192.168.100.238',25) except: log_error(f'Ошбка отправки сообщения с ощибками, {sys.stderr}') err_ms.close() class ErrSend(object): def __init__(self, type, msg, mail_list, host, port): self.type = str(type) self.msg = msg self.mail_list = mail_list self.host = str(host) self.port = int(port) self.settings = {'smtp':self.host, 'port':self.port, 'frm':'<EMAIL>'} message = MIMEMultipart("alternative") if self.type == '-s': message[ "Subject"] = f'Отчет об ошибках функции get_svin на момент {datetime.datetime.today().strftime(" %Y/%m/%d; %H:%M;")}' if self.type == '-k': message[ "Subject"] = f'Отчет об ошибках функции get_korm на момент {datetime.datetime.today().strftime(" %Y/%m/%d; %H:%M;")}' message["From"] = self.settings.get('frm') message["To"] = ', '.join(self.mail_list) html = f"<html><body><p><strong>{self.msg}</strong></p></body></html>" # Сделать их текстовыми\html объектами MIMEText message.attach(MIMEText(msg, "plain")) message.attach(MIMEText(html, "html")) mailObj = smtplib.SMTP(self.settings.get('smtp'), self.settings.get('port')) mailObj.sendmail(self.settings.get('frm'), self.mail_list, message.as_string()) mailObj.quit() class Mount(object): def __init__(self, param, path, mount_point): self.param = param self.path = path self.mount_point = mount_point self.info = log_info() self.error = log_error() today = datetime.datetime.today() year = today.strftime("%Y") week = today.isocalendar()[1] try: os.system(f"mount.cifs -o username=s_korm,password=<PASSWORD>,domain=agrohold.ru {self.path} {self.mount_point}") except: log_error('Ошибка при монтировании раздела') else: log_info('Раздел примонтирован') if self.param == '-k': try: shutil.copy(f'/mnt/winshare/КОРМА/{year}/неделя {week}/ОБЩИЙ график.xls', 'tmp/korm_temp.xls') except: log_error('Ошибка при копировании файла ОБЩИЙ график.xls') if self.param == '-s': try: shutil.copy(f'/mnt/winshare/График отгрузок/{year}/неделя-{week}/График свиновозов.xlsm','tmp/svin_temp.xlsm') except: log_error('Ошибка при копировании файла График свиновозов.xlsm') try: os.system(f"umount {self.mount_point}") except: log_error('Раздел не размонтирован') else: log_info('Раздел размонтирован') def verify_ip(user_ip): #Проверка ip адресса на доступ к функциям granted_ip = ['192.168.100.101', '192.168.100.4','192.168.100.12', '192.168.100.6','192.168.100.104','192.168.100.102', '192.168.102.209','192.168.100.100','192.168.100.103', '192.168.100.193','192.168.14.41','192.168.96.3', '192.168.96.6','192.168.96.11','192.168.96.12', '192.168.96.13','192.168.96.16','192.168.96.120', '127.0.0.1','192.168.1.2','192.168.1.100', '192.168.12.137','192.168.100.2','192.168.100.202', '192.168.100.208','192.168.100.252'] verify = granted_ip.count(user_ip) return verify def cleaner(): tempfile = {'kormview': 'tmp/korm_res.r', 'svinview': 'tmp/svin_res.r', 'errfile': 'tmp/errfile.src', 'kormtemp': 'tmp/korm_temp.xls', 'svintemp': 'tmp/svin_temp.xlsm'} #try: for temp in tempfile.values(): if os.path.isfile(temp) == True: os.remove(temp) #except: #loggs.log_error( #f'Ошибка при удалении {tempfile.get("svinview")}, {tempfile.get("kormview")}, {tempfile.get("svintemp")}, {tempfile.get("kormtemp")}, {tempfile.get("errfile")}') def run(param): if param == '-s': cleaner() Mount('-s', '//192.168.100.10/Documents/Общая', '/mnt/winshare') ParseXls('-s').parsing() if param == '-k': cleaner() Mount('-k', '//192.168.100.10/Documents/Общая', '/mnt/winshare') ParseXls('-k').parsing() def log_info(msg): logfile = open(file='tmp/info.log', mode='a', encoding='utf-8') logfile.write(f'{datetime.datetime.today().strftime("[%Y-%m-%d|%H:%M]")} {msg}\n') def log_error(msg): logfile = open(file='tmp/error.log', mode='a', encoding='utf-8') logfile.write(f'{datetime.datetime.today().strftime("[%Y-%m-%d|%H:%M]")} {msg}\n')
fbc601bd5941ffaac6deefbbea0b417d5bf11896
[ "Python" ]
2
Python
vinc09333/ParsingXLS
83ec8e6714a27934c9b4987e899f8a77a51c93c9
8725542326c0b4b18b2cfe67b21e2ee02d6215a3
refs/heads/master
<repo_name>ToDuyHung/assignment_with_SIRD_model<file_sep>/SIR model/Bai4.py import pandas as pd import numpy as np import scipy.stats as st import seaborn as sns import matplotlib.pyplot as plt import json import datetime from datetime import date #1st mus, sigma : for beta #2nd mus, sigma : for gamma mus = [0.66, 0.573] sigma = [0.11, 0.1] def gauss_pdf(param): return st.norm.pdf(param, mus, sigma) def metropolis_hastings(iter=120): # Construct init parameter from normal pdf # 1st param: beta # 2nd param: gamma param = [0.6 , 0.5] pi = gauss_pdf(param) # samples size is iterations, each sample is a pair (beta, gamma) samples = np.zeros((iter, 2)) for i in range(iter): # Random normal distribution with size = 2 and new mean = previous beta, gamma param_star = np.array(param) + np.random.normal(size=2) # Calculate gauss_pdf with proposal sample pi_star = gauss_pdf(param_star) # Calculate probability to keep the proposal sample r = min(1, (pi_star[0]*pi_star[1]*1.)/(pi[0]*pi[1])) # Generate random varible q from U(0,1) q = np.random.uniform(low=0, high=1) # if (q < r) keep proposal sample if q < r: param = param_star pi = pi_star samples[i] = param return samples #number=1580515200 if __name__ == '__main__': samples = metropolis_hastings(iter=100000) # for i in samples: # print(i[0]) number=1584835200 #number represents for date in timestamp (1584835200 = 22nd March, 2020) X =[] while number< 1595203200: # 1595203200 = 20th July, 2020 timestamp = date.fromtimestamp(number) url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/'+timestamp.strftime('%m-%d-%Y')+'.csv' df = pd.read_csv(url) confirmed = df['Confirmed'][df.Country_Region == 'Italy'] recovered = df['Recovered'][df.Country_Region == 'Italy'] x=confirmed+recovered X.append(x) number+=86400 R0=0.0 for x, sam in zip(X,samples): pi = st.gamma.pdf(x,a=sam[0],scale= sam[1]) R0 = R0 + pi*(sam[0]/sam[1]) print('R0 of Italy is ',sum(R0)) while number< 1595203200: # 1595203200 = 20th July, 2020 timestamp = date.fromtimestamp(number) url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/'+timestamp.strftime('%m-%d-%Y')+'.csv' df = pd.read_csv(url) confirmed = df['Confirmed'][df.Country_Region == 'Vietnam'] recovered = df['Recovered'][df.Country_Region == 'Vietnam'] x=confirmed+recovered X.append(x) number+=86400 R0=0.0 for x, sam in zip(X,samples): pi = st.gamma.pdf(x,a=sam[0],scale= sam[1]) R0 = R0 + pi*(sam[0]/sam[1]) print('R0 of Vietnam is ',sum(R0)) <file_sep>/README.md # assignment_with_SIRD_model assignment for math modeling <file_sep>/SIR model/sample.py import numpy as np import scipy.stats as st import seaborn as sns import matplotlib.pyplot as plt import json # 1st mus, sigma : for beta # 2nd mus, sigma : for gamma mu_beta = float(input("Insert mu for beta: ")) sigma_beta = float(input("Insert sigma for beta: ")) mu_gamma = float(input("Insert mu for gamma: ")) sigma_gamma = float(input("Insert sigma for gamma: ")) iter = int(input("Insert interation: ")) mus = [mu_beta, mu_gamma] sigma = [sigma_beta, sigma_gamma] def gauss_pdf(param): return st.norm.pdf(param, mus, sigma) def metropolis_hastings(iter=1000): # Construct init parameter from normal pdf # 1st param: beta # 2nd param: gamma param = [0.6 , 0.5] pi = gauss_pdf(param) accepted = [] # samples size is iterations, each sample is a pair (beta, gamma) samples = np.zeros((iter, 2)) for i in range(iter): # Random normal distribution with size = 2 and new mean = previous beta, gamma param_star = np.array(param) + np.random.normal(size=2) # Calculate gauss_pdf with proposal sample pi_star = gauss_pdf(param_star) # Calculate probability to keep the proposal sample r = min(1, (pi_star[0]*pi_star[1]*1.)/(pi[0]*pi[1])) # Generate random varible q from U(0,1) q = np.random.uniform(low=0, high=1) # if (q < r) keep proposal sample if q < r: param = param_star pi = pi_star accepted.append(param) samples[i] = param return samples, accepted samples, accepted = metropolis_hastings(iter) with open('samples2.txt', 'w') as f: f.writelines(','.join(str(j) for j in i) + '\n' for i in samples) #print(accepted) beta_hist = plt.figure() sns.distplot(samples[:,0]) plt.xlabel(r'$\beta$') plt.ylabel('Probability density') beta_hist.savefig('beta2.png') gamma_hist = plt.figure() sns.distplot(samples[:,1]) plt.xlabel(r'$\gamma$') plt.ylabel('Probability density') gamma_hist.savefig('gamma2.png') joint_distribution = plt.figure() sns.jointplot(samples[:, 0], samples[:, 1]) plt.xlabel(r'$\beta$') plt.ylabel(r'$\gamma$') plt.savefig('samples2.png')
52011a00c0e600741e3f06188b3ec6ef2a7c6d04
[ "Markdown", "Python" ]
3
Python
ToDuyHung/assignment_with_SIRD_model
b4cc8ac6b64207244e1f0b2608f0f7cd7b56a804
1268ac0be539ba95cb74ede8470b516fec593907
refs/heads/master
<file_sep>ig.module( 'game.entities.piece' ) .requires( 'impact.entity', 'impact.game' ) .defines(function(){ EntityPiece = ig.Entity.extend({ size: {x:64, y:64}, moveDistance: 1, movedirection: [5, 6, 7], animSheet: null, color: "black", iBelongToPlayer: null, collides: ig.Entity.COLLIDES.PASSIVE, type: ig.Entity.TYPE.A, isSelected: false, init: function(x, y, settings){ this.parent(x, y, settings); this.animSheet = ig.game.myPieceSheet; if (settings.color == "black"){ this.iBelongToPlayer = ig.game.currentModel.playerIDs.black; } else if( settings.color == "white"){ this.iBelongToPlayer = ig.game.currentModel.playerIDs.white; } //if (ig.game.iAmPlayerColor == "black"){ // this.flipPiece(); //} //individual animation and sprite frames defined in specific entities. }, update: function(){ if (this.isSelected){ //this.pos.x = ig.input.mouse.x-32; //this.pos.y = ig.input.mouse.y-32; } this.parent(); //this.update(); }, draw: function(){ if (this.isSelected){ this.parent(); ig.system.context.beginPath(); ig.system.context.fillStyle = "rgba(0, 0, 255, 0.5)"; ig.system.context.arc( (this.pos.x+32)*ig.system.scale, (this.pos.y+32)*ig.system.scale, 32, 0, Math.PI*2 ); ig.system.context.closePath(); ig.system.context.fill(); } else{ this.parent(); } }, check: function(){ this.parent(); }, select: function(){ //makes the current piece the active piece. this.isSelected = true; ig.game.selectedPiece = this; }, deselect: function(){ this.isSelected = false; ig.game.selectedPiece = null; }, flipPiece: function(){ this.anims.standing.flip.x = true; this.anims.standing.flip.y = true; //this.anims.standing.flip.x = true; //this.anims.standing.flip.y = true; } }); }); <file_sep>ig.module( 'game.entities.pawn' ) .requires( 'impact.entity', 'game.entities.piece' ) .defines(function(){ EntityPawn = EntityPiece.extend({ canMoveTwo: true, init: function(x, y, settings){ this.parent(x, y, settings); if (this.color == "black"){ this.addAnim('standing', 1, [25], true); } else if (this.color == "white"){ this.addAnim('standing', 1, [55], true); } }, update: function(){ this.parent(); } }); });<file_sep>ig.module( 'game.entities.bishop' ) .requires( 'impact.entity', 'game.entities.piece' ) .defines(function(){ EntityBishop = EntityPiece.extend({ init: function(x, y, settings){ this.parent(x, y, settings); if (this.color == "black"){ this.addAnim('standing', 1, [10], true); } else if (this.color == "white"){ this.addAnim('standing', 1, [40], true); } }, update: function(){ this.parent(); } }); });<file_sep>//this is the main chessjs file module ig.module( 'game.chessjs' ) .requires( 'impact.game', 'game.gameModel', 'game.entities.piece', 'game.entities.pawn', 'game.entities.rook', 'game.entities.knight', 'game.entities.bishop', 'game.entities.queen', 'game.entities.king', 'game.entities.mousePointer', 'game.levels.BoardSetup' ) .defines(function(){ Chessjs = ig.Game.extend({ pieceSheet: null, backgroundSheet: null, selectedPiece: null, iAmPlayerNumber: 0, iAmPlayerColor: null, myPieceSheet: new ig.AnimationSheet('media/piecessheet.png', 64, 64), currentModel: {turns: 0, playerIDs: {white:0, black:9}, whoseTurn:0, boardLayout: [ [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0] ] }, init: function(){ this.loadLevel(LevelBoardSetup); //this.placePieces(); this.loadSetup(this.iAmPlayerNumber); //localStorage.setItem("chessjs", "this is a chess string"); //this.spawnEntity( EntityPawn, 0, 0, {}); //this.saveSetup(); ig.input.initMouse(); ig.input.bind(ig.KEY.MOUSE1, 'leftClick'); ig.input.bind(ig.KEY.MOUSE2, 'rightClick'); ig.input.bind(ig.KEY.ESC, 'escape'); this.spawnEntity(EntityMousePointer, 0, 0); }, update: function(){ this.parent(); }, loadSetup: function(whoIsViewing){ //This reads the board setup from a gameModel object as a json object. //for the moment this is GameModel in the gameModel.js module. var modelString = localStorage.getItem("chessjsSavedModel"); if (modelString != null){ //saved game exists in html5 localStorage var loadedModel = JSON.parse(modelString); //if (loadedModel.playerIDs.white == this.iAmPlayerNumber){ // //do not flip //} //else if (loadedModel.playerIDs.black == this.iAmPlayerNumber0){ // //flip // for (i=0; i<loadedModel.boardLayout.length; i++){ // loadedModel.boardLayout[i].reverse(); // } // loadedModel.boardLayout.reverse(); //} //else{ // alert("Player ID not recognized"); //} this.currentModel = loadedModel; } else { this.currentModel = GameModel; //THIS is what you would change //for loading from database remotely. } if (this.currentModel.playerIDs.white == this.iAmPlayerNumber){ this.iAmPlayerColor = "white"; } else if (this.currentModel.playerIDs.black == this.iAmPlayerNumber){ this.iAmPlayerColor = "black"; } else { alert("player ID not recognized: "+this.iAmPlayerNumber); } var currBox = { x:0, //starting box y:0, step:64, //dimensions of box move: function(){ if (this.x == this.step*7){ this.y += this.step; this.x = 0; } else { this.x += this.step; } } }; for (j=0; j<this.currentModel.boardLayout.length; j++){ //y values for (i=0; i<this.currentModel.boardLayout[j].length; i++){ //x values switch(this.currentModel.boardLayout[j][i]){ case "bpawn": ig.game.spawnEntity(EntityPawn, currBox.x, currBox.y, {color:"black", name:"bpawn"}); break; case "wpawn": ig.game.spawnEntity(EntityPawn, currBox.x, currBox.y, {color:"white", name:"bpawn"}); break case "brook": ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:"black"}); break case "bbishop": ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:"black"}); break case "bknight": ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:"black"}); break case "bking": ig.game.spawnEntity(EntityKing, currBox.x, currBox.y, {color:"black"}); break case "bqueen": ig.game.spawnEntity(EntityQueen, currBox.x, currBox.y, {color:"black"}); break case "wrook": ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:"white"}); break case "wbishop": ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:"white"}); break; case "wknight": ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:"white"}); break; case "wking": ig.game.spawnEntity(EntityKing, currBox.x, currBox.y, {color:"white"}); break; case "wqueen": ig.game.spawnEntity(EntityQueen, currBox.x, currBox.y, {color:"white"}); break; default: } currBox.move(); } } if (this.iAmPlayerColor == "black"){ ig.system.context.translate(ig.system.width*ig.system.scale, ig.system.height*ig.system.scale); ig.system.context.rotate(Math.PI); var piecesArray = this.getEntitiesByType(EntityPiece); for (m=0; m<piecesArray.length; m++){ //for (eachEntity in piecesArray){ piecesArray[m].flipPiece(); } //alert("length of pieces array: "+piecesArray.length); } }, saveSetup: function(){ //saves the board setup to a gameModel object then converts to json //and textifies it. Currenly this will write to html5 local storage //but can be made to POST to a remote database/listener. var saveString = JSON.stringify(this.currentModel); localStorage.setItem("chessjsSavedModel", saveString); }, placePieces: function(){ var currBox = { x:0, //starting box y:0, step:64, move: function(){ if (this.x ==this.step*8){ this.y += this.step; this.x = 0; } else { this.x += this.step; } } }; var side = "black"; ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityQueen, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKing, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:side}); currBox.move(); for (i = 0; i<=8; i++) { ig.game.spawnEntity(EntityPawn, currBox.x, currBox.y, {color:side}); currBox.move(); } side = "white"; currBox.x = 0; currBox.y = currBox.step*6; //moves to the white row for (i = 0; i<=8; i++) { ig.game.spawnEntity(EntityPawn, currBox.x, currBox.y, {color:side}); currBox.move(); } ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKing, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityQueen, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityBishop, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityKnight, currBox.x, currBox.y, {color:side}); currBox.move(); ig.game.spawnEntity(EntityRook, currBox.x, currBox.y, {color:side}); } }); //Game Startup. ig.main( '#canvas', Chessjs, 30, 512, 512, 2); }); <file_sep>ig.module( 'game.entities.mousePointer' ) .requires( 'impact.entity' ) .defines(function(){ EntityMousePointer = ig.Entity.extend({ //mousePointer entity is made to handle mouseovers and mouseclicks type: ig.Entity.TYPE.B, checkAgainst: ig.Entity.TYPE.A, collides: ig.Entity.COLLIDES.NEVER, animSheet: null, hasPiece: false, size: {x:1, y:1}, init: function(x, y, settings){ this.animSheet = ig.game.myPieceSheet; this.parent(x, y, settings); this.pos.x = ig.input.mouse.x; this.pos.y = ig.input.mouse.y; if (ig.game.iAmPlayerColor == "black"){ this.flipMouse(); } //alert("init mousepointer"); }, update: function(){ this.pos.x = ig.input.mouse.x; this.pos.y = ig.input.mouse.y; if (ig.game.iAmPlayerColor == "black"){ this.flipMouse(); } if (this.hasPiece){ if (ig.input.pressed('rightClick')){ this.hasPiece = false; ig.game.selectedPiece.deselect(); } } this.parent(); }, draw: function(){ if (this.hasPiece){ ig.system.context.beginPath(); ig.system.context.fillStyle = "rgba(0, 255, 0, 0.5)"; ig.system.context.arc( (this.pos.x) * ig.system.scale, (this.pos.y) * ig.system.scale, 32, 0, Math.PI*2 ); ig.system.context.closePath(); ig.system.context.fill(); } else { this.parent(); } }, check: function( piece ){ if (!this.hasPiece && (piece.iBelongToPlayer == ig.game.iAmPlayerNumber)){ if (ig.input.pressed('leftClick')){ ig.game.selectedPiece = piece; ig.game.selectedPiece.select(); this.hasPiece = true; //ig.game.selectedPiece.pos.x = ig.input.mouse.x-32; //ig.game.selectedPiece.pos.y = ig.input.mouse.y-32; //this.anims = ig.copy(ig.game.selectedPiece.anims); //this.currAnim = ig.copy(ig.game.selectedPiece.currAnim); //alert("clicky"); } } }, flipMouse: function(){ this.pos.x = ig.system.width - this.pos.x; this.pos.y = ig.system.height - this.pos.y; } }); });
b7fdb3dfc0ef49a454f4d7971eb45bc75d9f8aa3
[ "JavaScript" ]
5
JavaScript
killbot/chessjs
ea70e0836ae3b075ead574b56d364e605bec969b
249861cf632528f79e79cc18434c91aa82e1649a
refs/heads/master
<repo_name>saadrds/LoginFront<file_sep>/src/app/login/login.component.ts import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Router } from '@angular/router'; import { LoginserviceService } from '../loginservice.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { private token : string=""; constructor(private loginservice : LoginserviceService,private router : Router) { } ngOnInit(): void { if(localStorage.getItem("token")){ this.router.navigate(['/home']); } } onLogin(loginxform: NgForm){ let a = this.loginservice.postAgent(loginxform.value).subscribe( (response)=>{console.log("dd1",response);}, (err : HttpErrorResponse) => { console.log (err) console.log(err.status + " ddd") if(err.status == 200){ console.log("user founded"); this.token = err.error.text; localStorage.setItem("token",this.token); this.router.navigate(['/home']); } else{ console.log("wrong username or password!"); } })} } <file_sep>/src/app/loginservice.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User } from './user'; @Injectable({ providedIn: 'root' }) export class LoginserviceService { private host = "https://localhost:44364/api"; constructor(private http:HttpClient) { } public getUser() : Observable<User>{ var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer '+localStorage.getItem("token")}); return this.http.get<User>(this.host + "/Login",{headers : tokenHeader}); } public postAgent(agent : any) : Observable<any>{ console.log("post method entred"); console.log(agent); return this.http.post<any>(this.host + "/Login",agent); } } <file_sep>/src/app/home/home.component.ts import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { LoginserviceService } from '../loginservice.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private router : Router, private loginService : LoginserviceService) { } ngOnInit(): void { if(!localStorage.getItem("token")){ this.router.navigate(['/login']); } else{ this.getUser(); } } public getUser(){ this.loginService.getUser().subscribe( (response)=>{console.log(response)}, (error : HttpErrorResponse)=>{ console.log("er ",error); } ); } }
3c7e252797f5a3e5de002d5c7cf7e5b81f8acd3e
[ "TypeScript" ]
3
TypeScript
saadrds/LoginFront
9770314989b17fd4d19ceb9fecaa4723b848d149
32924e4590db1c3fecad18611d40b21ed8df5965
refs/heads/master
<file_sep># vim: foldmethod=marker #imports {{{ import numpy as np from . import utilities #}}} def negativity(rho, dims, mask): #{{{ rho_pt = ptranspose(rho, dims, mask) rho_pt_eigvals = np.linalg.eigvalsh(rho_pt) return (sum(abs(rho_pt_eigvals)) - rho.trace()).real/2 #}}} def ptranspose(rho, dims, mask): #{{{ #computes the partial transpose of an np.array object #transposes the subsystems where mask == 1 dA = 1 sp_dims = np.array(dims) sp_mask = np.array(mask) for iter in sp_dims*sp_mask: if iter != 0: dA = dA*iter else: continue dB = int((len(rho))/dA) if dA*dB != len(rho): print("dA doesn't divide the dimension of rho") return if not ((sp_mask == 0) + (sp_mask == 1)).all(): print("mask should be either 0 or 1") order = np.argsort(1 - sp_mask) rho = utilities.perm(rho, dims, order) rho_pt = rho.reshape([dA, dB, dA, dB]).transpose([2,1,0,3]).reshape([len(rho), len(rho)]) return utilities.perm(rho_pt, dims, np.argsort(order)) #}}} <file_sep># random-measurement Code for https://arxiv.org/abs/1806.05465 The code producing Figure 3 is `plot_negativity_increase.ipynb`. The code producing Table 1 and Figure 4 is `distance_negativity_post.ipynb`. Warning: `distance_negativity_post.ipynb` takes approximately 6 hours to run with the current parameters. <file_sep>__all__ = ["ann", "ptrace", "ptranspose", "perm", "relative_entropy", "mutual_information", "entropy", "negativity", "randu", "abs"] from quantum.utilities import * from quantum.entropy import * from quantum.entanglement import * <file_sep># vim: foldmethod=marker #imports {{{ import numpy as np from . import utilities #}}} def relative_entropy(rho, sigma, eps=1e-10): #{{{ from math import log2 if not ((np.allclose(rho.conj().transpose(), rho, atol=eps)) or (np.allclose(sigma.conj().transpose(), sigma, atol=eps))): print("rho or sigma is not hermitian") return [rvals, rvecs] = np.linalg.eigh(rho) [svals, svecs] = np.linalg.eigh(sigma) rvecs = rvecs.transpose() svecs = svecs.transpose() if (rvals < -eps).any() or (svals < -eps).any(): print("rho or sigma is not positive") return slogvals = [] for i in svals: if abs(i) > eps: slogvals.append(log2(i)) else: slogvals.append(0) rlogvals = [] rel_trace = 0 for i in rvals: if abs(i) > eps: rel_trace += i*log2(i) for i in range(len(rvals)): for j in range(len(slogvals)): if abs(svals[j]) < eps and norm(rvals[i] * vdot(rvecs[i],svecs[j])) > eps: return float('inf') else: rel_trace -= np.real(rvals[i] * slogvals[j] * np.linalg.norm(np.vdot(rvecs[i],svecs[j])**2 )) return rel_trace #}}} def mutual_information(rho, dims, mask): #{{{ #computes mutual entropy of subsystems with mask 0 and mask 1 rhoA = utilities.ptrace(rho, dims, mask) rhoB = utilities.ptrace(rho, dims, [1-i for i in mask]) return entropy(rhoA) + entropy(rhoB) - entropy(rho) #}}} def entropy(rho): #{{{ #computes the entropy of rho return -1 * relative_entropy(rho, np.eye(len(rho))) #}}} <file_sep># vim: foldmethod=marker #imports {{{ import numpy as np from math import sqrt, pi from cmath import exp #}}} def ann(d): #{{{ #create annihilation operator of dimension d a = np.zeros([d, d], dtype=complex) for i in range(d-1): a[i, i+1] = sqrt(i+1) return a #}}} def ptrace(rho, dims, mask): #{{{ #computes partial trace of an np.array object #traces out the subsystems where mask == 1 dA = 1 sp_dims = np.array(dims) sp_mask = np.array(mask) for iter in sp_dims*sp_mask: if iter != 0: dA = dA*iter else: continue dB = int((len(rho))/dA) if dA*dB != len(rho): print("dA doesn't divide the dimension of rho") return if not ((sp_mask == 0) + (sp_mask == 1)).all(): print("mask should be either 0 or 1") rho = perm(rho, dims, np.argsort(1 - sp_mask)) return rho.reshape([dA, dB, dA, dB]).transpose([0,2,1,3]).trace(axis1=0, axis2=1) #}}} def perm(rho, dims, order): #{{{ #permute the subsystems in rho dim = 1 for iter in dims: dim = dim*iter if len(rho) != dim: print("rho is of the wrong shape") return shape = np.concatenate((dims, dims)) t_order = np.arange(2*len(dims)).reshape(2,len(dims)).transpose().flatten() index = np.arange(2*len(dims)).reshape(len(dims),2)[order].flatten() inv_t_order = np.argsort(t_order) return rho.reshape(shape).transpose(t_order).transpose(index).transpose(inv_t_order).reshape([dim, dim]) #}}} def randu(dim): #{{{ z = np.random.randn(dim, dim) + 1j*np.random.randn(dim, dim) q, r = np.linalg.qr(z) return q@np.diag(r.diagonal().conjugate()/abs(r.diagonal())) #}}} def absm(rho): #{{{ u, s, v = np.linalg.svd(rho) return v.conj().transpose() @ np.diag(s) @ v #}}} def weyl_x(n): #{{{ x = np.zeros([n,n], dtype=complex) for i in range(n): x[((i+1) % n), i] = 1 return x #}}} def weyl_z(n): #{{{ z = np.zeros([n,n], dtype=complex) omega = exp(2j*pi/n) for i in range(n): z[i,i] = omega**i return z #}}}
6a3d5f9460826b0a047965977abfa1b84315f772
[ "Markdown", "Python" ]
5
Python
rganardi/random-measurement
0aa1d6112521e9518888b2370aa08bb2b7d9a837
5b75b5ff6a8092e5edaaa7cde904e3e4efd72fa2
refs/heads/master
<repo_name>adamgoth/ios-firebase-push-notifs<file_sep>/push-my-notifs/ViewController.swift // // ViewController.swift // push-my-notifs // // Created by <NAME> on 10/6/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import Firebase import FirebaseInstanceID import FirebaseMessaging class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() FIRMessaging.messaging().subscribe(toTopic: "topics/news") } }
f85fa178fafa13449ad712f24171fdee4c701db3
[ "Swift" ]
1
Swift
adamgoth/ios-firebase-push-notifs
caf670a4fa9cce9a4540ba702d128cf4bafff882
a3044d9845f018181c13250a538a551b15efcf70
refs/heads/main
<repo_name>fireclint/Open-Weather-Map-API<file_sep>/src/components/Styles.js import styled from 'styled-components'; export const Container = styled.div` background-image: url('https://source.unsplash.com/1600x900/?sunny'); background-size: cover; background-position: bottom; transition: 0.4 ease-out; text-align: center; font-family: 'Rubik', sans-serif; `; export const Main = styled.main` min-height: 100vh; background-image: linear-gradient( to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.75) ); padding: 25px; color: whitesmoke; `; export const Search = styled.input` display: block; width: 100%; padding: 15px; appearance: none; background: none; border: none; outline: none; background-color: rgba(255, 255, 255, 0.55); border-radius: 8px; color: #313131; font-size: 20px; transition: 0.4s ease; `; export const WeatherDisplay = styled.div` margin-top: 8rem; `; export const WeatherLocation = styled.h2` font-size: 26px; margin: 0.6rem; ` export const WeatherDescription = styled.p` text-transform: capitalize; font-size: 24px; ` export const Temp = styled.h1` font-size: 84px; margin: 0.6rem; ` export const TempRange = styled.div` display: flex; margin: auto; justify-content: center; margin-top: 0.5rem; ` export const TempRangeTxt = styled.p` padding: 1rem; `
5aa01d4e6bb9e869413902570f64784eafaed654
[ "JavaScript" ]
1
JavaScript
fireclint/Open-Weather-Map-API
0a104d113cf19cff496062954f397cdcb8806607
b052cea9c71df491097b4f72cde0b74ae978fdd4
refs/heads/master
<file_sep><?php class Database{ private $hostname = "localhost"; private $severname = "root"; private $password = ""; private $db = "qlthanhvien_mvc"; private $conn = NULL; private $result = NULL; public function connect(){ $this->conn = new mysqli($this->hostname, $this->severname, $this->password, $this->db); if(!$this->conn){ echo "kết nối thất bại"; exit(); }else{ mysqli_set_charset($this->conn,"utf8"); } return $this->conn; } //thực thi câu lệnh truy vấn public function implement($sql){ $this->result = $this->conn->query($sql); return $this->result; } //phương thức lấy dữ liệu public function getData(){ if($this->result){ $data = mysqli_fetch_array($this->result); }else{ $data = 0; } return $data; } public function getAllData(){ if(!$this->result){ $data = 0; }else{ while($datas = $this->getData()){ $data[] = $datas; } } return $data; } //phương thức đếm số bản ghi //phương thức thêm dữ liệu public function InsertData($hoTen, $namSinh, $queQuan){ $sql = "Insert into thanhvien(id, hoTen, namSinh, queQuan) values(null,'$hoTen','$namSinh','$queQuan')"; return $this->result($sql); } //phương thức sửa dữ liệu public function updateData($id, $hoTen, $namSinh, $queQuan){ $sql = "update thanhvien set hoTen = '$hoTen', namSinh ='$namSinh', queQuan = '$queQuan' where id = '$id'"; return $this->result($sql); } //phương thức xóa public function delete($id){ $sql = "delete from thanhvien where id = '$id'"; return $this->result($sql); } } ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Máy chủ: 127.0.0.1 -- Thời gian đã tạo: Th12 27, 2018 lúc 09:53 AM -- Phiên bản máy phục vụ: 10.1.36-MariaDB -- Phiên bản PHP: 7.2.11 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 */; -- -- Cơ sở dữ liệu: `qlgame` -- -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `danhmucgame` -- CREATE TABLE `danhmucgame` ( `idgame` int(10) NOT NULL, `tengame` varchar(250) COLLATE utf8_unicode_ci NOT NULL, `ngayup` date NOT NULL, `soluottai` int(250) NOT NULL, `link` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `imgGame` text COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Đang đổ dữ liệu cho bảng `danhmucgame` -- INSERT INTO `danhmucgame` (`idgame`, `tengame`, `ngayup`, `soluottai`, `link`, `imgGame`) VALUES (1, 'PillBall', '2016-12-06', 54324343, 'https://gamevui.vn/choc-pha-co-hang-xom/game', ''), (2, '<NAME>', '2017-03-12', 219278, 'https://gamevui.vn/tho-dan-ne-tranh/game', ''), (3, 'Đại chiến RoBot', '2018-04-28', 3425432, 'https://gamevui.vn/dai-chien-robot/game', ''), (4, 'Cuộc chiến sao anime', '2018-06-28', 4564564, 'https://gamevui.vn/dai-chien-sao-anime/game', ''), (5, 'Chú hề nấu ăn', '2017-11-05', 45335435, 'https://gamevui.vn/nau-an-ngay-tet/game', ''), (6, 'Shin', '2017-12-20', 4343243, 'https://gamevui.vn/cau-be-but-chi-phieu-luu/game', ''), (7, 'Chăm sóc vợ', '2017-12-04', 2344324, 'https://gamevui.vn/cham-soc-be-cung/game', ''), (8, 'Bắn ếch', '2015-05-06', 543234, 'https://gamevui.vn/ban-ca-dai-duong/game', ''), (9, 'Bắn cá', '2015-12-27', 4343423, 'https://gamevui.vn/ban-ca/game', ''), (10, 'Nuôi quái vật', '2017-04-03', 432342, 'https://gamevui.vn/nuoi-quai-thu/game', ''), (12, 'Tranformer', '2012-10-22', 342432, 'https://gamevui.vn/robot-ban-sung/game', ''), (13, 'Phi tiêu', '2016-05-03', 4323242, 'https://gamevui.vn/nem-phi-tieu/game', ''), (14, 'Làm kem', '2017-02-24', 3442234, 'https://gamevui.vn/lam-kem/game', ''), (15, 'Temprun2', '2012-10-22', 4322423, 'https://gamevui.vn/temple-run-2/game', ''), (16, 'Bắn chim', '2015-02-24', 32112321, 'https://gamevui.vn/ban-chim2/game', ''), (17, 'Đột kích 3', '2015-12-20', 54334, 'https://gamevui.vn/dot-kich-3/game', ''), (18, 'Chiến đấu nào', '2012-10-22', 4323432, 'https://gamevui.vn/truong-hoc-dai-chien/game', ''), (19, '<NAME>', '2018-05-04', 432424, 'https://gamevui.vn/perry-tro-lai/game', ''), (20, 'Rambo lùn', '2012-10-22', 3213213, 'https://gamevui.vn/rambo-dot-kich/game', ''), (21, 'Anh hùng chiến loạn', '2012-10-22', 564456, 'https://gamevui.vn/anh-hung-chien-loan/game', ''), (22, 'Điệp vụ perry 2', '2014-04-25', 76486, 'https://gamevui.vn/diep-vu-perry/game', ''), (23, 'Songoku4', '2014-02-19', 74275, 'https://gamevui.vn/songoku-4/game', ''), (24, '<NAME>', '2014-07-09', 264724, 'https://gamevui.vn/rong-den3/game', ''), (25, 'Naruto', '2015-05-30', 5406398, 'https://gamevui.vn/naruto-chien-dau/game', ''), (26, 'Pokemon đại chiến', '2012-10-22', 32543, 'https://gamevui.vn/pokemon-dai-chien-3/game', ''), (27, 'Rồng đen 3', '2012-10-22', 76476, 'https://gamevui.vn/rong-den/game', ''), (28, 'Songoku5', '2012-10-22', 5438, 'https://gamevui.vn/songoku-4/game', ''), (29, 'Anh hùng chiến loạn 3', '2012-10-22', 6434746, 'https://gamevui.vn/anh-hung-chien-loan/game', ''), (30, 'Đại chiến siêu nhân', '2012-10-22', 645645, 'https://gamevui.vn/tan-sieu-hung-dai-chien/game', ''), (31, 'Võ sĩ giác đấu', '2012-10-22', 765755, 'https://gamevui.vn/duong-den-hoang-cung/game', ''), (32, 'Ch<NAME>', '2012-10-22', 43895, 'https://gamevui.vn/chi-huy-khong-gian/game', ''), (33, 'Bé kẹo ngọt', '2016-12-05', 523546, 'https://gamevui.vn/vuong-quoc-keo-ngot/game', ''), (34, 'Cờ caro', '2016-12-05', 64574, 'https://gamevui.vn/choi-co-caro/game', ''), (35, 'Công nhân chở hàng', '2016-12-05', 1019, 'https://gamevui.vn/xe-keo-cho-hang/game', ''), (36, '<NAME>', '2016-12-05', 549863, 'https://gamevui.vn/lien-quan-dai-chien/game', ''), (37, 'Gấu bông diệt zombie', '2016-12-05', 647482, 'https://gamevui.vn/gau-teddy-diet-zombie/game', ''), (38, 'Hoa quả nổi giận 2', '2016-12-05', 5745, 'https://gamevui.vn/hoa-qua-noi-gian/game', ''), (39, 'Người que đại chiến', '2016-12-05', 8564435, 'https://gamevui.vn/nguoi-que-dai-chien/game', ''), (40, 'Lego tìm sao', '2016-12-05', 64589, 'https://gamevui.vn/tim-sao/game', ''), (41, 'Liên quân mobile online', '2016-12-05', 86940, 'https://gamevui.vn/lien-quan-dai-chien/game', ''), (42, 'Game AngryBird', '2016-12-05', 754906, 'https://gamevui.vn/angry-birds-tran-chien-cuoi-cung/game', ''), (43, 'Điều khiển máy bay', '2016-12-05', 5890363, 'https://gamevui.vn/dau-may-bay/game', ''), (44, 'Gunny', '2016-12-05', 58306, 'https://gamevui.vn/gunny-mini/game', ''), (45, 'Robot bắn súng', '2016-12-05', 796, 'https://gamevui.vn/robot-ban-sung/game', ''), (46, 'Robot khủng long khủng lồ ', '2016-12-05', 6834, 'https://gamevui.vn/robot-khung-long-khong-lo/game', ''); -- -- Chỉ mục cho các bảng đã đổ -- -- -- Chỉ mục cho bảng `danhmucgame` -- ALTER TABLE `danhmucgame` ADD PRIMARY KEY (`idgame`); -- -- AUTO_INCREMENT cho các bảng đã đổ -- -- -- AUTO_INCREMENT cho bảng `danhmucgame` -- ALTER TABLE `danhmucgame` MODIFY `idgame` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=47; 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><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../css/style.css"> <title>Quản lý thành viên</title> </head> <body> </body> </html> <?php include '../Model/DBConfig.php'; $database = new Database; $database->connect(); if(isset($_GET['controller'])){ $controller = $_GET['controller']; }else{ $controller = ""; } switch($controller){ case 'thanh-vien':{ require_once('../Controller/thanhvien/index1.php'); } } ?> <file_sep><?php if(isset($_GET['action'])){ $action = $_GET['action']; }else{ $action = ""; } switch($action){ case 'add':{ require_once('../../View/ThanhVien/add_user.php'); if(isset($_POST['add_user'])){ $hoten = $_POST['hoten']; $namsinh = $_POST['namsinh']; $quequan = $_POST['quequan']; $database->InsertData($hoten,$namsinh,$quequan); } break; } case'edit':{ require_once('../../View/ThanhVien/edit_user.php'); if(isset($_POST['add_user'])){ $id = $_POST['id']; $hoten = $_POST['hoten']; $namsinh = $_POST['namsinh']; $quequan = $_POST['quequan']; $database->updateData($id,$hoten,$namsinh,$quequan); } break; } case 'delete':{ require_once('../../View/ThanhVien/delete.user.php'); if(isset($_POST['delete_user'])){ $id = $_POST['id']; $database->delete($id); } break; } default:{ require_once('../../View/ThanhVien/list.php'); break; } } ?>
87bd1cbd63abfab2c5a3525e373a888996a754b0
[ "SQL", "PHP" ]
4
PHP
minhvu9/CSE485_N062338.
9ffb774f9b946b75f1c94ebd626a9d5f1bee08d6
26c906f1b9eff323fe70a9dd16191d45b14bb83a
refs/heads/master
<file_sep>package currency_rate.converters; import org.springframework.format.FormatterRegistry; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by lav on 25.09.15. */ @Component public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { super.addFormatters(registry); registry.addConverter(new StringToLocalDate()); } } <file_sep>package currency_rate; import currency_rate.xml.ValCursType; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.BufferedInputStream; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; /** * Created by lav on 25.09.15. */ @Service public class CurrencyRateService { private static final String API_URL = "http://www.cbr.ru/scripts/XML_daily.asp?date_req="; @Value("${updatePeriod}") private int updatePeriod; private static long lastUpdate = 0; private Map<LocalDate, Map<String, Double>> rates = new HashMap<>(); private DateTimeFormatter sberDateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); public CurrencyRate getRates(String currency, LocalDate date) { if (date == null) { date = LocalDate.now().plusDays(1); } long currentTimeMillis = System.currentTimeMillis(); long elapsedTime = currentTimeMillis - lastUpdate; if (elapsedTime > updatePeriod || !rates.containsKey(date)) { loadRates(date); lastUpdate = currentTimeMillis; } Double rate = rates.get(date).get(currency); return new CurrencyRate(currency, rate, date); } public synchronized void loadRates(LocalDate date) { String strDate = date.format(sberDateFormatter); String url = API_URL + strDate; try { JAXBContext jc = JAXBContext.newInstance(ValCursType.class); Unmarshaller um = jc.createUnmarshaller(); URL website = new URL(url); ValCursType data = (ValCursType) um.unmarshal(new BufferedInputStream(website.openStream())); Map<String, Double> currencyMap = rates.computeIfAbsent(date, localDate -> new HashMap<>()); data.getValute().forEach(valuteType -> { double rate = valuteType.getValue() / valuteType.getNominal(); rate = round(rate); currencyMap.put(valuteType.getCharCode(), rate); }); } catch (JAXBException | IOException e) { throw new RuntimeException("Failed to fetch " + url, e); } } private Double round(double v) { String str = Double.valueOf(v).toString(); BigDecimal d = new BigDecimal(str); return d.setScale(4, RoundingMode.HALF_UP).doubleValue(); } } <file_sep>package currency_rate; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import currency_rate.converters.JsonLocalDateSerializer; import java.time.LocalDate; /** * Created by lav on 25.09.15. */ public class CurrencyRate { private String code; private double rate; @JsonSerialize(using = JsonLocalDateSerializer.class) private LocalDate date; public CurrencyRate(String code, double rate, LocalDate date) { this.code = code; this.rate = rate; this.date = date; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public double getRate() { return rate; } public void setRate(double rate) { this.rate = rate; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } <file_sep>Запуск mvn spring-boot:run http://localhost:8080/currency/api/rate/USD/2015-09-24 <file_sep>package currency_rate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; @RestController @RequestMapping("/currency") public class CurrencyRateController { @Autowired private CurrencyRateService currencyRateService; @RequestMapping(value = "/api/rate/{code}/{date}", method = RequestMethod.GET) @ResponseBody public Object rate(@PathVariable String code, @PathVariable LocalDate date) { return currencyRateService.getRates(code, date); } }
4a1eff1e50c8bb9cdd7deb5aa7a822b7d493a465
[ "Markdown", "Java" ]
5
Java
aleks43/currency-rate
e5ed583fdaa9456c6aec60d2b6cd02e106a231c3
8b470b922be1b4ca6e1b3a0dadd30aff5cd6c6ae
refs/heads/master
<repo_name>hetaopi-code/mini-spring<file_sep>/README.md 仿照Spring实现了一个迷你版Spring,具体模块为IOC+AOP+MVC <file_sep>/src/main/java/com/hetaopi/service/combine/impl/HeadLineShopCategoryCombineServiceImpl2.java package com.hetaopi.service.combine.impl; import com.hetaopi.entity.dto.MainPageInfoDTO; import com.hetaopi.entity.dto.Result; import com.hetaopi.service.combine.HeadLineShopCategoryCombineService; import org.simpleframework.core.annotation.Service; @Service public class HeadLineShopCategoryCombineServiceImpl2 implements HeadLineShopCategoryCombineService { @Override public Result<MainPageInfoDTO> getMainPageInfo() { return null; } }
f67b1128170b1a41c78d514a9340e9941211e6cd
[ "Markdown", "Java" ]
2
Markdown
hetaopi-code/mini-spring
7fc340ef1f3fbefed02236a0331b6da7df672cee
bc697c96b8ee9f66b0dd40b50496dbe976ba7a56